fincore.simulation¶
MonteCarlo¶
fincore.simulation.monte_carlo.MonteCarlo(returns)
¶
Monte Carlo simulation engine for financial risk analysis.
Provides methods for: - Path simulation using Geometric Brownian Motion - Risk metric calculation (VaR, CVaR) - Stress testing scenarios
参数:
| 名称 | 类型 | 描述 | 默认 |
|---|---|---|---|
returns
|
Series or ndarray
|
Historical returns for parameter estimation. |
必需 |
simulate(n_paths=1000, horizon=252, *, drift=None, volatility=None, antithetic=False, seed=None)
¶
Simulate future return paths using Geometric Brownian Motion.
参数:
| 名称 | 类型 | 描述 | 默认 |
|---|---|---|---|
n_paths
|
int
|
Number of paths to simulate. |
1000
|
horizon
|
int
|
Number of time steps to simulate. |
252
|
drift
|
float
|
Annualized drift rate. If None, estimated from returns. |
None
|
volatility
|
float
|
Annualized volatility. If None, estimated from returns. |
None
|
antithetic
|
bool
|
Use antithetic variates for variance reduction. |
False
|
seed
|
int
|
Random seed for reproducibility. |
None
|
返回:
| 类型 | 描述 |
|---|---|
SimResult
|
Object containing simulated paths and statistics. |
示例:
var(alpha=0.05, n_paths=10000, horizon=252, seed=None)
¶
Calculate Value at Risk using Monte Carlo simulation.
参数:
| 名称 | 类型 | 描述 | 默认 |
|---|---|---|---|
alpha
|
float
|
Significance level (0.05 = 95% VaR). |
0.05
|
n_paths
|
int
|
Number of simulation paths. |
10000
|
horizon
|
int
|
Simulation horizon. |
252
|
返回:
| 类型 | 描述 |
|---|---|
float
|
VaR at the specified significance level. |
cvar(alpha=0.05, n_paths=10000, horizon=252, seed=None)
¶
Calculate Conditional Value at Risk (Expected Shortfall).
参数:
| 名称 | 类型 | 描述 | 默认 |
|---|---|---|---|
alpha
|
float
|
Significance level (0.05 = 95% CVaR). |
0.05
|
n_paths
|
int
|
Number of simulation paths. |
10000
|
horizon
|
int
|
Simulation horizon. |
252
|
返回:
| 类型 | 描述 |
|---|---|
float
|
CVaR at the specified significance level. |
price_paths(S0, n_paths=1000, horizon=252, mu=None, sigma=None, seed=None)
¶
Simulate price paths starting from given initial price.
参数:
| 名称 | 类型 | 描述 | 默认 |
|---|---|---|---|
S0
|
float
|
Initial asset price. |
必需 |
n_paths
|
int
|
Number of paths to simulate. |
1000
|
horizon
|
int
|
Number of trading days to simulate. |
252
|
mu
|
float
|
Annual drift. Estimated from returns if None. |
None
|
sigma
|
float
|
Annual volatility. Estimated from returns if None. |
None
|
seed
|
int
|
Random seed. |
None
|
返回:
| 类型 | 描述 |
|---|---|
SimResult
|
Simulated price paths. |
stress(scenarios=None)
¶
Perform stress testing on historical returns.
参数:
| 名称 | 类型 | 描述 | 默认 |
|---|---|---|---|
scenarios
|
list of str
|
Scenarios to apply. Options: 'crash', 'spike', 'vol_crush', 'vol_spike'. If None, applies all. |
None
|
返回:
| 类型 | 描述 |
|---|---|
dict
|
Stress test results for each scenario. |
stress_table()
¶
Generate a summary table of stress test results.
返回:
| 类型 | 描述 |
|---|---|
DataFrame
|
Formatted stress test results. |
from_parameters(mu, sigma, S0=1.0, n_paths=1000, horizon=252, seed=None)
staticmethod
¶
Create Monte Carlo simulation from known parameters.
参数:
| 名称 | 类型 | 描述 | 默认 |
|---|---|---|---|
mu
|
float
|
Annual drift rate. |
必需 |
sigma
|
float
|
Annual volatility. |
必需 |
S0
|
float
|
Initial price/return level. |
1.0
|
n_paths
|
int
|
Number of paths. |
1000
|
horizon
|
int
|
Simulation horizon in days. |
252
|
seed
|
int
|
Random seed. |
None
|
返回:
| 类型 | 描述 |
|---|---|
SimResult
|
Simulation result. |
Bootstrap¶
fincore.simulation.bootstrap
¶
Bootstrap methods for statistical inference.
Provides non-parametric statistical inference using resampling techniques.
bootstrap(returns, n_samples=10000, statistic='mean', seed=None)
¶
Bootstrap resampling for statistical inference.
Resamples the returns with replacement and computes a statistic on each resample to build its distribution.
参数:
| 名称 | 类型 | 描述 | 默认 |
|---|---|---|---|
returns
|
Series or ndarray
|
Input returns data. |
必需 |
n_samples
|
int
|
Number of bootstrap resamples. |
10000
|
statistic
|
str or callable
|
Statistic to compute. Can be: - String: 'mean', 'std', 'sharpe', 'median' - Callable: Custom function taking array and returning scalar |
"mean"
|
seed
|
int
|
Random seed for reproducibility. |
None
|
返回:
| 类型 | 描述 |
|---|---|
(ndarray, shape(n_samples))
|
Bootstrap distribution of the statistic. |
示例:
bootstrap_ci(returns, n_samples=10000, alpha=0.05, statistic='mean', method='percentile', seed=None)
¶
Calculate bootstrap confidence interval.
参数:
| 名称 | 类型 | 描述 | 默认 |
|---|---|---|---|
returns
|
Series or ndarray
|
Input returns data. |
必需 |
n_samples
|
int
|
Number of bootstrap resamples. |
10000
|
alpha
|
float
|
Significance level (0.05 = 95% confidence interval). |
0.05
|
statistic
|
str or callable
|
Statistic to compute. |
"mean"
|
method
|
str
|
Method for CI calculation: - 'percentile': Simple percentile method - 'bc': Bias-corrected (not implemented) - 'bca': BCa method (not implemented) |
"percentile"
|
seed
|
int
|
Random seed for reproducibility. |
None
|
返回:
| 类型 | 描述 |
|---|---|
tuple(lower, upper)
|
Lower and upper bounds of the confidence interval. |
示例:
bootstrap_summary(returns, n_samples=10000, alpha=0.05, seed=None)
¶
Compute comprehensive bootstrap statistics summary.
参数:
| 名称 | 类型 | 描述 | 默认 |
|---|---|---|---|
returns
|
Series or ndarray
|
Input returns data. |
必需 |
n_samples
|
int
|
Number of bootstrap resamples. |
10000
|
alpha
|
float
|
Significance level for confidence intervals. |
0.05
|
seed
|
int
|
Random seed for reproducibility. |
None
|
返回:
| 类型 | 描述 |
|---|---|
dict
|
Dictionary containing bootstrap statistics for multiple metrics. |
Paths¶
fincore.simulation.paths
¶
Path generation methods for Monte Carlo simulation.
Implements various stochastic processes for generating price/return paths: - Geometric Brownian Motion (GBM) - Jump Diffusion - Heston Stochastic Volatility (future)
geometric_brownian_motion(S0, mu, sigma, T, dt, n_paths, rng=None, seed=None)
¶
Generate price paths using Geometric Brownian Motion.
The GBM model is: dS = mu * S * dt + sigma * S * dW
Discrete form: S(t+dt) = S(t) * exp((mu - 0.5sigma^2)dt + sigmasqrt(dt)Z)
where Z ~ N(0,1).
参数:
| 名称 | 类型 | 描述 | 默认 |
|---|---|---|---|
S0
|
float
|
Initial asset price. |
必需 |
mu
|
float
|
Annualized drift rate. |
必需 |
sigma
|
float
|
Annualized volatility. |
必需 |
T
|
float
|
Total time in years. |
必需 |
dt
|
float
|
Time step size in years. |
必需 |
n_paths
|
int
|
Number of paths to simulate. |
必需 |
rng
|
Generator
|
Random number generator. |
None
|
seed
|
int
|
Random seed for reproducibility. |
None
|
返回:
| 类型 | 描述 |
|---|---|
(ndarray, shape(n_paths, n_steps))
|
Simulated price paths. |
gbm_from_returns(returns, horizon=252, n_paths=1000, frequency=252, rng=None, seed=None)
¶
Generate GBM paths estimated from historical returns.
参数:
| 名称 | 类型 | 描述 | 默认 |
|---|---|---|---|
returns
|
Series or ndarray
|
Historical returns to estimate parameters from. |
必需 |
horizon
|
int
|
Number of time steps to simulate. |
252
|
n_paths
|
int
|
Number of paths to generate. |
1000
|
frequency
|
int
|
Number of periods per year (for parameter estimation). |
252
|
rng
|
Generator
|
Random number generator. |
None
|
seed
|
int
|
Random seed for reproducibility. |
None
|
返回:
| 类型 | 描述 |
|---|---|
(ndarray, shape(n_paths, horizon))
|
Simulated cumulative return paths. |
antithetic_variates(paths)
¶
Generate antithetic variates for variance reduction.
Creates mirror paths using -Z instead of Z, which reduces Monte Carlo variance by approximately half.
参数:
| 名称 | 类型 | 描述 | 默认 |
|---|---|---|---|
paths
|
ndarray
|
Original paths generated with random variates Z. |
必需 |
返回:
| 类型 | 描述 |
|---|---|
ndarray
|
Original paths concatenated with antithetic paths. |
latin_hypercube_sampling(n_samples, n_dimensions, rng=None, seed=None)
¶
Generate Latin Hypercube samples for quasi-Monte Carlo.
LHS provides better coverage of the sample space than pure random sampling, often reducing required samples.
参数:
| 名称 | 类型 | 描述 | 默认 |
|---|---|---|---|
n_samples
|
int
|
Number of samples to generate. |
必需 |
n_dimensions
|
int
|
Number of dimensions (time steps). |
必需 |
rng
|
Generator
|
Random number generator. |
None
|
seed
|
int
|
Random seed for reproducibility. |
None
|
返回:
| 类型 | 描述 |
|---|---|
(ndarray, shape(n_samples, n_dimensions))
|
LHS samples in [0, 1]. |
Scenarios¶
fincore.simulation.scenarios
¶
Stress testing scenarios for portfolio analysis.
Generates extreme market scenarios for stress testing portfolios.
stress_test(returns, scenarios=None, custom_scenarios=None)
¶
Perform stress testing on returns under various scenarios.
参数:
| 名称 | 类型 | 描述 | 默认 |
|---|---|---|---|
returns
|
Series or ndarray
|
Historical returns to stress test. |
必需 |
scenarios
|
list of str
|
Predefined scenarios to apply. Options: - 'crash': Sudden market crash (-20% or more) - 'spike': Sudden market jump (+10% or more) - 'vol_crush': Volatility crush (vol drops 50%) - 'vol_spike': Volatility spike (vol doubles) - 'correlation_breakdown': Correlation goes to 1 If None, applies all predefined scenarios. |
None
|
custom_scenarios
|
dict
|
Custom scenarios as {name: {params}}. Each params dict can contain: - 'return_shift': Additive return adjustment - 'return_mult': Multiplicative return adjustment - 'vol_mult': Volatility multiplier |
None
|
返回:
| 类型 | 描述 |
|---|---|
dict
|
Dictionary with scenario names as keys and results as values. Each result contains: - 'stressed_returns': The stressed return series - 'cumulative': Cumulative stressed return - 'max_drawdown': Maximum drawdown under stress - 'volatility': Volatility under stress |
generate_correlation_breakdown(n_assets, target_correlation=1.0)
¶
Generate correlation matrix for correlation breakdown stress test.
In correlation breakdown, all assets become perfectly correlated, which eliminates diversification benefits.
参数:
| 名称 | 类型 | 描述 | 默认 |
|---|---|---|---|
n_assets
|
int
|
Number of assets. |
必需 |
target_correlation
|
float
|
Target correlation between all assets. |
1.0
|
返回:
| 类型 | 描述 |
|---|---|
(ndarray, shape(n_assets, n_assets))
|
Correlation matrix with uniform correlation. |
scenario_table(stress_results)
¶
Format stress test results as a table.
参数:
| 名称 | 类型 | 描述 | 默认 |
|---|---|---|---|
stress_results
|
dict
|
Output from stress_test() function. |
必需 |
返回:
| 类型 | 描述 |
|---|---|
DataFrame
|
Summary table of stress test results. |