news 2026/9/15 18:52:07

gs-quant 因子风险报告 FactorRiskReport 完全指南:创建、运行与风险归因结果提取

作者头像

张小明

前端开发工程师

1.2k 24
文章封面图
gs-quant 因子风险报告 FactorRiskReport 完全指南:创建、运行与风险归因结果提取

gs-quant 因子风险报告 FactorRiskReport 完全指南:创建、运行与风险归因结果提取

【免费下载链接】gs-quantPython toolkit for quantitative finance项目地址: https://gitcode.com/GitHub_Trending/gs/gs-quant

FactorRiskReport 是 gs-quant 中面向因子风险分析的核心报告类,它基于指定风险模型,对组合(Portfolio)或单一资产(Asset)的历史风险与因子归因进行系统化分析。本文从类的构造、生命周期管理、结果提取到底层实现逐层展开,帮助你用它快速搭建一套可复用的因子风险监控与归因工作流。

认识 FactorRiskReport:它解决什么问题

在 gs_quant/markets/report.py 中,FactorRiskReport的类文档(docstring)给出了精确定位:

Historical analyses on both the risk and attribution of a portfolio or asset to various factors determined by the specified risk model

即:对组合或资产在风险模型定义的各种因子上的历史风险与归因进行量化分析。其典型输出包括因子 PnL、因子敞口(exposure)、因子风险占比(proportion of risk)、年化/日度风险、前瞻性 VaR 等指标,是组合经理评估持仓因子暴露、定位风险来源的核心工具。

FactorRiskReport继承自 gs_quant/markets/report.py 中的通用报告基类Report,因此它天然拥有报告的创建、保存、调度、运行、删除等全套生命周期能力,同时在此基础上扩展了专属的风险分析数据方法。这一继承关系也正是 docs/classes/gs_quant.markets.report.FactorRiskReport.rst 中所列方法清单的来源:__init__deletefrom_targetgetget_annual_riskget_benchmark_idget_daily_riskget_ex_ante_varget_factor_exposureget_factor_pnlget_factor_proportion_of_riskget_most_recent_jobget_resultsget_risk_model_idget_tableget_viewrunsavescheduleset_position_source

构造 FactorRiskReport:核心参数与自动推断

构造函数签名

FactorRiskReport.__init__(gs_quant/markets/report.py)的关键参数如下:

参数类型说明
risk_model_idstr风险模型 ID,决定分析使用哪套因子体系
fx_hedgedbool仓位源是否做了 FX 对冲,默认True
benchmark_idstr可选,参与结果对比的基准资产 Marquee ID
report_idstr已存在的 Marquee 报告 ID(更新/获取已有报告时使用)
namestr报告名称
position_source_idstr仓位源 ID(组合或资产)
position_source_typestr/PositionSourceType仓位源类型:PortfolioAssetBacktestHedge
report_typestr/ReportType报告类型,如Portfolio Factor RiskAsset Factor Risk
earliest_start_date/latest_end_datedt.date报告数据覆盖的起止日期
statusstr/ReportStatus报告状态,默认ReportStatus.new
percentage_completefloat报告完成度
tagstuple[PositionTag, ...]报告标签

源码中的标准构造示例:

from gs_quant.markets.report import FactorRiskReport from gs_quant.markets import PositionSourceType risk_report = FactorRiskReport( risk_model_id='RISKMODELID', fx_hedged=True, benchmark_id=benchmark.get_marquee_id(), position_source_id='PORTFOLIOID', position_source_type=PositionSourceType.Portfolio )

自动推断逻辑:少写两个参数

构造时无需显式指定position_source_typereport_type,gs_quant/markets/report.py 会按以下规则自动推断:

  • 若只传了position_source_id而未传position_source_type:ID 以MP前缀开头判定为组合(Portfolio),否则判定为资产(Asset);
  • 若已确定position_source_type而未传report_type:组合自动映射为ReportType.Portfolio_Factor_Risk,资产映射为ReportType.Asset_Factor_Risk

