API reference¶
Author: Artur Sepp / First recorded: 2026-07-25.
Implemented in qis — Quantitative Investment Strategies. Software citation: CITATION.cff.
Public means exported from src/qis/__init__.py. This page is regenerated on every build, so it
cannot drift from the exports.
The reference is in two parts. The core API is the documented surface: every symbol there
carries an Args or Attributes block, and the boundary is drawn by measured usage - a
symbol is core when a package that depends on qis, or qis’s own examples and documentation, call
it. src/qis/tests/test_core_api.py enforces that. Also exported lists everything else that
can be imported: usable, but with no prose promise and no stability guarantee beyond the
CHANGELOG.
Grouping in the core section is by capability rather than by defining module, so moving a symbol between subpackages costs no documentation change.
Core API¶
Instrument portfolio stress¶
28 symbols.
Methodology: Instrument portfolios and standard stress reports, Stress testing with options.
Named factor family with an explicit total-bump allocation. |
|
Public extension for a composite valued in reference currency. |
|
A signed primitive valued in its underlying's quote currency. |
|
An absolute-position snapshot referencing the canonical QIS risk model. |
|
Supported primitive payoffs. |
|
One-sided quote derivative used consistently across a holding's legs. |
|
Read-only labelled market view for public composite payoff implementations. |
|
Original position identity with an observed reference-currency mark. |
|
Computed report inputs, detached from live portfolio/model objects. |
|
Evaluated scenario values with explicit source-mark and model anchors. |
|
Currency basis of the fitted response. |
|
Policy for factors which a request leaves unspecified. |
|
Explicit units of requested factor or family bumps. |
|
Requested factor/family anchors with explicit completion and return units. |
|
Numerical analysis settings with explicit covariance horizon. |
|
An actual quote with a possibly shared fitted response. |
|
Revalue requested, conditional, historical and grid shocks through one portfolio. |
|
Paths written by a report operation; the numerical result remains reusable. |
|
Presentation options and caller-supplied estimation diagnostics. |
|
Render a completed result without fitting or re-evaluating any payoff. |
|
Reconciled reference-currency account ledger, independent of fitted coverage. |
|
Declared accounting role; negative marks alone do not identify borrowing. |
|
Accounting meaning of the denominator used for report ratios. |
|
Caller-owned response construction facts; reporting never alters the series. |
|
Declared origin of a fitted response history. |
|
Return convention of a supplied fitted response. |
|
Select the worst monthly returns of a named factor and replay full vectors. |
|
Caller-assigned account allocation buckets, separate from risk factors. |
Performance statistics¶
19 symbols.
Methodology: The performance-statistic catalogue, Sharpe ratios: conventions and inference, Drawdowns and time under water, Alpha, beta and benchmark-relative performance, Returns, NAVs, excess returns, fees and leverage, Signal diagnostics: information coefficient and information ratio, Two-sided turnover conventions.
sampling frequencies and conventions for risk-adjusted performance statistics. |
|
the column set of every performance table in qis. |
|
Compute the full risk-adjusted performance table. |
|
risk-adjusted performance statistics as a table of formatted strings, ready to render. |
|
Compute returns for assets grouped by frequency. |
|
Convert prices to returns with specified methodology. |
|
Convert returns to NAV time series. |
|
Recover unlevered asset-level returns from levered portfolio returns. |
|
Estimate the implicit leverage ratio between two return series via OLS. |
|
backfill an infrequently reported series onto a frequent grid with a Brownian bridge. |
|
Container for cross-sectional signal diagnostic outputs. |
|
IC information ratio per horizon — the time-series counterpart to the pooled IC in |
|
Cross-sectional predictive regression of forward returns on lagged signal. |
|
Select the holdings and denominator used to compute two-sided turnover. |
|
Compute per-instrument two-sided turnover before resampling or rolling aggregation. |
|
Annualised arithmetic Sharpe difference and paired HAC inference. |
|
Test equal arithmetic Sharpe ratios on paired periodic returns with HAC. |
|
Compare every non-base portfolio with one base on a common return sample. |
|
Draw a two-decimal HAC Sharpe comparison table and return its numeric data. |
Portfolio and backtesting¶
16 symbols.
Methodology: Portfolio backtesting: targets, held units, and implementation, Self-financed FX accounting, Portfolio risk and Euler contributions, Factor risk models, Tracking error and benchmark-relative risk, Portfolio breadth and allocation efficiency.
Explicit financing, collateral and sizing choices for an FX account. |
|
Owned account histories and event receipts, in explicit monetary units. |
|
Run a self-financed cash ledger for signed cash equities and cash-settled FX forwards. |
|
simulate a rebalanced portfolio from prices and target weights. |
|
turn a fixed allocation into a rebalancing weight frame over the live universe. |
|
the contract every portfolio in the stack satisfies, and the input to the factsheet layer. |
|
several portfolios reported together, against a common benchmark. |
|
Dated covariance matrices with an optional point-in-time factor block. |
|
tradable factor price levels, optionally validated against a factor-set descriptor. |
|
Computes the risk contribution of each asset to the portfolio's total risk. |
|
Compute normalized Euler risk contributions that sum to one. |
|
Aggregate normalized Euler risk contributions over supplied groups. |
|
linear factor model with exponentially weighted time-varying loadings. |
|
Compute annualised EWMA realised (ex-post) tracking error from NAVs. |
|
Container for portfolio-breadth statistics and their numerical audit trails. |
|
Compute point-in-time universe, capital and risk breadth on target-weight dates. |
Factor stress testing¶
11 symbols.
Methodology: Factor stress testing: shocks, valuation and prediction bands.
Exact asset valuation and additive attribution of a log-factor scenario. |
|
Pointwise Gaussian prediction band with fixed baseline portfolio exposures. |
|
Joint-anchor grid, exact valuation and analytical band. |
|
Convert positive price endpoints to a log-return shock. |
|
Convert a simple market return with fixed exposure to a factor log return. |
|
Convert a yield change using the first-order duration approximation. |
|
Condition free log-factor shocks on explicit anchors under a zero-mean model. |
|
Compute a Schur complement, retaining full factor order and zero anchor rows. |
|
Value each asset through expm1 of its frozen log-factor exposure, then aggregate. |
|
Compute analytical conditional-factor plus independent-residual prediction bounds. |
|
Run an explicit simple-return grid through joint conditioning, valuation and bands. |
Factsheets and reporting¶
8 symbols.
Methodology: Factsheets and reporting, Performance statistics and reporting frequency.
Render the appropriate qis factsheet across a chosen reporting frequency in a single call. |
|
multi-page factsheet for one strategy against a benchmark. |
|
factsheet comparing one strategy against one benchmark, as a list of A4 figures. |
|
factsheet comparing several structurally different strategies, as a list of A4 figures. |
|
draw strategy and benchmark exposures as two stacked-area panels on a shared scale. |
|
the grid a factsheet is computed on. |
|
the report keyword arguments for a given reporting frequency and reported span. |
|
key parameters for report comps and visuals on different time period or data frequency. |
EWM estimation¶
11 symbols.
Methodology: Exponentially weighted estimators, Covariance, correlation and principal components, Risk-adjusted returns and volatility targeting.
which mean is subtracted before an EWM second moment is computed. |
|
how the EWM recursion treats a missing observation. |
|
exponentially weighted moving average of a t-by-n panel. |
|
exponentially weighted volatility, or variance when |
|
Fit an exponentially weighted linear trend with an intercept, through each row. |
|
exponentially weighted covariance matrix at every date, as a 3-d tensor. |
|
EWM covariance tensor computed on vol-normalised returns, with the vols returned alongside. |
|
vol-normalise returns, then band-pass them with a long/short EWM filter. |
|
covariance or correlation of a returns panel, computed pairwise over the observed entries. |
|
EWM covariance matrix sampled on a rebalancing schedule, ready for a rolling backtest. |
|
Plot a correlation matrix heatmap with volatilities on the diagonal. |
FX analytics¶
22 symbols.
Methodology: Return conventions and FX adjustments, FX hedging and market-data boundaries, Self-financed FX accounting.
Economic object, independently of its numerical coordinate. |
|
Coordinate with a kind-dependent, explicitly validated meaning. |
|
Cash measurement account, independent of return and hedge frequencies. |
|
Cash accrual policy; quote provenance does not imply provider normalization. |
|
Explicit synthetic index normalization, not a self-financing account engine. |
|
Sample one ACT/365F cash index with calendar month-end opening resets. |
|
Asset-panel request with one economic kind and one coordinate. |
|
Currency-panel request, with no invented asset price panel. |
|
Owned return values and their economic/timing contract. |
|
Compute typed FX analytics, grouped by cadence, without an automatic NAV. |
|
FX spot rates and domestic short rates, aligned on a common index. |
|
read FX spots and domestic short rates from the saved CSV pair. |
|
The FX spot series belonging to each instrument, on the index of its prices. |
|
Decompose an asset's reference-currency return into its local and FX legs. |
|
Reference-currency NAV and return of a local-currency asset at a given hedge ratio. |
|
EWMA FX volatility and the asset's beta to the FX leg. |
|
Mean-variance optimal FX hedge ratios, plus the carry and beta references. |
|
returns of a futures position in a foreign currency, converted to the quote currency. |
|
returns of a cash position in a foreign currency, converted to the quote currency. |
|
Hedging performance metrics for a panel of local-currency assets in a reference ccy. |
|
Single-asset FX-hedging tearsheet for a local-currency asset in a reference ccy. |
|
Multi-asset FX-hedging comparison report (heatmap tables). |
Regime reporting¶
1 symbols.
Methodology: Regime-conditional performance, The convexity premium and smart diversification.
Regime classifier based on benchmark return quantiles. |
Bootstrap¶
5 symbols.
Methodology: Resampling and the bootstrap.
how observations are resampled. |
|
the shape a bootstrap function returns, which follows from the shape of its input. |
|
draw resampling indices, without touching any data. |
|
resample a series or panel with replacement, preserving the cross-section within each draw. |
|
resample price levels by resampling their returns and recompounding. |
Unsmoothing¶
3 symbols.
Methodology: Private-asset unsmoothing and de-levering, Serial dependence and autocorrelation.
Apply rolling EWMA AR(q) unsmoothing to a price panel, optionally mixed-frequency. |
|
rolling AR(1) unsmoother; a shim over |
|
Apply static AR(q) unsmoothing following Getmansky-Lo-Makarov (2004). |
Plots¶
16 symbols.
plot columns of a DataFrame against its index, with summary statistics in the legend. |
|
plot price or NAV series with performance statistics in the legend. |
|
plot price series above their running drawdown, on a shared date axis. |
|
plot columns of a DataFrame as bars, grouped or stacked, one group per index entry. |
|
x-y scatter with a fitted relationship, optionally split by a grouping variable. |
|
x-y scatter with the sample split into buckets of x, and a fit within each bucket. |
|
draw a DataFrame as a colour-coded table. |
|
quantile-quantile plot of each column against the normal distribution. |
|
render a DataFrame as a matplotlib table, with optional per-cell colouring. |
|
box plots of y within quantile buckets of x. |
|
box plots of a wide DataFrame melted into long form, one box per hue value. |
|
which summary statistics the legend prints beside each series name. |
|
set the figure-level title above all its axes. |
|
Plot one portfolio's asset counts and breadth-efficiency ratios through time. |
|
Compare the latest breadth counts and efficiencies of named portfolio layers. |
|
Plot current cumulative absolute capital and risk-contribution concentration. |
Dates, schedules and annualisation¶
11 symbols.
Methodology: Performance statistics and reporting frequency, Notation and conventions.
a start and end date, with the conversions and slicing every qis function expects. |
|
the TimePeriod spanned by a frame's index, or by an index directly. |
|
the date range of a frame's index, formatted for a chart title or a table header. |
|
tz-aware schedule of dates spanning a time period at a given frequency. |
|
boolean rebalancing flags aligned to an observation index. |
|
the roll schedule of a fixed-maturity instrument: for each observation time, the expiry held. |
|
Finds the latest date in the index that is on or before the specified date. |
|
slice from |
|
Get factor to convert between pandas frequencies. |
|
Calculate annualization factor from pandas frequency string. |
|
the number of periods per year implied by a frame's index frequency. |
DataFrame utilities¶
24 symbols.
sum of absolute values of finite entries along axis: |
|
sum of absolute values of strictly positive finite entries along axis |
|
sum of absolute values of strictly negative finite entries along axis |
|
sum of finite entries along axis |
|
sum of strictly positive finite entries along axis |
|
sum of strictly negative finite entries along axis |
|
sum of finite entries along axis, after clipping the data to [a_min, a_max] |
|
mean of finite entries along axis |
|
mean of strictly positive finite entries along axis |
|
mean of finite entries along axis, after clipping the data to [a_min, a_max] |
|
median of finite entries along axis |
|
last row (axis=0) or last column (axis=1); is_nonan takes the last finite value per key. |
|
weighted sum of finite entries: |
|
map each group label to the tickers belonging to it. |
|
one-hot loadings of instruments on groups. |
|
split a panel's columns into one frame per group. |
|
Compute cross-sectional standardized scores (z-scores) for DataFrame or Series. |
|
equal weights across the assets observed on each date. |
|
normalise each row to sum to one after setting negative values to zero. |
|
normalise each row to sum to one. |
|
convert a covariance matrix to the corresponding correlation matrix. |
|
broadcast a 1-d array down the columns of a frame-shaped array. |
|
ordinary least squares of y on the columns of x, with a formatted summary of the fit. |
|
merge two keyword dictionaries, with the second winning on collisions. |
File and figure output¶
9 symbols.
read one DataFrame from a CSV under the managed path layout. |
|
read a dict of DataFrames, one CSV per key. |
|
read one sheet of an Excel workbook into a DataFrame. |
|
write one DataFrame to a CSV under the managed path layout. |
|
write a dict of DataFrames, one CSV per key. |
|
write a matplotlib figure to an image or vector file. |
|
write several matplotlib figures to one multi-page PDF, one figure per page. |
|
decorator printing the wall-clock runtime of the decorated function. |
|
Resolve the input/resource directory, without creating missing inputs by default. |
Also exported¶
Exported and importable, not part of the documented core. Signatures may change without a migration path.
Enums¶
24 exported.
input for computation of get_performance_attribution_data() |
|
which pairs of a correlation matrix |
|
which cross statistic |
|
which statistics |
|
abstract enum with a map function |
|
how an EWM recursion is seeded when no explicit |
|
enumerate some combinations for perf stat labels can refer through value perf_stats_labels=qis.PerfStatsLabels.DETAILED_WITH_DD.value perf_stats_labels=qis.PerfStatsLabels.DETAILED_WITH_DDVOL.value perf_stats_labels=qis.PerfStatsLabels.TOTAL_DETAILED.value |
|
which statistic a regime-conditional table reports. |
|
what a rejected observation becomes. |
|
how a price series is converted to a return. |
|
enumerated tuple for name and format |
|
which Sharpe ratio numerator a statistic reports. |
|
Column-name constants for the regression result DataFrames. |
|
shape of the signal-to-weight map in |
|
input for computation of get_performance_attribution_data() |
|
Return engine used by native-price reconstruction. |
|
Dataclasses¶
14 exported.
keep data for producing meta and aggregation |
|
Joint EWMA-WLS alpha/beta estimates with Bartlett-HAC inference. |
|
Settings for zero-drift linear Gaussian Monte Carlo VaR. |
|
Allow bounded missing-beta dust and explicitly supplied proxy histories. |
|
A linear factor model for analyzing asset returns using multiple factors. |
|
Factorial and Shapley attribution of layered-model feature effects. |
|
Full-sample alpha/beta decomposition of model-layer NAVs. |
|
Post-warm-up cumulative realised alpha under point-in-time EWMA betas. |
|
Point-in-time model-layer attribution under lagged EWMA betas. |
|
Current exponentially weighted model-layer regression attribution. |
|
Benchmark and model-layer NAVs for one feature coalition or effect. |
|
define data inputs for portfolio construction |
|
Diversification frontiers of candidate overlays stacked on a principal portfolio. |
|
data class instance applied for output of strategy backtest data |
Classes¶
8 exported.
Regime classifier based on positive vs negative benchmark returns. |
|
Regime classifier based on benchmark volatility quantiles. |
|
variable characteristic for columns variable for table |
|
key parameters for report comps and visuals on different time period or data frequency. |
|
Reusable antithetic normal draws for portfolio and benchmark marginal VaR. |
|
specify filtering policy params |
|
Abstract base class for regime classification. |
Functions¶
234 exported.
Rescale component NAVs so their PA returns sum to the portfolio PA return. |
|
Unsmooth observed returns with a rolling EWMA AR(q) beta vector. |
|
Unsmooth observed returns by shifting the lagged-factor response to contemporaneous. |
|
Jointly EWMA-fit phi_1 (own-lag) and beta_1 (lagged factor) and unsmooth. |
|
align a weight specification to a set of instrument columns. |
|
append csv file |
|
Append older history before newer data with newer values winning overlaps. |
|
eigen decomposition of a symmetric matrix, ordered from the largest eigenvalue down. |
|
Extend newer time series backward with older provider histories. |
|
resample the residuals of a fitted AR(1) per column and rerun the recursion. |
|
resample price panels and AR(1) fundamentals jointly with one shared index array. |
|
AR(1) price-level shim with the shared quarterly defaults. |
|
fit an AR(1) per column and return the residuals on complete lag pairs. |
|
lagged Pearson autocorrelation of each column, with the lag as the index. |
|
lag-one Pearson autocorrelation of non-overlapping blocks of |
|
Compute summary statistics of a drawdown (or run-up) series. |
|
Return simple peak-to-trough and peak-to-recovery returns on benchmark dates. |
|
Computes the Euler contributions of active positions to tracking error. |
|
Split each period's portfolio return into benchmark contributions and a residual. |
|
Split each period's portfolio return into benchmark contributions and a residual. |
|
Compute benchmark regime performance attribution table. |
|
Compute BHB attribution from weighted arithmetic return contributions. |
|
Compute historical CVaR (expected shortfall) as a loss-positive quantity. |
|
explained-variance shares through time, from an EWM correlation or covariance tensor. |
|
Aggregate a time series at a given frequency and compute descriptive statistics. |
|
descriptive statistics per column, formatted for display. |
|
Compute a sorted table of drawdown episodes and their statistics. |
|
Return ranked PCA portfolio weights scaled to unit variance. |
|
EWM alpha and R-squared of a given prediction. |
|
Compute one-factor EWMA beta, alpha, one-step-ahead prediction and diagnostics. |
|
uncentred EWM correlation of every requested pair of columns, one column per pair. |
|
uncentred EWM correlation path of a two-column return panel. |
|
EWM cross moment, beta or correlation of y on x, pair by pair. |
|
Signal smoother (long/short EWM band-pass) for DataFrame / Series / ndarray. |
|
EWM lagged cross moments of a panel as two columns, |
|
exponentially weighted Newey-West variance or volatility. |
|
span = 1: daily ra returns |
|
Contemporaneous EWM score |
|
Annualised EWM Sharpe-ratio paths of return columns. |
|
smoothed, volatility-normalised signal with unit standard deviation for IID input. |
|
EWM autocorrelation ratio of each column: EWM lagged moment over EWM second moment. |
|
EWM autocorrelation ratio of each column after removing its EWM mean. |
|
Compute an EWM beta tensor from factor and asset returns. |
|
Compute NAVs for excess returns over risk-free rate. |
|
Subtract the cash return accrued over each return period. |
|
Compute Monte Carlo VaR, benchmark beta and TE from supplied covariance. |
|
Per-date IC series for every horizon in a diagnostic result. |
|
Compute whole-sample TE and IR tables across return-differential panels. |
|
Split weights or contributions using explicit fractions and ordinary labels. |
|
Compute the realised maximum drawdown and the current drawdown. |
|
Compute mean returns and frequency for each regime. |
|
Compute factorial and Shapley attribution for layered-model feature changes. |
|
Compute a full-sample OLS decomposition of model-layer log returns. |
|
Rebase cumulative lagged-beta alpha after a point-in-time warm-up. |
|
Estimate model-layer alpha using point-in-time, lagged EWMA betas. |
|
Estimate a current model-layer decomposition by EWMA-WLS with joint HAC inference. |
|
Compute additive current EWMA return-to-volatility contributions. |
|
Compute EWMA Sharpe paths after adding model-layer components sequentially. |
|
Compute additive full-sample return contributions over full-sample volatility. |
|
Compute expanding-prefix EWMA-WLS annualised alpha paths. |
|
Compute net NAVs after management and performance fees. |
|
Compute net returns after management and performance fees. |
|
Compute number of years in price series. |
|
EWM betas of every asset column on one factor. |
|
Compute annualized excess returns with geometric compounding. |
|
Compute annualized (per annum) return with geometric compounding. |
|
explained-variance shares of the eigenvalues of a symmetric matrix. |
|
Estimate one β per (asset, horizon) from the diagnostic pairs. |
|
Compute return-based performance metrics per asset. |
|
Compute simple periodic returns for a price panel. |
|
compute table for heatmap: columns are monthly returns, rows are years implemented only for single asset with price passed as series |
|
Compute portfolio beta-alpha attribution using benchmark decomposition. |
|
Computes portfolio VaR accounting for correlations, optionally grouped by categories. |
|
Compute portfolio benchmark betas as weight-aggregated instrument betas. |
|
Computes the undiversified portfolio VaR: the sum of standalone instrument VaRs. |
|
Computes portfolio volatility from a point-in-time EWM covariance of the returns. |
|
Compute the risk-adjusted performance table augmented with alpha/beta to a benchmark. |
|
divide returns by a lagged EWM volatility: |
|
Compute conditional means and annualized contributions by regime. |
|
Compute comprehensive regime-conditional performance table. |
|
Compute comprehensive dictionary of return metrics. |
|
apply the returns transform selected by |
|
Compute risk metrics (vol, drawdown, skew/kurtosis) per asset using vectorised ops. |
|
mean path of each column under a mean-adjustment convention, same shape as the input. |
|
Compute joint drawdown and time-under-water series. |
|
Compute the running drawdown series from peak. |
|
observations minus their mean path under |
|
compute rolling performance default stats is 1y rolling for prices with roll_freq = 'B' for monthly returns anf 5y rolling use roll_freq='ME' and roll_periods=5*12 |
|
span = 1: daily ra returns otherwise compute sum of returns and then their vols interpretation: voltargeting for returns over span ewm_lambda is vol over the span too |
|
Compute annualized realized volatility from sampled returns. |
|
sum risk-adjusted returns within non-overlapping calendar periods of |
|
span = 1: daily ra returns otherwise compute sum of daily ra-returns interpretation: pnl of daily voltargeting returns over span |
|
Compute whole-sample tracking error and information ratio from return differentials. |
|
Compute total return from first to last price. |
|
Unsmooth supplied native marks per cadence and align reconstructed NAVs to their grid. |
|
compute correlation row between pivot row of returns and return columns in data pivot returns are row data (r1,r2) data columns are column data ([c1, c2]) output is correlation row of pivot to columns columns may have nans but pivot must be non-nan |
|
Navs of the principal portfolio mixed with one overlay at eleven overlay weights. |
|
rebalancing_freq are series with data of type {'SPY': 'QE', 'TLT': 'ME'} |
|
Wrapper to asfreq with closed period. |
|
plot boxplot using data by columns x-axis will be colum names |
|
plot data frame by aggregating by columns xvar is the index appropriate when y data is uniform conditional n regimes |
|
get dict of dfs and add regime vars, key = (x_column, y_column) use x as classification var and plod box plot relative to quatiles of x is_value_labels will be same across different df and x |
|
dict keys are added as hue plot boxplot using data by columns x-axis will be colum names |
|
mean of strictly negative finite entries along axis |
|
weighted average across axis, with weights rescaled at each line to sum to one over the finite entries only: mu_t = sum_i w_i x_ti / sum_i w_i 1{x_ti finite}. |
|
Format a DataFrame as strings, with per-column format overrides. |
|
standard sample autocorrelations and partial autocorrelations of one series. |
|
partial (default) or ordinary sample autocorrelations of many paths, one column per path. |
|
estimate the Dimson aggregated-coefficient beta to detect return smoothing. |
|
Estimate linear factor model from price data. |
|
Fit joint EWMA-weighted alpha/beta regressions with Bartlett-HAC inference. |
|
Estimate volatility from return samples. |
|
Winsorise each column at full-sample quantiles of its EWM score. |
|
EWM correlation or beta of rolling h-row returns with their own lag or with a signal. |
|
Build the default (PerfParams, BenchmarkReturnsQuantilesRegime) pair used outside the factsheet-config path. |
|
Expand a FactsheetConfig into the keyword arguments consumed by the generate_*_factsheet(...) functions. |
|
Remove outliers by the cuts of an |
|
Flatten nested group attribution into one DataFrame per group. |
|
Compare average and final realised sleeve exposures with grouped horizontal bars. |
|
one-page cross-sectional factsheet comparing instruments against a benchmark. |
|
display 2*2 plot with nav and Brinson attribution |
|
Plot signal, volatility, leverage and weight histories for each instrument. |
|
Compute excess return NAV after funding costs. |
|
file data management is organised as: file_path = RESOURCE_PATH/folder_name/file_name+file_type.value default value without optional arguments will be: file_path = RESOURCE_PATH/file_name.file_type.value |
|
Get the first or last non-NaN index for each column/series. |
|
Resolve the output directory through YAML, creating missing parents by default. |
|
pair normalised sums of risk-adjusted returns with the signal known before each window. |
|
Read YAML configuration, with private entries overriding packaged defaults. |
|
return annualised difference between mat_date and value_time |
|
Map a 1-based index to an alphabet character (1 -> A, 26 -> Z). |
|
set standard for joining parts of file name |
|
Apply constant leverage to an unlevered asset return series. |
|
loag Excel sheets to pandas dict dataset_keys = None, it will read all sheets |
|
pandas dict from csv files |
|
pandas dict from parquet files |
|
load dfs from feather files |
|
pandas from parquet |
|
Convert log returns to NAV using exponential compounding. |
|
Compute NAV for long-short strategy. |
|
map a signal to a bounded weight through the shape selected by |
|
eigenvalue clipping of a symmetric matrix: eigenvalues at or below |
|
column with xvar_str will be repeated to melted y_column index is ignored |
|
multiply data set with vector column-wise and normalize accounting for nans in data data can be indicators data with False/True |
|
in case operation of np array is needed to apply to pandas row wise, the numpy array is broadcast to pandas index the lenth = pandas.index |
|
plot boxplot of df[[x, y]] original_index use for melted df in term of original index |
|
Create comprehensive visualization of Brinson attribution results. |
|
Create formatted table visualization of Brinson attribution summary. |
|
Render supplied trees and membership with automatic or caller-owned axes. |
|
define plot time series |
|
Plot an existing full linkage with optional cluster-cutoff annotation. |
|
table with ci |
|
Plot labelled point estimates with optional error and reference values. |
|
Plot each input series as a density or histogram. |
|
line plot wrapper for sns, lineplot plot df using index x: str = None: x column y: str = None: y column hue: str = None: hue |
|
Plot the current annualised EWMA return bridge with Bartlett-HAC intervals. |
|
Plot additive current EWMA log-return Sharpe contributions. |
|
Plot full-sample return contributions over full-sample volatility. |
|
Plot expanding-prefix EWMA-WLS annualised alpha paths. |
|
Stacked portfolios by group and an optional solved coverage-floor frontier. |
|
plot returns at specified frequency for datadrfame columns are periods, rows are prices.columns |
|
compute annual matrix of performance var for a dict of strat end periods |
|
compute table of performance var for a dict of strat end periods |
|
scatter plot of performance stats |
|
plot ra perf table columns |
|
plot ra perf table and get ra performance columns with data as string for tables |
|
plot regime-conditional data of the classifier as stacked bars with regime colors. |
|
plot time series of returns correlations infered from prices |
|
plot corr table of prices |
|
Plot the last EWM return correlation matrix or its time average. |
|
Plot periodic returns as a colour-coded calendar table. |
|
plot returns at specified dates dict |
|
plot rolling performance |
|
Plot scatter regression with regime-conditional betas. |
|
Two-row diagnostic figure for a signal panel. |
|
Boxplot of per-asset β across horizons. |
|
Distribution of cross-sectional returns conditional on the signal. |
|
Run the predictive regression and render the composite figure. |
|
Per-group β distribution as boxplots, with regression t-stat annotation. |
|
plot returns at specified frequency |
|
Plot DataFrame columns as stacked areas or stacked bars. |
|
overlay the deepest drawdown episodes, each re-indexed to the number of grid steps since its start. |
|
Plot signed, stacked horizontal bars without relabeling caller data. |
|
Adjust asset NAVs to make PA returns additive to portfolio total. |
|
Aggregate portfolio returns across assets to single NAV. |
|
Score aligned predictions without clipping negative out-of-sample R-squared. |
|
Resample prices to specified frequency. |
|
Scale price returns by constant factor. |
|
dictionary of pandas to same Excel with dfs as separate sheets w adds/replaces with new excel; a appends to exisiting |
|
pandas dict to csv files |
|
pandas dict to parquet files |
|
pandas or list of pandas to one excel if_sheet_exists only for append mode mode = w: write new file mode = a: append to existing file |
|
save df to feather files index_col stands for the index: needs to be reset when saving and put back when loading |
|
pandas to parquet |
|
save matplotlib figures dict |
|
Transform each factor in its declared units using the standard return kernel. |
|
finite repciprocal with inf fills |
|
Compute portfolio returns from asset weights and returns. |
|
Compound returns to quarter-end via NAV round-trip. |
|
Compute total returns over entire price history. |
|
Set first non-NaN return(s) to zero for NAV initialization. |
|
update csv file with new rows: if the file exists, load the existing data, concatenate with df, optionally drop duplicate index entries via keep, and rewrite the file. |
|
Build weights and tracking-error panels for a strategy and benchmark. |
Explicitly imported modules¶
Not exported from qis: import these names from their module, for example
from qis.regimes import compute_regime_premium_table. They carry Args blocks and are
covered by the handbook chapters linked under each module.
qis.regimes¶
21 documented.
Methodology: The convexity premium and smart diversification.
Student-t degrees of freedom matching a sample excess kurtosis, |
|
Convexity premium, the realised Bear contribution less its null |
|
Regime means and second moments of a Gaussian benchmark, from its periodic volatility. |
|
Null regime contributions |
|
Closed-form frontier of the blends |
|
Bear contribution of a portfolio by the aggregation identity. |
|
Per-regime OLS betas of every asset on the benchmark, with the intercepts discarded. |
|
Regime betas of a panel with their stationary block-bootstrap standard errors. |
|
EWMA conditional means with the span applied within each regime's own return stream. |
|
EWMA-weighted per-regime betas on the benchmark and the calendar-time residual variances. |
|
Kappa of the symmetric three-bucket partition, the Sharpe cost of one unit of correlation. |
|
Annualised regime-mixture covariance by the law of total covariance. |
|
Annualised regime-mixture covariance of one complete classified panel. |
|
Correlation loading of each regime contribution under the Gaussian or Student-t null. |
|
Stationary block-bootstrap standard error and interval of each asset's convexity premium. |
|
Regime decomposition, null and convexity premium of every asset of a sampled frame. |
|
Per-period empirical regime moments of the benchmark on a supplied classification. |
|
Periodic returns with the benchmark-quantile regime of each period, from returns. |
|
Validated partition probabilities, the one-sigma cut when none are given. |
|
Ordered regime ids of a partition, from the lowest benchmark bucket up. |
|
Population probability of each bucket, the width of its probability interval. |
qis.utils.quantile_buckets¶
7 documented.
Methodology: Regime-conditional performance, The convexity premium and smart diversification.
Raised when estimated quantile edges leave a bucket without observations. |
|
Bucket of each observation for given interior edges, closed on the right with open ends. |
|
Quantile bucket of each observation as an ordered categorical. |
|
Quantile bucket of each observation, with the edges estimated from the observations. |
|
Interior quantile edges of the finite observations. |
|
Sample quantiles of the finite observations by the rule of this module. |
|
Probabilities of a partition, from 0 to 1. |