Skip to content

About

To view our Python packages, run the command pip install meridianalgo in your terminal, or you can access our files here:

Topics

Resources

Code of conduct

Contributing

Security policy

Stars

2 stars

Watchers

0 watching

Forks

Repository files navigation

MeridianAlgo

PyPI version Python versions License CI Docs

MeridianAlgo is a Python library for quantitative finance. It has portfolio optimizers, risk models, option and bond pricing, a vectorized and an event driven backtester, volatility and credit models, Monte Carlo simulation, execution schedulers, and about forty technical indicators.

The core install needs only numpy, pandas, and scipy. Machine learning, convex solvers, and GARCH estimation are optional extras.

Install

pip install meridianalgo
pip install "meridianalgo[ml]"            # scikit-learn, torch, statsmodels, hmmlearn
pip install "meridianalgo[optimization]"  # cvxpy, cvxopt
pip install "meridianalgo[volatility]"    # arch, for maximum likelihood GARCH
pip install "meridianalgo[data]"          # lxml, beautifulsoup4, polygon-api-client
pip install "meridianalgo[distributed]"   # ray, dask
pip install "meridianalgo[all]"           # all of the above

Python 3.10 to 3.13 is supported.

Quick start

Every example below runs on a fresh install. They use the built in sample data generator so you can try things without downloading prices. Swap in your own DataFrame of prices (dates down the rows, one column per asset) when you are ready.

import meridianalgo as ma

prices = ma.sample_prices(n_assets=4, n_days=756, seed=1)  # simulated, not real data
returns = ma.to_returns(prices)

print(ma.annualize_return(returns))      # CAGR per asset
print(ma.annualize_volatility(returns))

portfolio = returns.mean(axis=1)         # equal weight, rebalanced daily
print(ma.tearsheet(portfolio))           # about 28 statistics as a text table
print(ma.drawdown_table(portfolio, top=3))

Backtest a strategy

backtest_weights takes a table of target weights and returns the equity curve, the weights actually held, turnover, and costs. Weights decided on day t are traded on day t + 1, so a signal cannot see the return it is trying to predict.

import meridianalgo as ma

prices = ma.sample_prices(n_assets=5, n_days=1260, seed=3)

# 12 month momentum, long the assets that went up, sized by inverse volatility
momentum = prices.pct_change(252)
risk = ma.inverse_volatility_weights(prices.pct_change(), window=63)
weights = ma.normalize_weights(risk.where(momentum > 0, 0.0), max_weight=0.4)

result = ma.backtest_weights(prices, weights, cost_bps=5, rebalance="ME")
print(result)
print(result.tearsheet())
print(result.drawdowns(top=3))

result.returns, result.equity, result.weights, result.turnover, and result.costs are plain pandas objects, so anything else in the library can take them as input. For order level simulation with fills and slippage, see BacktestEngine.

Position sizing helpers

import meridianalgo as ma

returns = ma.sample_returns(n_assets=6, n_days=500, seed=0)

ma.equal_weights(returns)                             # 1/n
ma.inverse_volatility_weights(returns)                # full sample, sums to 1
ma.normalize_weights(returns.mean(), long_only=True)  # scores to weights

cov = ma.shrinkage_covariance(returns, periods_per_year=252)  # Ledoit-Wolf
print(cov.attrs["shrinkage"])

strategy = returns.mean(axis=1)
leverage = ma.volatility_target(strategy, target=0.10, window=21)
scaled = strategy * leverage.shift(1)                 # run at about 10% volatility

Examples by topic

Return series utilities

import meridianalgo as ma

prices = ma.sample_prices(n_assets=2, seed=2)
returns = ma.to_returns(prices)                 # simple returns, first row dropped
log_returns = ma.to_returns(prices, method="log")
wealth = ma.to_prices(returns, initial=100.0)   # compound back into a path

ma.infer_periods_per_year(returns)              # 252, 52, 12, 4, or 1
ma.annualize_return(returns, geometric=False)   # scaled arithmetic mean
monthly = ma.resample_returns(returns, "ME")    # compounds within each month
excess = ma.excess_returns(returns, risk_free_rate=0.05)
joined = ma.align(returns["ASSET_1"], returns["ASSET_2"])

drawdown_table returns one row per drawdown, deepest first, with peak, valley, recovery, depth, length, and recovery_length. A drawdown that has not recovered by the end of the series has NaT for recovery.

Rolling metrics and comparisons

import meridianalgo as ma

returns = ma.sample_returns(n_assets=2, seed=5)
strategy, benchmark = returns["ASSET_1"], returns["ASSET_2"]

