Skip to content

Latest commit

 

History

History
160 lines (111 loc) · 5.12 KB

File metadata and controls

160 lines (111 loc) · 5.12 KB

Quick Start Guide

Get up and running with MeridianAlgo in minutes. Every snippet here matches the live API.

Installation

pip install meridianalgo

# Verify installation
python -c "import meridianalgo; print(meridianalgo.__version__)"

Requires Python 3.10 or newer. For machine learning, optimization, or volatility extras, install the matching group. See installation.md for the full list.

pip install "meridianalgo[ml]"

From prices to returns

Most of the library takes a return series. These helpers get you there and back, and work out the periodicity of your index for you.

import meridianalgo as ma

returns = ma.to_returns(prices)              # method="log" for log returns
wealth = ma.to_prices(returns, initial=100)  # compound back into a path

ma.infer_periods_per_year(returns)           # 252 for daily, 12 for monthly
ma.annualize_return(returns)                 # CAGR
ma.annualize_volatility(returns)

monthly = ma.resample_returns(returns, "ME")
print(ma.drawdown_table(returns, top=5))     # deepest drawdowns, one row each

Top level metrics

The fastest way in is the set of convenience metrics that take a return series and hand back a number.

import meridianalgo as ma

sharpe = ma.calculate_sharpe_ratio(returns)
sortino = ma.calculate_sortino_ratio(returns)
calmar = ma.calculate_calmar_ratio(returns)
max_dd = ma.calculate_max_drawdown(returns)
cvar_95 = ma.calculate_expected_shortfall(returns)

# One call summary of around 28 metrics plus a formatted text report
stats = ma.summary_stats(returns)
print(ma.tearsheet(returns))

Technical indicators

More than forty indicators ship as plain functions on numpy and pandas. They need no extras and run in the base install.

import meridianalgo as ma

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

Portfolio optimization

Each optimizer takes expected returns as a pandas Series and a covariance matrix as a pandas DataFrame. Annualize both before you pass them in.

from meridianalgo import MeanVariance, HierarchicalRiskParity, RiskParity, BlackLitterman

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

max_sharpe = MeanVariance().optimize(expected_returns, covariance, objective="max_sharpe")
min_vol = MeanVariance().optimize(expected_returns, covariance, objective="min_volatility")
hrp = HierarchicalRiskParity().optimize(expected_returns, covariance, returns_data=returns)
rp = RiskParity().optimize(expected_returns, covariance)
bl = BlackLitterman().optimize(expected_returns, covariance)

print(max_sharpe.weights.sort_values(ascending=False))
print(f"Max sharpe ratio {max_sharpe.sharpe_ratio:.4f}")

Each call returns an OptimizationResult with weights, expected_return, volatility, sharpe_ratio, and a success flag.

Risk analysis

from meridianalgo import RiskAnalyzer

risk = RiskAnalyzer(portfolio_returns)
var_95 = risk.value_at_risk(confidence=0.95, method="historical")
var_99 = risk.value_at_risk(confidence=0.99, method="cornish_fisher")
cvar_95 = risk.conditional_var(confidence=0.95)

print(f"Historical VaR 95 percent {var_95:.2%}")
print(f"Cornish Fisher VaR 99 percent {var_99:.2%}")
print(f"CVaR 95 percent {cvar_95:.2%}")

Kelly criterion position sizing

from meridianalgo import KellyCriterion

kc = KellyCriterion(fraction=0.5)  # half kelly

f = kc.single_asset(win_prob=0.55, win_loss_ratio=1.0)
weights = kc.optimize(returns)
g = kc.growth_rate(expected_return=0.12, volatility=0.18)

print(f"Kelly fraction {f:.2%}")

Performance summary

from meridianalgo import PerformanceAnalyzer

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

Machine learning, requires the ml extra

The machine learning models need the ml extra. With it installed you get LSTM and GRU predictors, walk forward cross validation, and feature engineering.

from meridianalgo.ml import FeatureEngineer, WalkForwardValidator
from sklearn.ensemble import RandomForestClassifier

features = FeatureEngineer().create_features(
    prices, features=["returns", "rsi", "macd", "volume_ratio", "volatility", "momentum"],
)
labels = (returns.shift(-1) > 0).astype(int)

results = WalkForwardValidator().validate(
    features, labels,
    model=RandomForestClassifier(n_estimators=200, random_state=42),
    train_window=252, test_window=21,
)
print(f"Average accuracy {results['accuracy'].mean():.2%}")

Next steps

Getting help