Quantitative Methodology

How MAISNER Works

A technical reference for the mathematical models underlying the platform. Written for quantitative professionals, portfolio managers, and technically minded investors.

Portfolio Optimization — Mean-Variance

MAISNER implements Markowitz Mean-Variance Optimization (MVO) with several institutional-grade enhancements. The core problem maximizes the Sharpe ratio subject to linear constraints.

Objective Function

Max Sharpe Portfolio
\[ \max_{\mathbf{w}} \frac{\mathbf{w}^\top \boldsymbol{\mu} - r_f}{\sqrt{\mathbf{w}^\top \boldsymbol{\Sigma} \mathbf{w}}} \]
where w = portfolio weights, μ = expected return vector, Σ = covariance matrix, rf = risk-free rate (3.80%)

Constraints

Standard Constraints
\[ \sum_i w_i = 1, \quad w_i \geq 0, \quad w_i \leq w_{max} \]
Full investment, long-only, individual weight cap (default 35%)

Three portfolios are computed simultaneously: Max Sharpe, Minimum Variance, and Equal Weight. This allows direct comparison of optimization strategies against a naive benchmark.

ParameterValueDescription
RISK_FREE3.80%Risk-free rate (ECB rate proxy)
WEIGHT_MAX35%Maximum weight per asset
FREQ252 / 12Daily if ≥400 obs, else monthly

Constrained Optimization

The Constrained Optimizer allows portfolio managers to impose explicit structural requirements on individual positions and sectors, then optimizes the remaining free budget using the same RMT-MVO engine. This is the institutional standard for managing client mandates, regulatory constraints, and conviction-driven overrides.

Asset Partition

All assets in the portfolio are classified into one of three sets before optimization begins.

Partition of Assets
\[ \mathcal{A} = \mathcal{L} \cup \mathcal{B} \cup \mathcal{F} \]
𝓛 = locked set (fixed weight: wi = wilock)
𝓑 = bounded set (per-ticker bounds: lbi ≤ wi ≤ ubi)
𝓕 = free set (standard bounds: 0 ≤ wi ≤ wmax)

Remaining Budget

Free Budget After Locking
\[ c_{\mathcal{F}} = 1 - \sum_{i \in \mathcal{L}} w_i^{\text{lock}} \]
The optimizer distributes c𝓕 across 𝓑 ∪ 𝓕. If locked weights sum to more than 1, the problem is infeasible and an error is raised before optimization.

Full Optimization Problem

Constrained Max Sharpe
\[ \max_{\mathbf{w}} \frac{\mathbf{w}^\top \boldsymbol{\mu} - r_f}{\sqrt{\mathbf{w}^\top \boldsymbol{\Sigma} \mathbf{w}}} \] \[ \text{subject to} \quad \sum_i w_i = 1 \] \[ w_i = w_i^{\text{lock}}, \quad i \in \mathcal{L} \] \[ \mathrm{lb}_i \leq w_i \leq \mathrm{ub}_i, \quad i \in \mathcal{B} \] \[ 0 \leq w_i \leq w_{\max}, \quad i \in \mathcal{F} \] \[ \sum_{i \in \text{sector}_k} w_i \leq s_k^{\max}, \quad \forall k \]
Locked positions enter the covariance matrix in full — they affect the risk structure of the free portfolio. Sector caps are applied to the entire weight vector, including locked positions.
Locked positions shift the covariance structure of the optimization subproblem. Adding a zero-weight locked asset changes the T/N ratio in the RMT filter and the Cholesky decomposition — this is mathematically correct behavior, not a bug.

Constraint Types

TypeSyntaxDescription
Locked weightwi = cPosition fixed at exact percentage. Optimizer cannot move it.
Locked sharesni = kFixed number of shares. Weight derived from current market price.
Min/max per tickerlbi ≤ wi ≤ ubiOptimizer chooses within the specified range.
Sector floorΣsector ≥ sminForces minimum allocation to a sector.
Sector ceilingΣsector ≤ smaxCaps total allocation to a sector (default 40%).

Infeasibility Handling

If the set of constraints is infeasible (e.g. locked weights sum to more than 1, or sector caps conflict with locked positions), MAISNER raises an explicit error identifying which constraint is violated. It never silently relaxes user-defined constraints.

Random Matrix Theory — Covariance Cleaning

Raw sample covariance matrices are notoriously noisy for typical portfolio sizes. MAISNER applies Marchenko-Pastur filtering to separate signal eigenvalues from noise eigenvalues.

Marchenko-Pastur Distribution

Noise Eigenvalue Bounds
\[ \lambda_{\pm} = \sigma^2 \left(1 \pm \sqrt{\frac{T}{N}}\right)^2 \]
T = observations, N = assets. Eigenvalues within [λ, λ+] are noise and replaced with their mean.

The ratio Q = T/N determines the noise floor. For small portfolios with limited history, RMT cleaning provides substantial improvement in out-of-sample covariance estimates. The cleaned matrix retains the information eigenvalues (genuine risk factors) while suppressing estimation error.

MAISNER uses 2-year daily returns for the covariance matrix. A hybrid approach (10-year monthly + 2-year daily) was tested but produced spurious correlations between unrelated assets — pure 2-year daily provides cleaner signal.

Quality Tilt

Pure Sharpe maximization often overweights assets with recent momentum. MAISNER applies a quality penalty to the MVO objective, tilting the optimizer toward fundamentally strong companies.

Quality Score

Quality-Adjusted Objective
\[ \max_{\mathbf{w}} \; S(\mathbf{w}) - \lambda_Q \sum_i w_i \cdot \mathbb{1}[q_i < q_{thresh}] \]
λQ = quality penalty weight (0.05), qthresh = minimum quality threshold (0.30)

Quality scores are computed from FMP fundamental data: ROE, gross margin, operating margin, and debt coverage ratio. Each metric is normalized and combined into a composite score in [0, 1].

ParameterValue
LAMBDA_QUAL0.05
QUALITY_THRESH0.30
MetricsROE, Gross Margin, Op. Margin, Debt Coverage

CVaR Optimization

For multi-asset portfolios including options and non-linear instruments, mean-variance optimization is inappropriate. MAISNER uses Conditional Value-at-Risk (CVaR) minimization via linear programming.

CVaR Definition

Expected Shortfall
\[ \text{CVaR}_\alpha = \mathbb{E}[L \mid L \geq \text{VaR}_\alpha] \]
α = 0.95. CVaR is the expected loss given that losses exceed the 95th percentile VaR.

Correlated Scenario Generation

Cholesky Decomposition
\[ \mathbf{R}_{sim} = \mathbf{L} \mathbf{Z}, \quad \mathbf{\Sigma} = \mathbf{L} \mathbf{L}^\top \]
L = Cholesky factor of the RMT-cleaned covariance matrix. Z = matrix of independent standard normal draws. Produces correlated return scenarios preserving cross-asset dependencies.
ParameterValue
Scenarios5,000
Alpha0.95
MethodLP (linear programming)
CorrelationCholesky on RMT-cleaned Σ

Monte Carlo Simulation

Long-horizon wealth projections are generated via Geometric Brownian Motion with correlated asset paths.

GBM Asset Path
\[ S_t = S_0 \exp\left[\left(\mu - \frac{\sigma^2}{2}\right)t + \sigma W_t\right] \]
μ = annualised return, σ = annualised volatility, Wt = Wiener process. Portfolio paths use correlated draws via Cholesky decomposition.
ParameterValue
Paths10,000
Horizon10 years
Output5th / 50th / 95th percentile
MetricsP(loss), P(2×), Median@10y, Range

