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__、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_id | str | 风险模型 ID,决定分析使用哪套因子体系 |
fx_hedged | bool | 仓位源是否做了 FX 对冲,默认True |
benchmark_id | str | 可选,参与结果对比的基准资产 Marquee ID |
report_id | str | 已存在的 Marquee 报告 ID(更新/获取已有报告时使用) |
name | str | 报告名称 |
position_source_id | str | 仓位源 ID(组合或资产) |
position_source_type | str/PositionSourceType | 仓位源类型:Portfolio、Asset、Backtest、Hedge等 |
report_type | str/ReportType | 报告类型,如Portfolio Factor Risk或Asset Factor Risk |
earliest_start_date/latest_end_date | dt.date | 报告数据覆盖的起止日期 |
status | str/ReportStatus | 报告状态,默认ReportStatus.new |
percentage_complete | float | 报告完成度 |
tags | tuple[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_type与report_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_model、benchmark、fx_hedged、tags正是因子风险报告相关的核心配置项。
报告生命周期:保存、调度、运行与删除
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枚举:new、ready、executing、calculating、done、error、cancelled、waiting、queued(gs_quant/target/reports.py);done():任务处于done/error/cancelled任一状态即视为结束;result():任务完成后返回因子风险结果 DataFrame;若任务处于cancelled或error状态则直接抛出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)返回报告最原始的因子风险数据,是其余所有分析方法的底层数据源。其关键参数:
| 参数 | 默认值 | 说明 |
|---|---|---|
mode | FactorRiskResultsMode.Portfolio | 结果粒度:Portfolio(组合层)或Positions(持仓层) |
factors | None | 因子名列表,默认返回全部因子 |
factor_categories | None | 因子类别列表,默认全部 |
start_date/end_date | None | 日期区间过滤 |
currency | None | 结果币种(Currency枚举) |
return_format | ReturnFormat.DATA_FRAME | DATA_FRAME(Pandas DataFrame)或JSON |
unit | FactorRiskUnit.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)返回按界面“资产级表格”格式化后的明细,必须显式传入mode(FactorRiskTableMode,如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_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。实现上先取Total的dailyRisk,再用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_names与factor_categories均默认为“全部”,按需传入可显著减小结果集。而get_results支持的mode枚举(Portfolio/Positions)定义于 gs_quant/markets/report.py,FactorRiskUnit(Percent/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_Risk与Asset_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)。
报告对象还从基类暴露了只读属性: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_results(get_results底层)、get_factor_risk_report_view(get_view底层)、get_factor_risk_report_table(get_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_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),仅供参考