模拟
带随机种子可复现性的自助法、蒙特卡洛与压力情景。
面向任务的示例参见使用指南。以下签名由与本站点其余内容同一提交的公共头文件生成。
-
class simulation_result
持有路径、终值统计与风险度量的模拟结果对象。
实例由 analyze_simulation_paths 创建;接受现成状态的构造函数为私有。拷贝与移动操作会复制或转移所持有的路径帧、统计量与终值分布。
公共函数
-
simulation_result(const simulation_result&) = default
复制路径帧、统计量与终值分布。
- 参数:
other -- Result to copy.
-
simulation_result(simulation_result&&) = default
移动路径帧、统计量与终值分布。
- 参数:
other -- Result to move from.
-
simulation_result &operator=(const simulation_result&) = default
通过复制路径帧、统计量与终值分布进行赋值。
- 参数:
other -- Result to copy.
- 返回:
This result after assignment.
-
simulation_result &operator=(simulation_result&&) = default
通过移动路径帧、统计量与终值分布进行赋值。
- 参数:
other -- Result to move from.
- 返回:
This result after assignment.
-
~simulation_result() = default
销毁所持有的路径帧、统计量与终值分布。
-
const dataframe &paths() const noexcept
返回所持有的路径帧。
- 返回:
Const reference valid for the lifetime of this result.
-
const simulation_terminal_statistics &statistics() const noexcept
返回缓存的终值统计。
- 返回:
Const reference to the statistics computed at construction.
-
std::size_t path_count() const noexcept
返回模拟路径数量。
- 返回:
Number of path columns and terminal values.
-
std::size_t observation_count() const noexcept
返回每条路径的观测数量。
- 返回:
Number of rows in the path frame index.
-
double terminal_value_at_risk(double alpha = 0.05) const
计算置信水平 alpha 下的终值 VaR。
结果为终值序列线性插值后的 alpha 分位数。
- 参数:
alpha -- Tail probability in
(0, 1); defaults to 0.05.- 返回:
The percentile, or NaN when
alphais not finite or outside(0, 1).
-
double terminal_conditional_value_at_risk(double alpha = 0.05) const
计算置信水平 alpha 下的终值条件 VaR。
结果为不高于对应 VaR 的终值的算术平均。
- 参数:
alpha -- Tail probability in
(0, 1); defaults to 0.05.- 抛出:
input_error -- If no terminal value lies in the tail or the mean is not finite.
- 返回:
The tail mean, or NaN when
alphais not finite or outside(0, 1).
-
simulation_result(const simulation_result&) = default
-
struct bootstrap_confidence_interval_result
分位数自助法区间的上下界。
-
struct bootstrap_summary_result
均值、标准差与比率统计量的自助法摘要。
公共成员
-
bootstrap_summary_statistic mean
均值统计量的摘要。
-
bootstrap_summary_statistic sample_standard_deviation
样本标准差统计量的摘要。
-
bootstrap_summary_statistic sharpe_ratio
类夏普比率的摘要。
-
bootstrap_summary_statistic sortino_ratio
类索提诺比率的摘要。
-
bootstrap_summary_statistic mean
-
struct bootstrap_summary_statistic
单个自助法统计量的摘要。
公共成员
-
double value
在剔除 NaN 的输入样本上观测到的统计量。
-
double standard_error
自助法抽样的样本标准差。
-
bootstrap_confidence_interval_result confidence_interval
自助法抽样的分位数区间。
-
double value
-
struct custom_stress_scenario
用户自定义的压力变换。
每个受压收益率按 (return + return_shift) * return_multiplier 计算。名称必须非空、互不相同,且不得复用预定义名称。
-
struct simulation_parameters
由周期性收益率估计的年化漂移与波动率。
-
struct simulation_terminal_percentiles
采用线性插值的终值分位数。
-
struct simulation_terminal_statistics
终值路径的汇总统计。
公共成员
-
double mean
终值的算术平均。
-
double sample_standard_deviation
样本标准差(n - 1);仅一条路径时为 NaN。
-
double median
终值中位数。
-
simulation_terminal_percentiles percentiles
终值分位数。
-
double mean
-
struct stress_scenario_result
单个压力情景的结果。
-
enum class fincore::bootstrap_statistic
对每次自助法重抽样计算的统计量。
取值:
-
enumerator mean
抽样样本的算术平均。
-
enumerator sample_standard_deviation
样本标准差(n - 1);仅一个值时为 NaN。
-
enumerator median
中位数,取中间两个值的平均。
-
enumerator sharpe_ratio
均值 / 样本标准差,并按 sqrt(252) 缩放。
-
enumerator sortino_ratio
均值 / 下行偏差,并按 sqrt(252) 缩放。
-
enumerator minimum
最小的抽样值。
-
enumerator maximum
最大的抽样值。
-
enumerator mean
-
enum class fincore::predefined_stress_scenario
预定义的压力变换。
取值:
-
enumerator crash
将中间的收益率设为 -0.20(崩盘)。
-
enumerator spike
将中间的收益率设为 0.10(飙升)。
-
enumerator volatility_crush
将每个收益率减半(vol_crush)。
-
enumerator volatility_spike
将每个收益率加倍(vol_spike)。
-
enumerator crash
-
simulation_result fincore::analyze_simulation_paths(const dataframe &paths)
将路径帧分析为模拟结果。
该帧必须具有非空索引且只包含 double 列,每列长度必须与索引一致。每列的最后一个值即其终值,且必须为有限值。结果持有路径的副本以及终值统计与分布。
- 参数:
paths -- Path frame whose columns are simulation paths.
- 抛出:
input_error -- If the frame is structurally invalid, a terminal value is not finite, or allocation fails.
- 返回:
A result owning the copied paths, terminal statistics and terminal distribution.
-
double fincore::annualize(double value, std::string_view period = "daily")
使用源实现的周期因子对类波动率值做年化。
可识别的周期不区分大小写,包括 daily (252)、weekly (52)、monthly (12) 与 yearly (1);其他取值使用日度因子。结果为 value * sqrt(factor)。
- 参数:
value -- Volatility-like value to scale.
period -- Period label; defaults to
daily.
- 返回:
The scaled value.
-
dataframe fincore::antithetic_variates(const dataframe &paths)
向路径帧追加对偶镜像路径。
保留所有 double 列,并新增名为 antithetic_
的伴随列,其值为 2 * c - x,其中 c 为第一个 double 列的首个值。输入的索引与列顺序保持不变,镜像列紧随源列之后。 - 参数:
paths -- Path frame with only double columns.
- 抛出:
input_error -- If the frame has no rows or no double columns, contains a non-double column, has mismatched column lengths, a derived name collides with an input name, or a derived name is unrepresentable.
- 返回:
A frame containing the original columns followed by their mirrors.
-
bootstrap_confidence_interval_result fincore::bootstrap_confidence_interval(const dataframe &returns, std::size_t resample_count = 10000U, double alpha = 0.05, bootstrap_statistic statistic = bootstrap_statistic::mean, std::optional<std::uint64_t> seed = std::nullopt, std::string_view column = returns_column)
计算分位数自助法置信区间。
区间取生成的统计量分布中 alpha / 2 与 1 - alpha / 2 的线性插值分位数。对 alpha 的校验在任何重抽样之前完成。
- 参数:
returns -- Frame containing the selected return column.
resample_count -- Number of bootstrap draws.
alpha -- Significance level in
(0, 1); defaults to 0.05.statistic -- Statistic computed for every draw.
seed -- Optional deterministic seed.
column -- Double return column to resample.
- 抛出:
input_error -- If
alphais not finite or outside(0, 1), the distribution rejects the input, or generated statistics are not finite.- 返回:
The lower and upper percentile bounds.
-
dataframe fincore::bootstrap_distribution(const dataframe &returns, std::size_t resample_count = 10000U, bootstrap_statistic statistic = bootstrap_statistic::mean, std::optional<std::uint64_t> seed = std::nullopt, std::string_view column = returns_column)
生成单个统计量的自助法分布。
重抽样前会剔除 NaN 收益率并拒绝无穷值。resample_count 次抽样中的每一次都以原有规模对保留的总体进行有放回抽样。提供随机种子可使原生 64 位梅森旋转序列可复现;省略时由 std::random_device 播种。不保证原生抽样与其他随机数实现一致。
- 参数:
returns -- Frame containing the selected return column.
resample_count -- Number of bootstrap draws; 0 yields an empty frame after input validation.
statistic -- Statistic computed for every draw.
seed -- Optional deterministic seed.
column -- Double return column to resample.
- 抛出:
input_error -- If the column or statistic is invalid, no non-NaN return remains, a retained value is infinite, or the output size is unrepresentable.
- 返回:
A frame with an ordinal index and one
bootstrapdouble column.
-
dataframe fincore::bootstrap_distribution(const dataframe &returns, std::span<const std::vector<std::size_t>> draw_indices, bootstrap_statistic statistic = bootstrap_statistic::mean, std::string_view column = returns_column)
由显式抽样索引生成自助法分布。
抽样索引指向剔除 NaN 后按位置排列的输入总体。每次抽样必须恰好包含该总体的规模,且只能使用范围内索引。不使用随机引擎。在输入与统计量校验通过后,空的 draw_indices 产生空分布。
- 参数:
returns -- Frame containing the selected return column.
draw_indices -- Resampling index sets, one per output row.
statistic -- Statistic computed for every draw.
column -- Double return column to resample.
- 抛出:
input_error -- If the column or statistic is invalid, no non-NaN return remains, a retained value is infinite, a draw length or index is invalid, or the output size is unrepresentable.
- 返回:
A frame with an ordinal index and one
bootstrapdouble column.
-
bootstrap_summary_result fincore::bootstrap_summary(const dataframe &returns, std::size_t resample_count = 10000U, double alpha = 0.05, std::optional<std::uint64_t> seed = std::nullopt, std::string_view column = returns_column)
计算四个统计量的自助法摘要。
每个统计量都在一次独立的原生运行中按给定种子汇总,报告其观测值、抽样的样本标准差,以及 alpha / 2 与 1 - alpha / 2 处的分位数区间。对 alpha 与重抽样次数的校验发生在访问输入之前。
- 参数:
returns -- Frame containing the selected return column.
resample_count -- Number of draws per statistic; must be at least 2.
alpha -- Significance level in
(0, 1); defaults to 0.05.seed -- Optional deterministic seed.
column -- Double return column to resample.
- 抛出:
input_error -- If
alphais invalid,resample_countis less than 2, the input is malformed, or an observed or generated summary value is not finite.- 返回:
Summaries for the mean, sample deviation, Sharpe and Sortino statistics.
-
simulation_parameters fincore::estimate_simulation_parameters(const dataframe &returns, std::size_t periods_per_year = 252, std::string_view column = returns_column)
由收益率列估计年化漂移与波动率。
剔除 NaN 并拒绝无穷值;至少需要保留两个收益率。漂移为保留样本的均值乘以 periods_per_year;波动率为样本标准差(n - 1)乘以 sqrt(periods_per_year)。不利用时间戳顺序。
- 参数:
returns -- Frame containing the selected double return column.
periods_per_year -- Positive number of periods per year.
column -- Double return column name.
- 抛出:
input_error -- If the column is missing or not double,
periods_per_yearis zero, fewer than two finite returns remain, a value is infinite, or arithmetic overflows.- 返回:
Annualized drift and sample volatility.
-
dataframe fincore::gbm_from_returns(const dataframe &returns, std::size_t horizon = 252U, std::size_t path_count = 1000U, std::size_t periods_per_year = 252U, std::optional<std::uint64_t> seed = std::nullopt, std::string_view column = returns_column)
基于历史收益率标定的参数模拟累积收益率路径。
由所选收益率列(剔除 NaN)估计年化漂移与波动率,从 1.0 起按 periods_per_year 模拟 horizon 个周期的价格,删除初始价格行,每条路径存储 price_t - 1。列名为 path_
。 - 参数:
returns -- Frame containing the selected return column.
horizon -- Number of periods to simulate.
path_count -- Number of paths; must be positive.
periods_per_year -- Positive periods per year used for calibration and step sizing.
seed -- Optional deterministic seed; omitted seeds are not reproducible.
column -- Double return column used for calibration.
- 抛出:
input_error -- If calibration or path generation rejects the input, or the requested names or output shape is unrepresentable.
- 返回:
A frame whose index excludes the initial row and whose path columns hold cumulative returns.
-
dataframe fincore::generate_correlation_breakdown(std::span<const std::string_view> asset_names, double target_correlation = 1.0)
构建方阵式相关性瓦解矩阵。
矩阵按给定顺序为每个资产生成一行一列 double 列,索引为序号。对角元素为 1.0,所有非对角元素为 target_correlation,即使其落在 [-1, 1] 之外也照原样保留。asset_names 为空时产生空帧。
- 参数:
asset_names -- Ordered asset names; entries must be non-empty, distinct and free of embedded NULs.
target_correlation -- Finite off-diagonal correlation value.
- 抛出:
input_error -- If a name is empty, duplicated or contains an embedded NUL, the target is not finite, or the matrix is unrepresentable.
- 返回:
A square frame with one double column per asset.
-
dataframe fincore::geometric_brownian_motion(double initial_value, double annualized_drift, double annualized_volatility, double total_years, double time_step, std::size_t path_count, std::optional<std::uint64_t> seed = std::nullopt)
模拟几何布朗运动价格路径。
每条路径从 initial_value 开始,演化 trunc(total_years / time_step) 步,递推式为 S[k + 1] = S[k] * exp((drift - volatility^2 / 2) * time_step + volatility * sqrt(time_step) * Z),其中 Z 为标准正态抽样。输出索引为序号,路径命名为 path_
;第一行为初始值。 - 参数:
initial_value -- Starting price of every path.
annualized_drift -- Annualized drift of the process.
annualized_volatility -- Annualized volatility of the process.
total_years -- Total horizon in years.
time_step -- Time between observations in years; must be positive.
path_count -- Number of paths; must be positive.
seed -- Optional deterministic seed; omitted seeds are not reproducible.
- 抛出:
input_error -- If an input is not finite,
time_stepis not positive,total_yearsis negative,path_countis zero, or the requested index, names or output shape is unrepresentable.- 返回:
A frame with one initial row plus one row per truncated step, and one double column per path.
-
dataframe fincore::latin_hypercube_sampling(std::size_t sample_count, std::size_t dimension_count, std::optional<std::uint64_t> seed = std::nullopt)
采样拉丁超立方设计。
每个输出列都是 [0, 1) 内 sample_count 个等概率分层的某种排列,每个分层取一个均匀分布的点。索引为序号,列名为 lhs_dimension_
。计数为 0 时产生相应的空形状。提供随机种子可使原生 64 位梅森旋转序列可复现;省略种子时不可复现,且原生抽样不做跨实现随机数一致性的声明。 - 参数:
sample_count -- Number of rows to generate.
dimension_count -- Number of independent dimensions (columns).
seed -- Optional deterministic seed.
- 抛出:
input_error -- If the requested index, names, stratum count or output shape is unrepresentable, or a sampled point is not finite.
- 返回:
A frame with an ordinal index and one double column per dimension.
-
dataframe fincore::scenario_table(std::span<const stress_scenario_result> results)
构建压力情景结果的表格摘要。
表格索引为序号,每个结果一行,列为 scenario、cumulative_return、max_drawdown、volatility 和 final_value。输入为空时产生带类型的空表。
- 参数:
results -- Scenario results to tabulate.
- 返回:
A frame with one row per result.
-
simulation_result fincore::simulate_monte_carlo(const dataframe &returns, std::size_t path_count = 1000U, std::size_t horizon = 252U, bool antithetic = false, std::optional<std::uint64_t> seed = std::nullopt, std::string_view column = returns_column)
基于历史收益率模拟标定参数的蒙特卡洛路径集。
由所选收益率列(剔除 NaN)估计年化漂移与波动率,从 1.0 起按每年 252 个周期模拟 horizon 步几何布朗运动,并将得到的价格路径转换为累积收益率。当 antithetic 为 true 时对这些路径应用 antithetic_variates,因此存储的路径数会翻倍。
- 参数:
returns -- Frame containing the return column.
path_count -- Number of base paths.
horizon -- Number of simulated periods.
antithetic -- Whether to append antithetic mirror paths.
seed -- Optional deterministic seed; omitted seeds are not reproducible.
column -- Double return column used for calibration.
- 抛出:
input_error -- If calibration or path generation rejects the input.
- 返回:
A simulation result owning the path frame and terminal statistics.
-
simulation_result fincore::simulate_monte_carlo_from_parameters(double annualized_drift, double annualized_volatility, double initial_value = 1.0, std::size_t path_count = 1000U, std::size_t horizon = 252U, std::optional<std::uint64_t> seed = std::nullopt)
直接由年化参数模拟价格路径。
将年化漂移与波动率转换为单步值(drift / 252 与 volatility / sqrt(252)),以 1 / 252 年步长模拟 horizon 个周期。返回的路径从 initial_value 开始并包含初始行。
- 参数:
annualized_drift -- Annualized drift of the price process.
annualized_volatility -- Annualized volatility of the price process.
initial_value -- Starting price of every path.
path_count -- Number of paths.
horizon -- Number of simulated periods.
seed -- Optional deterministic seed; omitted seeds are not reproducible.
- 抛出:
input_error -- If an input is non-finite,
path_countis zero, or the requested index, names or output shape are unrepresentable.- 返回:
A simulation result owning the price paths and terminal statistics.
-
std::vector<stress_scenario_result> fincore::stress_test(const dataframe &returns, std::string_view column = returns_column)
按源实现顺序运行四个预定义压力情景。
依次应用 crash、spike、vol_crush 与 vol_spike。
- 参数:
returns -- Frame containing the return column.
column -- Double return column to stress.
- 抛出:
input_error -- If the column is missing, not double, empty or contains NaN.
- 返回:
One result per predefined scenario, in source order.
-
std::vector<stress_scenario_result> fincore::stress_test(const dataframe &returns, std::span<const predefined_stress_scenario> scenarios, std::span<const custom_stress_scenario> custom_scenarios = {}, std::string_view column = returns_column)
运行选定的预定义与自定义压力情景。
预定义结果先按调用方顺序出现,随后是调用方顺序的自定义结果。拒绝 NaN 收益率,但保留无穷收益率。
- 参数:
returns -- Frame containing the return column.
scenarios -- Predefined scenarios to apply; duplicates are rejected.
custom_scenarios -- Custom scenarios to apply; names must be non-empty, distinct and not one of
crash,spike,vol_crushorvol_spike.column -- Double return column to stress.
- 抛出:
input_error -- If return validation fails, a predefined scenario is unknown or duplicated, or a custom scenario has an empty, reserved or duplicate name or non-finite parameters.
- 返回:
One result per requested scenario, in the order described above.
-
std::vector<double> fincore::validate_returns(std::span<const double> returns)
校验并复制收益率序列。
源实现拒绝空输入与 NaN;原生契约还拒绝无穷值,因此返回的每个值都是有限的。契约校验失败会抛出带有结构化校验类别/代码的 fincore_error。
- 参数:
returns -- Return values to validate.
- 抛出:
fincore_error -- If
returnsis empty, contains NaN, or contains infinity.- 返回:
A validated copy of
returns.
-
std::vector<double> fincore::validate_returns(const dataframe &returns, std::string_view column = returns_column)
校验并复制帧中指定名称的收益率列。
- 参数:
returns -- Frame containing the selected double column.
column -- Name of the double return column; must not be empty.
- 抛出:
fincore_error -- If
columnis empty or missing, the column is not a double column, or the selected values are empty, NaN or infinite.- 返回:
A validated copy of the selected column.
-
constexpr std::string_view fincore::antithetic_path_column_prefix{"antithetic_"}
生成的对偶镜像列的前缀。
-
constexpr std::string_view fincore::bootstrap_statistic_column = {"bootstrap"}
生成的自助法统计量列的名称。
-
constexpr std::string_view fincore::gbm_path_column_prefix = {"path_"}
生成的几何布朗运动路径列的前缀。
-
constexpr std::string_view fincore::latin_hypercube_dimension_column_prefix{"lhs_dimension_"}
拉丁超立方维度列的前缀。
-
constexpr std::string_view fincore::stress_cumulative_return_column{"cumulative_return"}
情景表中累积收益率列的名称。
-
constexpr std::string_view fincore::stress_final_value_column = {"final_value"}
情景表中终值列的名称。
-
constexpr std::string_view fincore::stress_max_drawdown_column = {"max_drawdown"}
情景表中最大回撤列的名称。
-
constexpr std::string_view fincore::stress_scenario_name_column = {"scenario"}
情景表中情景名称列的名称。
-
constexpr std::string_view fincore::stress_volatility_column = {"volatility"}
情景表中波动率列的名称。