Stress Testing

Historical scenario analysis replays actual crisis return distributions against the current and optimised portfolios. Custom stress mode allows arbitrary macro shock specification.

Historical Scenarios

ScenarioPeriodS&P 500 Drawdown
2008 GFCSep 2008 – Mar 2009−56.8%
2020 COVIDFeb 2020 – Mar 2020−33.9%
2022 Rate ShockJan 2022 – Oct 2022−25.4%
2000 Dot-comMar 2000 – Oct 2002−49.1%

Advanced Stress — Custom Shocks

Users can define simultaneous shocks across equity markets (by region/sector), interest rates, FX rates, and individual ticker overrides. Shocks are applied as multiplicative return adjustments to portfolio weights.

Leverage Analysis

The Leverage Analyzer quantifies the risk and return impact of applying financial leverage to a portfolio. It combines the Kelly Criterion for optimal leverage sizing with continuous-time volatility decay, margin call analytics, and Monte Carlo liquidation probability.

Kelly Criterion — Optimal Leverage

Kelly Optimal Leverage
\[ f^* = \frac{\mu_p - r_f}{\sigma_p^2} \]
μp = annualised portfolio return, rf = risk-free rate (3.80%), σp = annualised portfolio volatility. f* is the leverage ratio that maximises the long-run geometric growth rate. Half Kelly (f*/2) is the standard practical optimum.

Leveraged Return and Volatility

Leveraged Portfolio Metrics
\[ \mu_L = L \cdot \mu_p - (L - 1) \cdot r_m \] \[ \sigma_L = L \cdot \sigma_p \] \[ S_L = \frac{\mu_L - r_f}{\sigma_L} \]
L = leverage ratio, rm = margin borrowing rate. Net return subtracts the financing cost on the borrowed fraction (L−1) of portfolio value. Volatility scales linearly with leverage.

Volatility Decay (Continuous-Time Drag)

Leverage Decay
\[ \text{decay} = -\frac{1}{2}(L^2 - L)\,\sigma_p^2 \]
Arises from the Itô correction in continuous-time GBM. At L=1 decay is zero; at L=2 it equals −½σ². Grows quadratically — a 3× levered position on a 20% vol portfolio loses ~3.6% per year to decay alone before financing costs.

Margin Call Threshold

Margin Call Drop
\[ \Delta_{MC} = \frac{1 - m}{L} \]
m = maintenance margin fraction (US RegT: 0.25, EU ESMA: 0.50). ΔMC is the portfolio drawdown from entry that triggers a margin call. At 2× leverage under RegT: ΔMC = 37.5%.

Monte Carlo Liquidation Probability

MAISNER simulates 5,000 independent GBM paths over a 252-trading-day horizon. Each path uses portfolio drift μL and volatility σL. A path is classified as a liquidation event if its running minimum touches the margin call threshold at any point during the year.

GBM Path (Daily)
\[ V_{t+1} = V_t \cdot \exp\!\left[\left(\mu_L - \frac{\sigma_L^2}{2}\right)\frac{1}{252} + \sigma_L \sqrt{\frac{1}{252}}\, Z_t\right] \]
Zt ~ N(0,1), seeded deterministically (seed=42) for reproducibility. Liquidation probability = fraction of 5,000 paths where min(V) ≤ V0(1 − ΔMC).

Historical Stress Scenarios

ScenarioS&P 500 DrawdownApplied to Leveraged Portfolio
2008 GFC−56.8%DD × L, then check MC threshold
2020 COVID−33.9%DD × L, then check MC threshold
2022 Rate Shock−25.4%DD × L, then check MC threshold
2000 Dot-com−49.1%DD × L, then check MC threshold
1987 Black Monday−22.6%DD × L, then check MC threshold
Kelly f* is an upper bound, not a recommendation. Leverage above Half Kelly introduces path-dependency risk where adverse sequences can permanently impair capital even when expected returns are positive. MAISNER displays Half Kelly and Quarter Kelly alongside f* for this reason.
ParameterValueDescription
MC_PATHS_LEV5,000GBM paths for liquidation probability
MC_HORIZON_LEV252 days1-year daily simulation
US Maintenance25%RegT maintenance margin requirement
EU Maintenance50%ESMA margin requirement
Leverage range1× – 3×Table computed at 1.0, 1.5, 2.0, 2.5, 3.0

Stop Loss Calculator

The Stop Loss Calculator derives position-level and portfolio-level exit thresholds from the volatility structure of the portfolio. The methodology follows Giuseppe Paleologo's Advanced Portfolio Management (2021), which frames stop-loss placement as a statistical inference problem rather than an ad-hoc rule.

Position-Level Volatility Stop

Each position's stop is calibrated to its realised volatility (from the RMT-cleaned covariance diagonal) and the chosen horizon. The parameter k controls the width — how many volatility-adjusted standard deviations separate entry from exit.

Vol-Based Stop (Paleologo APM)
\[ \sigma_i^{\text{daily}} = \sqrt{\frac{\Sigma_{ii}}{252}} \] \[ \text{stop\%}_i = k \cdot \sigma_i^{\text{daily}} \cdot \sqrt{T} \] \[ S_i^{\text{stop}} = S_i^{\text{entry}} \cdot (1 - \text{stop\%}_i) \] \[ \text{Dollar Risk}_i = w_i \cdot V \cdot \text{stop\%}_i \]
Σii = annualised variance (RMT covariance diagonal), T = horizon in trading days, k ∈ {1.5, 2.0, 2.5}, V = portfolio value. The square-root scaling places the stop at the k-σ level of the price distribution over the horizon.

Portfolio Drawdown Limit

The portfolio-level stop integrates correlation structure via the full covariance matrix, capturing diversification effects that position-level stops ignore.

Portfolio Drawdown and VaR
\[ \sigma_p^{\text{daily}} = \sqrt{\frac{\mathbf{w}^\top \boldsymbol{\Sigma}\, \mathbf{w}}{252}} \] \[ \text{MaxDD\%} = k \cdot \sigma_p^{\text{daily}} \cdot \sqrt{T} \] \[ \text{VaR}_\alpha = \sigma_p \cdot \sqrt{T/252} \cdot \Phi^{-1}(\alpha) \]
σp = annualised portfolio volatility, α ∈ {0.90, 0.95, 0.99}. VaR is the parametric normal-distribution estimate; MaxDD is the k-σ loss bound over the horizon.

Sharpe-Adjusted Stop (Paleologo Key Insight)

Paleologo's central contribution is showing that a strategy with genuine edge (positive Sharpe ratio) should use a tighter stop than a zero-edge strategy. The intuition: if returns are reliably positive, an observed loss of k-σ is stronger evidence of a regime change than it would be for a random walk.

Sharpe-Adjusted Stop
\[ \text{adj\_stop} = \sigma_p^{\text{daily}} \cdot \sqrt{T} \cdot \left( k - \frac{SR \cdot \sqrt{T/252}}{k} \right) \]
T = horizon in trading days (same as position-level formula). SR = annualised Sharpe ratio. The SR term is scaled by √(T/252) — converting the Sharpe to the same horizon as the vol term — while σdaily·√T gives the k-σ bound in the same units. Non-binding when SR·√(T/252) ≥ k²; a tighter condition than it appears — at T=30 days, k=2.0 requires SR ≥ 2.31 to suppress the stop. Binding stop (adj_stop > 0) tightens the threshold relative to the pure-volatility stop.
Non-binding stop interpretation: if the Sharpe-adjusted stop is non-binding, it means the expected daily drift dominates the volatility over the horizon. Paleologo's prescription is to not exit on pure-vol grounds — only a structural signal justifies exiting a high-edge strategy.

