Upload bayesian_layer.py
Browse files- bayesian_layer.py +134 -0
bayesian_layer.py
ADDED
|
@@ -0,0 +1,134 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Bayesian Probabilistic Forecasting Layer."""
|
| 2 |
+
import numpy as np
|
| 3 |
+
import pandas as pd
|
| 4 |
+
from scipy import stats
|
| 5 |
+
from typing import Dict, Tuple, Optional
|
| 6 |
+
import warnings
|
| 7 |
+
warnings.filterwarnings('ignore')
|
| 8 |
+
|
| 9 |
+
|
| 10 |
+
class BayesianForecaster:
|
| 11 |
+
"""Probabilistic forecasting with Bayesian methods."""
|
| 12 |
+
|
| 13 |
+
def __init__(self, prior_mean: float = 0.0, prior_std: float = 0.2):
|
| 14 |
+
self.prior_mean = prior_mean
|
| 15 |
+
self.prior_std = prior_std
|
| 16 |
+
self.posterior_mean = prior_mean
|
| 17 |
+
self.posterior_std = prior_std
|
| 18 |
+
self.update_count = 0
|
| 19 |
+
|
| 20 |
+
def update(self, new_returns: np.ndarray):
|
| 21 |
+
"""Bayesian update with new observations."""
|
| 22 |
+
n = len(new_returns)
|
| 23 |
+
sample_mean = np.mean(new_returns)
|
| 24 |
+
sample_var = np.var(new_returns) if n > 1 else self.posterior_std ** 2
|
| 25 |
+
|
| 26 |
+
# Conjugate update (Normal-Normal for mean)
|
| 27 |
+
prior_precision = 1.0 / (self.posterior_std ** 2)
|
| 28 |
+
likelihood_precision = n / sample_var
|
| 29 |
+
|
| 30 |
+
posterior_precision = prior_precision + likelihood_precision
|
| 31 |
+
self.posterior_std = 1.0 / np.sqrt(posterior_precision)
|
| 32 |
+
self.posterior_mean = (
|
| 33 |
+
(prior_precision * self.posterior_mean + likelihood_precision * sample_mean) /
|
| 34 |
+
posterior_precision
|
| 35 |
+
)
|
| 36 |
+
|
| 37 |
+
self.update_count += 1
|
| 38 |
+
|
| 39 |
+
def forecast(self, horizon: int = 1) -> Dict:
|
| 40 |
+
"""Generate probabilistic forecast."""
|
| 41 |
+
forecast_mean = self.posterior_mean * horizon
|
| 42 |
+
forecast_std = self.posterior_std * np.sqrt(horizon)
|
| 43 |
+
|
| 44 |
+
alpha = 0.05
|
| 45 |
+
z = stats.norm.ppf(1 - alpha / 2)
|
| 46 |
+
|
| 47 |
+
return {
|
| 48 |
+
'mean': forecast_mean,
|
| 49 |
+
'std': forecast_std,
|
| 50 |
+
'ci_lower': forecast_mean - z * forecast_std,
|
| 51 |
+
'ci_upper': forecast_mean + z * forecast_std,
|
| 52 |
+
'prob_positive': 1 - stats.norm.cdf(0, forecast_mean, forecast_std),
|
| 53 |
+
'prob_negative': stats.norm.cdf(0, forecast_mean, forecast_std),
|
| 54 |
+
'posterior_confidence': 1.0 / self.posterior_std
|
| 55 |
+
}
|
| 56 |
+
|
| 57 |
+
def ensemble_forecast(self,
|
| 58 |
+
predictions: Dict[str, float],
|
| 59 |
+
uncertainties: Dict[str, float]) -> Dict:
|
| 60 |
+
"""Combine multiple predictions with Bayesian weighting."""
|
| 61 |
+
weights = {}
|
| 62 |
+
total_precision = 0
|
| 63 |
+
|
| 64 |
+
for model, pred in predictions.items():
|
| 65 |
+
uncertainty = uncertainties.get(model, 0.1)
|
| 66 |
+
precision = 1.0 / (uncertainty ** 2)
|
| 67 |
+
weights[model] = precision
|
| 68 |
+
total_precision += precision
|
| 69 |
+
|
| 70 |
+
weights = {k: v / total_precision for k, v in weights.items()}
|
| 71 |
+
|
| 72 |
+
ensemble_mean = sum(w * predictions[m] for m, w in weights.items())
|
| 73 |
+
ensemble_std = 1.0 / np.sqrt(total_precision)
|
| 74 |
+
|
| 75 |
+
return {
|
| 76 |
+
'ensemble_mean': ensemble_mean,
|
| 77 |
+
'ensemble_std': ensemble_std,
|
| 78 |
+
'weights': weights,
|
| 79 |
+
'ci_lower': ensemble_mean - 1.96 * ensemble_std,
|
| 80 |
+
'ci_upper': ensemble_mean + 1.96 * ensemble_std
|
| 81 |
+
}
|
| 82 |
+
|
| 83 |
+
|
| 84 |
+
class BayesianOptimizer:
|
| 85 |
+
"""Bayesian portfolio optimization with uncertainty."""
|
| 86 |
+
|
| 87 |
+
def __init__(self, risk_aversion: float = 2.0):
|
| 88 |
+
self.risk_aversion = risk_aversion
|
| 89 |
+
|
| 90 |
+
def optimize_with_uncertainty(self,
|
| 91 |
+
mu: np.ndarray,
|
| 92 |
+
Sigma: np.ndarray,
|
| 93 |
+
mu_uncertainty: np.ndarray) -> Dict:
|
| 94 |
+
"""
|
| 95 |
+
Robust optimization accounting for parameter uncertainty.
|
| 96 |
+
|
| 97 |
+
Uses Bayesian shrinkage: shrink predictions toward prior (zero alpha)
|
| 98 |
+
proportional to their uncertainty.
|
| 99 |
+
"""
|
| 100 |
+
# Shrinkage factor
|
| 101 |
+
precision = 1.0 / (mu_uncertainty ** 2 + 1e-8)
|
| 102 |
+
prior_precision = 1.0 / (np.mean(mu_uncertainty) ** 2)
|
| 103 |
+
shrinkage = prior_precision / (precision + prior_precision)
|
| 104 |
+
|
| 105 |
+
# Shrunk estimates
|
| 106 |
+
mu_shrunk = (1 - shrinkage) * mu + shrinkage * 0.0 # Prior is zero alpha
|
| 107 |
+
|
| 108 |
+
# Add uncertainty to diagonal of covariance
|
| 109 |
+
Sigma_robust = Sigma + np.diag(mu_uncertainty ** 2)
|
| 110 |
+
|
| 111 |
+
# Mean-variance optimization
|
| 112 |
+
n = len(mu)
|
| 113 |
+
|
| 114 |
+
def objective(w):
|
| 115 |
+
return -(np.dot(w, mu_shrunk) - self.risk_aversion * np.dot(w, np.dot(Sigma_robust, w)))
|
| 116 |
+
|
| 117 |
+
constraints = [{'type': 'eq', 'fun': lambda w: np.sum(w) - 1.0}]
|
| 118 |
+
bounds = [(0, 0.25) for _ in range(n)]
|
| 119 |
+
w0 = np.ones(n) / n
|
| 120 |
+
|
| 121 |
+
from scipy.optimize import minimize
|
| 122 |
+
result = minimize(objective, w0, method='SLSQP', bounds=bounds, constraints=constraints)
|
| 123 |
+
|
| 124 |
+
weights = np.maximum(result.x, 0)
|
| 125 |
+
weights /= np.sum(weights)
|
| 126 |
+
|
| 127 |
+
return {
|
| 128 |
+
'weights': weights,
|
| 129 |
+
'mu_raw': mu,
|
| 130 |
+
'mu_shrunk': mu_shrunk,
|
| 131 |
+
'shrinkage_factors': shrinkage,
|
| 132 |
+
'expected_return': np.dot(weights, mu_shrunk),
|
| 133 |
+
'uncertainty': np.sqrt(np.dot(weights, np.dot(Sigma_robust, weights)))
|
| 134 |
+
}
|