专业的编程技术博客社区

网站首页 > 博客文章 正文

pybroker-创业板-单标的-动量择时策略年化18.7%,最大回测18.3%

baijin 2024-11-10 08:27:39 博客文章 4 ℃ 0 评论

2024年9月19日

一.效果

二.实现

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()

完整代码已上传到知识星球上。

Tags:

本文暂时没有评论,来添加一个吧(●'◡'●)

欢迎 发表评论:

最近发表
标签列表