同时构造时会把这组参数打包进ReportParameters(risk_model=..., fx_hedged=..., benchmark=..., tags=...)传给基类(见 gs_quant/markets/report.py)。ReportParameters的完整字段定义在 gs_quant/target/common.py,其中risk_modelbenchmarkfx_hedgedtags正是因子风险报告相关的核心配置项。

报告生命周期:保存、调度、运行与删除

FactorRiskReport继承自Report的通用方法完整覆盖了报告生命周期:

  • save():报告不存在则创建,已存在则更新。实现中通过TargetReport组装请求,再调用GsReportApi.create_report/update_report(gs_quant/markets/report.py);
  • set_position_source(entity_id):根据实体 ID 设置仓位源。以MP开头视为组合并同时把报告类型设为Portfolio_Factor_Risk,否则视为资产并设为Asset_Factor_Risk(gs_quant/markets/report.py);
  • schedule(start_date, end_date, backcast):为报告安排执行。源码中校验了“只有拥有合法 ID 与仓位源 ID 的报告才能调度”,且非组合类报告必须显式指定起止日期;对组合报告,若日期为空会从组合的历史 position dates 自动推导——backcast=True时起始日取最早持仓日前推一年,结束日取最早持仓日(gs_quant/markets/report.py);
  • run(start_date, end_date, backcast=False, is_async=True):内部先调用schedule,随后通过get_most_recent_job()拿到最新的ReportJobFuture。默认is_async=True立即返回 future;设为False时则轮询等待任务完成并返回结果 DataFrame(每 6 秒查询一次,gs_quant/markets/report.py);
  • delete():调用GsReportApi.delete_report从 Marquee 删除报告(gs_quant/markets/report.py);
  • get_most_recent_job():拉取报告的全部 job,按createdTime倒序取最新一条,封装为ReportJobFuture(gs_quant/markets/report.py)。

异步任务的载体是ReportJobFuture(gs_quant/markets/report.py),它提供:

  • status():查询任务当前状态,取值对应ReportStatus枚举:newreadyexecutingcalculatingdoneerrorcancelledwaitingqueued(gs_quant/target/reports.py);
  • done():任务处于done/error/cancelled任一状态即视为结束;
  • result():任务完成后返回因子风险结果 DataFrame;若任务处于cancellederror状态则直接抛出MqValueError
  • wait_for_completion(sleep_time=10, max_retries=10):周期轮询直至完成,可配置超时与重试;
  • reschedule():重新调度任务。

获取结果的三层接口:get_results / get_view / get_table

get_results:原始结构化结果

get_results(gs_quant/markets/report.py)返回报告最原始的因子风险数据,是其余所有分析方法的底层数据源。其关键参数:

参数默认值说明
modeFactorRiskResultsMode.Portfolio结果粒度:Portfolio(组合层)或Positions(持仓层)
factorsNone因子名列表,默认返回全部因子
factor_categoriesNone因子类别列表,默认全部
start_date/end_dateNone日期区间过滤
currencyNone结果币种(Currency枚举)
return_formatReturnFormat.DATA_FRAMEDATA_FRAME(Pandas DataFrame)或JSON
unitFactorRiskUnit.Notional金额口径:Notional(名义金额)或Percent(百分比)

源码示例:

factor_and_total_results = risk_report.get_results( factors=['Factor', 'Specific'], start_date=dt.date(2022, 1, 1), end_date=dt.date(2021, 1, 1) ) print(factor_and_total_results)

get_view:UI 视角结果

get_view(gs_quant/markets/report.py)返回与 Marquee 界面展示一致的结果,例如factorCategoriesTable类别表。一个典型用法是提取各因子的风险占比、边际风险贡献与敞口:

category_table = risk_report.get_view( start_date=risk_report.latest_end_date, end_date=risk_report.latest_end_date, unit=FactorRiskUnit.Notional ).get('factorCategoriesTable') category_df = pd.DataFrame(category_table).filter(items=[ 'name', 'proportionOfRisk', 'marginalContributionToRiskPercent', 'relativeMarginalContributionToRisk', 'exposure', 'avgProportionOfRisk' ])

