一.效果

二.实现
1.获取数据

2.用talib定义动量指标
#https://www.pybroker.com/zh-cn/latest/notebooks/5.%20Writing%20Indicators.html#%E4%BD%BF%E7%94%A8-TA-Lib
# rsi_20 = pybroker.indicator('rsi_20', lambda data: talib.RSI(data.close, timeperiod=20))
#talib 获取标的20日收益率数据,计算20日收益率
roc_20 = pybroker.indicator('roc_20', lambda data: talib.ROC(data.close, timeperiod=20)/100)
roc_20(df)
3.定义买入卖出规则函数
#https://www.pybroker.com/zh-cn/latest/notebooks/2.%20Backtesting%20a%20Strategy.html#%E5%AE%9A%E4%B9%89%E7%AD%96%E7%95%A5%E8%A7%84%E5%88%99
#如果没有持仓,20日roc大于8%时买入100%
#如果20日roc小于0时,卖出所有
def pick_time(ctx):
if not ctx.long_pos() and ctx.indicator("roc_20")[-1] > 0.08:
ctx.buy_shares = ctx.calc_target_shares(1.0)
if ctx.indicator("roc_20")[-1] < 0:
ctx.sell_all_shares()
4.回测
from pybroker import Strategy, StrategyConfig
config = StrategyConfig(bars_per_year=252, exit_on_last_bar=True)
#1.策略起始时间和结束时间
strategy = Strategy(df, "20111209", "20240913", config)
#2.对标的159915 添加pick_time 执行条件,用到了roc_20指标
strategy.add_execution(pick_time, ["159915.SZ"], indicators=[roc_20])
result = strategy.backtest()
发布者:股市刺客,转载请注明出处:https://www.95sca.cn/archives/268138
站内所有文章皆来自网络转载或读者投稿,请勿用于商业用途。如有侵权、不妥之处,请联系站长并出示版权证明以便删除。敬请谅解!