GBM First-Passage Barrier Probability (Analytical)

The probability that a position touches its stop before the horizon is computed analytically using the reflection principle for Geometric Brownian Motion — no Monte Carlo required.

First-Passage Probability (Shreve 2004, reflection principle)
\[ P\!\left(\min_{0 \le t \le T} S_t \le S_0(1-\text{stop\%})\right) = \mathcal{N}(-d_1) + e^{-2\nu\lambda/\sigma^2}\,\mathcal{N}(-d_2) \] \[ \lambda = -\ln(1 - \text{stop\%}), \quad \nu = \mu - \tfrac{\sigma^2}{2}, \quad d_1 = \frac{\lambda + \nu T}{\sigma\sqrt{T}}, \quad d_2 = \frac{\lambda - \nu T}{\sigma\sqrt{T}} \]
λ = log-distance to barrier. ν = μ − σ²/2 is the log-space (physical) drift. Positive drift reduces the barrier probability: the exponent −2νλ/σ² < 0 when ν > 0, dampening the reflection term. The exponent is clamped to [−40, 40] to prevent overflow.

Kelly Connection

The Kelly Criterion provides a natural consistency check: a stop that implies a maximum loss exceeding the Kelly-optimal risk budget is oversized relative to the strategy's edge.

Kelly Fraction and Stop Consistency
\[ f^* = \frac{\mu_p - r_f}{\sigma_p^2} \] \[ \text{Max Loss}_i^{\text{Kelly}} = f^* \cdot V \cdot \text{stop\%}_i \cdot w_i \]
The total Kelly max-loss across positions should not exceed the portfolio drawdown limit. If it does, the stop widths are inconsistent with Kelly-optimal sizing and the positions are oversized.

Re-Entry Level

After a stop is triggered, the re-entry level accounts for the short-term mean-reversion noise band estimated as 0.5-σ over 5 trading days.

Re-Entry Price
\[ S_i^{\text{reentry}} = S_i^{\text{stop}} \cdot \left(1 - 0.5\,\sigma_i^{\text{daily}}\,\sqrt{5}\right) \]
Provides a slightly lower re-entry point after exit, accounting for the expected noise band at the 0.5-σ level over a 5-day window (roughly one trading week).
ParameterValuesDescription
k_multiplier1.5 / 2.0 / 2.5Stop width in daily-vol units × √T
horizon_days30 / 60 / 90Horizon for √T scaling
confidence α0.90 / 0.95 / 0.99VaR confidence level (parametric)
RF3.80%Risk-free rate (Kelly denominator)
Covariance sourceRMT diagonalPer-ticker variance from Marchenko-Pastur cleaned Σ

Options Pricing

European Options — Black-Scholes

Black-Scholes Call Price
\[ C = S_0 N(d_1) - K e^{-rT} N(d_2) \] \[ d_1 = \frac{\ln(S_0/K) + (r + \sigma^2/2)T}{\sigma\sqrt{T}}, \quad d_2 = d_1 - \sigma\sqrt{T} \]

American Options — Barone-Adesi Whaley (BAW)

American-style options cannot be priced with Black-Scholes due to early exercise. MAISNER implements the Barone-Adesi Whaley approximation, which provides a closed-form solution by decomposing the American option into a European component and an early exercise premium.

Implied Volatility

When live market prices are available, MAISNER back-calculates implied volatility using Brent's method — a bracketed root-finding algorithm that is guaranteed to converge. If the IV calculation fails (e.g., deep ITM/OTM with negligible time value), the platform falls back to historical volatility.

Bond Analytics

Duration and Convexity

Modified Duration
\[ D_{mod} = \frac{1}{P} \sum_{t=1}^{T} \frac{t \cdot C_t}{(1+y)^{t+1}} \]
P = bond price, Ct = cash flow at time t, y = yield to maturity

Vasicek Interest Rate Model

Bond returns in stress scenarios and portfolio projections use the Vasicek mean-reverting short rate model for interest rate simulation.

Vasicek SDE
\[ dr_t = \kappa(\theta - r_t)\,dt + \sigma_r\,dW_t \]
κ = mean reversion speed, θ = long-run rate, σr = rate volatility
ParameterValue
BOND_MAX60% of portfolio
CONVEXITY_THRESH0.05
Credit ratingsAAA → CCC (FMP data)

Factor Analysis

The Factor Explorer computes Information Coefficient (IC) and related statistics for 11 cross-sectional factors.

Information Coefficient

IC — Rank Correlation
\[ IC_t = \text{Spearman}\left(\text{rank}(f_{t}),\; \text{rank}(r_{t+1})\right) \]
Rank correlation between factor scores at time t and forward returns at t+1. Robust to outliers; range [−1, +1].

Information Ratio

ICIR
\[ ICIR = \frac{\bar{IC}}{\sigma_{IC}} \]
Annualised ratio of mean IC to IC volatility. ICIR > 0.5 indicates a reliably predictive factor.
FactorCategory
momentum_12mMomentum (12-1)
momentum_1mShort-term reversal
value_compositeP/E, P/B, EV/EBITDA
quality_compositeROE, margins, debt
low_volatility12-month realised vol
fcf_yieldFCF / Market cap
earnings_revisionEPS estimate changes
sizeLog market cap
dividend_yieldTrailing dividend yield
growth_compositeRevenue + EPS growth
short_interestShort % of float

Backtesting & Deflated Sharpe Ratio

Walk-Forward Validation

All strategy backtests use walk-forward analysis: the strategy is fitted on a training window and evaluated on an out-of-sample test window that rolls forward in time. This prevents look-ahead bias and provides a realistic estimate of live performance.

Deflated Sharpe Ratio

Multiple testing bias is a major source of overfitting in quantitative strategies. MAISNER computes the Deflated Sharpe Ratio (DSR), which adjusts the observed Sharpe Ratio for the number of trials tested and the non-normality of returns.

Deflated Sharpe Ratio
\[ DSR = \Phi\left(\frac{(\hat{SR} - SR^*)\sqrt{T-1}}{\sqrt{1 - \gamma_3 \hat{SR} + \frac{\gamma_4-1}{4}\hat{SR}^2}}\right) \]
SR* = expected maximum Sharpe Ratio under repeated testing. γ3 = skewness, γ4 = kurtosis. DSR > 0.95 indicates the strategy survives multiple-testing correction.
DSR < 0.5 typically indicates the strategy is overfitted to the training data. MAISNER flags strategies with low DSR and warns users before live deployment.

Performance Attribution

MAISNER implements the Brinson-Hood-Beebower (BHB) three-effect decomposition, which explains the difference between portfolio return and benchmark return as the sum of allocation, selection, and interaction effects. The benchmark is a synthetic SPY blend constructed from sector ETF returns weighted by approximate S&P 500 sector weights.

Brinson-Hood-Beebower Decomposition

Let wp = portfolio sector weight, wb = benchmark sector weight, Rp = portfolio sector return, Rb = benchmark sector return, Rbtotal = total benchmark return.