table = ma.compare({"strategy": strategy, "benchmark": benchmark})
roll_sharpe = ma.rolling_sharpe(strategy, window=63)
roll_vol = ma.rolling_volatility(strategy, window=63)
roll_beta = ma.rolling_beta(strategy, benchmark, window=63)
underwater = ma.rolling_drawdown(strategy)

Portfolio optimization

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

import meridianalgo as ma

returns = ma.sample_returns(n_assets=6, seed=4)
mu = returns.mean() * 252
cov = returns.cov() * 252

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

print(max_sharpe.weights.round(3))
print(f"max Sharpe portfolio: Sharpe {max_sharpe.sharpe_ratio:.2f}")
print(f"min variance portfolio: volatility {min_vol.volatility:.2%}")

Kelly criterion

import meridianalgo as ma

returns = ma.sample_returns(n_assets=3, seed=6)
kc = ma.KellyCriterion(fraction=0.5)  # half Kelly

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

Value at risk and stress scenarios

import numpy as np
import pandas as pd
import meridianalgo as ma

returns = ma.sample_returns(n_assets=3, seed=7)
portfolio = returns.mean(axis=1)

risk = ma.RiskAnalyzer(portfolio)
print(risk.value_at_risk(confidence=0.95, method="historical"))
print(risk.value_at_risk(confidence=0.99, method="cornish_fisher"))
print(risk.conditional_var(confidence=0.95))

weights = pd.Series(1 / 3, index=returns.columns)
gen = ma.CorrelationScenario(
    returns.mean(), returns.corr(), returns.std(), weights
)
scenarios = gen.generate(n_scenarios=50_000, stress_correlation=True, stress_factor=0.5)
print(scenarios["var_99"])

Credit risk

import pandas as pd
import meridianalgo as ma

merton = ma.MertonModel(
    equity_value=500e6, equity_volatility=0.35,
    debt_face_value=800e6, time_to_maturity=1.0, risk_free_rate=0.05,
)
fit = merton.calibrate()
print(fit["distance_to_default"], fit["default_probability"])

cds = ma.CreditDefaultSwap(hazard_rate=0.02, recovery_rate=0.40, maturity=5.0)
print(f"fair spread {cds.price().fair_spread * 1e4:.1f} bp")

exposures = pd.DataFrame({
    "pd": [0.010, 0.025, 0.050], "lgd": [0.45, 0.40, 0.60], "ead": [2e6, 1.5e6, 0.5e6],
})
print(ma.CreditRiskAnalyzer().portfolio_expected_loss(exposures)["total_el"])

z = ma.ZSpreadCalculator(
    cash_flows=[6, 6, 6, 6, 106], times=[1, 2, 3, 4, 5],
    risk_free_rates=[0.035, 0.038, 0.040, 0.042, 0.044],
)
print(f"z-spread {z.z_spread(market_price=97.5) * 1e4:.1f} bp")

Volatility

RealizedVolatility accepts OHLCV columns in any capitalization.

import meridianalgo as ma

bars = ma.sample_ohlcv(n_days=500, seed=8)
estimates = ma.RealizedVolatility(bars).all_estimators(window=21)
print(estimates[["close_to_close_vol", "parkinson_vol", "yang_zhang_vol"]].iloc[-1])

daily = bars["close"].pct_change().dropna()
term = ma.VolatilityTermStructure(daily)
term.build(horizons=[5, 21, 63, 126])
print(term.slope())
print(ma.VolatilityRegimeDetector(daily).classify().value_counts())

GARCH fitting by maximum likelihood needs the volatility extra:

fit = ma.GARCHModel(daily, model_type="garch", p=1, q=1).fit()
print(fit.persistence, fit.half_life)

Monte Carlo

import meridianalgo as ma

gbm = ma.GeometricBrownianMotion(mu=0.08, sigma=0.20)
paths = gbm.simulate(S0=100, T=1.0, n_paths=20_000, n_steps=252, antithetic=True)
print(paths.mean, paths.percentile_5, paths.percentile_95)

call = gbm.call_price(S0=100, K=105, T=0.25, r=0.05, n_paths=50_000)
print(call["price"], call["std_error"])

engine = ma.MonteCarloEngine(model="heston")
engine.configure(mu=0.05, v0=0.04, kappa=2.0, theta=0.04, xi=0.30, rho=-0.7)
engine.simulate(S0=100, T=1.0, n_paths=20_000)
print(engine.price_option(K=95, r=0.05, T=1.0, option_type="put")["price"])

HestonModel, JumpDiffusionModel, and CIRModel can also be used directly.

Portfolio insurance

import meridianalgo as ma

equity = ma.sample_returns(n_assets=1, seed=9).iloc[:, 0]

