当前位置: 首页 > 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.jsqmd.com/news/1131834/

相关文章:

  • Vision-Language-Action:LMDrive双损失函数训练模块与 LangAuto 基准评测框架
  • HarmonyKit | 鸿蒙新特性对比:Tabs vs HdsTabs 选型深度解析
  • 嘉立创SMT 2026下单实战:3种器件库存状态解析与5步高效备料策略
  • 高并发秒杀三大核心技术实战
  • vsftpd 3.0.5 安全配置实战:5项关键设置加固FTP服务器
  • KubeFed v0.3.1 实战部署:2集群联邦配置与Nginx应用分发验证
  • 最小权限原则实战:从Linux进程到云原生的五层权限收缩
  • 小产和流产有什么区别?
  • 2026最新8款AI编程助手学生党平替实测合集
  • 【共创季稿事节】随机数生成器:Math.random() 的原理与应用
  • NVMe 2.0b 控制器架构解析:3种控制器类型与2种模型的核心差异
  • web第十一次作业
  • 基于51单片机指纹密码锁/指纹解锁/指纹识别门禁系统/电子21(设计源文件+万字报告+讲解)(支持资料、图片参考_相关定制)_
  • 现代密码学实战:Python实现3种经典密码(凯撒、维吉尼亚、RSA)
  • SmileCli04 Multi_Agent实现
  • 如何轻松获取大疆无人机历史固件:5个简单步骤实现固件自由
  • OpenCV 4.x 形态学操作实战:3种结构元素与5种算子对字符识别效果对比
  • 2026最新5款AI编程工具平替实测合集|开发者全方位权威榜单
  • C++中内存池的简单原理及实现详解
  • 告别AI能力局限:从零读懂Tool Calling,实现大模型调用外部工具、落地真实业务
  • PCIe 6.0 DMWr 实战:3步配置与 64B/128B 负载性能对比
  • OnlyOffice 编译包跨平台部署:CentOS 7 系统 5 项关键服务配置详解
  • 今天我重读了一次《重构》,说说我觉得能在AI中用到的几个地方
  • 5分钟解锁:FGA如何让你每天从FGO刷本中解放3小时
  • 河南洛阳无人机维修机构推荐|河南筋斗云翼航空一站式低空产业实训基地
  • 首月半价cursor
  • 26-MCP协议是什么
  • Plone安全架构解析:默认拒绝与五维控制的开源实践
  • 深度学习过拟合实战:L1/L2正则化与Dropout在Auto MPG回归任务中的5方案对比
  • VOC、COCO、YOLO 3 种目标检测数据集格式对比与 Python 转换脚本