Allocation Effect
\[ A_s = (w_s^p - w_s^b)(R_s^b - R_{\text{total}}^b) \]
Measures the value added by over- or under-weighting a sector relative to the benchmark. Positive when the portfolio over-weights a sector that outperforms the overall benchmark.
Selection Effect
\[ S_s = w_s^b (R_s^p - R_s^b) \]
Measures the value added by selecting securities that outperform the sector benchmark. Uses benchmark weight to isolate pure security selection skill.
Interaction Effect
\[ I_s = (w_s^p - w_s^b)(R_s^p - R_s^b) \]
Cross-effect from simultaneously over-weighting and outperforming a sector. Represents the combined effect of active allocation and active selection.
Active Return Decomposition
\[ R_{\text{active}} = R^p - R^b = \sum_s (A_s + S_s + I_s) \]
The total active return equals the sum of all sector-level effects. Effects are expressed in basis points (bp = 0.01%).

Benchmark Construction

The sector benchmark uses approximate SPY sector weights (Technology 30%, Financials 13.2%, Healthcare 12.8%, …) applied to sector ETF returns (XLK, XLF, XLV, XLY, XLI, XLC, XLP, XLE, XLB, XLU, XLRE). SPY actual return is also fetched for reference.

Sector resolution uses a two-layer lookup with a 24-hour in-process cache: (1) FMP Professional /stable/profile is queried first for accurate GICS sector classification (e.g. AMZN → Consumer Discretionary, JPM → Financials, JNJ → Healthcare); (2) the internal Stocks.xlsx sector column (normalised from Russian to English) is used as fallback for tickers not found in FMP or for EU-listed securities. The same enriched sector map is applied consistently across the Optimizer, Constrained Optimizer, Stress Tests, and Attribution engine. Tickers that remain unresolved after both lookups are excluded from the BHB decomposition and do not affect total effects — all sector-level effects still sum exactly to active return over the resolved weight subset.

SectorETFSPY Weight
TechnologyXLK30.0%
FinancialsXLF13.2%
HealthcareXLV12.8%
Consumer DiscretionaryXLY10.1%
IndustrialsXLI8.7%
CommunicationXLC8.6%
Consumer StaplesXLP5.9%
EnergyXLE3.8%
MaterialsXLB2.4%
UtilitiesXLU2.3%
Real EstateXLRE2.2%

Portfolio Monitor

The Portfolio Monitor provides real-time P&L tracking, currency exposure breakdown, and option expiry management for user-defined portfolios. Unlike the Analyzer and Optimizer, the Monitor supports multi-asset portfolios (stocks, ETFs, bonds, options, futures, crypto) for all subscription tiers.

Position-Level P&L

P&L Calculation
\[ \text{Cost}_{i,\text{USD}} = Q_i \cdot P_i^{\text{purchase}} \cdot \text{FX}_{C_i \to \text{USD}} \] \[ \text{Value}_{i,\text{USD}} = Q_i \cdot P_i^{\text{live}} \cdot \text{FX}_{C_i \to \text{USD}} \] \[ \text{P\&L}_i = \text{Value}_{i,\text{USD}} - \text{Cost}_{i,\text{USD}} \] \[ \text{P\&L\%}_i = \left(\frac{\text{Value}_{i,\text{USD}}}{\text{Cost}_{i,\text{USD}}} - 1\right) \times 100 \]
Q = quantity, P = price, FX = exchange rate to USD. Live prices are fetched from FMP Professional with per-instrument currency conversion; Yahoo Finance is used as fallback.

Option Valuation

For live options (expiry > today), the Monitor computes an estimated current value as intrinsic value plus an approximate time value derived from a simplified Black-Scholes formula with σ = 25% assumed volatility. Expired options (expiry ≤ today) are marked to zero (conservative) and displayed with an EXPIRED badge — they should be removed from the portfolio.

Option Monitor Value (approximate)
\[ V_{\text{call}}^{\text{intrinsic}} = \max(0, S - K) \] \[ V_{\text{put}}^{\text{intrinsic}} = \max(0, K - S) \] \[ V_{\text{time}} \approx S \cdot N(d_1) \cdot \sigma \cdot \sqrt{T} \cdot 0.4 \] \[ V_{\text{option}} = V^{\text{intrinsic}} + V_{\text{time}} \]
S = underlying spot, K = strike, T = years to expiry. The time value factor 0.4 is a rough ATM approximation. For precise option analytics use the dedicated Options Pricing engine.

Currency Exposure

Currency is inferred from the exchange suffix of each ticker (.DE/.PA → EUR, .L → GBP, .ST → SEK, etc.; no suffix → USD). The currency breakdown shows the percentage of total portfolio value held in each currency. FX rates are fetched from FMP at runtime.

Long/Short Optimizer

The Long/Short Optimizer extends the standard MVO framework to allow negative portfolio weights (short positions). The mathematical structure is identical to the long-only case — the same Sharpe objective, the same RMT-cleaned covariance matrix — with two key adaptations: a borrow cost term subtracted from the expected return of shorted positions, and relaxed weight bounds that permit negative values.

Portfolio Modes

Two net-exposure configurations are available:

  • Long/Short (net = 1): Σwᵢ = 1. Standard fully-invested portfolio allowing some short positions. Long gross > net; short gross < long gross.
  • Market Neutral (net = 0): Σwᵢ = 0. Dollar-neutral — long exposure equals short exposure. A minimum gross constraint (Σ|wᵢ| ≥ 0.5) prevents the degenerate all-zero solution.

Borrow Cost Adjustment

Effective Expected Return
\[ \mu_i^{\text{eff}} = \mu_i - b \cdot \mathbf{1}[w_i < 0] \] \[ \mu_p^{\text{eff}} = \sum_i w_i \mu_i^{\text{eff}} = \sum_i w_i \mu_i - b \sum_{w_i < 0} |w_i| \]
b = annual borrow rate (default 0.5%). The borrow cost is subtracted from the expected return contribution of each short position. Long positions are unaffected. This makes high-borrow-rate environments naturally discourage shorting when the alpha is insufficient to cover the cost.

Objective Modes

ModeObjectiveL/S Adaptation
Standardmax (μ_eff − r_f) / σSame Sharpe with borrow-adjusted μ; bounds [-max_short, max_long]
Conservativemin wᵀΣwMinimise portfolio variance; negative weights allowed; tends toward fewer shorts
Balancedmax Sharpe s.t. σ ≤ vol_capSLSQP vol constraint; falls back to min-variance if vol_cap is infeasible
Aggressivemax μ_effPure return maximisation; bounds widened to [−1.5×max_short, 1.5×max_long]
Dividendmax Σ(wᵢ>0)×ROIᵢ − 0.3σYield only from long leg; vol penalty prevents pure high-yield concentration

Weight Constraints

Feasible Region
\[ -m_s \le w_i \le m_l \quad \forall i, \qquad \sum_i w_i = \eta, \qquad \text{(MN only:)} \quad \sum_i |w_i| \ge 0.5 \]
mₛ = max_short (default 0.30), mₗ = max_long (default 0.35), η = 1 (long/short) or 0 (market neutral). Aggressive mode uses 1.5× widened bounds. The market-neutral gross constraint prevents the trivial zero-weight solution.

Portfolio Statistics

