gs-quant 因子风险报告 FactorRiskReport 完全指南:创建、运行与风险归因结果提取
gs-quant 因子风险报告 FactorRiskReport 完全指南创建、运行与风险归因结果提取【免费下载链接】gs-quantPython toolkit for quantitative finance项目地址: https://gitcode.com/GitHub_Trending/gs/gs-quantFactorRiskReport 是 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__、delete、from_target、get、get_annual_risk、get_benchmark_id、get_daily_risk、get_ex_ante_var、get_factor_exposure、get_factor_pnl、get_factor_proportion_of_risk、get_most_recent_job、get_results、get_risk_model_id、get_table、get_view、run、save、schedule、set_position_source。构造 FactorRiskReport核心参数与自动推断构造函数签名FactorRiskReport.__init__gs_quant/markets/report.py的关键参数如下参数类型说明risk_model_idstr风险模型 ID决定分析使用哪套因子体系fx_hedgedbool仓位源是否做了 FX 对冲默认Truebenchmark_idstr可选参与结果对比的基准资产 Marquee IDreport_idstr已存在的 Marquee 报告 ID更新/获取已有报告时使用namestr报告名称position_source_idstr仓位源 ID组合或资产position_source_typestr/PositionSourceType仓位源类型Portfolio、Asset、Backtest、Hedge等report_typestr/ReportType报告类型如Portfolio Factor Risk或Asset Factor Riskearliest_start_date/latest_end_datedt.date报告数据覆盖的起止日期statusstr/ReportStatus报告状态默认ReportStatus.newpercentage_completefloat报告完成度tagstuple[PositionTag, ...]报告标签源码中的标准构造示例from gs_quant.markets.report import FactorRiskReport from gs_quant.markets import PositionSourceType risk_report FactorRiskReport( risk_model_idRISKMODELID, fx_hedgedTrue, benchmark_idbenchmark.get_marquee_id(), position_source_idPORTFOLIOID, position_source_typePositionSourceType.Portfolio )自动推断逻辑少写两个参数构造时无需显式指定position_source_type与report_typegs_quant/markets/report.py 会按以下规则自动推断若只传了position_source_id而未传position_source_typeID 以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_model、benchmark、fx_hedged、tags正是因子风险报告相关的核心配置项。报告生命周期保存、调度、运行与删除FactorRiskReport继承自Report的通用方法完整覆盖了报告生命周期save()报告不存在则创建已存在则更新。实现中通过TargetReport组装请求再调用GsReportApi.create_report/update_reportgs_quant/markets/report.pyset_position_source(entity_id)根据实体 ID 设置仓位源。以MP开头视为组合并同时把报告类型设为Portfolio_Factor_Risk否则视为资产并设为Asset_Factor_Riskgs_quant/markets/report.pyschedule(start_date, end_date, backcast)为报告安排执行。源码中校验了“只有拥有合法 ID 与仓位源 ID 的报告才能调度”且非组合类报告必须显式指定起止日期对组合报告若日期为空会从组合的历史 position dates 自动推导——backcastTrue时起始日取最早持仓日前推一年结束日取最早持仓日gs_quant/markets/report.pyrun(start_date, end_date, backcastFalse, is_asyncTrue)内部先调用schedule随后通过get_most_recent_job()拿到最新的ReportJobFuture。默认is_asyncTrue立即返回 future设为False时则轮询等待任务完成并返回结果 DataFrame每 6 秒查询一次gs_quant/markets/report.pydelete()调用GsReportApi.delete_report从 Marquee 删除报告gs_quant/markets/report.pyget_most_recent_job()拉取报告的全部 job按createdTime倒序取最新一条封装为ReportJobFuturegs_quant/markets/report.py。异步任务的载体是ReportJobFuturegs_quant/markets/report.py它提供status()查询任务当前状态取值对应ReportStatus枚举new、ready、executing、calculating、done、error、cancelled、waiting、queuedgs_quant/target/reports.pydone()任务处于done/error/cancelled任一状态即视为结束result()任务完成后返回因子风险结果 DataFrame若任务处于cancelled或error状态则直接抛出MqValueErrorwait_for_completion(sleep_time10, max_retries10)周期轮询直至完成可配置超时与重试reschedule()重新调度任务。获取结果的三层接口get_results / get_view / get_tableget_results原始结构化结果get_resultsgs_quant/markets/report.py返回报告最原始的因子风险数据是其余所有分析方法的底层数据源。其关键参数参数默认值说明modeFactorRiskResultsMode.Portfolio结果粒度Portfolio组合层或Positions持仓层factorsNone因子名列表默认返回全部因子factor_categoriesNone因子类别列表默认全部start_date/end_dateNone日期区间过滤currencyNone结果币种Currency枚举return_formatReturnFormat.DATA_FRAMEDATA_FRAMEPandas DataFrame或JSONunitFactorRiskUnit.Notional金额口径Notional名义金额或Percent百分比源码示例factor_and_total_results risk_report.get_results( factors[Factor, Specific], start_datedt.date(2022, 1, 1), end_datedt.date(2021, 1, 1) ) print(factor_and_total_results)get_viewUI 视角结果get_viewgs_quant/markets/report.py返回与 Marquee 界面展示一致的结果例如factorCategoriesTable类别表。一个典型用法是提取各因子的风险占比、边际风险贡献与敞口category_table risk_report.get_view( start_daterisk_report.latest_end_date, end_daterisk_report.latest_end_date, unitFactorRiskUnit.Notional ).get(factorCategoriesTable) category_df pd.DataFrame(category_table).filter(items[ name, proportionOfRisk, marginalContributionToRiskPercent, relativeMarginalContributionToRisk, exposure, avgProportionOfRisk ])get_table资产级明细表get_tablegs_quant/markets/report.py返回按界面“资产级表格”格式化后的明细必须显式传入modeFactorRiskTableMode如Pnl。日期处理上存在实用默认值当start_date与end_date均为空时PnL 模式取latest_end_date前推一个月、其他模式取单日快照latest_end_date。返回的 DataFrame 会按factors/factor_categories过滤列并以name为索引。若接口返回warning而非表格数据会抛出MqValueError。风险指标速查六个开箱即用的分析方法以下方法均封装在FactorRiskReport中底层统一通过get_results拉取数据、再由_format_multiple_factor_tablegs_quant/markets/report.py转成“日期为行、因子为列”的宽表 DataFrameget_annual_risk(factor_names, start_date, end_date, currency)年化风险序列factor_names限定为Factor、Specific、Totalgs_quant/markets/report.pyget_daily_risk(factor_names, start_date, end_date, currency)日度风险序列参数约束同上gs_quant/markets/report.pyget_ex_ante_var(confidence_interval95.0, start_date, end_date, currency)风险模型定义的前瞻性 VaR。实现上先取Total的dailyRisk再用z_score st.norm.ppf(confidence_interval / 100)计算正态分位数令var dailyRisk * z_scoregs_quant/markets/report.py即默认 95% 置信度下z ≈ 1.645get_factor_pnl(mode, factor_names, factor_categories, start_date, end_date, currency, unit)历史因子 PnL。当unitFactorRiskUnit.Percent且针对组合时会额外获取组合的 Performance 报告 AUM 数据做平滑化处理把名义 PnL 折算为百分比gs_quant/markets/report.pyget_factor_exposure(mode, factor_names, factor_categories, start_date, end_date, currency, unit)历史因子敞口序列gs_quant/markets/report.pyget_factor_proportion_of_risk(factor_names, factor_categories, start_date, end_date, currency)历史因子风险占比反映每个因子对组合总风险的贡献比例gs_quant/markets/report.py。注意factor_names与factor_categories均默认为“全部”按需传入可显著减小结果集。而get_results支持的mode枚举Portfolio/Positions定义于 gs_quant/markets/report.pyFactorRiskUnitPercent/Notional定义于 gs_quant/markets/report.py。反序列化与元数据get / from_target / get_risk_model_id / get_benchmark_idFactorRiskReport.get(report_id)类方法按 Marquee 报告 ID 拉取目标对象并重建FactorRiskReport实例gs_quant/markets/report.pyfrom_target(report)类方法将接口返回的TargetReport反序列化为FactorRiskReport。实现中会先校验报告类型只有Portfolio_Factor_Risk与Asset_Factor_Risk才允许转换否则抛出MqValueErrorgs_quant/markets/report.pyget_risk_model_id()返回报告绑定的风险模型 IDgs_quant/markets/report.pyget_benchmark_id()返回基准资产的 Marquee 唯一标识gs_quant/markets/report.py。报告对象还从基类暴露了只读属性id、name、position_source_id、position_source_type、type、parameters、earliest_start_date、latest_end_date、latest_execution_time、status、percentage_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_pnl、test_get_factor_proportion_of_risk、test_get_factor_exposure、test_get_annual_risk、test_get_daily_risk均断言返回 DataFrame 长度符合预期test_get则校验了FactorRiskReport.get返回实例的type为Portfolio_Factor_Risk。这些测试同时是理解“各方法返回结构”的快速参考。使用要点小结组合 ID 以MP开头构造时可不传position_source_type与report_typeSDK 会自动推断组合报告的schedule/run可不传日期SDK 会从历史持仓日推导非组合报告必须显式给日期生产环境中建议使用run(is_asyncFalse)或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),仅供参考