下表显示了在 中生成信号row 2
然后在 中生成相反信号的策略示例row 5
。
row open_signal close_signal live
1 0 0 0
2 1 0 1
3 0 0 1
4 0 0 1
5 0 1 0
6 0 0 0
我想优化live
列的计算。
有没有办法在Pandas或Numpy中对这个问题进行矢量化以提高性能,生成与下面的 for 循环示例相同的结果?
import pandas as pd
from datetime import datetime
example = {'date': [str(datetime(2017,1,1)), str(datetime(2017,1,2)),str(datetime(2017,1,3)),str(datetime(2017,1,4)),str(datetime(2017,1,5)),str(datetime(2017,1,6)),
str(datetime(2017,1,7)), str(datetime(2017,1,8)),str(datetime(2017,1,9)), str(datetime(2017,1,10)),str(datetime(2017,1,11)), str(datetime(2017,1,12)),
str(datetime(2017,1,13)),str(datetime(2017,1,14))],
'open': [142.11, 142.87, 141.87, 142.11, 142.00, 142.41, 142.50, 142.75, 140.87, 141.25, 141.10, 141.15, 142.55, 142.75],
'close': [142.87, 141.87, 142.11, 142.00, 142.41, 142.50, 142.75, 140.87, 141.25, 141.10, 141.15, 142.55, 142.75, 142.11],
'open_signal': [False, False, False, False, False, True, False, False, False, False, False, False, False, False],
'close_signal':[False, False, False, False, False, False, False, False, False, True, False, False, False, False]
}
data = pd.DataFrame(example)
in_trade = False
for i in data.iterrows():
if i[1].open_signal:
in_trade = True
if i[1].close_signal:
in_trade = False
data.loc[i[0],'in_trade'] = in_trade