Gross and Net Exposure
\[ \text{Gross} = \sum_i |w_i|, \qquad \text{Net} = \sum_i w_i, \qquad \text{L/S Ratio} = \frac{\sum_{w_i > 0} w_i}{\sum_{w_i < 0} |w_i|} \]
Gross exposure > 1 indicates leverage. L/S ratio = 1 for market-neutral. Borrow cost = borrow_rate × short_gross.

Volatility and Sharpe (identical to long-only)

Portfolio Variance — unchanged with negative weights
\[ \sigma_p^2 = \mathbf{w}^\top \Sigma \mathbf{w} \] \[ \text{Sharpe} = \frac{\mu_p^{\text{eff}} - r_f}{\sigma_p} \]
The covariance matrix wᵀΣw is always non-negative regardless of the sign of individual weights. RMT-cleaned covariance is used identically to the standard optimizer. Sharpe is computed using the borrow-adjusted expected return.

Upper Barrier Probability for Short Stop-Losses

When L/S portfolio weights are passed to the Stop Loss Calculator, short positions (w < 0) use the upper barrier formula (stop triggered when price rises above entry):

Upper Barrier — Short Position Stop-Out
\[ P\!\left(\max_{0 \le t \le T} S_t \ge S_0(1+\text{stop\%})\right) = \mathcal{N}(-d_2) + e^{+2\nu\lambda/\sigma^2}\,\mathcal{N}(-d_1) \] \[ \lambda = \ln(1 + \text{stop\%}), \quad d_1 = \frac{\lambda + \nu T}{\sigma\sqrt{T}}, \quad d_2 = \frac{\lambda - \nu T}{\sigma\sqrt{T}} \]
Positive drift ν > 0 increases upper-barrier probability (stock trends toward short stop). Note: d₁ and d₂ are swapped vs the long (lower-barrier) formula, and the exponent sign is positive. Stop price for short = entry × (1 + stop_pct).

Long/Short Analyzer

The Long/Short Analyzer evaluates an existing L/S portfolio given the user's actual positions — ticker, quantity, direction, and purchase price. Live prices are fetched at run-time to compute current mark-to-market values, realised P&L, and forward-looking risk metrics using the same RMT covariance infrastructure as the optimizer.

Position Valuation and P&L

Mark-to-Market P&L per Position
\[ \text{PnL}_i = \text{sign}_i \times (\text{qty}_i \times P_i^{\text{live}} - \text{qty}_i \times P_i^{\text{purchase}}) \] \[ \text{sign}_i = \begin{cases} +1 & \text{LONG} \\ -1 & \text{SHORT} \end{cases} \]
Long positions profit when price rises; short positions profit when price falls. Total portfolio P&L = Σ PnL_i.

Portfolio Exposure

Gross, Net, and L/S Ratio
\[ V_i^{\text{live}} = \text{qty}_i \times P_i^{\text{live}}, \qquad V_{\text{gross}} = \sum_i V_i^{\text{live}} \] \[ V_{\text{net}} = V_{\text{long}} - V_{\text{short}}, \qquad w_i = \frac{\text{sign}_i \times V_i^{\text{live}}}{V_{\text{gross}}} \] \[ \text{L/S Ratio} = \frac{V_{\text{long}}}{V_{\text{short}}}, \qquad \text{Net Exposure} = \frac{V_{\text{net}}}{V_{\text{gross}}} \]
Weights are normalised by gross value. Long weights are positive; short weights are negative. Net exposure = 1 for a long-only book; = 0 for market-neutral.

Portfolio Risk (RMT Covariance)

Volatility, Sharpe, and VaR
\[ \sigma_p = \sqrt{\mathbf{w}^\top \Sigma_{\text{RMT}} \,\mathbf{w}}, \qquad \mu_p^{\text{eff}} = \sum_i w_i \mu_i - b \sum_{w_i < 0} |w_i| \] \[ \text{Sharpe} = \frac{\mu_p^{\text{eff}} - r_f}{\sigma_p} \] \[ \text{VaR}_{95\%} = \sigma_p \times z_{0.95} = \sigma_p \times 1.645 \] \[ \text{CVaR}_{95\%} = \sigma_p \times \frac{\phi(z_{0.95})}{1 - 0.95} \approx \sigma_p \times 2.063 \]
Parametric VaR and CVaR under normality. σ_p uses RMT-cleaned covariance (identical to optimizer pipeline). Borrow cost b is deducted from expected return of short positions only. VaR and CVaR are expressed as a percentage of gross portfolio value, annualised.

Stress Scenarios (Beta-Adjusted)

Scenario Impact
\[ \text{Impact} = \sum_i \text{sign}_i \times \beta_i \times r_{\text{mkt}} \times V_i^{\text{live}} \]
For each historical scenario (GFC 2008, COVID 2020, Rate Shock 2022, Dot-com 2000, Black Monday 1987), the position-level impact is computed using the stock's beta (from Stocks.xlsx; default β = 1) and the scenario's market return. Long positions lose when the market falls; short positions gain (hedge effect). The sum shows how well shorts offset long-side losses under each scenario.

Hedging Optimizer

Implements the Yu & Sun (2017) model: "Optimal Hedging with Options and Futures against Price Risk and Background Risk", Math. Comput. Appl. 22(1):5. The model simultaneously optimises a put option hedge and a futures hedge for a commodity or equity position subject to correlated background risk (weather, operational, yield).

Model Structure

The terminal profit from the hedged position is (Equation 1 of the paper):

ΠT = (1 + β·ZT) · { PT·Q + [(K − FT)+ − Φ·e]·h·Q + (F0·e − FT)·H·Q } + (1 − β)·ZT
SymbolMeaning
PTSpot commodity price at horizon T (lognormal)
FTFutures price at horizon T (lognormal, corr ρ1 with PT)
F0Current futures price
QQuantity held
KPut option strike — grid-searched over [0.7⋅F0, 1.3⋅F0]
ΦBlack-Scholes European put price at K
hOption hedge ratio (units of puts per unit of Q)
HFutures hedge ratio — grid-searched over [0, 2]
ZTBackground risk ~ N(0, σz2), corr ρ2 with PT
βBackground mix: β=0 pure additive, β=1 pure multiplicative
rRisk-free rate (3.80%)
τHedging horizon in years

Budget Constraint

The option budget is a fraction d of the position value P0·Q:

h = d · P0 / Φ

When Φ is near zero (deep in-the-money or very short expiry), h is clamped to zero to avoid a degenerate hedge.

Simulation

N = 10,000 correlated paths are drawn via a factored Cholesky structure. Three independent N(0,1) variates W1, W2, W3 give:

log(PT/P0) = (μs − σs2/2)τ + σs√τ · W1
log(FT/F0) = (μf − σf2/2)τ + σf√τ · (ρ1W1 + √(1−ρ12)·W2)
ZT = σz · (ρ2W1 + √(1−ρ22)·W3)

This exactly reproduces corr(PT, FT) = ρ1, corr(PT, ZT) = ρ2, corr(FT, ZT) = ρ1·ρ2.

Risk Measure: ESα (TCE)

The risk measure minimised is the Expected Shortfall (ES) of the normalised loss, which equals the Tail Conditional Expectation (TCE) by Proposition 1 of the paper. For a loss distribution L = −(ΠT − W0) / W0:

ESα = E[L | L ≥ VaRα(L)] = E[L | L ≥ q1−α(L)]

All results are expressed as a fraction (or percentage) of initial wealth W0 = P0·Q, making them comparable across different position sizes.

