Skip to content

Latest commit

 

History

History
293 lines (206 loc) · 9.02 KB

File metadata and controls

293 lines (206 loc) · 9.02 KB

Module guide

A short tour of every module in MeridianAlgo. Each section lists what the module is for, the main names it exports, whether it needs an optional extra, and a snippet that runs against the real API. Every snippet here matches the tested code, the same code used in the README and verified in TEST_RESULTS.md.

The base install (pip install meridianalgo) covers everything below except the few items marked with an extra. Install extras with pip install meridianalgo[ml] and friends. See installation.md for the full list.

portfolio

Portfolio construction and position sizing. Mean variance, hierarchical risk parity, risk parity, Black Litterman, the Kelly criterion, and CPPI portfolio insurance.

Exports MeanVariance, HierarchicalRiskParity, RiskParity, BlackLitterman, KellyCriterion, CPPI, TimeInvariantCPPI.

Each optimizer takes annualized expected returns as a Series and a covariance DataFrame, and returns an OptimizationResult with weights, expected_return, volatility, sharpe_ratio, and a success flag.

from meridianalgo import MeanVariance, HierarchicalRiskParity

expected_returns = returns.mean() * 252
covariance = returns.cov() * 252

max_sharpe = MeanVariance().optimize(expected_returns, covariance, objective="max_sharpe")
hrp = HierarchicalRiskParity().optimize(expected_returns, covariance, returns_data=returns)
print(max_sharpe.weights.sort_values(ascending=False))

risk

Value at risk, conditional value at risk, stress testing, risk budgeting, and scenario analysis.

Exports RiskAnalyzer, VaRCalculator, CVaRCalculator, StressTesting, RiskBudgeting, ScenarioAnalyzer, CorrelationScenario.

from meridianalgo import RiskAnalyzer

risk = RiskAnalyzer(portfolio_returns)
var_95 = risk.value_at_risk(confidence=0.95, method="historical")
cvar_95 = risk.conditional_var(confidence=0.95)
print(f"VaR 95 {var_95:.2%}, CVaR 95 {cvar_95:.2%}")

credit

Credit risk modeling. The Merton structural model, credit default swaps, the Z spread, and portfolio expected loss.

Exports MertonModel, CreditDefaultSwap, CreditRiskAnalyzer, ZSpreadCalculator.

from meridianalgo import MertonModel

model = MertonModel(
    equity_value=500e6, equity_volatility=0.35,
    debt_face_value=800e6, time_to_maturity=1.0, risk_free_rate=0.05,
)
result = model.calibrate()
print(f"Default probability {result['default_probability']:.2%}")

volatility

Volatility estimation and forecasting. Realized volatility with five estimators, GARCH family models, the term structure, and regime detection.

Exports GARCHModel, RealizedVolatility, VolatilityForecaster, VolatilityTermStructure, VolatilityRegimeDetector.

RealizedVolatility accepts OHLCV columns in any capitalization. Maximum likelihood GARCH fitting through the arch package needs the volatility extra, the built in estimators do not.

from meridianalgo import RealizedVolatility

rv = RealizedVolatility(ohlcv)
est = rv.all_estimators(window=21)
print(est[["close_to_close_vol", "parkinson_vol", "yang_zhang_vol"]].iloc[-1])

monte_carlo

Path simulation and Monte Carlo option pricing. Geometric Brownian motion, Heston stochastic volatility, jump diffusion, the CIR short rate model, and variance reduction.

Exports GeometricBrownianMotion, HestonModel, JumpDiffusionModel, CIRModel, MonteCarloEngine, QuasiRandomSampler.

from meridianalgo import GeometricBrownianMotion

gbm = GeometricBrownianMotion(mu=0.08, sigma=0.20)
res = gbm.simulate(S0=100, T=1.0, n_paths=100_000, n_steps=252, antithetic=True)
print(f"Mean {res.mean:.2f}, 5th pct {res.percentile_5:.2f}")

derivatives

Options pricing and the greeks. Black Scholes, implied volatility, the greeks, option chains, and a Monte Carlo pricer.

Exports BlackScholes, GreeksCalculator, ImpliedVolatility, OptionChain, MonteCarloPricer.

from meridianalgo import BlackScholes, ImpliedVolatility

call = BlackScholes(S=100, K=105, T=0.25, r=0.05, sigma=0.20, option_type="call")
print(f"Call {call['price']:.4f}, delta {call['delta']:.4f}")
iv = ImpliedVolatility(market_price=3.50, S=100, K=105, T=0.25, r=0.05, option_type="call")
print(f"Implied volatility {iv:.4f}")

fixed_income

Bond pricing and the yield curve. Price, duration, modified duration, curve fitting, and forward rates.

