Turn signals into weights, and compute performance metrics that are actually correct. TRIGGER - portfolio weights, allocation, rebalancing, mean-variance, Black-Litterman, risk parity, HRP, HERC, NCO, efficient frontier, covariance shrinkage or denoising, PyPortfolioOpt, riskfolio, skfolio, cvxportfolio; or computing Sharpe, Sortino, Calmar, CAGR, annualized volatility, max drawdown, VaR, CVaR, beta, alpha, a tearsheet, quantstats, pyfolio, empyrical, ffn, or performance attribution. Load before quoting any performance number: popular libraries disagree on identical input, one silently discards the risk-free rate you pass it, and an absurdly negative Sharpe has one known cause. SKIP for the optimizer's own mathematics and what it does to estimation error (portfolio-optimizers), and for whether the result survives multiple testing (backtest-validation).
Ships in fin-core. Installing the plugin adds it to Claude Code.
What the skill costs in Claude's context, stage by stage
Name and description: Claude knows it exists.
SKILL.md joins the conversation and stays.
Read when SKILL.md points to them; scripts run unread.
Two independent problems live here. §1 picks an optimizer. §2 is the one you cannot skip: the same return series produces different Sharpe ratios in different libraries, and one popular function silently ignores an argument you passed it.
| Task | Use | Not |
|---|---|---|
| Textbook mean-variance / Black-Litterman, small universe, prototype | PyPortfolioOpt | — |
| Broadest risk-measure menu (26 convex: CVaR, CDaR, EVaR, RLVaR, OWA), robust worst-case, integer constraints | Riskfolio-Lib | PyPortfolioOpt — too few risk measures |
sklearn Pipeline / GridSearchCV / cross-validation over portfolio models; entropy pooling; vine copulas | skfolio | Riskfolio-Lib — no sklearn API |
| Multi-period, transaction-cost-aware simulation of the trading policy | cvxportfolio — 🚨 GPL-3.0 | PyPortfolioOpt — single-period only |
| HRP | Riskfolio-Lib / skfolio / PyPortfolioOpt HRPOpt | 🚨 mlfinlab — proprietary, delisted from PyPI |
| HERC, NCO, Schur complementary | Riskfolio-Lib or skfolio only | PyPortfolioOpt does not implement these |
| Marcenko–Pastur denoising / detoning | Riskfolio-Lib denoiseCov, skfolio Denoise/Detone | 🚨 PyPortfolioOpt has neither — its CovarianceShrinkage is Ledoit-Wolf, a different estimator |
| Deep-learning end-to-end allocation | deepdow — ⚠️ dormant since Jan 2024 | — |
Gotchas that bite immediately:
HRPOpt(returns=...) takes a RETURNS matrix. Passing prices runs silently and produces
garbage.CombinatorialPurgedCV.split() yields (train, [test_0, test_1, ...]) — multiple
test folds per split, not sklearn's 2-tuple contract. And purged_size/embargo_size are counted
in observations, not time — with dollar/volume bars a fixed count is a wildly varying span.references/_solver-layer.md first if you hit a
SolverError.Verified by executing the libraries (quantstats 0.0.81, empyrical-reloaded 0.5.12, ffn 1.1.5, pandas 3.0.5) on the same seeded 1,260-day return series — not inferred from docs.
rf=0)| Metric | quantstats | empyrical | ffn | Hand-computed |
|---|---|---|---|---|
| Sharpe | 1.279985 | 1.279985 | 1.273744 ¹ | 1.279985 (ddof=1) |
| Sortino | 1.955876 | 1.955876 | — | 1.955876 |
| Max drawdown | −0.226178 | −0.226178 | −0.226178 | −0.226178 |
| Annual volatility | 0.188495 | 0.188495 | 0.188554 ¹ | 0.188495 (ddof=1) |
| CAGR | 0.250378 | 0.250378 | 0.258761 | 0.250378 (len/252) / 0.260442 (calendar) |
| VaR 95% | −0.018574 | −0.018111 | — | −0.018111 (historical) / −0.018574 (Gaussian) |
| CVaR 95% | −0.023346 | −0.022786 | — | −0.022786 (historical tail mean) |
¹ ffn derives returns from prices via pct_change(), losing the first observation (n=1259 vs 1260).
The CAGR and VaR/CVaR rows are real, systematic disagreements, not rounding. quantstats' VaR is Gaussian; empyrical's is historical. If your returns have fat tails — and they do — these are different risk numbers. Know which one you are quoting.
Libraries interpret the same rf number in incompatible units:
| Library | Parameter | Units it expects |
|---|---|---|
| quantstats | rf= | ANNUAL (converts geometrically) |
| empyrical / pyfolio-reloaded | risk_free= | 🔴 PER-PERIOD (daily!) — subtracted raw, no conversion |
| ffn | rf= | ANNUAL |
| PyPortfolioOpt | risk_free_rate= | ANNUAL |
empyrical's docstring is explicit — "risk_free : int, float — Constant daily risk-free return" —
but the parameter is named risk_free, defaults to 0.0, and sits next to period='daily', so
almost everyone passes an annual rate. Measured:
qs.stats.sharpe(r, rf=0.05) # 1.021119 correct: 5% annual
ep.sharpe_ratio(r, risk_free=0.05) # -65.565185 ← subtracts 5% PER DAY
ep.sharpe_ratio(r, risk_free=(1.05**(1/252)-1)) # 1.021119 correct usage
🔴 A wildly negative Sharpe is the diagnostic signature of this bug. If you ever see one out of empyrical or pyfolio, check the units before debugging anything else.
quantstats.stats.cagr() silently ignores rfSignature is cagr(returns, rf=0.0, compounded=True, periods=252) and the docstring says it
computes the CAGR "of excess returns". The parameter has no effect. Root cause in
quantstats/utils.py::_prepare_returns — it dispatches on the caller's function name:
function = inspect.stack()[1][3]
unnecessary_function_calls = ["_prepare_benchmark", "cagr", "gain_to_pain_ratio", "rolling_volatility"]
if function not in unnecessary_function_calls:
if rf > 0:
return to_excess_returns(data, rf, nperiods)
"cagr" is on the exclusion list, so rf is accepted and discarded. Compute excess-return CAGR
yourself. The same exclusion list silently disables rf for gain_to_pain_ratio and
rolling_volatility.
ffn (it infers annualization from the
index) plus a hand-rolled check, not quantstats defaults.252 is not universal — crypto is 365, and a strategy that trades weekly is not 252.arch (Kevin Sheppard) for GARCH/EGARCH/HAR. It is the reference
implementation and is actively maintained.For "is this result real after I tried many things" — Deflated Sharpe, PBO, White's Reality Check,
Hansen's SPA, StepM, Model Confidence Set (all in arch.bootstrap) — go to
backtest-validation. Do not settle that question with a tearsheet.
⚠️ No mature Brinson-attribution library exists in Python. Single-period Brinson-Fachler is
~20 lines and is included in references/_attribution.md; multi-period linking (Carino, Menchero)
you must implement. Factor attribution is better served by regressing against explicit factor
returns — see factor-and-timeseries-research.
references/<library>.md — version, licence, what it implements that others don't, exact
signatures, and its measured quirks. references/_solver-layer.md covers cvxpy and solver choice.
grep -ril "risk_free\|annualiz" plugins/fin-core/skills/portfolio-and-risk/references/
The optional fin-libraries plugin carries a dedicated skill for each library below. Load one
only after this skill has told you which library you want:
lib-pyportfolioopt — pyportfoliooptlib-quantstats — quantstatslib-riskfolio — riskfoliolib-skfolio — skfolioreferences/_attribution.md (opens in a new tab)references/_solver-layer.md (opens in a new tab)references/analytics-libraries.md (opens in a new tab)references/cvxportfolio.md (opens in a new tab)references/optimizers.md (opens in a new tab)references/pyportfolioopt.md (opens in a new tab)references/risk-measures.md (opens in a new tab)references/riskfolio-lib.md (opens in a new tab)references/skfolio.md (opens in a new tab)scripts/brinson_attribution.py (opens in a new tab)What SKILL.md sets; muted values are Claude Code's defaults
Other plugins' skills for the same job
/fin-core:portfolio-and-riskfrom fin-core
npx claudepluginhub howard-lynn-ye/fin-rsi --plugin fin-core18 skills in this plugin
/backtesting-enginesChoose a backtesting engine and know what it silently models wrong. TRIGGER - "backtest this", backtest a crossover or a moving-average strategy, simulate a strategy, walk-forward, parameter sweep, "test this trading idea"; comparing or choosing backtest frameworks; vectorbt, backtesting.py, backtrader, zipline, PyBroker, bt, nautilus_trader, LEAN, freqtrade, jesse; how an engine models fills, slippage, commissions; what slippage to assume, partial fills, margin, shorting or delistings; taking a strategy from backtest to live; "my backtest looks too good"; "works in backtest but loses money live". Several popular engines fill at the signal's own bar close by default. SKIP for judging whether a finished result is real (backtest-validation) for A-share rules (china-trading-stack), for crypto funding and perpetuals (crypto-data-and-execution), for options, which need assignment and settlement no engine here models (options-backtesting), and for measuring fills you already have (execution-cost-analysis)./backtest-overfittingDecide whether an edge that passed every mechanical check is still just the best of N tries. TRIGGER - PBO, probability of backtest overfitting, CSCV, combinatorially symmetric cross validation, logit of the out-of-sample rank; minimum backtest length, MinBTL, "how much history do I need", "how many parameter sets can I try on N years of data"; a grid search, Optuna or AutoML picked a winner and it decayed; "in-sample Sharpe 2, live Sharpe 0", "the best parameter set stopped working", "is this peak on my parameter surface real"; pypbo, RiskLabAI CSCV. SKIP for the deflated and probabilistic Sharpe ratios, the trial ledger and SPA/StepM/MCS against a benchmark (backtest-validation); for family-wise error and false-discovery control over a whole research programme (multiple-testing-ledger); for the purged and combinatorial CV splitters themselves (lib-purgedcv); for the mechanical leakage gates that come first (research-integrity-guards); and for regime coverage of the test window (regime-detection)./backtest-validationDecide whether a result survives the number of things you tried. TRIGGER - "I tried N strategies or parameters and the best one..."; overfitting, p-hacking, data snooping, "is this result real", "is this statistically significant"; deflated Sharpe, DSR, PSR, the trial ledger; White's Reality Check, Hansen SPA, StepM, model confidence set, arch.bootstrap; purged or combinatorial cross-validation, embargo, walk-forward, "cross validation on time series without leaking"; a grid search, hyperopt or AutoML picked a winner; triple-barrier labeling, meta-labeling, fractional differentiation, mlfinlab. Load whenever a Sharpe ratio is about to be offered as evidence for trading. SKIP for plain performance metrics - Sharpe, Sortino, CAGR, drawdown (portfolio-and-risk); for PBO, CSCV and the minimum backtest length (backtest-overfitting); and for Bonferroni, Holm, Benjamini-Hochberg or Benjamini-Yekutieli over a ledger of trials (multiple-testing-ledger). The deflated and probabilistic Sharpe ratios are computed HERE./broker-execution-apisConnect to a broker and place orders without accidentally trading live money. TRIGGER - connect to Interactive Brokers, TWS, IB Gateway, ib_async, ib_insync, ibapi, Alpaca, Schwab, schwab-py, Tastytrade, Tradier or Robinhood; place, modify or cancel an order; read positions or balances; set up paper trading; order types, time-in-force, bracket or OCO orders, client order ID; FIX, quickfix, simplefix; "make sure I don't send a live order"; a broker connection being refused. Load before any code that can transmit an order. SKIP for crypto exchanges and ccxt (crypto-data-and-execution), and for vnpy, CTP, QMT or any Chinese broker gateway (china-trading-stack). This skill answers TWS/Gateway port and connection failures on its own - the fin-libraries deep dive is optional and most installs will not have it./combining-data-sourcesCombine information of DIFFERENT kinds into one research view whose every number can be traced back to what was knowable when. TRIGGER - joining prices to fundamentals, earnings or a macro series; building a signal from a filing plus a price; merging two vendors into one series; "which vendor do I trust"; combine_first / fillna / bfill across sources; assembling a company dossier, profile or research view from several places; a field that must carry its provenance; "when did this number become knowable"; period_end vs filed vs available; a ticker that changed company mid-sample; filling a ResultCard's data block. SKIP for the mechanics of ONE as-of join (safe_asof, in market-data-engineering); for reconciling two price series from two vendors (reconcile_sources, in market-data-sourcing); for auditing a finished backtest (research-integrity-guards); and for resolving a ticker to a permanent id (security-master-and-symbology)./derivatives-pricingChoose a derivatives pricing library and get its Greek units and conventions right. TRIGGER - option pricing, implied volatility, IV, Greeks, delta, gamma, vega, theta, rho; which pricing library, exotics coverage; QuantLib, vollib, py_vollib, financepy, rateslib, optionlab; option chains. Greek scaling differs by 100x and 365x between the three common libraries, and one popular fixed-income package is not open source. SKIP for option lifecycle events - assignment, pin risk, expiry - live or backtested, and for historical option chains and vendors (options-backtesting). SKIP for the models themselves - implementing one (option-pricing-models), fitting a smile (implied-vol-surface), building a curve (term-structure-models), bond accrued and the 30/360 family (bond-conventions-and-accrued), duration and DV01 (duration-convexity-and-dv01), and projection-versus-discount choice on a swap (ois-discounting-and-multi-curve).