Grid Search

The joint optimum (H*, K*) is found by exhaustive grid search:

(H*, K*) = argminH ∈ [0,2], K ∈ [0.7F0, 1.3F0] ESα(−ΠT(H,K) / W0)

Grid: H — 21 points (0.0, 0.1, …, 2.0); K — 20 points uniformly spaced. The optimal h* follows from the budget constraint: h* = d·P0/Φ(K*).

Over-Hedge

When H* > 1 the futures short exceeds the underlying exposure. This can be ES-optimal when β is high (multiplicative background risk dominates) or when ρ1 is low (futures are a poor spot proxy so a larger position is needed to hedge the residual). The UI flags over-hedge with an amber badge.

Sensitivity Analysis

SeriesWhat it shows
ES vs βHow additive vs multiplicative background risk changes the hedge benefit (11 points, [0,1]).
ES vs d (budget)Marginal value of increasing the option budget from 1% to 50% of position value (10 points).
ES vs αHow the optimal ES varies with the tail probability from 1% to 10% (10 points).
ES vs σspotHedge effectiveness across volatility regimes: 10%, 16%, 20%, 40%, 60% (5 points; paths re-simulated for each).

Futures Diagnostic Curve

At the optimal strike K*, ESα is computed for H ∈ [0, 2] (41 points) with options at d fixed. The resulting U-shaped (or monotone) curve shows whether futures add value beyond options alone (it will be non-trivial when ρ1 < 1 and σspot ≠ σfutures). H* is annotated with a dashed vertical line.

Three Comparison Scenarios

ScenarioHhPurpose
No Hedge00Baseline unhedged position
Options Only0d⋅P0Pure put hedge without futures
OptimalH*h*Joint optimum from grid search

Portfolio-Native Mapping

The abstract Yu & Sun model is mapped to a real portfolio by treating the portfolio as Q = W₀ / P₀ units of the hedge underlying (e.g. SPY). Portfolio statistics are estimated from price_history.xlsx (1-year monthly log-returns).

Model paramPortfolio quantityNotes
QW₀ / P₀Portfolio value in units of hedge underlying
σspotσportfolioAnnualised vol from monthly returns (12-month window)
σfuturesσhedgeVol of hedge underlying — used for BS put pricing
ρ1corr(port returns, hedge returns)Hedge effectiveness; higher = better hedge
ρ2√(1 − ρ12) × 0.5Conservative approximation for background-spot correlation
σzσportfolio × √(1 − ρ12)Idiosyncratic (unhedgeable) vol
μspotrf + max(0, β) × 5%CAPM estimate; β = cov(port, hedge) / var(hedge)
μfuturesrfRisk-neutral futures drift
F0P0 × eFair futures price (continuous compounding, no dividends)

Hedge Strategies Evaluated

StrategyStructureFree params optimised
Protective PutLong put on hedge underlying, H = 0K (strike)
CollarLong put + short call, same expiry, H = 0Kput, Kcall
Put + FuturesLong put + short futures (full Yu & Sun 2017)K, H
Futures OnlyShort futures only, h = 0H

All strategies are ranked by ESα. The best strategy and trade instructions (number of contracts = ⌈h × Q / 100⌉, estimated premium, cost as % of AUM) are shown in the results panel alongside ES vs Budget and ES vs Horizon sensitivity charts.

Option Pricing

The put premium Φ is priced with the Black-Scholes formula using the futures price F0 as the underlying:

Φ = K·e−rτ·Φ(−d2) − F0·Φ(−d1),    d1 = [ln(F0/K) + (r + σf2/2)τ] / (σf√τ),    d2 = d1 − σf√τ

The futures volatility σf is used for this pricing step, not the spot volatility, as the put is written on the futures contract.

Platform Constants

ConstantValueDescription
RISK_FREE3.80%Risk-free rate (annualised)
WEIGHT_MAX35%Max weight per linear asset
CRYPTO_MAX15%Max total crypto allocation
FUTURES_MAX20%Max total futures allocation
BOND_MAX60%Max total bond allocation
OPTION_MAX30%Max total options allocation
LAMBDA_QUAL0.05Quality tilt penalty weight
QUALITY_THRESH0.30Min quality score threshold
MC_PATHS10,000Monte Carlo simulation paths
MC_HORIZON10 yearsMonte Carlo time horizon
CVAR_SCENARIOS5,000CVaR scenario count
CVAR_ALPHA0.95CVaR confidence level
DATA_HISTORY10 yearsPrice history for analysis
STALENESS30 daysMax data age before refresh

Data sources: FMP Professional (primary — fundamentals, prices, dividends), Polygon (secondary — US equities), yfinance (EU tickers, fallback). All data fetched over HTTPS with API key authentication.

PRIIPs KID Generator

Implements EU Regulation 1286/2014 (PRIIPs) and Commission Delegated Regulation 2017/653 as amended by 2021/2268. Generates a Key Information Document using Method 1 (historical block bootstrap) for Category 3 products (equities / ETFs) with at least 24 months of price history. Five years (60 months) is recommended per ESMA guidance.

Summary Risk Indicator — VEV, MRM, SRI

Value-at-Risk Equivalent Volatility (Method 1)
\[\text{VEV} = \hat{\sigma}_{\text{monthly}} \times \sqrt{12}\]
σ̂_monthly = sample standard deviation (ddof=1) of monthly portfolio log-returns over available history. VEV is the annualised volatility used as the PRIIPs Method 1 market risk proxy.
MRM from VEV
\[\text{MRM} = \begin{cases} 1 & \text{VEV}\leq0.5\%\\ 2 & \leq1.2\%\\ 3 & \leq2.0\%\\ 4 & \leq3.0\%\\ 5 & \leq8.0\%\\ 6 & \leq16.0\%\\ 7 & >16.0\% \end{cases}\]
MRM 1–7 derived from VEV bounds. Most diversified equity portfolios fall at MRM 5–6 (VEV 8–16%).
SRI Composition — PRIIPs Annex IV Table 4
\[\text{SRI} = \max(\text{MRM},\;\text{CRM}-1)\]
Exact implementation of the 7×6 regulatory lookup table. CRM = 1 for directly-held equities/ETFs (ring-fenced custody), so SRI = MRM in the standard case. CRM 2–6 applies to structured products, bonds with issuer credit risk, or positions with counterparty exposure.

Performance Scenarios — Block Bootstrap

Block bootstrap, 12-month blocks, 10,000 paths
\[V_T^{(i)} = V_0 \cdot \exp\!\Bigl(\sum_{j=1}^{T\times12} r_j^*\Bigr), \quad \{r_j^*\} = \text{blocks sampled with replacement from } \{r_t\}_{t=1}^{n}\]
Overlapping 12-month blocks are drawn with replacement, preserving return autocorrelation and volatility clustering (GARCH effects). Block length falls back to min(12, n÷2) when history is shorter than 24 months.
Net-of-cost terminal values
\[V_T^{\text{net}} = V_T^{\text{gross}} \cdot (1 - f_{\text{entry}}) \cdot (1 - f_{\text{ong}})^T \;-\; V_0\bigl(f_{\text{exit}} + f_{\text{perf}}\cdot T\bigr), \quad V_T^{\text{net}} \geq 0\]
Scenarios are shown net of all costs per PRIIPs Annex V. Terminal values are floored at zero.
Annualised scenario returns
\[\bar{r}_T = \left(\frac{V_T^{\text{net}}}{V_0}\right)^{1/T} - 1\]
PRIIPs requires "Average return each year" — geometric annual return over holding period T. Scenario percentiles: Stress = P₁, Unfavourable = P₁₀, Moderate = P₅₀, Favourable = P₉₀.

