Skip to content

pymetrix-finance

A plugin: a separate package

pymetrix-finance is a first-party plugin, installed on its own:

python -m pip install --pre pymetrix-finance

Financial econometrics for pymetrix: risk and backtests, multivariate GARCH, copulas, portfolios and strategies, options and volatility surfaces, yield curves, credit.

The names pymetrix_finance exports (its __all__), with their full documentation. Import them from the plugin: from pymetrix_finance import .... The plugin's README says more.

Public names

abnormal_returns

abnormal_returns(data: Dataset, events: Any, market: str | None = None, factors: Sequence[str] | None = None, estimation: tuple[int, int] = (-250, -11), window: tuple[int, int] = (-10, 10), car_window: tuple[int, int] | None = None) -> AbnormalReturns

Abnormal returns of assets around their events (a mapping of asset to dates, or (asset, date) pairs), against the market model, a factor model or the mean return, with the cross-sectional, Patell, BMP and rank tests over car_window (default: the whole event window).

AbnormalReturns dataclass

AbnormalReturns(events: tuple[tuple[str, str], ...], model: str, ar: DataFrame, sar: DataFrame, est_obs: ndarray, k: int = 1, ranks: DataFrame = None, car_window: tuple[int, int] = (0, 0), provenance: Any = None)

Abnormal returns around events, their averages and the tests that they are zero.

car

car(window: tuple[int, int] | None = None) -> Series

Each event's cumulative abnormal return over window (default: the tested window).

average

average() -> DataFrame

AAR and CAAR by relative period, with the AAR's cross-sectional t statistic.

statistics

statistics(window: tuple[int, int] | None = None) -> dict[str, tuple[float, float]]

Each test's statistic and two-sided p-value for the CAR over window.

backtest_strategy

backtest_strategy(data: Dataset, assets: Sequence[str], strategies: Sequence[str] = ('equal_weight', 'min_variance', 'risk_parity'), window: int = 60, rebalance: int = 1, cost: float = 0.0, rf: str | float = 0.0, long_only: bool = True, kind: Literal['simple', 'log'] = 'simple', periods_per_year: int | None = None) -> StrategyBacktest

Out-of-sample returns of rebalanced portfolio strategies (equal weight, inverse volatility, minimum variance, maximum Sharpe, risk parity), each re-estimated every rebalance periods on the window before, net of cost per unit of turnover.

black_litterman module-attribute

black_litterman: BlackLittermanPosterior = api('finance:black_litterman')(black_litterman)

The Black-Litterman posterior mean and covariance of returns, from market weights and views views @ mu = q. cov is the returns' covariance: an array, a DataFrame or a pymetrix table (data.cov([...])), whose names label the assets. A BlackLittermanPosterior (prior, posterior, views, optimal weights), which unpacks as mu, sigma = black_litterman(...).

BlackLittermanPosterior dataclass

BlackLittermanPosterior(assets: tuple[str, ...], prior: Series, posterior_mean: Series, posterior_cov: DataFrame, cov: DataFrame, market_weights: Series, views: DataFrame | None = None, q: Series | None = None, omega: DataFrame | None = None, omega_default: bool = True, delta: float = 2.5, tau: float = 0.05, provenance: Any = None)

Black-Litterman expected returns: the prior implied by the market weights, the views, and the posterior. Unpacks as mu, sigma (the posterior mean and covariance, arrays in the assets' order), as the function's tuple did.

confidences property

confidences: Series | None

Each view's variance (the diagonal of omega): smaller is more confident.

weights property

weights: Series

The unconstrained mean-variance weights for the posterior, (delta Sigma_post)^-1 mu_post.

table_frame

table_frame() -> DataFrame

By asset: market weight, prior (implied) return, posterior return, their difference, posterior standard deviation and optimal weight.

views_frame

views_frame() -> DataFrame

By view: its value q, variance (omega's diagonal) and standard deviation, and the view's value under the prior (P pi) and the posterior (P mu).

bond_measures module-attribute

bond_measures: dict[str, float] = api('finance:bond_measures')(bond_measures)

Price, continuous yield, Macaulay duration and convexity, and the Fisher-Weil duration, of cash flows at times discounted at the zero rates zeros (fractions); arrays or lists, one entry per cash flow.

cds_curve

cds_curve(maturities: Sequence[float], spreads: Sequence[float], recovery: float = 0.4, rate: float = 0.0) -> CDSCurve

Default intensities bootstrapped from CDS spreads (fractions a year: 0.01 for 100 basis points) at maturities (years, in quarters), with recovery and a flat continuously compounded rate.

CDSCurve dataclass

CDSCurve(maturities: ndarray, spreads: ndarray, hazards: ndarray, recovery: float, rate: float, provenance: Any = None)

Default intensities bootstrapped from a CDS curve, and the survival and default probabilities they imply.

compare_copulas

compare_copulas(data: Dataset, series: Sequence[str], families: Sequence[str] | None = None, garch: bool = False, dist: Literal['normal', 't'] | None = None, margins: Literal['empirical', 'normal', 't', 'skewt'] = 'empirical', method: Literal['ml', 'itau', 'joint'] = 'ml', gof: bool = False, draws: int = 100, seed: int = 0, bootstrap: Literal['parametric', 'multiplier'] = 'parametric') -> Table

Copula families fitted to the same returns and margins, side by side: log likelihood, AIC, BIC, Kendall's tau, tail dependence and, with gof, the Cramer-von Mises test (parametric or bootstrap="multiplier"). families defaults to every family that fits the number of series (those for negative dependence when Kendall's tau is negative; BB6, BB8, Tawn and the rotated two-parameter families only when listed).

copula

copula(data: Dataset, series: Sequence[str], family: Family = 't', garch: bool = False, dist: Literal['normal', 't'] | None = None, margins: Literal['empirical', 'normal', 't', 'skewt'] = 'empirical', method: Literal['ml', 'itau', 'joint'] = 'ml', gof: bool = False, draws: int = 100, seed: int = 0, bootstrap: Literal['parametric', 'multiplier'] = 'parametric') -> FittedCopula

A copula of the returns series (Gaussian, t, Clayton, Gumbel, Frank or Joe for any number; BB1, BB7 and the rotated families for two), of the returns or, with garch, of each one's GARCH(1,1) standardised residuals; margins by ranks or fitted (normal, t, Hansen's skewed t), method maximum likelihood (IFM with fitted margins), Kendall's tau or joint; gof adds the Cramer-von Mises test (draws samples of the parametric bootstrap, or of Kojadinovic and Yan's multiplier bootstrap with bootstrap="multiplier").