Exports BondPricer, YieldCurve, CreditSpreadAnalyzer.

from meridianalgo import BondPricer

bond = BondPricer().price_bond(
    face_value=1000, coupon_rate=0.05, yield_to_maturity=0.06,
    years_to_maturity=10, frequency=2,
)
print(f"Price {bond['price']:.4f}, duration {bond['duration']:.4f}")

analytics

Performance measurement and benchmark attribution. Around 28 metrics, active metrics against a benchmark, active share, and Brinson attribution.

Exports PerformanceAnalyzer, BenchmarkAnalytics, ActiveShare, BrinsonAttribution.

from meridianalgo import PerformanceAnalyzer

analyzer = PerformanceAnalyzer(portfolio_returns, benchmark=spy_returns, risk_free_rate=0.05)
metrics = analyzer.calculate_all_metrics()

metrics

Top level one call helpers built on the analytics module, no analyzer to construct first.

Exports summary_stats, tearsheet, compare, rolling_sharpe, rolling_volatility, rolling_sortino, rolling_drawdown, rolling_beta.

import meridianalgo as ma

stats = ma.summary_stats(returns)
print(ma.tearsheet(returns))
table = ma.compare({"strategy": returns, "benchmark": returns * 0.8})

roll_sharpe = ma.rolling_sharpe(returns, window=63)
roll_vol = ma.rolling_volatility(returns, window=63)
roll_sortino = ma.rolling_sortino(returns, window=63)
roll_beta = ma.rolling_beta(returns, benchmark, window=63)
drawdown = ma.rolling_drawdown(returns)

The rolling helpers return a pandas Series aligned to the input, with NaN over the warmup window. rolling_drawdown uses the full history to date rather than a fixed window.

backtesting

An event driven backtesting engine. It processes market, signal, order, and fill events through a portfolio and order manager rather than a single run call.

Exports BacktestEngine, Backtest, Strategy, with Backtester as an alias for BacktestEngine.

from meridianalgo import BacktestEngine

engine = BacktestEngine(initial_capital=100_000, commission=0.001, slippage=0.0005)
metrics = engine.get_performance_metrics()

ml

Machine learning for time series. LSTM and GRU predictors, walk forward cross validation, and feature engineering. Needs the ml extra.

Exports LSTMPredictor, ModelTrainer, ModelSelector, TimeSeriesCV, WalkForwardOptimizer, WalkForwardValidator, prepare_data_for_lstm, with ModelValidator as an alias for WalkForwardValidator.

from meridianalgo.ml import FeatureEngineer, WalkForwardValidator

features = FeatureEngineer().create_features(
    prices, features=["returns", "rsi", "macd", "volume_ratio", "volatility", "momentum"],
)

execution

Order execution schedulers. They are built with the order size and a time window, then driven slice by slice as the market moves.

Exports VWAP, TWAP, POV, ImplementationShortfall.

from meridianalgo import VWAP

vwap = VWAP(total_quantity=10_000, start_time="09:30", end_time="16:00")
slice_order = vwap.execute_slice(
    current_time=now, market_volume=500_000, market_price=100.0, max_participation=0.1,
)

strategies

Ready made trading strategies. Momentum, RSI mean reversion, MACD crossover, pairs trading, and Bollinger Bands.

Exports MomentumStrategy, RSIMeanReversion, MACDCrossover, PairsTrading, BollingerBandsStrategy.

quant

Statistical arbitrage and market microstructure. The z score helper runs on the base install, the cointegration test relies on statsmodels through the ml extra.

Exports StatisticalArbitrage at the top level.

import meridianalgo as ma

stat_arb = ma.StatisticalArbitrage(prices)
zscore = stat_arb.calculate_zscore(window=21)

signals

More than forty technical indicators as plain functions on numpy and pandas. No extras needed.

Exports RSI, MACD, BollingerBands, ATR, SMA, EMA, and many more, all available at the top level.

import meridianalgo as ma

rsi = ma.RSI(prices, period=14)
upper, mid, lower = ma.BollingerBands(prices, period=20)
atr = ma.ATR(high, low, close, period=14)

core

Core primitives shared across the package. Returns, drawdowns, Sharpe, Sortino, Calmar, expected shortfall, and a market data fetcher.

Exports calculate_returns, calculate_metrics, calculate_sharpe_ratio, calculate_sortino_ratio, calculate_calmar_ratio, calculate_max_drawdown, calculate_expected_shortfall, get_market_data, TimeSeriesAnalyzer.

Checking what is available

Every module registers itself at import time, so you can see exactly what loaded with the bundle you installed.

import meridianalgo as ma

print(ma.ModuleRegistry.status())          # dict of module name to True or False
print(ma.ModuleRegistry.is_available("ml"))