Cost Disclosure — Reduction in Yield (RIY)

Cost components
\[C_{\text{entry}} = I \cdot f_{\text{entry}} \qquad C_{\text{ongoing}}(T) = I\Bigl[1-\bigl(1-f_{\text{ong}}\bigr)^T\Bigr]\] \[C_{\text{exit}} = V_T^{\text{net,pre-exit}} \cdot f_{\text{exit}} \qquad C_{\text{perf}} = \max\!\bigl(V_T^{\text{net,pre-perf}} - I_{\text{invested}},\;0\bigr)\cdot f_{\text{perf}}\]
Entry fee deducted upfront from initial investment. Ongoing: compound annual drag on I. Exit fee: percentage of the net terminal value before exit deduction. Performance fee: percentage of positive gain above invested amount (after entry and ongoing deductions). Iinvested = I × (1 − fentry).
Reduction in Yield (RIY) — bootstrap-derived
\[\text{RIY}(T) = \left(\frac{V_T^{\text{gross,mod}}}{I}\right)^{1/T} - \left(\frac{V_T^{\text{net,mod}}}{I}\right)^{1/T}\]
RIY is the difference between the annualised gross return and annualised net return at the moderate (P₅₀) bootstrap scenario. Unlike simplified analytic approximations, this correctly captures the interaction of all four cost types at the actual scenario terminal value. Reported in % per year.

Multi-Asset Optimizer

Extends the core MVO engine to portfolios containing equities, ETFs, futures, crypto, bonds, and options simultaneously. Each asset class is handled by a dedicated sub-optimizer; results are stitched into a single set of weights subject to class-level allocation caps.

Asset Class Constraints

ClassCapTreatment
Equities / ETFs / Crypto35% per ticker · 15% total cryptoStandard MVO with RMT cleaning
Bonds60% totalVasicek synthetic returns → MVO
Futures20% totalLinear payoff → included in MVO
Options30% totalScenario-based CVaR-LP

Bond Sub-Optimizer — Vasicek Synthetic Returns

Vasicek mean-reverting short rate
\[dr_t = \kappa(\theta - r_t)\,dt + \sigma_r\,dW_t\]
κ = mean-reversion speed, θ = long-run mean, σᵣ = yield volatility (7 bp/yr for government, 12 bp/yr for corporate, 30 bp/yr for high yield). Initial rate r₀ = risk-free + credit_spread(rating). 504 daily steps synthesize bond price paths. Modified duration and convexity control price sensitivity to rate moves.
Bond price return approximation
\[\frac{\Delta P}{P} \approx -D_{\text{mod}}\,\Delta y + \frac{1}{2}\,\mathcal{C}\,(\Delta y)^2\]
D_mod = modified duration, C = convexity. Second-order Taylor expansion captures the asymmetric (convex) price response. Used to construct 2-year daily synthetic return series for bond tickers before feeding into MVO.

Options Sub-Optimizer — CVaR Linear Programme

CVaR-LP (Rockafellar & Uryasev, 2000)
\[\min_{w,z,\zeta}\; \zeta + \frac{1}{(1-\alpha)S}\sum_{s=1}^{S} z_s \quad \text{s.t. } z_s \geq -r_s^\top w - \zeta,\; z_s \geq 0,\; \sum w_i = \text{opt\_alloc}\]
S = 5,000 scenarios, α = 0.95 (user-configurable). Each scenario r_s is computed from the Black-Scholes option P&L over the horizon. The LP minimises the expected shortfall of the option sub-portfolio while keeping total option weight at opt_alloc.

Combined Portfolio Metrics

Sharpe — linear + bond weights only
\[\text{Sharpe} = \frac{\mu_p - r_f}{\sigma_p}, \quad \text{where } \mu_p, \sigma_p \text{ use RMT-cleaned covariance of linear + bond assets}\]
Options are excluded from the Sharpe denominator (non-linear payoffs invalidate Gaussian variance). Portfolio Greeks (Δ, Γ, Θ, V) are aggregated across all option legs and displayed separately.

Portfolio Analyzer

Holdings-based workflow: enter current positions as (ticker, shares) pairs, and the engine computes current portfolio metrics, runs a full MVO re-optimization, and produces a rebalancing plan with trade-level cost estimates.

Holdings → Weights

Current weight computation
\[w_i^{\text{cur}} = \frac{n_i \cdot S_i}{\sum_j n_j \cdot S_j}\]
nᵢ = shares held, Sᵢ = current price. Weights are recomputed at analysis time using live prices from FMP (primary) → Polygon → Yahoo fallback chain. The denominator is the total portfolio market value.

Rebalancing Plan

Trade quantity and cost
\[\Delta n_i = \frac{(w_i^* - w_i^{\text{cur}}) \cdot V_{\text{total}}}{S_i}, \quad C_{\text{tx}} = |{\Delta n_i}| \cdot S_i \cdot c\]
w*ᵢ = MVO-optimal weight, V_total = total portfolio value, c = transaction cost (default 0.10%). ΔnΔn > 0 → BUY, ΔnΔn < 0 → SELL. Fractional shares are rounded to the nearest integer; residual cash is tracked.

Comparison Metrics

MetricFormula
Sharpe(μ − r_f) / σ
Sortino(μ − r_f) / σ_down, σ_down = √(E[min(r,0)²]×252)
BetaCov(r_p, r_SPY) / Var(r_SPY)
Alpha (Jensen)μ_p − r_f − β(μ_SPY − r_f)
Max Drawdownmax(V_peak − V_trough) / V_peak over 2-year daily log

Advanced Stress Test — Custom Scenarios

Extends the historical scenario library with a fully configurable shock constructor. The user specifies a base crisis (optional), market-wide shock, per-sector shocks, and per-ticker overrides. A GBM path is generated to visualise how portfolio value evolves through the scenario.

Shock Priority Chain