dcc_copula

dcc_copula(data: Dataset, series: Sequence[str], family: Literal['gaussian', 't'] = 'gaussian', garch: bool = False, dist: Literal['normal', 't'] | None = None, margins: Literal['empirical', 'normal', 't', 'skewt'] = 'empirical') -> FittedDCCCopula

A time-varying Gaussian or t copula of two or more returns whose correlation matrix follows Engle's (2002) DCC recursion on the copula's scores (the normal or t quantiles of the uniforms), by maximum likelihood on the margins' uniforms (ranks, fitted, or with garch the standardised residuals), with the filtered correlations, forecasts, forward simulation and portfolio VaR.

dynamic_nelson_siegel

dynamic_nelson_siegel(data: Dataset, series: Sequence[str], maturities: Sequence[float], var: Literal['diagonal', 'full'] = 'diagonal', maxiter: int = 2000) -> FittedDNS

The dynamic Nelson-Siegel model of the yields series at maturities (years): the decay, the factors' VAR(1) and the measurement errors by maximum likelihood with the Kalman filter, starting from the two-step fit.

factor_model

factor_model(data: Dataset, assets: Sequence[str], factors: Sequence[str], rf: str | None = None) -> FactorModel

Each asset's excess return (over rf, if given) on the factors, with Newey-West errors, and the GRS test that every alpha is zero.

FactorModel dataclass

FactorModel(assets: tuple[str, ...], factors: tuple[str, ...], fits: dict[str, Any], excess: DataFrame, factor_values: DataFrame, test: tuple[float, float, int, int] = (nan, nan, 0, 0), provenance: Any = None)

Time-series factor regressions of several assets, with the GRS test of their alphas.

rolling_betas

rolling_betas(window: int = 60) -> DataFrame

Each asset's betas by least squares on the last window periods, through the sample.

FittedCopula dataclass

FittedCopula(series: tuple[str, ...], family: str, params: dict[str, Any], u: ndarray, residuals: ndarray, scale_next: ndarray, mean_next: ndarray, garch: bool = False, index: Any = None, margins: str = 'empirical', method: str = 'ml', margin_fits: tuple[Margin, ...] = (), se: dict[str, float] = dict(), gof_result: dict[str, float] | None = None, margin_loglike: float | None = None, gof_bootstrap: str = 'parametric', provenance: Any = None)

A copula of several returns, with their margins, for dependence and portfolio risk.

loglike property

loglike: float

The copula's log likelihood.

total_loglike property

total_loglike: float | None

Margins and copula together, with parametric margins.

tau property

tau: float

Kendall's tau implied by the copula (of the first two series).

simulate

simulate(n: int = 10000, seed: int | None = 0) -> ndarray

n draws of the copula's uniforms, one column a series.

goodness_of_fit

goodness_of_fit(draws: int = 100, seed: int | None = 0, bootstrap: str = 'parametric') -> dict[str, float]

The Cramer-von Mises test of the family against the empirical copula, its p-value by parametric bootstrap (Genest, Remillard and Beaudoin 2009) or with bootstrap="multiplier" Kojadinovic and Yan's (2011) multiplier bootstrap, on the pseudo-observations whatever the margins.

portfolio_var

portfolio_var(weights: Sequence[float], level: float = 0.99, n: int = 100000, margins: str | None = None, seed: int | None = 0) -> dict[str, float]

Next period's VaR and ES of a portfolio by simulation from the copula and the margins: the fitted margins (by default), "empirical" quantiles or a "normal" fitted to the returns or residuals.

FittedDCCCopula dataclass