get_table:资产级明细表

get_table(gs_quant/markets/report.py)返回按界面“资产级表格”格式化后的明细,必须显式传入modeFactorRiskTableMode,如Pnl)。日期处理上存在实用默认值:当start_dateend_date均为空时,PnL 模式取latest_end_date前推一个月、其他模式取单日快照(latest_end_date)。返回的 DataFrame 会按factors/factor_categories过滤列,并以name为索引。若接口返回warning而非表格数据,会抛出MqValueError

风险指标速查:六个开箱即用的分析方法

以下方法均封装在FactorRiskReport中,底层统一通过get_results拉取数据、再由_format_multiple_factor_table(gs_quant/markets/report.py)转成“日期为行、因子为列”的宽表 DataFrame:

  • get_annual_risk(factor_names, start_date, end_date, currency):年化风险序列,factor_names限定为"Factor""Specific""Total"(gs_quant/markets/report.py);
  • get_daily_risk(factor_names, start_date, end_date, currency):日度风险序列,参数约束同上(gs_quant/markets/report.py);
  • get_ex_ante_var(confidence_interval=95.0, start_date, end_date, currency):风险模型定义的前瞻性 VaR。实现上先取TotaldailyRisk,再用z_score = st.norm.ppf(confidence_interval / 100)计算正态分位数,令var = dailyRisk * z_score(gs_quant/markets/report.py),即默认 95% 置信度下z ≈ 1.645
  • get_factor_pnl(mode, factor_names, factor_categories, start_date, end_date, currency, unit):历史因子 PnL。当unit=FactorRiskUnit.Percent且针对组合时,会额外获取组合的 Performance 报告 AUM 数据做平滑化处理,把名义 PnL 折算为百分比(gs_quant/markets/report.py);
  • get_factor_exposure(mode, factor_names, factor_categories, start_date, end_date, currency, unit):历史因子敞口序列(gs_quant/markets/report.py);
  • get_factor_proportion_of_risk(factor_names, factor_categories, start_date, end_date, currency):历史因子风险占比,反映每个因子对组合总风险的贡献比例(gs_quant/markets/report.py)。

注意factor_namesfactor_categories均默认为“全部”,按需传入可显著减小结果集。而get_results支持的mode枚举(Portfolio/Positions)定义于 gs_quant/markets/report.py,FactorRiskUnitPercent/Notional)定义于 gs_quant/markets/report.py。

反序列化与元数据:get / from_target / get_risk_model_id / get_benchmark_id

  • FactorRiskReport.get(report_id):类方法,按 Marquee 报告 ID 拉取目标对象并重建FactorRiskReport实例(gs_quant/markets/report.py);
  • from_target(report):类方法,将接口返回的TargetReport反序列化为FactorRiskReport。实现中会先校验报告类型,只有Portfolio_Factor_RiskAsset_Factor_Risk才允许转换,否则抛出MqValueError(gs_quant/markets/report.py);
  • get_risk_model_id():返回报告绑定的风险模型 ID(gs_quant/markets/report.py);
  • get_benchmark_id():返回基准资产的 Marquee 唯一标识(gs_quant/markets/report.py)。

报告对象还从基类暴露了只读属性:idnameposition_source_idposition_source_typetypeparametersearliest_start_datelatest_end_datelatest_execution_timestatuspercentage_complete,便于在提取结果时直接引用(如risk_report.latest_end_date)。

底层实现与测试佐证

从源码结构看,FactorRiskReport的所有数据方法都收敛到GsReportApi的四个接口:get_factor_risk_report_resultsget_results底层)、get_factor_risk_report_viewget_view底层)、get_factor_risk_report_tableget_table底层),以及Report基类复用的get_report/create_report/update_report/delete_report/get_report_jobs/schedule_report。换言之,整个 SDK 层是 Marquee 报告服务的薄封装,风险模型计算本身由服务端完成。

