一.效果

二.实现
1.第一步获取df数据

2.获取动量指标数据
# 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 = pyb.indicator(
"roc_20", lambda data: talib.ROC(data.close, timeperiod=20) / 100
)
3.设置交易规则,定义排序函数,轮转函数
# https://www.pybroker.com/zh-cn/latest/notebooks/10.%20Rotational%20Trading.html
# 购买 20 天涨幅(ROC)最高的buy_nums只股票。
# 将我们的资本的 1/buy_nums 分配给每只股票。
# 如果其中一只股票不再位于前buy_nums名的 20 天涨幅(ROC)中,则我们将清盘该股票。
# 每天交易这些规则。
buy_nums = 1
config = StrategyConfig(max_long_positions=buy_nums, bars_per_year=252, exit_on_last_bar=True)
pyb.param("target_size", 1 / config.max_long_positions)
pyb.param("rank_threshold", buy_nums) # 排名阀值
# 实现一个排名函数,根据每只股票的 20 天涨幅(ROC)降序 排列,从最高到最低。
def rank(ctxs: dict[str, ExecContext]):
scores = {symbol: ctx.indicator("roc_20")[-1] for symbol, ctx in ctxs.items()}
sorted_scores = sorted(
scores.items(), key=lambda score: score[1], reverse=True # 降序
)
threshold = pyb.param("rank_threshold")
top_scores = sorted_scores[:threshold]
top_symbols = [score[0] for score in top_scores]
pyb.param("top_symbols", top_symbols)
# 实现一个 轮动 函数来管理轮动交易。
def rotate(ctx: ExecContext):
if ctx.long_pos():
if ctx.symbol not in pyb.param("top_symbols"):
ctx.sell_all_shares()
else:
target_size = pyb.param("target_size")
ctx.buy_shares = ctx.calc_target_shares(target_size)
ctx.score = ctx.indicator("roc_20")[-1]
4.执行回测
# 1.策略起始时间和结束时间
strategy = Strategy(df, "20130729", "20240913", config)
# 2.先排序
strategy.set_before_exec(rank)
# 3.执行轮转策略
strategy.add_execution(rotate, symobls, indicators=[roc_20])
result = strategy.backtest()
发布者:股市刺客,转载请注明出处:https://www.95sca.cn/archives/268137
站内所有文章皆来自网络转载或读者投稿,请勿用于商业用途。如有侵权、不妥之处,请联系站长并出示版权证明以便删除。敬请谅解!