简介
在下单函数后调用 write_logs(contest)
,将order、trade、position对象,以csv格式输出三张表至研究,新的数据将追加在数据框后,在回测和模拟交易中均可使用。支持每日、分钟策略保存对象,分为每日定时调用保存函数和按order调用保存函数,若分钟级策略按order调用时,可能由于下单数量过多导致回测速度下降,建议使用定时调用保存函数。本篇使用官网回测环境,给出期货每日定时调用保存函数的简单实例,文件输出在研究根目录下,若使用客户端请自行在根目录中寻找文件。
Order
Trade
Position
def process_initialize(context):
ls=['security']
g.__df1 = pd.DataFrame(columns=ls)
g.__df2 = pd.DataFrame(columns=ls)
g.__df3 = pd.DataFrame(columns=ls)
def write_logs(context):
orders = get_orders()
i=0
ls1 = ['order_id','status','security','price','amount',\
'avg_cost','Time','is_buy','filled','side','action']
df1 = pd.DataFrame(columns=ls1)
for _orders in orders.values():
df1.loc[i,'order_id'] = _orders.order_id
df1.loc[i,'status'] = _orders.status
df1.loc[i, 'security'] = _orders.security
df1.loc[i,'price'] = _orders.price
df1.loc[i,'amount'] = _orders.amount
df1.loc[i,'avg_cost'] = _orders.avg_cost
df1.loc[i, 'Time'] = _orders.add_time
df1.loc[i, 'is_buy'] = _orders.is_buy
df1.loc[i, 'filled'] = _orders.filled
df1.loc[i, 'side'] = _orders.side
df1.loc[i, 'action'] = _orders.action
i=i 1
df1.set_index('Time',drop=True,inplace=True)
g.__df1 = g.__df1.append(df1)
write_file('orders.csv', g.__df1.to_csv())
trades = get_trades()
i=0
ls2 = ['Time','order_id','trade_id','security','price','amount']
df2 = pd.DataFrame(columns=ls2)
for _trades in trades.values():
df2.loc[i,'Time'] = _trades.time
df2.loc[i,'order_id'] = _trades.order_id
df2.loc[i, 'trade_id'] = _trades.trade_id
df2.loc[i,'security'] = _trades.security
df2.loc[i,'price'] = _trades.price
df2.loc[i,'amount'] = _trades.amount
i=i 1
df2.set_index('Time',drop=True,inplace=True)
g.__df2 = g.__df2.append(df2)
write_file('trade.csv', g.__df2.to_csv())
position = context.portfolio.positions.keys()
i=0
ls3 = ['security','price','acc_avg_cost','avg_cost','Time','transact_time','total_amount',\
'closeable_amount','today_amount','locked_amount','value','side']
df3 = pd.DataFrame(columns=ls3)
for stock in position:
df3.loc[i,'security']=context.portfolio.positions[stock].security
df3.loc[i,'price'] = context.portfolio.positions[stock].price
df3.loc[i,'acc_avg_cost'] = context.portfolio.positions[stock].acc_avg_cost
df3.loc[i,'avg_cost'] = context.portfolio.positions[stock].avg_cost
df3.loc[i, 'Time'] = context.portfolio.positions[stock].init_time
df3.loc[i,'transact_time'] = context.portfolio.positions[stock].transact_time
df3.loc[i,'total_amount'] = context.portfolio.positions[stock].total_amount
df3.loc[i,'closeable_amount'] = context.portfolio.positions[stock].closeable_amount
df3.loc[i,'today_amount'] = context.portfolio.positions[stock].today_amount
df3.loc[i,'locked_amount'] = context.portfolio.positions[stock].locked_amount
df3.loc[i,'value'] = context.portfolio.positions[stock].value
df3.loc[i,'side'] = context.portfolio.positions[stock].side
i=i 1
df3.set_index('Time',drop=True,inplace=True)
g.__df3 = g.__df3.append(df3)
write_file('Position.csv', g.__df3.to_csv())