FittedDCCCopula(series: tuple[str, ...], family: str, params: dict[str, float], se: dict[str, float], loglike: float, u: ndarray, residuals: ndarray, scale_next: ndarray, mean_next: ndarray, garch: bool = False, index: Any = None, margins: str = 'empirical', margin_fits: tuple[Margin, ...] = (), constant_loglike: float | None = None, provenance: Any = None)

A Gaussian or t copula of several series whose correlation matrix follows a DCC recursion on the copula's scores: the parameters, the filtered correlations, forecasts and simulation.

path property

path: DataFrame

The filtered correlation of every pair by period.

correlation_matrices

correlation_matrices() -> ndarray

R_t for every period, (T, d, d).

forecast

forecast(horizon: int = 10) -> ndarray

The correlation matrices 1 to horizon periods after the sample, (horizon, d, d): the recursion's next one, then Engle and Sheppard's approximation R_{T+h} = Rbar + (a + b)^(h-1) (R_{T+1} - Rbar), as mgarch.

simulate

simulate(horizon: int = 1, n: int = 10000, seed: int | None = 0) -> dict[str, ndarray]

n paths horizon periods forward: u (n, horizon, d) and R (n, horizon, d, d), the first period's correlation the forecast, each later one's from the recursion on the simulated scores.

portfolio_var

portfolio_var(weights: Sequence[float], level: float = 0.99, n: int = 100000, margins: str | None = None, seed: int | None = 0) -> dict[str, float]

Next period's VaR and ES of a portfolio, the copula at its forecast correlation (margins as for copula).

FittedDNS dataclass

FittedDNS(series: tuple[str, ...], maturities: ndarray, lam: float, mu: ndarray, A: ndarray, Q: ndarray, H: ndarray, loglike: float, factors: DataFrame, filtered: DataFrame, yields: DataFrame, full: bool = False, converged: bool = True, provenance: Any = None)

The dynamic Nelson-Siegel model, estimated in one step by the Kalman filter.

observed property

observed: Series

True for each calendar period with at least one quote; False for those the filter carried the factors through without a measurement update.

gaps property

gaps: Index

The calendar periods without any quote.

forecast

forecast(horizon: int = 12) -> DataFrame

The yields forecast 1 to horizon periods ahead from the last filtered factors and the VAR(1).

FittedHAR dataclass

FittedHAR(series: str, lags: tuple[int, ...], log: bool, fit: Any, rv: Series, names: tuple[str, ...] = (), provenance: Any = None)

A heterogeneous autoregression of realised variance (Corsi 2009).

forecast

forecast(horizon: int = 22) -> Series

Realised variance forecast 1 to horizon days ahead (in levels; from logs by exponentiating, with no correction).

value_at_risk

value_at_risk(level: float = 0.99, mean: float = 0.0) -> dict[str, float]

Tomorrow's normal VaR and ES of the daily return, with the HAR's variance forecast.

FittedMGARCH dataclass

FittedMGARCH(model: str, variables: tuple[str, ...], index: Index, returns: ndarray, mu: ndarray, H: ndarray, names: tuple[str, ...] = (), values: ndarray = (lambda: zeros(0))(), se: ndarray = (lambda: zeros(0))(), loglike: float = float('nan'), state: dict[str, Any] = dict(), provenance: Any = None)

An estimated multivariate GARCH: parameters, conditional covariances and correlations, and forecasts.

correlations property

correlations: DataFrame

Each pair's conditional correlation by period.

volatilities property

volatilities: DataFrame

Each series' conditional standard deviation by period.

forecast

forecast(horizon: int = 10) -> ndarray

