qis.PortfolioData¶
- class qis.PortfolioData(nav, weights=None, units=None, prices=None, instrument_pnl=None, realized_costs=None, input_weights=None, is_rebalancing=None, tickers_to_names_map=None, group_data=None, group_order=None, instrument_names=None, benchmark_prices=None, ticker=None, strategy_signal_data=None, covar_dict=None, turnover_unit_notional=None, turnover_computation_type=TurnoverComputationType.EXECUTED_NOTIONAL_NAV)[source]¶
Bases:
objectthe contract every portfolio in the stack satisfies, and the input to the factsheet layer.
Produced either by
qis.backtest_model_portfolio()or by an external backtester whose outputs match these fields; in the second casestrategy_signal_datacan carry the signals that drove the weights so the signal panels render too.Only
navis required. Everything else is derived in__post_init__when omitted, and the defaults describe a single-instrument delta-one holding of the nav itself:pricesbecomes the nav as a one-column frame,weightsandunitsbecome 1.0, costs become 0.0, and each instrument becomes its own group. A portfolio built that way reports correctly but has nothing to attribute, so pass the panels if attribution is wanted.instrument_pnl, when not given, is reconstructed asprices.ffill().pct_change() * weights.shift(1)— arithmetic returns on lagged weights, valued on last observed marks so a resumed quote books its full move. Pass it explicitly if the backtester computed pnl on a different convention.- Variables:
nav (pandas.Series) – portfolio nav, net of all costs and fees. The only required field
weights (pandas.DataFrame) – realised weights per instrument, which drift with prices between rebalancings; these are not the target weights that were requested
units (pandas.DataFrame) – instrument units held
prices (pandas.DataFrame) – prices of the portfolio universe
turnover_unit_notional (pandas.DataFrame) – value of one unit for turnover. Defaults to
pricesfor cash instruments; derivative backtests should supply contract notionalsturnover_computation_type (qis.perfstats.turnover.TurnoverComputationType) – default turnover convention for this portfolio
instrument_pnl (pandas.DataFrame) – arithmetic pnl contribution by instrument. When reconstructed from
pricesandweightsit is gross of trading costsrealized_costs (pandas.DataFrame) – trading costs actually incurred, by instrument
input_weights (numpy.ndarray | pandas.DataFrame | Dict[str, float]) – the target weights as supplied, kept for reference against
weightsis_rebalancing (pandas.Series) – flag per date marking where rebalancing took place
tickers_to_names_map (Dict[str, str] | None) – display names for long or opaque tickers
group_data (pandas.Series) – asset-class label per ticker, indexed by ticker; drives every grouped panel in the factsheets. Defaults to one group per instrument
group_order (List[str]) – display order of the groups
instrument_names (pandas.Series) – long names per ticker
benchmark_prices (pandas.DataFrame) – benchmark panel, reindexed onto the nav index and forward filled
ticker (str) – portfolio name; taken from
nav.namewhen omittedstrategy_signal_data (qis.portfolio.signal_data.StrategySignalData) – signals behind the weights, for the signal factsheet panels
covar_dict (Dict[pandas.Timestamp, pandas.DataFrame]) – annualised covariance matrix per date, required for risk contributions and tracking error
- Parameters:
nav (Series)
weights (DataFrame)
units (DataFrame)
prices (DataFrame)
instrument_pnl (DataFrame)
realized_costs (DataFrame)
is_rebalancing (Series)
group_data (Series)
instrument_names (Series)
benchmark_prices (DataFrame)
ticker (str)
strategy_signal_data (StrategySignalData)
turnover_unit_notional (DataFrame)
turnover_computation_type (TurnoverComputationType)
- __init__(nav, weights=None, units=None, prices=None, instrument_pnl=None, realized_costs=None, input_weights=None, is_rebalancing=None, tickers_to_names_map=None, group_data=None, group_order=None, instrument_names=None, benchmark_prices=None, ticker=None, strategy_signal_data=None, covar_dict=None, turnover_unit_notional=None, turnover_computation_type=TurnoverComputationType.EXECUTED_NOTIONAL_NAV)¶
- Parameters:
nav (Series)
weights (DataFrame)
units (DataFrame)
prices (DataFrame)
instrument_pnl (DataFrame)
realized_costs (DataFrame)
is_rebalancing (Series)
group_data (Series)
instrument_names (Series)
benchmark_prices (DataFrame)
ticker (str)
strategy_signal_data (StrategySignalData)
turnover_unit_notional (DataFrame)
turnover_computation_type (TurnoverComputationType)
- Return type:
None
Methods
__init__(nav[, weights, units, prices, ...])add_regime_shadows(ax, regime_benchmark[, ...])add regime shadows using regime_benchmark
compute_distribution_yield(paid_dividends[, ...])Ex-ante portfolio volatility sqrt(w' Σ w) implied by dated covariance matrices.
Per-period split of the portfolio return into benchmark contributions and a residual.
compute_portfolio_benchmark_betas(...[, ...])Holdings-based EWM betas of the portfolio to each benchmark.
compute_portfolio_vars([is_correlated, ...])Grouped report using Series labels and optional static look-through fractions.
compute_portfolio_vol([time_period, freq, span])Annualised EWM portfolio volatility, from holdings and from realised NAV returns.
compute_ra_perf_table([time_period, ...])compute_realized_pnl([time_period])Euler risk contributions w_i (Σ w)_i / sqrt(w' Σ w) implied by dated covariances.
compute_volume_participation(volumes[, ...])using avg weight
get_brinson_inputs([time_period, freq, is_net])Return instrument contributions and prior holdings for Brinson attribution.
get_costs([is_agg, is_grouped, time_period, ...])Return realized costs in raw currency or NAV-normalized units.
get_group_navs([time_period, ...])group total will exclude transaction costs so it is not equal to portfolio nav
get_grouped_cum_pnls([total_name, ...])compute grouped net long / short exposues
Computes grouped net long/short exposures by instrument groups.
get_input_weights([time_period])get_instruments_navs([time_period, ...])Return instrument contributions to compounded portfolio P&L.
using avg weight
Return simple instrument returns on the native reporting grid.
get_instruments_pnl([add_total, ...])Arithmetic P&L contribution of each instrument per period.
Shares of the realised P&L risk by instrument, summing to one.
get_instruments_returns([time_period])get_num_investable_instruments([time_period])get_performance_attribution([add_total, ...])get_portfolio_nav([time_period, freq, ticker])get nav using consistent function for all return computations
get nav using consistent function for all return computations
get_total_nav_with_group_navs([time_period, ...])group total will exclude transaction costs so it is not equal to portfolio nav
get_turnover([is_agg, is_grouped, ...])Grouped report using Series labels and optional static look-through fractions.
get_weights([is_input_weights, columns, ...])Grouped report using Series labels and optional static look-through fractions.
load(ticker)plot_benchmark_betas(benchmark_prices[, ...])plot_best_worst_returns([time_period, ...])plot_contributors([time_period, num_assets, ax])plot_current_var([snapshot_period, ...])Grouped report using Series labels and optional static look-through fractions.
plot_current_weights([is_grouped, ...])Grouped report using Series labels and optional static look-through fractions.
plot_distribution_yield(paid_dividends[, ...])plot_group_nav([regime_benchmark, ...])Grouped report using Series labels and optional static look-through fractions.
plot_last_weights_change([is_grouped, ...])Grouped report using Series labels and optional static look-through fractions.
plot_monthly_returns_heatmap([time_period, ax])plot_nav([regime_benchmark, time_period, ...])plot_performance_attribution([time_period, ...])attribute a portfolio metric across its instruments, one bar per instrument.
plot_periodic_returns([benchmark_prices, ...])Grouped report using Series labels and optional static look-through fractions.
plot_pnl([time_period])plot_portfolio_grouped_var([is_correlated, ...])Grouped report using Series labels and optional static look-through fractions.
plot_portfolio_vols([time_period, freq, ...])plot_ra_perf_table([benchmark_price, ...])Grouped report using Series labels and optional static look-through fractions.
plot_regime_data(benchmark_price[, ...])Grouped report using Series labels and optional static look-through fractions.
plot_returns_scatter(benchmark_price[, ...])Grouped report using Series labels and optional static look-through fractions.
plot_rolling_perf([rolling_perf_stat, ...])plot_turnover([regime_benchmark, is_agg, ...])Grouped report using Series labels and optional static look-through fractions.
plot_var_stack([is_grouped, is_correlated, ...])Grouped report using Series labels and optional static look-through fractions.
plot_vol_regimes(benchmark_price[, ...])Grouped report using Series labels and optional static look-through fractions.
plot_weights([is_input_weights, ...])save(ticker[, local_path])set_benchmark_prices(benchmark_prices)set_group_data(group_data[, group_order])set_ticker(ticker)Attributes
- strategy_signal_data: StrategySignalData = None¶
- turnover_computation_type: TurnoverComputationType = 'executed_notional_nav'¶
get nav using consistent function for all return computations
- Parameters:
time_period (TimePeriod)
freq (str | None)
ticker (str | None)
- Return type:
get nav using consistent function for all return computations
- Parameters:
time_period (TimePeriod)
freq (str | None)
- Return type:
- get_instruments_pnl(add_total=False, time_period=None, is_net=False, is_unit_based_traded_volume=True, is_compounded=False, freq=None)[source]¶
Arithmetic P&L contribution of each instrument per period.
- Parameters:
add_total (bool) – Insert a leading
Totalcolumn summing the instruments.time_period (TimePeriod) – Optional date interval applied after the net adjustment.
is_net (bool) – Deduct each period’s realised trading cost by instrument. The cost is divided by the preceding NAV, the capital base of the arithmetic contributions, so for a portfolio without fees, funding or carry the net contributions sum to the NAV return of each period. The opening trade is paid out of the baseline NAV and is not deducted from a return. Before aggregation, a missing contribution permits a cost-only fill only with confirmed zero beginning-period exposure; held or unknown exposure preserves missing P&L.
is_unit_based_traded_volume (bool) – Normalise currency costs by the preceding NAV when true; when false, deduct the currency costs unscaled.
is_compounded (bool) – Apply
expm1to the result.freq (str | None) – Optional resampling frequency; contributions are summed within each bin.
- Returns:
Instrument P&L contributions indexed by date.
- Raises:
ValueError – If NAV-normalized costs and NAV do not have identical unique row labels.
- Return type:
- get_performance_attribution(add_total=True, time_period=None, is_compounded=False)[source]¶
- Parameters:
add_total (bool)
time_period (TimePeriod)
is_compounded (bool)
- Return type:
- Parameters:
time_period (TimePeriod)
constant_trade_level (bool)
- Return type:
group total will exclude transaction costs so it is not equal to portfolio nav
- Parameters:
lookthrough_matrix (DataFrame | None) – Optional static instrument-by-sleeve fractions. Supplied rows are finite, nonnegative and sum to one; omitted rows use group_data. None preserves categorical reporting. This is an accounting split.
group_data (Series | None) – Ordinary instrument labels as a Series; defaults to portfolio metadata where available. Fractional memberships belong in lookthrough_matrix.
time_period (TimePeriod)
constant_trade_level (bool)
is_add_group_total (bool)
- Return type:
DataFrame | None
group total will exclude transaction costs so it is not equal to portfolio nav
- Parameters:
lookthrough_matrix (DataFrame | None) – Optional static instrument-by-sleeve fractions. Supplied rows are finite, nonnegative and sum to one; omitted rows use group_data. None preserves categorical reporting. This is an accounting split.
group_data (Series | None) – Ordinary instrument labels as a Series; defaults to portfolio metadata where available. Fractional memberships belong in lookthrough_matrix.
time_period (TimePeriod)
- Return type:
- get_weights(is_input_weights=False, columns=None, time_period=None, is_grouped=False, add_total=False, freq='W-WED', group_data=None, group_order=None, *, lookthrough_matrix=None)[source]¶
Grouped report using Series labels and optional static look-through fractions.
- Parameters:
lookthrough_matrix (DataFrame | None) – Optional static instrument-by-sleeve fractions. Supplied rows are finite, nonnegative and sum to one; omitted rows use group_data. None preserves categorical reporting. This is an accounting split.
group_data (Series) – Ordinary instrument labels as a Series; defaults to portfolio metadata where available. Fractional memberships belong in lookthrough_matrix.
is_input_weights (bool)
time_period (TimePeriod)
is_grouped (bool)
add_total (bool)
freq (str | None)
- Return type:
- get_grouped_long_short_weights(time_period=None, total_name='Total', weights_freq='W-WED', total_column=None, *, group_data=None, lookthrough_matrix=None)[source]¶
Computes grouped net long/short exposures by instrument groups.
Groups portfolio weights by predefined instrument categories and calculates aggregate exposure metrics including total exposure, net long positions, and net short positions for each group.
- Parameters:
lookthrough_matrix (DataFrame | None) – Optional static instrument-by-sleeve fractions. Supplied rows are finite, nonnegative and sum to one; omitted rows use group_data. None preserves categorical reporting. This is an accounting split.
group_data (Series | None) – Ordinary instrument labels as a Series; defaults to portfolio metadata where available. Fractional memberships belong in lookthrough_matrix.
time_period (TimePeriod) – Time period for which to calculate exposures. If None, uses the full available time series.
total_name (str) – Column name for the total exposure aggregation. Defaults to ‘Total’.
weights_freq (str | None) – Frequency for resampling exposures data. Defaults to ‘W-WED’ (weekly on Wednesday).
total_column (str | None) – Column name for total in group dictionary. If None, no total column is included in grouping.
- Returns:
grouped_weights_agg: Dictionary mapping group names to DataFrames with columns for total, net long, and net short exposures.
grouped_weights_by_inst: Dictionary mapping group names to DataFrames containing individual instrument exposures within each group.
- Return type:
A tuple containing
Note
Positive exposures represent long positions, negative exposures represent short positions. Net long sums only positive values, net short sums only negative values.
- get_grouped_cum_pnls(total_name='Total', time_period=None, *, group_data=None, lookthrough_matrix=None)[source]¶
compute grouped net long / short exposues
- Parameters:
lookthrough_matrix (DataFrame | None) – Optional static instrument-by-sleeve fractions. Supplied rows are finite, nonnegative and sum to one; omitted rows use group_data. None preserves categorical reporting. This is an accounting split.
group_data (Series | None) – Ordinary instrument labels as a Series; defaults to portfolio metadata where available. Fractional memberships belong in lookthrough_matrix.
total_name (str)
time_period (TimePeriod)
- Return type:
- get_turnover(is_agg=False, is_grouped=False, group_data=None, group_order=None, time_period=None, roll_period=260, is_vol_adjusted=False, add_total=True, vol_span=33, freq=None, is_unit_based_traded_volume=None, turnover_computation_type=None, vols=None, *, lookthrough_matrix=None, **kwargs)[source]¶
Grouped report using Series labels and optional static look-through fractions.
- Parameters:
lookthrough_matrix (DataFrame | None) – Optional static instrument-by-sleeve fractions. Supplied rows are finite, nonnegative and sum to one; omitted rows use group_data. None preserves categorical reporting. This is an accounting split.
group_data (Series) – Ordinary instrument labels as a Series; defaults to portfolio metadata where available. Fractional memberships belong in lookthrough_matrix.
is_agg (bool)
is_grouped (bool)
time_period (TimePeriod)
roll_period (int | None)
is_vol_adjusted (bool)
add_total (bool)
vol_span (int)
freq (str | None)
is_unit_based_traded_volume (bool | None)
turnover_computation_type (TurnoverComputationType | None)
vols (DataFrame | None)
- Return type:
- get_costs(is_agg=False, is_grouped=False, time_period=None, add_total=True, is_unit_based_traded_volume=None, roll_period=260, freq=None, *, group_data=None, lookthrough_matrix=None)[source]¶
Return realized costs in raw currency or NAV-normalized units.
- Parameters:
lookthrough_matrix (DataFrame | None) – Optional static instrument-by-sleeve fractions. Supplied rows are finite, nonnegative and sum to one; omitted rows use group_data. None preserves categorical reporting. This is an accounting split.
group_data (Series | None) – Ordinary instrument labels as a Series; defaults to portfolio metadata where available. Fractional memberships belong in lookthrough_matrix.
is_agg (bool) – Aggregate costs across instruments when true.
is_grouped (bool) – Aggregate instruments using the portfolio’s group metadata.
time_period (TimePeriod) – Optional date interval applied after aggregation.
add_total (bool) – Add a portfolio-total column to non-aggregate results.
is_unit_based_traded_volume (bool | None) – Normalize currency costs by NAV when true. Normalized costs require identical unique NAV and cost row labels and align NAV by label.
roll_period (int | None) – Optional trailing observation count used to sum costs.
freq (str | None) – Optional resampling frequency applied before the rolling sum.
- Returns:
Cost series or frame retaining the report row labels.
- Raises:
ValueError – If normalized costs and NAV do not have identical unique row labels.
- Return type:
- compute_realized_pnl(time_period=None)[source]¶
- Parameters:
time_period (TimePeriod)
- Return type:
- compute_portfolio_benchmark_betas(benchmark_prices, time_period=None, freq_beta='B', factor_beta_span=63)[source]¶
Holdings-based EWM betas of the portfolio to each benchmark.
The portfolio beta to benchmark q is sum_i w_{i,t} beta_{i,q,t}, with instrument betas estimated by EWM regression of
freq_betalog returns. The defaults are those ofcompute_portfolio_benchmark_attribution, so the betas shown are the betas the attribution applies; the defaults werefreq_beta=None(the price index’s own grid) andfactor_beta_span=65before they were aligned.- Parameters:
benchmark_prices (DataFrame) – Benchmark prices, one column per benchmark.
time_period (TimePeriod) – Optional period applied to the output after estimation.
freq_beta (str) – Return frequency of the beta regressions (default ‘B’).
factor_beta_span (int) – EWM span of the beta regressions in
freq_betaperiods (default 63, a quarter of business days).
- Returns:
Portfolio beta per benchmark and date.
- Return type:
- compute_portfolio_benchmark_attribution(benchmark_prices, time_period=None, freq_beta='B', factor_beta_span=63, residual_name='Alpha')[source]¶
Per-period split of the portfolio return into benchmark contributions and a residual.
On the grid of the betas, benchmark q contributes beta_{q,t-1} x_{q,t}, with x_{q,t} the simple benchmark return and beta the holdings-based beta of
compute_portfolio_benchmark_betasat the previous date; the residual column is the simple NAV return minus the sum of the contributions. The returns are per-period simple returns and nothing is compounded: the columns add up to the NAV return of each period, and their cumulative sums (as the factsheets plot) add up to the sum of NAV returns, not to the compounded return.- Parameters:
benchmark_prices (DataFrame) – Benchmark prices, one column per benchmark.
time_period (TimePeriod) – Optional period applied to the output after estimation.
freq_beta (str) – Return frequency of the beta regressions (default ‘B’).
factor_beta_span (int) – EWM span of the beta regressions in
freq_betaperiods (default 63, a quarter of business days).residual_name (str) – Name of the residual column.
- Returns:
Contribution of each benchmark and the residual per period.
- Return type:
- get_instruments_returns(time_period=None)[source]¶
- Parameters:
time_period (TimePeriod)
- Return type:
- get_instruments_periodic_returns(time_period=None, freq='ME')[source]¶
Return simple instrument returns on the native reporting grid.
- Parameters:
time_period (TimePeriod) – Optional interval; its first observed price is the starting baseline.
freq (str) – Reporting frequency, or None for the native observation grid.
- Returns:
Instrument returns with an undefined first reported row. On unique increasing dates, retain the opening price before native frequency sampling, which still determines the reported dates and first return. Ragged histories retain native gap reconstruction; other date axes retain native results and diagnostics.
- Return type:
- get_instruments_performance_attribution(time_period=None, constant_trade_level=False)[source]¶
Return instrument contributions to compounded portfolio P&L.
On unique, increasing dates, contributions accrue on preceding portfolio wealth, not on independently compounded instrument NAVs. Their sum is the compounded return of the supplied instrument P&L; it matches NAV performance only when both include the same costs, fees and cash flows. Missing contributions retain the existing zero-fill convention. Other date axes retain native instrument-NAV results, warnings and errors.
- Parameters:
time_period (TimePeriod) – Optional report interval; its first observation is the NAV baseline, so only subsequent contributions enter the result.
constant_trade_level (bool) – Retain the legacy arithmetic instrument-NAV return instead of scaling contributions by compounded portfolio wealth.
- Returns:
Float64 contributions indexed by instrument or configured display name, named after the portfolio. A single baseline observation has undefined (NaN) returns.
- Return type:
- get_instruments_pnl_risk_attribution(time_period=None, is_standalone=False)[source]¶
Shares of the realised P&L risk by instrument, summing to one.
By default the shares are the ex-post Euler contributions to the variance of the portfolio P&L. With x_{i,t} the arithmetic P&L contribution of instrument i (
get_instruments_pnl, gross of costs, missing values counted as zero) and x_{p,t} = sum_i x_{i,t}, instrument i has the share Cov(x_i, x_p) / Var(x_p), the slope of its P&L on the portfolio P&L. The shares sum to one because the sample covariance is bilinear; multiplied by the standard deviation of x_p they are contributions that add up to the portfolio P&L volatility. A hedge that lowered the realised volatility has a negative share.- Parameters:
time_period (TimePeriod) – Optional period over which the P&L is taken.
is_standalone (bool) – Return standalone volatility shares instead, the former output: the standard deviation of each instrument’s P&L (
ddof=0, over its dates with non-zero P&L) divided by the sum of these. They are non-negative, ignore correlation and do not decompose the portfolio risk.
- Returns:
Share per instrument, renamed with
tickers_to_names_map. NaN when the portfolio P&L has no variance, or, for standalone shares, for an instrument with no non-zero P&L.- Return type:
- get_performance_attribution_data(attribution_metric=AttributionMetric.PNL, time_period=None, turnover_computation_type=None, is_unit_based_traded_volume=None, vols=None, **kwargs)[source]¶
- Parameters:
attribution_metric (AttributionMetric)
time_period (TimePeriod)
turnover_computation_type (TurnoverComputationType | None)
is_unit_based_traded_volume (bool | None)
vols (DataFrame | None)
- Return type:
- get_num_investable_instruments(time_period=None)[source]¶
- Parameters:
time_period (TimePeriod)
- Return type:
- get_instruments_performance_table(time_period=None, portfolio_name='Attribution')[source]¶
using avg weight
- Parameters:
time_period (TimePeriod)
portfolio_name (str)
- Return type:
- get_brinson_inputs(time_period=None, freq='ME', is_net=False)[source]¶
Return instrument contributions and prior holdings for Brinson attribution.
Start from the full stored arithmetic instrument P&L before slicing, so the first requested return retains its preceding NAV/holding observation. With is_net=True, deduct each realised trading cost divided by the preceding NAV, exactly once. Management fees and cash funding are not instrument trading costs and are not added. Coarser-period contributions compound using within-period portfolio wealth; prior weights are averaged within the period. Those averages are effective exposures, not weights held constant throughout a month. For exact allocation effects across intra-period trades, use native inputs (freq=None), compute Brinson and only then aggregate its linked effect increments. Contributions reconcile to NAV returns when fees/funding are zero and is_net=True.
- Parameters:
time_period (TimePeriod | None) – Return dates to include, excluding the NAV baseline.
freq (str | None) – Optional aggregation frequency; None keeps the native observations.
is_net (bool) – Include realised trading-cost drag by instrument.
- Returns:
Arithmetic instrument return contributions and their applied weight panel.
- Raises:
ValueError – If net costs and NAV do not have identical unique row labels.
- Return type:
- get_attribution_table_by_instrument(time_period=None, freq='ME', is_input_weights=False)[source]¶
using avg weight
- Parameters:
time_period (TimePeriod)
freq (str)
is_input_weights (bool)
- Return type:
- compute_portfolio_vol(time_period=None, freq='W-WED', span=13)[source]¶
Annualised EWM portfolio volatility, from holdings and from realised NAV returns.
Both columns use simple returns on the
freqgrid.instrument weighted voliscompute_portfolio_volof the instrument returns with the realised weights forward-filled to the grid and lagged one period: the point-in-time EWM covariance contracted with the weights held over each period.strategy returns volis the EWM volatility of the simple NAV return, the realised counterpart. They differ by weight drift and rebalancing inside the grid periods, by costs and fees, and because the first applies the latest weights to the whole covariance history.- Parameters:
time_period (TimePeriod) – Optional period applied to the output after estimation.
freq (str) – Return grid (default ‘W-WED’).
span (int) – EWM span in
freqperiods (default 13).
- Returns:
DataFrame with the columns
instrument weighted volandstrategy returns vol.- Return type:
- compute_distribution_yield(paid_dividends, div_rolling_freq='ME', div_rolling_period=12, time_period=None)[source]¶
- compute_portfolio_vars(is_correlated=True, time_period=None, freq='B', total_column='Total', vol_span=33, group_data=None, group_order=None, *, lookthrough_matrix=None)[source]¶
Grouped report using Series labels and optional static look-through fractions.
- Parameters:
lookthrough_matrix (DataFrame | None) – Optional static instrument-by-sleeve fractions. Supplied rows are finite, nonnegative and sum to one; omitted rows use group_data. None preserves categorical reporting. This is an accounting split.
group_data (Series) – Ordinary instrument labels as a Series; defaults to portfolio metadata where available. Fractional memberships belong in lookthrough_matrix.
is_correlated (bool)
time_period (TimePeriod)
freq (str)
total_column (str | None)
- Return type:
- compute_ex_anti_portfolio_vol_implied_by_covar(covar_dict=None, freq=None)[source]¶
Ex-ante portfolio volatility sqrt(w’ Σ w) implied by dated covariance matrices.
With
freq=Nonethe volatility is evaluated on each covariance date with the input weights (the realised weights when the input was not a DataFrame) selected as of that date: the latest weights dated at or before it, zero before the first weight date, as inRiskModel. Withfreqset, it is evaluated on each date of the realised weights resampled tofreq, with the latest covariance at or before that date.- Parameters:
- Returns:
Portfolio volatility per date, in the units of the square root of the covariance. An asset without a covariance on a date (a NaN row and column) is ignored when its weight is zero; when it is held, the volatility on that date is NaN.
- Raises:
ValueError – If no covariance is supplied or stored.
- Return type:
- compute_risk_contributions_implied_by_covar(covar_dict=None, group_data=None, group_order=None, freq=None, normalise=False, time_period=None, *, lookthrough_matrix=None)[source]¶
Euler risk contributions w_i (Σ w)_i / sqrt(w’ Σ w) implied by dated covariances.
With
freq=Nonethe contributions are evaluated on each covariance date with the input weights (the realised weights when the input was not a DataFrame) selected as of that date: the latest weights dated at or before it, zero before the first weight date, as inRiskModel. Withfreqset, they are evaluated on each date of the realised weights resampled tofreqafter the first covariance date, with the latest covariance at or before that date.- Parameters:
lookthrough_matrix (DataFrame | None) – Optional static instrument-by-sleeve fractions. Supplied rows are finite, nonnegative and sum to one; omitted rows use group_data. None preserves categorical reporting. This is an accounting split.
covar_dict (Dict[Timestamp, DataFrame]) – Covariance matrix per date;
self.covar_dictwhen None.group_data (Series) – Optional group of each instrument; contributions are summed by group.
freq (str | None) – Optional grid of the realised weights; None evaluates on the covariance dates.
normalise (bool) – Rescale each row to sum to one (percentage contributions).
time_period (TimePeriod) – Optional period applied to the weights before the alignment.
- Returns:
Contributions per date and instrument or group, in volatility units, or shares when
normaliseis True. Unknown risk remains missing through grouping and normalization; genuinely zero risk stays zero.- Raises:
ValueError – If no covariance is supplied or stored.
- Return type:
- add_regime_shadows(ax, regime_benchmark, index=None, regime_classifier=<qis.perfstats.regime_classifier.BenchmarkReturnsQuantilesRegime object>)[source]¶
add regime shadows using regime_benchmark
- Parameters:
ax (Axes)
regime_benchmark (str)
index (Index)
regime_classifier (BenchmarkReturnsQuantilesRegime)
- Return type:
None
- Parameters:
regime_benchmark (str)
time_period (TimePeriod)
add_benchmarks (bool)
regime_classifier (BenchmarkReturnsQuantilesRegime)
ax (Axes)
- Return type:
None
Grouped report using Series labels and optional static look-through fractions.
- Parameters:
lookthrough_matrix (DataFrame | None) – Optional static instrument-by-sleeve fractions. Supplied rows are finite, nonnegative and sum to one; omitted rows use group_data. None preserves categorical reporting. This is an accounting split.
group_data (Series | None) – Ordinary instrument labels as a Series; defaults to portfolio metadata where available. Fractional memberships belong in lookthrough_matrix.
regime_benchmark (str)
time_period (TimePeriod)
add_benchmarks (bool)
regime_classifier (BenchmarkReturnsQuantilesRegime)
ax (Axes)
- Return type:
None
- plot_portfolio_vols(time_period=None, freq='W-WED', span=13, regime_benchmark=None, regime_classifier=<qis.perfstats.regime_classifier.BenchmarkReturnsQuantilesRegime object>, ax=None, **kwargs)[source]¶
- Parameters:
time_period (TimePeriod)
freq (str)
span (int)
regime_benchmark (str)
regime_classifier (BenchmarkReturnsQuantilesRegime)
ax (Axes)
- Return type:
- plot_rolling_perf(rolling_perf_stat=RollingPerfStat.SHARPE, add_benchmarks=False, regime_benchmark=None, time_period=None, rolling_window=1300, roll_freq=None, legend_stats=LegendStats.AVG_LAST, title=None, regime_classifier=<qis.perfstats.regime_classifier.BenchmarkReturnsQuantilesRegime object>, ax=None, **kwargs)[source]¶
- Parameters:
rolling_perf_stat (RollingPerfStat)
add_benchmarks (bool)
regime_benchmark (str)
time_period (TimePeriod)
rolling_window (int)
roll_freq (str | None)
legend_stats (LegendStats)
title (str | None)
regime_classifier (BenchmarkReturnsQuantilesRegime)
ax (Axes)
- Return type:
- compute_ra_perf_table(time_period=None, perf_params=None, perf_columns=(PerfStat.P.a. return, PerfStat.Vol, PerfStat.Sharpe (rf=0), PerfStat.Max DD, PerfStat.Skewness, PerfStat.An Alpha, PerfStat.Beta, PerfStat.R2, PerfStat.p-Alpha), **kwargs)[source]¶
- Parameters:
time_period (TimePeriod)
perf_params (PerfParams)
- Return type:
- plot_ra_perf_table(benchmark_price=None, benchmark=None, is_grouped=True, time_period=None, perf_params=None, perf_columns=(PerfStat.P.a. return, PerfStat.Vol, PerfStat.Sharpe (rf=0), PerfStat.Max DD, PerfStat.Skewness, PerfStat.An Alpha, PerfStat.Beta, PerfStat.R2, PerfStat.p-Alpha), title=None, ax=None, *, group_data=None, lookthrough_matrix=None, **kwargs)[source]¶
Grouped report using Series labels and optional static look-through fractions.
- Parameters:
lookthrough_matrix (DataFrame | None) – Optional static instrument-by-sleeve fractions. Supplied rows are finite, nonnegative and sum to one; omitted rows use group_data. None preserves categorical reporting. This is an accounting split.
group_data (Series | None) – Ordinary instrument labels as a Series; defaults to portfolio metadata where available. Fractional memberships belong in lookthrough_matrix.
benchmark (str)
is_grouped (bool)
time_period (TimePeriod)
perf_params (PerfParams)
title (str)
ax (Axes)
- Return type:
None
- plot_returns_scatter(benchmark_price, is_grouped=True, time_period=None, title=None, freq='QE', ax=None, *, group_data=None, lookthrough_matrix=None, **kwargs)[source]¶
Grouped report using Series labels and optional static look-through fractions.
- Parameters:
lookthrough_matrix (DataFrame | None) – Optional static instrument-by-sleeve fractions. Supplied rows are finite, nonnegative and sum to one; omitted rows use group_data. None preserves categorical reporting. This is an accounting split.
group_data (Series | None) – Ordinary instrument labels as a Series; defaults to portfolio metadata where available. Fractional memberships belong in lookthrough_matrix.
benchmark_price (Series)
is_grouped (bool)
time_period (TimePeriod)
title (str)
freq (str)
ax (Axes)
- Return type:
None
- plot_monthly_returns_heatmap(time_period=None, ax=None, **kwargs)[source]¶
- Parameters:
time_period (TimePeriod)
ax (Axes)
- Return type:
None
- plot_periodic_returns(benchmark_prices=None, is_grouped=True, time_period=None, heatmap_freq='YE', date_format='%Y', transpose=True, title=None, ax=None, *, group_data=None, lookthrough_matrix=None, **kwargs)[source]¶
Grouped report using Series labels and optional static look-through fractions.
- Parameters:
lookthrough_matrix (DataFrame | None) – Optional static instrument-by-sleeve fractions. Supplied rows are finite, nonnegative and sum to one; omitted rows use group_data. None preserves categorical reporting. This is an accounting split.
group_data (Series | None) – Ordinary instrument labels as a Series; defaults to portfolio metadata where available. Fractional memberships belong in lookthrough_matrix.
is_grouped (bool)
time_period (TimePeriod)
heatmap_freq (str)
date_format (str)
transpose (bool)
title (str)
ax (Axes)
- Return type:
None
- plot_regime_data(benchmark_price, is_grouped=True, regime_data_to_plot=RegimeData.REGIME_SHARPE, time_period=None, var_format=None, is_conditional_sharpe=True, legend_loc='upper center', title=None, perf_params=None, regime_classifier=<qis.perfstats.regime_classifier.BenchmarkReturnsQuantilesRegime object>, ax=None, *, group_data=None, lookthrough_matrix=None, **kwargs)[source]¶
Grouped report using Series labels and optional static look-through fractions.
- Parameters:
lookthrough_matrix (DataFrame | None) – Optional static instrument-by-sleeve fractions. Supplied rows are finite, nonnegative and sum to one; omitted rows use group_data. None preserves categorical reporting. This is an accounting split.
group_data (Series | None) – Ordinary instrument labels as a Series; defaults to portfolio metadata where available. Fractional memberships belong in lookthrough_matrix.
benchmark_price (Series)
is_grouped (bool)
regime_data_to_plot (RegimeData)
time_period (TimePeriod)
var_format (str | None)
is_conditional_sharpe (bool)
legend_loc (str | None)
title (str)
perf_params (PerfParams)
regime_classifier (BenchmarkReturnsQuantilesRegime)
ax (Axes)
- Return type:
- plot_vol_regimes(benchmark_price, is_grouped=True, time_period=None, title=None, freq='ME', ax=None, *, group_data=None, lookthrough_matrix=None, **kwargs)[source]¶
Grouped report using Series labels and optional static look-through fractions.
- Parameters:
lookthrough_matrix (DataFrame | None) – Optional static instrument-by-sleeve fractions. Supplied rows are finite, nonnegative and sum to one; omitted rows use group_data. None preserves categorical reporting. This is an accounting split.
group_data (Series | None) – Ordinary instrument labels as a Series; defaults to portfolio metadata where available. Fractional memberships belong in lookthrough_matrix.
benchmark_price (Series)
is_grouped (bool)
time_period (TimePeriod)
title (str)
freq (str)
ax (Axes)
- Return type:
- plot_contributors(time_period=None, num_assets=10, ax=None, **kwargs)[source]¶
- Parameters:
time_period (TimePeriod)
num_assets (int)
ax (Axes)
- Return type:
None
- plot_best_worst_returns(time_period=None, num_returns=10, ax=None, **kwargs)[source]¶
- Parameters:
time_period (TimePeriod)
num_returns (int)
ax (Axes)
- Return type:
None
- plot_pnl(time_period=None)[source]¶
- Parameters:
time_period (TimePeriod)
- Return type:
None
- plot_weights(is_input_weights=True, add_mean_levels=False, use_bar_plot=False, columns=None, freq=None, is_yaxis_limit_01=True, bbox_to_anchor=None, legend_stats=LegendStats.FIRST_AVG_LAST, var_format='{:.1%}', title=None, ax=None, **kwargs)[source]¶
- plot_performance_attribution(time_period=None, attribution_metric=AttributionMetric.PNL, add_top_bar_values=None, remove_zero_data=True, shorten_instrument_names=True, max_bars=None, fontsize=10, ax=None, turnover_computation_type=None, is_unit_based_traded_volume=None, vols=None, **kwargs)[source]¶
attribute a portfolio metric across its instruments, one bar per instrument.
The bar order is the instrument order of the portfolio, which is the group order, so the asset-class blocks are visible. That order is kept until the universe outgrows the panel: past roughly 60 instruments on a half-page panel the rotated tick labels overlap and the panel stops naming anything. Past that point
max_barsreduces it to the tails, sorted by the attributed value, with the folded remainder stated in the title. Seereduce_attribution_to_tails()for the reduction andqis.plots.utils.estimate_bar_label_capacity()for the geometry.- Parameters:
time_period (TimePeriod) – window to attribute over. None uses the full history
attribution_metric (AttributionMetric) – what is attributed - P&L, its risk share, costs or turnover
add_top_bar_values (bool | None) – print the value above each bar. None prints them at 20 bars or fewer, where they fit
remove_zero_data (bool) – drop instruments whose attribution is zero, which is what an instrument never traded in the window looks like
shorten_instrument_names (bool) – truncate names to 15 characters. This bounds how far the labels extend below the axis; it does not widen the axis, because a rotated label is as wide as the font is tall whatever the string says
max_bars (int | None) – bars to keep. None reduces only once the labels would crowd, so a panel that reads today is untouched. 0 disables the reduction and plots everything
fontsize (float) – tick label font size, which sets how many labels the panel holds
ax (Axes) – axis to draw on
turnover_computation_type (TurnoverComputationType | None) – turnover convention for turnover attribution
is_unit_based_traded_volume (bool | None) – deprecated turnover selector
vols (DataFrame | None) – annualized volatility panel for volatility-normalized weight turnover
**kwargs – forwarded to
qis.plot_bars()
- Return type:
None
- plot_benchmark_betas(benchmark_prices, regime_benchmark=None, time_period=None, freq='W-WED', title=None, beta_span=52, regime_classifier=None, add_zero_line=True, ax=None, **kwargs)[source]¶
- Parameters:
benchmark_prices (DataFrame)
regime_benchmark (str)
time_period (TimePeriod)
freq (str)
title (str)
beta_span (int)
regime_classifier (BenchmarkReturnsQuantilesRegime)
add_zero_line (bool)
ax (Axes)
- Return type:
None
- plot_portfolio_grouped_var(is_correlated=True, regime_benchmark=None, time_period=None, freq='B', title=None, total_column='Total', vol_span=33, regime_classifier=None, ax=None, *, group_data=None, lookthrough_matrix=None, **kwargs)[source]¶
Grouped report using Series labels and optional static look-through fractions.
- Parameters:
lookthrough_matrix (DataFrame | None) – Optional static instrument-by-sleeve fractions. Supplied rows are finite, nonnegative and sum to one; omitted rows use group_data. None preserves categorical reporting. This is an accounting split.
group_data (Series | None) – Ordinary instrument labels as a Series; defaults to portfolio metadata where available. Fractional memberships belong in lookthrough_matrix.
is_correlated (bool)
regime_benchmark (str)
time_period (TimePeriod)
freq (str)
title (str)
total_column (str | None)
vol_span (int)
regime_classifier (BenchmarkReturnsQuantilesRegime)
ax (Axes)
- Return type:
None
- plot_current_weights(is_grouped=False, add_top_bar_values=None, time_period=None, title=None, group_data=None, group_order=None, ax=None, *, lookthrough_matrix=None, **kwargs)[source]¶
Grouped report using Series labels and optional static look-through fractions.
- Parameters:
lookthrough_matrix (DataFrame | None) – Optional static instrument-by-sleeve fractions. Supplied rows are finite, nonnegative and sum to one; omitted rows use group_data. None preserves categorical reporting. This is an accounting split.
group_data (Series) – Ordinary instrument labels as a Series; defaults to portfolio metadata where available. Fractional memberships belong in lookthrough_matrix.
is_grouped (bool)
add_top_bar_values (bool | None)
time_period (TimePeriod)
title (str)
ax (Axes)
- Return type:
None
- plot_last_weights_change(is_grouped=False, title=None, add_top_bar_values=None, weights_change_lag=None, ax=None, *, group_data=None, lookthrough_matrix=None, **kwargs)[source]¶
Grouped report using Series labels and optional static look-through fractions.
- Parameters:
lookthrough_matrix (DataFrame | None) – Optional static instrument-by-sleeve fractions. Supplied rows are finite, nonnegative and sum to one; omitted rows use group_data. None preserves categorical reporting. This is an accounting split.
group_data (Series | None) – Ordinary instrument labels as a Series; defaults to portfolio metadata where available. Fractional memberships belong in lookthrough_matrix.
is_grouped (bool)
title (str)
add_top_bar_values (bool | None)
weights_change_lag (int | None)
ax (Axes)
- Return type:
None
- plot_current_var(snapshot_period=SnapshotPeriod.LAST, is_grouped=False, is_correlated=True, time_period=None, freq='B', title=None, add_top_bar_values=None, total_column='Total', vol_span=33, ax=None, *, group_data=None, lookthrough_matrix=None, **kwargs)[source]¶
Grouped report using Series labels and optional static look-through fractions.
- Parameters:
lookthrough_matrix (DataFrame | None) – Optional static instrument-by-sleeve fractions. Supplied rows are finite, nonnegative and sum to one; omitted rows use group_data. None preserves categorical reporting. This is an accounting split.
group_data (Series | None) – Ordinary instrument labels as a Series; defaults to portfolio metadata where available. Fractional memberships belong in lookthrough_matrix.
snapshot_period (SnapshotPeriod)
is_grouped (bool)
is_correlated (bool)
time_period (TimePeriod)
freq (str)
title (str)
add_top_bar_values (bool | None)
total_column (str | None)
ax (Axes)
- Return type:
None
- plot_var_stack(is_grouped=True, is_correlated=True, time_period=None, freq='B', title=None, stack_freq='W-WED', vol_span=33, ax=None, *, group_data=None, lookthrough_matrix=None, **kwargs)[source]¶
Grouped report using Series labels and optional static look-through fractions.
- Parameters:
lookthrough_matrix (DataFrame | None) – Optional static instrument-by-sleeve fractions. Supplied rows are finite, nonnegative and sum to one; omitted rows use group_data. None preserves categorical reporting. This is an accounting split.
group_data (Series | None) – Ordinary instrument labels as a Series; defaults to portfolio metadata where available. Fractional memberships belong in lookthrough_matrix.
is_grouped (bool)
is_correlated (bool)
time_period (TimePeriod)
freq (str)
title (str)
stack_freq (str | None)
vol_span (int)
ax (Axes)
- Return type:
None
- plot_distribution_yield(paid_dividends, time_period=None, div_rolling_freq='ME', div_rolling_period=12, axs=None, **kwargs)[source]¶
- plot_turnover(regime_benchmark=None, is_agg=False, is_grouped=False, group_data=None, group_order=None, time_period=None, turnover_rolling_period=260, freq_turnover='B', add_total=True, title=None, regime_classifier=None, ax=None, turnover_computation_type=None, is_unit_based_traded_volume=None, vols=None, *, lookthrough_matrix=None, **kwargs)[source]¶
Grouped report using Series labels and optional static look-through fractions.
- Parameters:
lookthrough_matrix (DataFrame | None) – Optional static instrument-by-sleeve fractions. Supplied rows are finite, nonnegative and sum to one; omitted rows use group_data. None preserves categorical reporting. This is an accounting split.
group_data (Series) – Ordinary instrument labels as a Series; defaults to portfolio metadata where available. Fractional memberships belong in lookthrough_matrix.
regime_benchmark (str)
is_agg (bool)
is_grouped (bool)
time_period (TimePeriod)
turnover_rolling_period (int | None)
freq_turnover (str | None)
add_total (bool)
title (str)
regime_classifier (BenchmarkReturnsQuantilesRegime)
ax (Axes)
turnover_computation_type (TurnoverComputationType | None)
is_unit_based_traded_volume (bool | None)
vols (DataFrame | None)
- Return type:
None