Zylh_Admin 发表于 2025-5-15 11:25:58

QMT策略回测中,在handlebar里,每天都取获取过去三天涨幅前50的品种

实现效果
https://www.xuntou.net/data/attachment/forum/202402/22/203439eez1v33q3ncenbdq.png
代码分享
# coding:gbk

def init(C):
    C.stock_list = C.get_stock_list_in_sector('沪深300')
    return


def handlebar(C):
    #当前k线日期
    bar_date = timetag_to_datetime(C.get_bar_timetag(C.barpos), '%Y%m%d%H%M%S')
    #回测不需要订阅最新行情使用本地数据速度更快 指定subscribe参数为否. 如果回测多个品种 需要先下载对应周期历史数据
    local_data = C.get_market_data_ex(['close'], C.stock_list, end_time = bar_date, period = C.period, count = 3)

    # 初始化涨幅和日期范围存储结构
    growth_rates = {}

    for stock, df in local_data.items():
      # 确保DataFrame是按日期排序的
      df_sorted = df.sort_index()
      # 计算涨幅:(最后一天的收盘价 - 第一天的收盘价) / 第一天的收盘价
      if len(df_sorted) >= 2:# 确保有至少两天的数据来计算涨幅
            start_date = df_sorted.index
            end_date = df_sorted.index[-1]
            growth_rate = (df_sorted['close'].iloc[-1] - df_sorted['close'].iloc) / df_sorted['close'].iloc
            # 存储涨幅和日期范围
            growth_rates = (growth_rate, start_date, end_date)

    # 将股票根据涨幅进行排序,得到一个由(股票, (涨幅, 起始日期, 结束日期))组成的列表
    sorted_growth_rates = sorted(growth_rates.items(), key=lambda x: x, reverse=True)

    # 提取排序后的前50个股票的名称
    top_50_stocks = ]

    # 打印股票列表
    print(f"{bar_date}Top 50 stocks by growth rate:")
    print(top_50_stocks)



页: [1]
查看完整版本: QMT策略回测中,在handlebar里,每天都取获取过去三天涨幅前50的品种