当前位置: 首页 > news >正文

7.3量化

-- coding: utf-8 --

import pandas as pd

====================== 全局配置 ======================

BENCHMARK = “000852.XSHG”
INDEX_CODE = “000852.XSHG”
STOCK_NUM = 50
SINGLE_MAX_WEIGHT = 0.03

FACTOR_WEIGHT = {
“pe”: 0.3,
“roe”: 0.3,
“gp”: 0.2,
“mom”: 0.2
}

====================== 因子预处理函数 ======================

def winsorize(ser):
q1 = ser.quantile(0.01)
q99 = ser.quantile(0.99)
return ser.clip(q1, q99)

def standard(ser):
mean_val = ser.mean()
std_val = ser.std()
return (ser - mean_val) / std_val

====================== 初始化 ======================

def initialize(context):
set_benchmark(BENCHMARK)
context.last_month = None

====================== 月度调仓核心 ======================

def rebalance(context):
today = context.current_dt.strftime(“%Y-%m-%d”)
# 获取中证1000成分股并过滤ST、新股
stock_list = get_index_stocks(INDEX_CODE, date=today)
valid = []
for s in stock_list:
info = get_security_info(s)
if “ST” in info.display_name:
continue
start_date = pd.to_datetime(info.start_date)
curr_date = pd.to_datetime(today)
if (curr_date - start_date).days >= 60:
valid.append(s)

target_count = len(valid) if len(valid) < STOCK_NUM else STOCK_NUM # 拉取财务因子 q = query( valuation.code, valuation.pe_ratio, indicator.roe, indicator.gross_profit_margin ).filter(valuation.code.in_(valid)) fund_df = get_fundamentals(q, date=today).set_index("code") fund_df = fund_df.dropna() if len(fund_df) == 0: log.info("无有效财务数据,跳过调仓") return # 计算动量,修复DataFrame取数报错 mom_dict = {} for code in fund_df.index: # 网页免费版get_price 返回DataFrame df = get_price(code, count=20, fields=["close"]) if len(df) < 5: continue # 正确取最后一日/首日收盘价 close_first = df["close"].iloc[0] close_last = df["close"].iloc[-1] mom_dict[code] = close_last / close_first - 1 # 动量缺失兜底 if len(mom_dict) > 0: mom_df = pd.DataFrame(list(mom_dict.items()), columns=["code", "mom"]).set_index("code") all_df = pd.concat([fund_df, mom_df], axis=1).dropna() else: log.info("动量数据缺失,仅使用财务因子打分") all_df = fund_df.copy() all_df["mom"] = 0 if len(all_df) < 1: log.info("无有效因子标的,跳过调仓") return # 多因子加权打分 score = pd.DataFrame(index=all_df.index) score["pe"] = -1 * standard(winsorize(all_df["pe_ratio"])) * FACTOR_WEIGHT["pe"] score["roe"] = standard(winsorize(all_df["roe"])) * FACTOR_WEIGHT["roe"] score["gp"] = standard(winsorize(all_df["gross_profit_margin"])) * FACTOR_WEIGHT["gp"] score["mom"] = standard(winsorize(all_df["mom"])) * FACTOR_WEIGHT["mom"] score["total"] = score.sum(axis=1) target_stocks = score.sort_values("total", ascending=False).head(target_count).index.tolist() single_weight = min(1 / len(target_stocks), SINGLE_MAX_WEIGHT) # 清仓不在目标内的股票 for pos_code in list(context.portfolio.positions.keys()): if pos_code not in target_stocks: order(pos_code, 0) # 买入新持仓,修复行情取数KeyError total_cash = context.portfolio.cash single_cash = total_cash * single_weight for code in target_stocks: df_check = get_price(code, count=1, fields=["close"]) if df_check.empty: continue close_price = df_check["close"].iloc[-1] # A股100股一手 trade_share = int(single_cash / close_price / 100) * 100 if trade_share > 0: order(code, trade_share) log.info(f"月度调仓完成,当期持仓{len(target_stocks)}只股票")

每日循环,按月判断调仓

def handle_data(context, data):
cur_month = context.current_dt.month
if cur_month != context.last_month:
rebalance(context)
context.last_month = cur_month

http://www.gsyq.cn/news/1643811.html

相关文章:

  • vsftpd 3.0.5 安全配置实战:5项关键设置加固FTP服务器
  • HarmonyKit | 鸿蒙新特性对比:Tabs vs HdsTabs 选型深度解析
  • 2026最新8款AI编程助手学生党平替实测合集
  • NVMe 2.0b 控制器架构解析:3种控制器类型与2种模型的核心差异
  • 2026最新5款AI编程工具平替实测合集|开发者全方位权威榜单
  • 河南洛阳无人机维修机构推荐|河南筋斗云翼航空一站式低空产业实训基地
  • 首月半价cursor
  • PCIe 6.0 DMWr 实战:3步配置与 64B/128B 负载性能对比
  • 26-MCP协议是什么
  • 深度学习过拟合实战:L1/L2正则化与Dropout在Auto MPG回归任务中的5方案对比
  • VOC、COCO、YOLO 3 种目标检测数据集格式对比与 Python 转换脚本
  • R-CNN系列3大模型演进对比:从53.7%到73.2% mAP的性能跃迁分析
  • 2026最新8款AI编程工具平替实测深度对比
  • Home Assistant Android应用mTLS证书闪退问题排查与修复指南
  • Grok Build:从构建工具到工作流语义引擎的范式跃迁
  • ESP-NOW 低功耗设备的可靠唤醒:一个被忽视的时序问题
  • AKShare金融数据接口:一站式解决Python量化投资的数据获取难题
  • 你每天用的 Claude Code,可能在偷偷标记你——阿里全员卸载背后的真相
  • 计算机考试-C语言计算static 静态变量—东方仙盟 —东方仙盟
  • 基于STM32单片机座位管理系统 图书馆智能选座设计4421(设计源文件+万字报告+讲解)(支持资料、图片参考_相关定制)_
  • 【OpenHarmony/HarmonyOs 】数学答题结果页设计:成绩统计、错题解析与复盘闭环
  • MySQL视图与数据表CRUD对比学习笔记
  • SO-101 Robot From Sim-to-Real With NVIDIA Isaac
  • WindiskWriter:Mac用户制作Windows启动盘的专业解决方案与技术解析
  • USB 控制传输深度剖析:11个标准请求与Windows驱动开发实战
  • 一个中层是怎么突然变强的?看完你就是中层的天花板
  • 【VRP问题】基于遗传算法求解应急物资配送路径最低成本优化问题附Matlab代码
  • YOLOv3 与 RealSense D435i 协同:600张图像训练,实现多目标无序抓取位姿估计
  • 如何用15分钟完成传统需要3小时的Hackintosh配置?OpCore-Simplify的智能革命
  • APKMirror客户端开发实战:构建安全高效的安卓应用下载平台