cppi = ma.CPPI(multiplier=3.0, floor_pct=0.80, safe_rate=0.04)
result = cppi.run(equity, initial_value=1_000_000)
print(result.total_return, result.max_drawdown, result.floor_breaches)

tipp = ma.TimeInvariantCPPI(multiplier=3.0, floor_pct=0.80)  # floor ratchets up
print(tipp.run(equity, initial_value=1_000_000).total_return)

Options

import meridianalgo as ma

call = ma.BlackScholes(S=100, K=105, T=0.25, r=0.05, sigma=0.20, option_type="call")
print(call["price"], call["delta"], call["vega"])

iv = ma.ImpliedVolatility(market_price=3.50, S=100, K=105, T=0.25, r=0.05, option_type="call")
print(iv)

Fixed income

import meridianalgo as ma

bond = ma.BondPricer().price_bond(
    face_value=1000, coupon_rate=0.05, yield_to_maturity=0.06,
    years_to_maturity=10, frequency=2,
)
print(bond["price"], bond["duration"], bond["modified_duration"])

curve = ma.YieldCurve()
for maturity, rate in [(0.25, 0.04), (1, 0.045), (2, 0.048), (5, 0.052), (10, 0.055), (30, 0.058)]:
    curve.add_point(maturity, rate)
curve.build_curve(method="nelson_siegel")
print(curve.get_yield(7), curve.get_forward_rate(5, 10))

Benchmark analytics

import pandas as pd
import meridianalgo as ma

returns = ma.sample_returns(n_assets=2, seed=10)
port, bench = returns["ASSET_1"], returns["ASSET_2"]

m = ma.BenchmarkAnalytics(portfolio_returns=port, benchmark_returns=bench).active_metrics()
print(m.tracking_error, m.information_ratio, m.beta)

held = pd.Series({"A": 0.5, "B": 0.3, "C": 0.2})
index = pd.Series({"A": 0.4, "B": 0.4, "D": 0.2})
share = ma.ActiveShare.compute(held, index)
print(share, ma.ActiveShare.categorize(share))

Technical indicators

import meridianalgo as ma

bars = ma.sample_ohlcv(n_days=300, seed=11)
close = bars["close"]

rsi = ma.RSI(close, period=14)
macd = ma.MACD(close)
upper, middle, lower = ma.BollingerBands(close, period=20)
atr = ma.ATR(bars["high"], bars["low"], close, period=14)

Execution schedules

import meridianalgo as ma

twap = ma.TWAP(total_quantity=10_000, duration_minutes=60, slice_interval_minutes=5)
vwap = ma.VWAP(total_quantity=10_000, start_time="09:30", end_time="16:00")
pov = ma.POV(total_quantity=10_000, target_pov=0.10)

Machine learning

Needs the ml extra.

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

features = FeatureEngineer().create_features(prices, features=["returns", "rsi", "macd", "volatility"])
labels = (returns.shift(-1) > 0).astype(int)
scores = WalkForwardValidator().validate(
    features, labels, model=RandomForestClassifier(n_estimators=200, random_state=0),
    train_window=252, test_window=21,
)

More examples for each module are in docs/MODULES.md.

Optional dependencies

If you call something whose extra is missing, you get a MissingDependencyError (a subclass of ImportError) that tells you which extra to install:

MissingDependencyError: This feature needs the optional dependency 'statsmodels',
which is not installed. Install it with pip install meridianalgo[ml]

To check first:

from meridianalgo.utils import has

if has("statsmodels"):
    print("cointegration tests available")

import meridianalgo is lazy and takes about 0.3 seconds. It does not load torch, scikit-learn, or statsmodels until you use a feature that needs them.

Command line

meridianalgo version     # installed version
meridianalgo info        # which modules can be imported
meridianalgo versions    # Python and dependency versions, for bug reports
meridianalgo demo        # small portfolio optimization on sample data
meridianalgo metrics AAPL --period 2y   # metrics for a ticker (needs internet)

If your shell cannot find meridianalgo, use python -m meridianalgo instead.

Reporting bugs

Run meridianalgo versions (or python -c "import meridianalgo; meridianalgo.show_versions()") and paste the output into a new issue along with a short example that shows the problem.

Documentation

Contributing

Pull requests are welcome. CONTRIBUTING.md covers setup, tests, and how releases work.

License

MIT. See LICENSE.

Disclaimer

This is research software. It is not investment advice. Trading carries a real risk of loss and past performance does not predict future results.

About

To view our Python packages, run the command pip install meridianalgo in your terminal, or you can access our files here:

Topics

Resources

Code of conduct

Contributing

Security policy

Stars

2 stars

Watchers

0 watching

Forks

Releases

Packages

Used by

Contributors

Languages