问题源码: Security(code=600030.XSHG) 在 positions 中不存在, 为了保持兼容, 我们返回空的 Position 对象, amount/price/avg_cost/acc_avg_cost 都是 0
源码:
导入聚宽函数库
import jqdata
初始化此策略
def initialize(context):
set_option('use_real_price',True)
g.sumprice = 0
g.stocks = ['000001.XSHE','600000.XSHG','600019.XSHG','600028.XSHG','600030.XSHG','600036.XSHG','600510.XSHG','601398.XSHG','601857.XSHG','601988.XSHG']
每个单位时间(如果按天回测,则每天调用一次,如果按分钟,则每分钟调用一次)调用一次
def handle_data(context,data):
hist = history(1,'1d','close',g.stocks)
for security in g.stocks:
p = hist[security][0]
g.sumprice = g.sumprice p
for security in g.stocks:
today = context.current_dt
current_price = hist[security][0]
if (today.month == 2 or today.month == 8) and today.day <= 10 and context.portfolio.positions[security].closeable_amount == 0 :
order_value(security, context.portfolio.available_cash*current_price/g.sumprice)
log.info("Buying %sw" % (security))
elif (today.month == 5 or today.month==10) and today.day >=10 and context.portfolio.positions[security].closeable_amount > 0:
order_target(security,0)
log.info("Selling %s" %(security))