0

我正在尝试加快我的交易策略回测。

现在,我有

for i in trange(1, len(real_choice), disable=not backtesting, desc="Converting HOLDs and calculating backtest correct/incorrect... [3/3]"):
      if (advice[i] == "HOLD"):
        advice[i] = advice[i-1]
      if (real_choice[i] == "HOLD"):
        real_choice[i] = real_choice[i-1]

      if advice[i] == real_choice[i]:
        correct[i] = "CORRECT"
      else:
        correct[i] =  "INCORRECT"

这部分代码耗时最长,所以我想加快速度。

我正在学习 Python,所以这很简单而且很有效,但现在我要为它付出的代价是回测需要多长时间。

有没有办法更快地做到这一点?

4

1 回答 1

1

您可以np.where用来比较两列并为这些行分配一个值

correct = np.where( advice == real_choice
                     , "CORRECT", "INCORRECT)

但为了让它看起来更像熊猫,它会

df['correct'] = np.where( df['advice'] == df['real_choice']
                     , "CORRECT", "INCORRECT)

有一些时间比较(完整代码)

A = randint(0, 10, 10000)

B = randint(0, 10, 10000)

df = pd.DataFrame({'A': A, 'B':B, 'C': "INCORRECT"})
print(df)


start = time.process_time()
for i in range(0, len(real_choice)):
      if df['A'][i] == df['B'][i]:
        df['C'][i] = "CORRECT"
      else:
        df['C'][i] =  "INCORRECT"
print("method 1", time.process_time() - start)


start = time.process_time()
df['C2'] = np.where( df['A'] == df['B'], "CORRECT", "INCORRECT")
print("method 2", time.process_time() - start)

方法 2 的计算时间更短

method 1 1.0530679999999997
method 2 0.0022619999999999862
于 2020-12-10T21:54:38.493 回答