对应的单元测试位于 gs_quant/test/markets/test_report.py,通过 mockGsSession验证了各方法的行为契约:test_get_factor_pnltest_get_factor_proportion_of_risktest_get_factor_exposuretest_get_annual_risktest_get_daily_risk均断言返回 DataFrame 长度符合预期,test_get则校验了FactorRiskReport.get返回实例的typePortfolio_Factor_Risk。这些测试同时是理解“各方法返回结构”的快速参考。

使用要点小结

  • 组合 ID 以MP开头,构造时可不传position_source_typereport_type,SDK 会自动推断;
  • 组合报告的schedule/run可不传日期,SDK 会从历史持仓日推导;非组合报告必须显式给日期;
  • 生产环境中建议使用run(is_async=False)job_future.wait_for_completion()阻塞获取结果,避免手动轮询;
  • 分析因子归因时优先使用get_factor_pnl/get_factor_exposure/get_factor_proportion_of_risk三个专属方法,需要原始明细时再回退到get_results/get_view/get_table
  • 相关文档入口:FactorRiskReport 类文档、Report 基类文档、报告类型与状态枚举、ReportParameters 参数模型。

【免费下载链接】gs-quantPython toolkit for quantitative finance项目地址: https://gitcode.com/GitHub_Trending/gs/gs-quant

创作声明:本文部分内容由AI辅助生成(AIGC),仅供参考

版权声明: 本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若内容造成侵权/违法违规/事实不符,请联系邮箱:809451989@qq.com进行投诉反馈,一经查实,立即删除!
网站建设 2026/9/15 18:51:16

北京百度网站排名优化速查手册:告别零流量的3个设计坑

北京百度网站排名优化速查手册:告别零流量的3个设计坑 网站上线三个月,后台看着空荡荡的访问记录,心里是不是在滴血?很多北京的项目经理都遇到过这种尴尬:代码写得再漂亮,服务器跑得再快,只要百度不给流量,一切白搭。这背后往往不是内容的问题,而是 网站结构设计 没对齐搜索引擎的抓取逻辑。…

作者头像 李华
网站建设 2026/9/15 18:51:14

抖音无水印下载5分钟实操:从一条视频到整账号备份

抖音无水印下载5分钟实操:从一条视频到整账号备份 【免费下载链接】douyin-downloader A practical Douyin downloader for both single-item and profile batch downloads, with progress display, retries, SQLite deduplication, and browser fallback support. …

作者头像 李华
网站建设 2026/9/15 18:50:26

AI如何革新学术专著写作:从文献处理到智能写作

1. 专著写作的范式革命:当AI遇上学术创作去年协助一位教授完成跨学科专著时,我们团队在文献综述环节遭遇了瓶颈——需要梳理近十年间发表的3000多篇相关论文。传统人工筛选方式至少需要两个月,而截稿日期就在眼前。当我引入语义分析工具构建文…

作者头像 李华
网站建设 2026/9/15 18:50:06

Dozzle 匿名统计机制全解:Beacon 字段、数据流向与隐私关闭方案

Dozzle 匿名统计机制全解:Beacon 字段、数据流向与隐私关闭方案 【免费下载链接】dozzle Realtime log viewer for containers. Supports Docker, Swarm and K8s. 项目地址: https://gitcode.com/GitHub_Trending/do/dozzle Dozzle 作为一款面向容器的实时日…

作者头像 李华
网站建设 2026/9/15 18:47:21

2026年AI编程工具实战指南:上下文感知与工作流嵌入

1. 这不是“工具清单”,而是一份2026年开发者真实工作流的切片快照你点开这篇内容,大概率不是为了收藏一个“33个AI编程工具”的名字列表——那太容易了,随便爬个网页就能凑够50个。真正让你停下来的,是标题里那个具体到年份的“2…

作者头像 李华
网站建设 2026/9/15 18:46:28

资金核对平台演进全解:从Excel手工对账到实时智能对账系统

1. 为什么资金核对平台会存在:先搞清楚对账在解决什么问题1.1 对账是“账实相符”的守门员做过支付、电商、财务或者任何跟资金流水打交道的人,应该都懂这个场景:系统里显示用户付了100元,银行渠道侧却只到了99.7元;或…

作者头像 李华