Per-asset shock resolution
\[r_i = \begin{cases} \text{ticker\_shocks}[i] & \text{if ticker override set} \\ \text{sector\_shocks}[\text{sector}(i)] & \text{elif sector shock set} \\ \text{base\_impact}[\text{sector}(i)] & \text{elif base crisis loaded} \\ \text{market\_shock} & \text{otherwise} \end{cases}\]
Four-level priority ensures fine-grained control. Sector shocks override the base crisis for specific sectors; ticker shocks are the highest priority and override everything else for individual positions.
Spillover between sectors
\[r_i' = r_i + \phi \sum_{s \neq \text{sector}(i)} \text{sector\_shocks}[s]\]
φ = spillover coefficient (0–1). When φ > 0, stress from other sectors bleeds into all positions, modelling contagion. φ = 0 (default) produces fully independent sector shocks.
Portfolio scenario return
\[R_p = \sum_i w_i \cdot r_i'\]
Weighted sum of per-asset shocked returns. Compared against the same portfolio under the current weights and under the MVO-optimal weights to highlight divergence.

GBM Path Generation

Constrained GBM
\[\text{innovations}_t \sim \mathcal{N}(0,\,\sigma\sqrt{\Delta t}), \quad \text{innovations rescaled s.t. } \sum_t \text{innov}_t = \ln(1 + R_p)\]
50-point path over T years. Random normal increments are generated then linearly rescaled to hit the target log-return exactly. This preserves the specified volatility while matching the scenario endpoint — giving a realistic visual trajectory rather than a straight line.

Options Strategy Builder

Assembles multi-leg options strategies from a ticker, spot price, implied volatility, and expiration date. Each strategy is defined as a set of legs with direction (+1 long / −1 short), option type, and a delta target used to select the appropriate strike.

Supported Strategies

StrategyLegsView
Covered CallLong stock + short OTM call (Δ≈0.30)Neutral-bullish, income
Protective PutLong stock + long OTM put (Δ≈−0.25)Bullish with downside insurance
CollarLong stock + short OTM call + long OTM putBounded risk and reward
Long StraddleLong ATM call + long ATM putVolatility long, direction neutral
Long StrangleLong OTM call (Δ≈0.25) + long OTM put (Δ≈−0.25)Vol long, cheaper than straddle
Bull Call SpreadLong ATM call + short OTM call (Δ≈0.30)Bullish, defined risk/reward
Bear Put SpreadLong ATM put + short OTM put (Δ≈−0.30)Bearish, defined risk/reward
Short StraddleShort ATM call + short ATM putSell volatility, range-bound
Iron CondorShort OTM call spread + short OTM put spreadLow-vol income, 4 legs

Strike Selection via Delta Targeting

Delta-implied strike
\[K = S \cdot \exp\!\left(\sigma\sqrt{\tau} \cdot d_1^{-1}(\Delta_{\text{target}})\right)\]
ATM legs target |Δ| = 0.50, OTM legs target |Δ| = 0.25–0.30. The strike is solved by inverting the Black-Scholes delta formula. BAW adjustment is applied for American-style options. The resulting legs are priced using the full BS/BAW engine.

Portfolio Greeks Aggregation

Aggregate greeks
\[\Delta_p = \sum_i q_i \cdot \text{dir}_i \cdot \Delta_i, \quad \Gamma_p = \sum_i q_i \cdot |\text{dir}_i| \cdot \Gamma_i\]
qᵢ = position size (contracts × 100 shares/contract), dirᵢ = ±1. Theta and Vega sum linearly. Portfolio delta-dollar = Δ_p × S (exposure to 1% move in spot). Greeks are recomputed live on price or IV change.

Tax Loss Harvesting

Identifies unrealised losses in a portfolio that exceed a user-defined threshold and estimates the potential tax saving from crystallising those losses. Accounts for country-specific rates, holding periods (US), and wash-sale restrictions. Suggests substitute securities to maintain market exposure during the exclusion window.

Core Calculation

Unrealised P&L and tax saving
\[\text{pnl}_i = (S_i - B_i) \cdot n_i, \quad \text{tax\_saving}_i = |\text{pnl}_i| \cdot \tau_i\]
Sᵢ = live price (Polygon → Yahoo → FMP), Bᵢ = cost basis per share, nᵢ = shares held. Position qualifies for harvesting when pnl_pct = pnl/cost ≤ −threshold (default 5%). τᵢ = applicable tax rate (see below).
Net harvestable loss
\[\text{usable\_loss} = \max(\text{total\_loss},\; -\text{realised\_gains})\]
If the user has already realised gains this year, harvestable losses are bounded by those gains (you cannot create a net loss greater than your total gains for the purpose of this estimate).

Country Tax Rates

CountryRateWash-saleNotes
US37% ST / 20% LT30 daysDual rate; holding > 1 year qualifies for LT
DE26.375%NoneAbgeltungsteuer 25% + 5.5% Solidaritätszuschlag
FR30%NonePFU flat tax (prélèvement forfaitaire unique)
UK20%30 daysBed-and-breakfasting rule; CGT higher rate
NLN/ABox 3 taxes fictitious return on net wealth; TLH not applicable
CHN/ANo CGT for private investors (Privatvermögen)

Substitute Selection

After crystallising a loss, the position is replaced with a similar-but-not-identical security to maintain sector exposure during the wash-sale window. Substitutes are sourced from: (1) a curated ticker map (~60 tickers); (2) same-sector ETFs; (3) FMP screener peers (same sector, similar market cap). Up to 4 substitutes are returned per position.

Signal Analysis

Evaluates each factor from the Factor Library as a standalone trading signal over forward periods of 1, 3, 6, and 12 months. Produces Information Coefficient, hit rate, long/short spread, and t-statistics. Supports ensemble composite construction via OLS signal combination.

Information Coefficient (IC)

Spearman rank IC
\[\text{IC} = \rho_S(\text{factor scores},\; r_{\text{fwd}})\]
ρ_S = Spearman rank correlation between cross-sectional factor scores and subsequent forward returns. IC ∈ [−1, 1]; IC > 0 means the factor predicts future returns positively. Significance assessed by p-value from exact Spearman distribution.

Hit Rate & Long/Short Spread

Long/Short classification and spread
\[\text{Long} = \{i : s_i \ge 0.67\}, \quad \text{Short} = \{i : s_i \le 0.33\}\] \[\text{Spread} = \bar{r}_{\text{long}} - \bar{r}_{\text{short}}, \quad \text{AnnSpread} = (1 + \text{Spread})^{12/T} - 1\]
Top/bottom tercile split. Hit rate = fraction of long positions with positive forward return. Spread = mean forward return difference between top and bottom tercile. T-statistic from Welch's two-sample t-test (unequal variance).

Ensemble Composite

OLS signal combination
\[\hat{r} = \sum_k \omega_k \cdot s_k^{(i)}, \quad \hat{\omega} = \arg\min \|r_{\text{fwd}} - X\omega\|^2\]
X = matrix of standardised factor scores (z-scores), r_fwd = forward returns. OLS weights ω̂ are estimated from the cross-section. The composite score ŝᵢ = Xᵢω̂ is used to rank stocks for the combined signal. Weights are clipped to [0, 1] and re-normalised to avoid factor cancellation.

Efficient Frontier

Generates the mean-variance efficient frontier by Monte Carlo sampling of random portfolios, then renders an interactive scatter chart. Clicking any point populates weight sliders; dragging a slider instantly recomputes portfolio metrics for the custom allocation.

Random Portfolio Generation

Dirichlet sampling (long-only)
\[\mathbf{w} \sim \text{Dirichlet}(\mathbf{1}_n), \quad \sum_i w_i = 1,\; w_i \ge 0\]
1,500 random portfolios are drawn from a symmetric Dirichlet distribution (concentration = 1, uniform over the simplex). Each portfolio's expected return (μ_p = w⊤μ) and volatility (σ_p = √(w⊤Σw)) are computed using the same RMT-cleaned covariance matrix as the main optimizer.
Sharpe colour axis
\[\text{Sharpe}_p = \frac{\mu_p - r_f}{\sigma_p}\]
Each point on the scatter chart is coloured by its Sharpe ratio. The maximum-Sharpe portfolio (tangency portfolio) appears at the rightmost tip of the upper envelope. The minimum-variance portfolio sits at the leftmost point of the frontier.

Interactive Metrics

MetricFormulaNotes
Sharpe(μ − r_f) / σUses RMT covariance
Sortino(μ − r_f) / σ_downσ_down = downside deviation × √252
BetaΣ wᵢ βᵢWeighted sum of individual betas vs SPY
QualityΣ wᵢ qᵢWeighted quality score (0–1)