def handle_bar(context, bar_dict):
# ?????????????
# bar_dict[order_book_id] ?????????bar??
# context.portfolio ???????????????
# ??order_shares(id_or_ins, amount)??????
# TODO: ??????????
# ?????????????????????
prices = history_bars(context.s1, context.LONGPERIOD+1, '1d', 'close')
# ??talib????????????array?????
short_avg = talib.SMA(prices, context.SHORTPERIOD)
long_avg = talib.SMA(prices, context.LONGPERIOD)
plot("short avg", short_avg[-1])
plot("long avg", long_avg[-1])
# ????portfolio??????
cur_position = context.portfolio.positions[context.s1].quantity
# ????portfolio????????????
shares = context.portfolio.cash / bar_dict[context.s1].close
# ??????????????????????bar?????????????????bar?????????????
if short_avg[-1] - long_avg[-1] < 0 and short_avg[-2] - long_avg[-2] > 0 and cur_position > 0:
# ????
order_target_value(context.s1, 0)
# ????????????????????
if short_avg[-1] - long_avg[-1] > 0 and short_avg[-2] - long_avg[-2] < 0:
# ????
order_shares(context.s1, shares)
评论列表
文章目录