import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
from scipy.optimize import minimize
from enum import Enum
# =============================================================================
# 1. DEFINITIONS AND ENUMS
# =============================================================================
class ProcessType(Enum):
GBM = "Geometric Brownian Motion" # Usually for Equities/Indices
VASICEK = "Vasicek" # Usually for Interest Rates (can go negative)
CIR = "Cox-Ingersoll-Ross" # Non-negative mean reverting (e.g., Volatility)
class Regime(Enum):
EXPANSION = 0
RECESSION = 1
# =============================================================================
# 2. STOCHASTIC PROCESS ENGINES
# =============================================================================
class StochasticEngine:
"""
Base class for stochastic processes using Euler-Maruyama discretization.
"""
@staticmethod
def simulate(process_type, s0, params, dt, n_steps, n_paths=1, random_seed=None):
if random_seed:
np.random.seed(random_seed)
# Generate random shocks for all steps and paths at once
dW = np.random.normal(0, np.sqrt(dt), (n_steps, n_paths))
if process_type == ProcessType.GBM:
return StochasticEngine._gbm(s0, params, dt, dW)
elif process_type == ProcessType.VASICEK:
return StochasticEngine._vasicek(s0, params, dt, dW)
elif process_type == ProcessType.CIR:
return StochasticEngine._cir(s0, params, dt, dW)
else:
raise ValueError("Unsupported Process Type")
@staticmethod
def _gbm(s0, params, dt, dW):
# S_t = S_{t-1} * exp((mu - 0.5*sigma^2)*dt + sigma*dW)
# Params: mu (drift), sigma (vol)
mu, sigma = params['mu'], params['sigma']
n_steps, n_paths = dW.shape
paths = np.zeros((n_steps + 1, n_paths))
paths[0] = s0
# Vectorized calculation
drift = (mu - 0.5 * sigma**2) * dt
diffusion = sigma * dW
log_returns = drift + diffusion
paths[1:] = s0 * np.exp(np.cumsum(log_returns, axis=0))
return paths
@staticmethod
def _vasicek(s0, params, dt, dW):
# dr_t = k(theta - r_t)dt + sigma*dW
# Params: k (speed), theta (long term mean), sigma (vol)
k, theta, sigma = params['k'], params['theta'], params['sigma']
n_steps, n_paths = dW.shape
paths = np.zeros((n_steps + 1, n_paths))
paths[0] = s0
for t in range(1, n_steps + 1):
paths[t] = paths[t-1] + k * (theta - paths[t-1]) * dt + sigma * dW[t-1]
return paths
@staticmethod
def _cir(s0, params, dt, dW):
# dr_t = k(theta - r_t)dt + sigma*sqrt(r_t)*dW
# Params: k, theta, sigma
k, theta, sigma = params['k'], params['theta'], params['sigma']
n_steps, n_paths = dW.shape
paths = np.zeros((n_steps + 1, n_paths))
paths[0] = s0
# Ensure Feller condition is roughly checked (2k*theta > sigma^2) for positivity
# Note: Euler discretization can still go negative, usually we floor at 0 or use reflection.
for t in range(1, n_steps + 1):
# Using abs() to prevent sqrt errors in extreme simulation edge cases
vol_factor = sigma * np.sqrt(np.maximum(paths[t-1], 0))
paths[t] = paths[t-1] + k * (theta - paths[t-1]) * dt + vol_factor * dW[t-1]
# Floor at zero (analytical approximation for CIR implies non-negative)
paths = np.maximum(paths, 0)
return paths
# =============================================================================
# 3. REGIME SWITCHING ENGINE
# =============================================================================
class MarkovRegimeSwitcher:
"""
Handles regime switching logic based on a Transition Matrix.
"""
def __init__(self, transition_matrix, regime_names):
"""
transition_matrix: 2x2 numpy array where P[i, j] is prob of moving i -> j.
"""
self.trans_mat = transition_matrix
self.regime_names = regime_names
self.n_regimes = len(regime_names)
def simulate_regimes(self, n_steps, start_regime_idx=0, random_seed=None):
if random_seed:
np.random.seed(random_seed)
regimes = np.zeros(n_steps, dtype=int)
regimes[0] = start_regime_idx
uniform_shocks = np.random.uniform(0, 1, n_steps)
current_regime = start_regime_idx
for t in range(1, n_steps):
# Determine next regime based on cumulative probabilities
thresh = self.trans_mat[current_regime]
cum_sum = np.cumsum(thresh)
rand_val = uniform_shocks[t]
next_regime = np.searchsorted(cum_sum, rand_val)
# Clip in case of numerical precision issues
current_regime = min(next_regime, self.n_regimes - 1)
regimes[t] = current_regime
return regimes
# =============================================================================
# 4. CALIBRATION UTILITIES
# =============================================================================
class MacroeconomicCalibrator:
"""
Calibrates stochastic parameters from historical time series data.
Uses Maximum Likelihood Estimation (MLE) or Method of Moments.
"""
@staticmethod
def calibrate_gbm(series):
"""
Calibrates mu and sigma for GBM from log returns.
"""
log_returns = np.log(series / series.shift(1)).dropna()
mu = log_returns.mean()
sigma = log_returns.std()
# Annualize if data is daily (assuming 252 trading days)
# In a real toolkit, we would detect frequency. Assuming Daily here.
mu_ann = mu * 252
sigma_ann = sigma * np.sqrt(252)
return {'mu': mu_ann, 'sigma': sigma_ann, 'process': ProcessType.GBM}
@staticmethod
def calibrate_vasicek(series):
"""
Calibrates k, theta, sigma for Vasicek using MLE on discrete approximation.
"""
# Clean data
rates = series.dropna().values
if len(rates) < 10:
raise ValueError("Not enough data points.")
# Negative Log Likelihood Function
def nll(params):
k, theta, sigma = params
if k <= 0 or sigma <= 0: return 1e5 # Bounds
# Discrete Vasicek: r_t+1 = a + b*r_t + eps
# Mapping: b = 1 - k*dt (assume dt=1/252 for daily data)
# This is a simplified calibration for the toolkit.
# For strict accuracy, we would regress r_t+1 vs r_t.
dt = 1/252
r_prev = rates[:-1]
r_next = rates[1:]
# Predicted mean
pred = r_prev + k * (theta - r_prev) * dt
# Residuals
resid = r_next - pred
# Likelihood of Normal(0, sigma*sqrt(dt))
ll = -np.sum(np.log(norm.pdf(resid, scale=sigma*np.sqrt(dt))))
return ll
# Initial Guess
res = minimize(nll, [0.5, np.mean(rates), np.std(rates)], method='L-BFGS-B',
bounds=[(1e-4, 5.0), (None, None), (1e-4, None)])
k, theta, sigma = res.x
# Annualize sigma
sigma_ann = sigma * np.sqrt(252)
# k is a rate (speed), usually left as is or adjusted based on time unit
return {'k': k, 'theta': theta, 'sigma': sigma_ann, 'process': ProcessType.VASICEK}
# =============================================================================
# 5. MAIN TOOLKIT CLASS
# =============================================================================
class ScenarioGenerator:
def __init__(self, time_horizon_years=5, freq='M'):
"""
freq: 'M' for Monthly, 'D' for Daily
"""
self.time_horizon = time_horizon_years
self.freq = freq
if freq == 'M':
self.dt = 1/12
self.n_steps = int(time_horizon_years * 12)
elif freq == 'D':
self.dt = 1/252
self.n_steps = int(time_horizon_years * 252)
else:
raise ValueError("Frequency must be 'M' or 'D'")
def generate(self, variables_config, regime_config=None, n_scenarios=1000, base_currency=None):
"""
variables_config: Dict of variables.
Format:
{
"GDP_Growth": {
"process": ProcessType.VASICEK,
"params": {"k": 0.5, "theta": 0.02, "sigma": 0.01},
"initial_value": 0.025
},
"Inflation": {...}
}
"""
results = {}
variable_names = list(variables_config.keys())
# 1. Handle Regimes
if regime_config:
mr_switcher = MarkovRegimeSwitcher(regime_config['matrix'], regime_config['names'])
# Pre-generate regime paths
regime_paths = np.zeros((self.n_steps + 1, n_scenarios), dtype=int)
for i in range(n_scenarios):
# Randomize starting regime or set specified
start = regime_config.get('start_regime', 0)
regime_paths[:, i] = mr_switcher.simulate_regimes(self.n_steps + 1, start_regime_idx=start)
else:
regime_paths = None
# 2. Simulate Variables
for name, config in variables_config.items():
p_type = config['process']
params = config['params']
s0 = config['initial_value']
# Check if this variable has regime-dependent parameters
is_regime_dependent = 'regime_params' in config
if is_regime_dependent and regime_paths is not None:
# More complex simulation: iterate step by step to check regime
paths = self._simulate_regime_variable(p_type, s0, params, config['regime_params'], regime_paths)
else:
# Simple simulation
paths = StochasticEngine.simulate(p_type, s0, params, self.dt, self.n_steps, n_scenarios)
# Store results
index = np.arange(0, self.time_horizon + self.dt, self.dt)
results[name] = pd.DataFrame(paths, index=index)
return results, pd.DataFrame(regime_paths) if regime_paths is not None else None
def _simulate_regime_variable(self, p_type, s0, base_params, regime_params, regime_paths):
n_steps, n_paths = regime_paths.shape[0] - 1, regime_paths.shape[1]
paths = np.zeros((n_steps + 1, n_paths))
paths[0] = s0
# Pre-generate noise
dW = np.random.normal(0, np.sqrt(self.dt), (n_steps, n_paths))
for t in range(1, n_steps + 1):
prev_val = paths[t-1]
noise = dW[t-1]
# Vectorized update based on regime
# We need to select parameters based on regime_paths[t]
# Regime 0 params vs Regime 1 params
# For simplicity, assuming Regime 0 is Base and Regime 1 modifies 'theta' or 'mu'
# A robust implementation would map specific params to specific regimes.
# Here we assume regime_params = {1: {'theta': -0.02, 'sigma': 0.05}}
# Start with base params
current_params = {k: np.full(n_paths, v) for k, v in base_params.items()}
# Override where regime is active
active_regimes = regime_paths[t]
for r_idx, r_p in regime_params.items():
mask = (active_regimes == r_idx)
for key, val in r_p.items():
current_params[key][mask] = val
# Calculate step (Generic Euler for Vasicek/GBM)
# Handling Vasicek style logic here for GDP example
if p_type == ProcessType.VASICEK:
k = current_params['k']
theta = current_params['theta']
sigma = current_params['sigma']
paths[t] = prev_val + k * (theta - prev_val) * self.dt + sigma * noise
return paths
# =============================================================================
# 6. DOCUMENTATION & USAGE EXAMPLE
# =============================================================================
def run_documentation_demo():
print("--- Macroeconomic Scenario Generator Toolkit ---")
# 1. Define Configuration
print("1. Configuring Parameters...")
# Time: 10 Years, Monthly Steps
gen = ScenarioGenerator(time_horizon_years=10, freq='M')
# Variables
variables = {
"US_GDP_Growth": {
"process": ProcessType.VASICEK,
"initial_value": 0.025, # 2.5% current growth
"params": {
"k": 0.5, # Mean reversion speed
"theta": 0.02, # Long term avg growth
"sigma": 0.01 # Volatility
},
# Regime 1 (Recession) overrides
"regime_params": {
1: {"theta": -0.02, "sigma": 0.03}
}
},
"US_Interest_Rate": {
"process": ProcessType.VASICEK,
"initial_value": 0.05,
"params": {
"k": 0.3,
"theta": 0.04,
"sigma": 0.01
}
},
"Equity_Index": {
"process": ProcessType.GBM,
"initial_value": 4000, # e.g., S&P 500 level
"params": {
"mu": 0.07, # Drift
"sigma": 0.15 # Vol
}
}
}
# Regime Logic (Markov Chain)
# Transition Matrix:
# Exp Rec
# Exp [0.95, 0.05]
# Rec [0.10, 0.90]
regime_conf = {
'matrix': np.array([[0.95, 0.05], [0.10, 0.90]]),
'names': [Regime.EXPANSION, Regime.RECESSION],
'start_regime': 0 # Start in Expansion
}
# 2. Run Simulation
print("2. Generating 1000 Scenarios...")
scenarios_data, regime_paths = gen.generate(
variables_config=variables,
regime_config=regime_conf,
n_scenarios=1000
)
# 3. Analysis
print("3. Analyzing Outputs...")
gdp_df = scenarios_data['US_GDP_Growth']
equity_df = scenarios_data['Equity_Index']
# Calculate Statistics
mean_gdp = gdp_df.mean(axis=1)
q5_gdp = gdp_df.quantile(0.05, axis=1)
q95_gdp = gdp_df.quantile(0.95, axis=1)
# Find Worst-Case Scenario (Min cumulative return)
final_values = equity_df.iloc[-1]
worst_case_idx = final_values.idxmin() # Actually column index (scenario ID)
# 4. Visualization
print("4. Plotting Results...")
fig, axs = plt.subplots(3, 1, figsize=(10, 12))
# Plot 1: Regime Probability
# Convert regime integers to probability of Recession
recession_prob = (regime_paths == 1).mean(axis=1)
axs[0].plot(regime_paths.index, recession_prob, color='red', label='Recession Probability')
axs[0].set_title('Probability of Recession Over Time')
axs[0].set_ylabel('Probability')
axs[0].legend()
# Plot 2: GDP Growth Fan Chart
axs[1].plot(mean_gdp, label='Mean', color='black')
axs[1].fill_between(mean_gdp.index, q5_gdp, q95_gdp, color='blue', alpha=0.2, label='90% CI')
axs[1].set_title('US GDP Growth Simulation (Regime Switching)')
axs[1].axhline(0, color='red', linestyle='--')
axs[1].legend()
# Plot 3: Equity Index Sample Paths
# Plot mean and 5 random paths
axs[2].plot(equity_df.mean(axis=1), color='black', linewidth=2, label='Mean Path')
# Plot random paths
rand_cols = np.random.choice(equity_df.columns, 10, replace=False)
axs[2].plot(equity_df[rand_cols], linewidth=0.5, alpha=0.5)
axs[2].set_title('Equity Index Paths (GBM)')
axs[2].legend()
plt.tight_layout()
plt.show()
print("Done.")
if __name__ == "__main__":
run_documentation_demo()