注意:ptrade需要开发策略者自己写持久化处理逻辑的
服务器异常、策略优化等诸多场景,都会使得正在进行的模拟盘和实盘策略存在中断后再重启的需求,但是一旦交易中止后,策略中存储在内存中的全局变量就清空了,因此通过持久化处理为量化交易保驾护航必不可少。
使用pickle模块保存 g 对象(全局变量)。
import pickle
from collections import defaultdict
'''
持仓N日后卖出,仓龄变量每日pickle进行保存,重启策略后可以保证逻辑连贯
'''
def initialize(context):
g.notebook_path = get_research_path()
#尝试启动pickle文件
try:
with open(g.notebook_path+'hold_days.pkl','rb') as f:
g.hold_days = pickle.load(f)
#定义空的全局字典变量
except:
g.hold_days = defaultdict(list)
g.security = '600570.SS'
set_universe(g.security)
# 仓龄增加一天
def before_trading_start(context, data):
if g.hold_days:
g.hold_days[g.security] += 1
# 每天将存储仓龄的字典对象进行pickle保存
def handle_data(context, data):
if g.security not in list(context.portfolio.positions.keys()) and g.security not in g.hold_days:
order(g.security, 100)
g.hold_days[g.security] = 1
if g.hold_days:
if g.hold_days[g.security] > 5:
order(g.security, -100)
del g.hold_days[g.security]
with open(g.notebook_path+'hold_days.pkl','wb') as f:
pickle.dump(g.hold_days,f,-1)