The covariance matrices forecast 1 to horizon periods after the sample, (horizon, N, N). DCC's correlations use Engle and Sheppard's approximation E[z z'] = R.

portfolio_var

portfolio_var(weights: Sequence[float], level: float = 0.99) -> dict[str, float]

Next period's VaR and ES (normal) of a portfolio with these weights, from the forecast covariance.

FittedTVCopula dataclass

FittedTVCopula(series: tuple[str, ...], family: str, params: dict[str, float], se: dict[str, float], loglike: float, u: ndarray, residuals: ndarray, scale_next: ndarray, mean_next: ndarray, lags: int = 10, garch: bool = False, index: Any = None, margins: str = 'empirical', margin_fits: tuple[Margin, ...] = (), constant_loglike: float | None = None, provenance: Any = None)

A time-varying bivariate copula (Patton 2006): the recursion's parameters and the filtered path.

path property

path: DataFrame

The filtered parameter by period: the correlation (and the t's tail dependence) or the tail dependence.

forecast

forecast() -> dict[str, float]

Next period's parameter (and tail dependence), from the recursion at the end of the sample.

simulate

simulate(horizon: int = 1, n: int = 10000, seed: int | None = 0) -> dict[str, ndarray]

n paths horizon periods forward: u (n, horizon, 2) and the parameter(s) each period (n, horizon), the first period's from the forecast, each later one's from the recursion on the simulated uniforms.

portfolio_var

portfolio_var(weights: Sequence[float], level: float = 0.99, n: int = 100000, margins: str | None = None, seed: int | None = 0) -> dict[str, float]

Next period's VaR and ES of a portfolio, the copula at its forecast parameter (margins as for copula).

FittedVine dataclass

FittedVine(series: tuple[str, ...], structure: str, trees: tuple[tuple[Edge, ...], ...], u: ndarray, residuals: ndarray, scale_next: ndarray, mean_next: ndarray, garch: bool = False, index: Any = None, margins: str = 'empirical', method: str = 'sequential', criterion: str = 'aic', trunc_level: int | None = None, margin_fits: tuple[Margin, ...] = (), margin_loglike: float | None = None, gof_result: dict[str, float] | None = None, provenance: Any = None)

A vine copula of several returns, with their margins: its trees of pair copulas, likelihood and simulation.

logpdf

logpdf(u: Any) -> ndarray

The vine copula's log density at the rows of u.

matrix

matrix() -> ndarray

The R-vine matrix, variables numbered from 1 as in VineCopula.

to_vinecopula

to_vinecopula() -> dict[str, ndarray]

The matrix, family codes and parameters (par, par2) in VineCopula's convention.

simulate

simulate(n: int = 10000, seed: int | None = 0) -> ndarray

n draws of the copula's uniforms, one column a series.

rosenblatt

rosenblatt(u: Any = None) -> ndarray

The vine's Rosenblatt transform of u (by default the uniforms it was fitted to): independent uniforms if the vine is right.

goodness_of_fit

goodness_of_fit(draws: int = 100, seed: int | None = 0) -> dict[str, float]

The Rosenblatt-transform test of the vine (VineCopula's ECP2 Cramer-von Mises statistic) with a parametric bootstrap p-value that refits the vine's parameters on each sample (structure and families kept), on the pseudo-observations whatever the margins (refitted there first when the margins are parametric).

tau_matrix

tau_matrix(n: int = 20000, seed: int | None = 0) -> ndarray

Kendall's tau between every two series, from n draws (the first tree's pairs exactly).

portfolio_var

portfolio_var(weights: Sequence[float], level: float = 0.99, n: int = 100000, margins: str | None = None, seed: int | None = 0) -> dict[str, float]

Next period's VaR and ES of a portfolio by simulation from the vine and the margins (as for copula).

summary

summary() -> Table

The structure: tree, edge, family, parameters, Kendall's tau and tail dependence of each pair copula.

FittedVolSurface dataclass

FittedVolSurface(model: str, params: DataFrame, quotes: DataFrame, spot: float = 100.0, rate: float = 0.0, dividend: float = 0.0, beta: float = 1.0, at_bounds: tuple[str, ...] = (), provenance: Any = None)

A model of the implied volatility surface fitted to option quotes.

vol

vol(strike: Any, expiry: float) -> ndarray

The model's implied volatility at strike and expiry (SVI and SABR: total variance interpolated linearly in expiry between the fitted ones, and flat beyond them).

arbitrage

arbitrage() -> Table

SVI: the butterfly condition's minimum on each expiry's smile, and calendar violations between expiries.

grid

grid(x: Literal['strike', 'moneyness'] = 'strike', strikes: int = 25, expiries: int = 12) -> DataFrame

The model's implied volatility over a grid: expiries down the rows (from the first quoted to the last; SVI and SABR interpolate total variance between the fitted ones), and across, strikes strikes over the quotes' range, or with x="moneyness" that many log forward moneyness values k = ln(K / F) over theirs (the strike at each expiry K = F e^k).

plot_surface

plot_surface(x: Literal['strike', 'moneyness'] = 'strike', strikes: int = 25, expiries: int = 12) -> Figure

The fitted surface in 3-D: implied volatility by strike (or log moneyness) and expiry (grid).

har

har(data: Dataset, series: str = 'rv', lags: Sequence[int] = (1, 5, 22), log: bool = False) -> FittedHAR

The HAR model of realised variance series: tomorrow's on today's and its averages over the lags days, by least squares with Newey-West standard errors.

heston_price module-attribute

heston_price: ndarray = api('finance:heston_price')(heston_price)

Heston prices of European options at strikes K by Lewis's single integral (Gauss-Legendre on [0, upper]).

implied_volatility

implied_volatility(data: Dataset, price: str, strike: str, expiry: str, spot: Any, rate: Any = 0.0, dividend: Any = 0.0, kind: str = 'call') -> VolatilitySmile

The Black-Scholes implied volatility of each option quote: price, strike and expiry (years) are series; spot, rate and dividend numbers or series; kind 'call', 'put', or a series of 1 for calls and -1 for puts.

merton

merton(data: Dataset, equity: str, debt: str, rate: str | float = 0.0, horizon: float = 1.0, drift: Literal['rate', 'assets'] = 'rate', periods_per_year: int | None = None, tol: float = 1e-06, max_iter: int = 200) -> MertonModel

Merton's model over time: asset values and volatility (the KMV iteration) from the equity value equity and the default point debt, with distances to default and default probabilities over horizon years.

merton_point module-attribute

merton_point: dict[str, float] = api('finance:merton_point')(merton_point)

One firm at one date: asset value and volatility, distance to default and probability of default (risk-neutral).

MertonModel dataclass

MertonModel(frame: DataFrame, asset_vol: float, iterations: int, horizon: float, drift: str, per_year: int, provenance: Any = None)

Asset values, asset volatility, distances to default and default probabilities by period.

mgarch

Multivariate GARCH: conditional covariances and correlations of several returns.

fit = mgarch(data, ["r1", "r2", "r3"], model="dcc")
fit.summary(); fit.plot()                      # parameters; conditional correlations and volatilities
fit.correlations                               # each pair's correlation by period
fit.forecast(10)                               # covariances and correlations up to 10 periods ahead
fit.portfolio_var([0.5, 0.3, 0.2], level=0.99) # next period's VaR and ES of a portfolio

The models, with H_t the covariance of the returns' surprises e_t given the past:

  • ccc, constant conditional correlation (Bollerslev 1990): a GARCH(1,1) for each series, H_t = D_t R D_t with D_t their conditional standard deviations and R the correlation of the standardised residuals z_t.
  • dcc, dynamic conditional correlation (Engle 2002): the same first stage, then Q_t = (1 - a - b) Qbar + a z_t-1 z_t-1' + b Q_t-1 and R_t = Q_t scaled to unit diagonal, with Qbar the covariance of z and (a, b) by quasi-maximum likelihood given the first stage. Their standard errors come from the second stage alone and so understate the uncertainty a little.
  • bekk, scalar BEKK with variance targeting (Engle and Kroner 1995): H_t = (1 - a - b) S + a e_t-1 e_t-1' + b H_t-1, S the sample covariance; diagonal_bekk: H_ij,t = (1 - a_i a_j - b_i b_j) S_ij + a_i a_j e_i e_j + b_i b_j H_ij,t-1. Both by Gaussian quasi-maximum likelihood on the demeaned returns.
  • deco, dynamic equicorrelation (Engle and Kelly 2012): DCC's Q_t, but every pair given the same correlation at t, rho_t, the mean of DCC's correlations; the equicorrelation matrix's determinant and inverse are in closed form, so it suits many series. With two series it is DCC.
  • diagonal_vech (Bollerslev, Engle and Wooldridge 1988, with variance targeting): H_ij,t = (1 - a_ij - b_ij) S_ij + a_ij e_i e_j + b_ij H_ij,t-1, a free (a_ij, b_ij) for each pair; it nests the diagonal and scalar BEKK, but H_t is not guaranteed positive definite, and periods where it is not are refused by the likelihood.
  • vech, the full VECH (Bollerslev, Engle and Wooldridge 1988) with variance targeting: vech(H_t) = (I - A - B) vech(S)
  • A vech(e_t-1 e_t-1') + B vech(H_t-1), A and B unrestricted m x m (m = N(N + 1) / 2), so every variance and covariance can respond to every square and cross-product. With 2 m^2 parameters it is for two or three series; it starts from the diagonal VECH it nests.

FittedMGARCH dataclass

FittedMGARCH(model: str, variables: tuple[str, ...], index: Index, returns: ndarray, mu: ndarray, H: ndarray, names: tuple[str, ...] = (), values: ndarray = (lambda: zeros(0))(), se: ndarray = (lambda: zeros(0))(), loglike: float = float('nan'), state: dict[str, Any] = dict(), provenance: Any = None)

An estimated multivariate GARCH: parameters, conditional covariances and correlations, and forecasts.

correlations property
correlations: DataFrame

Each pair's conditional correlation by period.

volatilities property
volatilities: DataFrame

Each series' conditional standard deviation by period.

forecast
forecast(horizon: int = 10) -> ndarray

The covariance matrices forecast 1 to horizon periods after the sample, (horizon, N, N). DCC's correlations use Engle and Sheppard's approximation E[z z'] = R.

portfolio_var
portfolio_var(weights: Sequence[float], level: float = 0.99) -> dict[str, float]

Next period's VaR and ES (normal) of a portfolio with these weights, from the forecast covariance.

dcc_step

dcc_step(Q: ndarray, z: ndarray, a: float, b: float, Qbar: ndarray, g: float = 0.0, Nbar: Any = None) -> ndarray

The next Q of DCC (g = 0) or asymmetric DCC: (1 - a - b) Qbar - g Nbar + a z z' + g n n' + b Q, n = min(z, 0).

adcc_bound

adcc_bound(Qbar: ndarray, Nbar: ndarray) -> float

delta, the largest eigenvalue of Qbar^-1/2 Nbar Qbar^-1/2: asymmetric DCC is stationary if a + b + delta g < 1.

dcc_path

dcc_path(z: ndarray, a: float, b: float, Qbar: ndarray, g: float = 0.0, Nbar: Any = None) -> ndarray

The (asymmetric) DCC correlations R_t (T, N, N) of standardised residuals z (T, N), starting from Q_1 = Qbar: dcc_step period by period, run as a linear filter for every element at once (dcc_path_linear).

dcc_path_linear

dcc_path_linear(z: ndarray, a: float, b: float, Qbar: ndarray, g: float = 0.0, Nbar: Any = None) -> tuple[ndarray, ndarray]

dcc_step run by a linear filter: each element of Q_t is the scalar recursion q_t = (1 - a - b) qbar - g nbar + a z_(t-1),i z_(t-1),j + g n_(t-1),i n_(t-1),j + b q_(t-1), q_1 = qbar (n = min(z, 0); g = 0 for DCC), run for all of them at once (scipy's lfilter) rather than period by period. The correlations R_t (T, N, N) and the next period's Q.

dcc_objective

dcc_objective(params: ndarray, z: ndarray, Qbar: ndarray, Nbar: Any = None) -> float

Minus the second-stage log likelihood of (asymmetric) DCC: half the sum of log|R_t| + z_t' R_t^-1 z_t - z_t'z_t.

equicorrelation

equicorrelation(R: ndarray) -> ndarray

rho_t, the mean off-diagonal correlation of each R_t (T, N, N).

deco_objective

deco_objective(params: ndarray, z: ndarray, Qbar: ndarray) -> float

Minus DECO's second-stage log likelihood, in closed form: |R| = (1 - rho)^(N-1) (1 + (N - 1) rho) and R^-1 = (I - rho / (1 + (N - 1) rho) J) / (1 - rho).

bekk_path

bekk_path(e: ndarray, S: ndarray, A: ndarray, B: ndarray) -> ndarray

Conditional covariances (T, N, N) of a variance-targeted BEKK with H_ij = (1 - A_ij - B_ij) S_ij + A_ij e_i e_j + B_ij H_ij,t-1 (A = a a' and B = b b' for the diagonal model, constants for the scalar), starting from S.

Each element is a scalar first-order recursion, run over every period at once by a linear filter (scipy's lfilter): the same arithmetic as the loop over periods, which is what took the time of a fit.

vech_path

vech_path(e: ndarray, S: ndarray, A: ndarray, B: ndarray) -> ndarray

Conditional covariances (T, N, N) of the full VECH with variance targeting, starting from S.

The terms that do not depend on H, (I - A - B) vech(S) + A vech(e_t e_t'), are formed for every period at once; only vech(H_t+1) = that + B vech(H_t) is left to the loop over periods.

mgarch

mgarch(data: Dataset, variables: Sequence[str], model: Literal['ccc', 'dcc', 'adcc', 'deco', 'bekk', 'diagonal_bekk', 'diagonal_vech', 'vech'] = 'dcc', asymmetric: bool = False) -> FittedMGARCH

A multivariate GARCH of the returns in variables: constant (ccc), dynamic (dcc) or asymmetric dynamic (adcc) conditional correlation or dynamic equicorrelation (deco) over GARCH(1,1) volatilities (GJR with asymmetric), or a scalar or diagonal BEKK or diagonal VECH (see the module notes).

optimize_portfolio

optimize_portfolio(data: Dataset, assets: Sequence[str], objective: Literal['min_variance', 'max_sharpe', 'target_return'] = 'min_variance', rf: float = 0.0, target_return: float | None = None, long_only: bool = True, bounds: Sequence[tuple[float, float]] | None = None, cov: Any = None, mu: Any = None) -> Portfolio

Portfolio weights that minimise variance, maximise the Sharpe ratio over rf or reach the mean return target_return with the least variance (target_return was called target, which still works, with a DeprecationWarning). bounds per asset (default: 0 to 1 when long_only, else -1 to 2); cov: a covariance matrix, or a fitted multivariate GARCH (its next-period forecast); mu: mean returns to use instead of the sample's (Black-Litterman's posterior, say).

option_price

option_price(spot: float, strike: float, expiry: float, rate: float, vol: float, dividend: float = 0.0, kind: Literal['call', 'put'] = 'call', american: bool = False, steps: int = 500) -> OptionValuation

The price and Greeks of a European option (Black-Scholes-Merton) or an American one (a binomial tree of steps steps).

OptionValuation dataclass

OptionValuation(kind: str, american: bool, inputs: dict[str, float], price: float, values: dict[str, float], method: str, provenance: Any = None)

An option's price and Greeks, with its inputs.

Performance dataclass

Performance(series: tuple[str, ...], kind: str, per_year: int, values: DataFrame, returns: DataFrame, rf: str | None = None, benchmark: str | None = None, provenance: Any = None)

Performance measures of one or more return series, with their cumulative returns and drawdowns.

cumulative

cumulative() -> DataFrame

The growth of 1 invested in each series.

performance

performance(data: Dataset, series: Sequence[str], rf: str | None = None, benchmark: str | None = None, kind: Literal['log', 'simple'] = 'log', periods_per_year: int | None = None) -> Performance

Performance measures of the return series: annual return and volatility, Sharpe (with its standard error) and Sortino ratios over rf, maximum drawdown, the Calmar ratio, hit rate, skewness and kurtosis, and, against a benchmark, alpha, beta, tracking error and the information ratio.

Portfolio dataclass

Portfolio(assets: tuple[str, ...], objective: str, weights: ndarray, mu: ndarray, cov: ndarray, rf: float = 0.0, bounds: tuple[tuple[float, float], ...] = (), source: str = 'sample', provenance: Any = None)

Optimal portfolio weights, with their mean, volatility and Sharpe ratio, and the efficient frontier.

frontier

frontier(points: int = 25) -> DataFrame

The efficient frontier within the same bounds: for target means from the minimum-variance portfolio's to the highest reachable, the least volatility and its weights.

realized_measures

realized_measures(data: Dataset, series: str, jump_level: float = 0.999, annualize: int = 252) -> Dataset

Each day's realised variance (rv), bipower variation (bv), tripower quarticity, the BNS jump statistic and its p-value, the jump variation on days it rejects at jump_level, the intraday returns counted, and the annualised realised volatility (rvol), from the intraday returns series.

returns

Returns from prices, drawdowns, and the performance of return series.

data = returns(data, ["spx", "bonds"])                 # spx_ret, bonds_ret: log returns (kind="simple" for p/p[-1] - 1)
perf = performance(data, ["spx_ret", "bonds_ret"], rf="tbill", benchmark="spx_ret")
perf.table(); perf.plot()                              # the measures; cumulative returns and drawdowns

Returns are fractions (0.01 for 1%), log or simple. Annualising uses the data's frequency (252 trading days a year for daily data, 52, 12, 4 or 1) unless periods_per_year is given: returns and their excess over rf are averaged and multiplied by it (log returns), or compounded (simple), and volatility is scaled by its square root. The Sharpe ratio's standard error is Lo's (2002) for independent returns, sqrt((1 + SR^2 / 2) / T) per period.

Performance dataclass

Performance(series: tuple[str, ...], kind: str, per_year: int, values: DataFrame, returns: DataFrame, rf: str | None = None, benchmark: str | None = None, provenance: Any = None)

Performance measures of one or more return series, with their cumulative returns and drawdowns.

cumulative
cumulative() -> DataFrame

The growth of 1 invested in each series.

annual_periods

annual_periods(index: Any) -> int

The periods in a year for annualising: 252 for daily data (trading days), 52, 12, 4 or 1.

drawdown

drawdown(r: Series, kind: Literal['log', 'simple'] = 'log') -> Series

The fall from the highest value so far of the wealth the returns make (0 at a new high, -0.2 when 20% below).

measures

measures(r: ndarray, q: int, kind: str, rf: ndarray | None = None, bench: ndarray | None = None) -> dict[str, float]

The performance measures of one return series (see the module notes).

returns

returns(data: Dataset, prices: Sequence[str], kind: Literal['log', 'simple'] = 'log', periods: int = 1, suffix: str = '_ret') -> Dataset

The dataset with each price's return over periods added as <price><suffix>: log (the change in its log) or simple (its ratio to periods earlier, less one).

performance

performance(data: Dataset, series: Sequence[str], rf: str | None = None, benchmark: str | None = None, kind: Literal['log', 'simple'] = 'log', periods_per_year: int | None = None) -> Performance

Performance measures of the return series: annual return and volatility, Sharpe (with its standard error) and Sortino ratios over rf, maximum drawdown, the Calmar ratio, hit rate, skewness and kurtosis, and, against a benchmark, alpha, beta, tracking error and the information ratio.

risk_contributions

risk_contributions(data: Dataset, assets: Sequence[str], weights: Sequence[float], level: float = 0.99, method: Literal['normal', 'historical'] = 'normal', cov: Any = None) -> RiskContributions

Marginal and component VaR and ES of each asset in a portfolio with weights, normal (with the sample covariance, a given one, or a fitted multivariate GARCH's next-period forecast) or historical.

risk_parity_weights

risk_parity_weights(cov: Any, budgets: Any = None) -> ndarray

Long-only weights whose shares of the portfolio's variance are budgets (equal by default).

RiskContributions dataclass

RiskContributions(assets: tuple[str, ...], weights: ndarray, level: float, method: str, var: float, es: float, parts: dict[str, ndarray], source: str = 'sample', provenance: Any = None)

Each asset's marginal and component VaR and ES in a portfolio.

RiskForecast dataclass

RiskForecast(series: str, level: float, method: str, window: int, frame: DataFrame, provenance: Any = None)

Value at risk and expected shortfall forecast one period ahead, with the returns that followed.

StrategyBacktest dataclass

StrategyBacktest(assets: tuple[str, ...], strategies: tuple[str, ...], returns: DataFrame, gross: DataFrame, weights: dict[str, DataFrame], turnover: DataFrame, window: int = 60, rebalance: int = 1, cost: float = 0.0, per_year: int = 12, rf: Any = None, provenance: Any = None)

Rebalanced portfolio strategies' returns, weights and turnover, out of sample.

tv_copula

tv_copula(data: Dataset, series: Sequence[str], family: Literal['gaussian', 't', 'clayton', 'gumbel', 'sjc'] = 'gaussian', lags: int = 10, garch: bool = False, dist: Literal['normal', 't'] | None = None, margins: Literal['empirical', 'normal', 't', 'skewt'] = 'empirical') -> FittedTVCopula

A time-varying copula of two returns (Patton 2006): the Gaussian or t correlation, or the Clayton, Gumbel or symmetrised Joe-Clayton tail dependence, following an ARMA-type recursion on the last lags periods; by maximum likelihood on the margins' uniforms (ranks, fitted, or with garch the standardised residuals), with the filtered path, next period's forecast and forward simulation.

value_at_risk

value_at_risk(data: Dataset, series: str, level: float = 0.99, method: Literal['historical', 'normal', 't', 'cornish_fisher', 'garch', 'fhs'] = 'historical', window: int = 250, refit: int = 20, start: Any = None, dist: Literal['normal', 't'] = 'normal', asymmetric: bool = False) -> RiskForecast

One-period-ahead value at risk and expected shortfall of the returns in series, for each period from start (default: once window returns are available), each from the returns before it only. See the module notes for the methods. For GARCH and filtered historical simulation, dist="t" gives the GARCH Student-t errors and asymmetric=True the GJR form (more response to falls than to rises).

vine_copula

vine_copula(data: Dataset, series: Sequence[str], structure: Literal['rvine', 'cvine', 'dvine'] = 'rvine', order: Sequence[str] | None = None, families: Sequence[str] | None = None, criterion: Literal['aic', 'bic'] = 'aic', indeptest: bool = False, alpha: float = 0.05, trunc_level: int | None = None, method: Literal['sequential', 'joint'] = 'sequential', garch: bool = False, dist: Literal['normal', 't'] | None = None, margins: Literal['empirical', 'normal', 't', 'skewt'] = 'empirical', matrix: Sequence[Sequence[int]] | None = None, gof: bool = False, draws: int = 100, seed: int = 0) -> FittedVine

A vine copula of the returns series: an R-vine (or a C- or D-vine) whose trees are selected by Dissmann et al.'s maximum spanning trees of |Kendall's tau|, each pair copula's family by AIC or BIC among families (all the plugin's bivariate families, rotations and independence), estimated tree by tree or joint; order fixes a D-vine's path or a C-vine's roots, matrix an R-vine matrix (VineCopula's, variables numbered from 1); trunc_level makes the trees above it independence; families="all" adds BB6, BB8, Tawn and the rotated two-parameter families to those selected among. Margins as for copula; gof adds the Rosenblatt-transform goodness-of-fit test (draws parametric bootstrap samples, each refitted).

vol_surface

vol_surface(data: Dataset, price: str, strike: str, expiry: str, spot: float, rate: float = 0.0, dividend: float = 0.0, kind: str = 'call', model: Literal['svi', 'sabr', 'heston'] = 'svi', beta: float = 1.0) -> FittedVolSurface

An SVI, SABR (each expiry) or Heston (the whole surface) model fitted to option quotes' implied volatilities.

VolatilitySmile dataclass

VolatilitySmile(frame: DataFrame, spot: Any = None, provenance: Any = None)

Implied volatilities of option quotes, by strike and expiry.

surface

surface() -> DataFrame

Implied volatility by strike (rows) and expiry (columns).

yield_curve

yield_curve(data: Dataset, series: Sequence[str], maturities: Sequence[float], model: Literal['nelson_siegel', 'svensson'] = 'nelson_siegel', lam: float | None = None, lam2: float | None = None) -> YieldCurve

Nelson-Siegel (or Svensson) level, slope and curvature of the yields series at maturities (years), each period, with the decay lam (and lam2) given or estimated over the whole sample: the dataset's active sample (with_sample), all its periods without one.

YieldCurve dataclass

YieldCurve(series: tuple[str, ...], maturities: ndarray, model: str, lam: float, lam2: float | None, factors: DataFrame, yields: DataFrame, residuals: DataFrame, estimated: bool = False, provenance: Any = None)

Nelson-Siegel or Svensson factors of a yield curve, period by period.

curve

curve(period: Any = None, maturities: Any = None) -> Series

The fitted curve at one period (default: the last), at maturities (default: 3 months to the longest).

ar1

ar1() -> DataFrame

Each factor's AR(1), f_t = c + phi f_(t-1) + e_t, by least squares.

forecast

forecast(horizon: int = 12) -> DataFrame

The yields forecast 1 to horizon periods ahead from each factor's AR(1).

forwards

forwards(maturities: Any, period: Any = None) -> Series

Instantaneous forward rates at maturities from one period's fitted curve (default: the last).

discount

discount(maturities: Any, period: Any = None, percent: bool = True) -> Series

Discount factors exp(-y(m) m), reading the curve as continuously compounded zero rates (in percent unless percent=False).

bond

bond(coupon: float, maturity: float, freq: int = 2, period: Any = None, percent: bool = True) -> dict[str, float]

A coupon bond's price per 100, continuous yield, duration, convexity and Fisher-Weil duration from the curve.

par_coupon

par_coupon(maturity: float, freq: int = 2, period: Any = None, percent: bool = True) -> float

The coupon (percent a year) that prices a bond of maturity at par.

Plugin plumbing

What pymetrix's plugin loader reads (PLUGIN, register) and the plugin's version.

PLUGIN module-attribute

PLUGIN = PluginInfo(name='pymetrix-finance', version=__version__, license='BSD-3-Clause', maintainer='Geoffrey Heenan', description='Financial econometrics: value at risk and expected shortfall with backtests; multivariate GARCH; returns and performance; factor models and portfolios; options; yield curves; risk contributions; event studies; realised volatility and HAR; strategy backtests; bonds and dynamic Nelson-Siegel')