if __name__ =='__main__':
ticks = get_ticks_for_backtesting("E:\\Downloads\\600036_data\\600036_ticks.csv","E:\\Downloads\\600036_data\\600036_5m.csv")# 获取回测数据
ast = AstockTrading('ma')
ast.run_backtestting(ticks)# 运行回测数据print('ast._current_orders:')print(ast._current_orders)print("-------------------------------------")print('ast._history_orders:')print(ast._history_orders)# 使用matplotlib绘制盈亏柱状图
profit_orders =0# 盈利的交易数
loss_orders =0# 亏损的交易数
orders = ast._history_orders
for key in orders.keys():if orders[key]['pnl']>=0:
profit_orders +=1else:
loss_orders +=1
win_rate = profit_orders /len(orders)
loss_rate = loss_orders /len(orders)# T = transpose
orders_df = pd.DataFrame(orders).T
orders_df.loc[:,'pnl'].plot.bar()
plt.show()# 使用 mplfinance 绘制k线图:订单交易价格与时间
bar5 = pd.read_csv("E:\\Downloads\\600036_data\\600036_5m.csv",
parse_dates=['datetime'])
bar5.loc[:,'datetime']=[date2num(x)for x in bar5.loc[:,'datetime']]
fig, ax = plt.subplots()
candlestick_ohlc(
ax,
quotes=bar5.values,
width=0.2,
colorup="r",
colordown='g',
alpha=1.0,)# put orders in candle sticksfor index, row in orders_df.iterrows():
ax.plot([row['open_datetime'], row['close_datetime']],[row['open_price'], row['close_price']],
color='darkblue',
marker='o',)
plt.show()
二、回测实现
1 - 获取回测数据ticks
defget_ticks_for_backtesting(tick_path, bar_path):"""
:func: get ticks for backtesting, need two params
:param1 tick_path: 生成的回测数据路径
csv file with tick data,
when there is not tick data,
use bat_path to create tick data
example: "E:\\Downloads\\600036_data\\600036_ticks.csv"
:param2 bar_path: 历史数据的tick路径
csv file with bar data,
used in creating tick data
example: "E:\\Downloads\\600036_data\\600036_5m.csv"
:return: ticks in list with tuples in it, such as
[(datetime, last_price), (datetime, last_price)]
"""if os.path.exists(tick_path):# 如果已存在回测数据,直接读取回测数据ticks
ticks = pd.read_csv(
tick_path,
parse_dates=['datetime'],
index_col='datetime')
tick_list =[]for index, row in ticks.iterrows():
tick_list.append((index, row[0]))
ticks = np.array(tick_list)else:
bar_5m = pd.read_csv(bar_path)# 使用pandas读取csv数据
ticks =[]for index, row in bar_5m.iterrows():# 根据不同的开盘价设置步长if row['open']<30:
step =0.01elif row['open']<60:
step =0.03elif row['open']<90:
step =0.05else:
step =0.1# in case of np.arrange(30, 30.11, 0.02), (open, high, step)# we will not have 30.11 as the highest price,# we might not catch high when step is more than 0.01# that is why me need: arr = np.append(arr, row['high']) and# arr = np.append(arr, row['low'])
arr = np.arange(row['open'], row['high'], step)# 按步长生成从open到high的数据
arr = np.append(arr, row['high'])# 这个是为了弥补步长的不对等会漏掉high
arr = np.append(arr, np.arange(row['open']- step, row['low'],-step))# 按步长生成从open到low的数据
arr = np.append(arr, row['low'])# 这个是为了弥补步长的不对等会漏掉low
arr = np.append(arr, row['close'])
i =0
dt = parser.parse(row['datetime'])- timedelta(minutes=5)for item in arr:
ticks.append((dt + timedelta(seconds=0.1* i), item))# 将数据时间模拟到0.1秒递进
i +=1
tick_df = pd.DataFrame(ticks, columns=['datetime','price'])
tick_df.to_csv(tick_path, index=0)# 保存到csv回测数据中return ticks
2 - 运行回测
defrun_backtestting(self, ticks):"""
:method: ticks will be used to generate bars,
when bars is long enough, call strategy()
:param ticks: list with (datetime, price) in the list
:return: none
"""for tick in ticks:
self.bar_generator_for_backtesting