Plotting
PortfolioOptimisers.plot_portfolio_cumulative_returns — Function
plot_portfolio_cumulative_returns(
w::VecNum_VecVecNum,
X::MatNum,
fees::Option{<:Fees} = nothing;
ts::AbstractVector = 1:size(X, 1),
compound::Bool = false,
kwargs...
) -> Plot
plot_portfolio_cumulative_returns(
w::VecNum_VecVecNum,
pr::Pr_RR,
fees::Option{<:Fees} = nothing;
ts::AbstractVector = 1:size(pr.X, 1),
compound::Bool = false,
kwargs...
) -> Plot
plot_portfolio_cumulative_returns(
res::OptimisationResult,
pr::Pr_RR;
fees::Option{<:Fees} = nothing,
compound::Bool = false,
kwargs...
) -> Plot
plot_portfolio_cumulative_returns(
res::OptimisationResult;
fees::Option{<:Fees} = nothing,
compound::Bool = false,
kwargs...
) -> Plot
plot_portfolio_cumulative_returns(
pred::Union{PredictionResult, MultiPeriodPredictionResult};
compound::Bool = false,
kwargs...
) -> Plot
plot_portfolio_cumulative_returns(
ppred::PopulationPredictionResult;
compound::Bool = false,
kwargs...
) -> Plot
plot_portfolio_cumulative_returns(
net_ret::VecNum_VecVecNum;
ts::AbstractVector,
compound::Bool = false,
kwargs...
) -> PlotPlot the cumulative returns of a portfolio against time.
The curve is cumulative_returns of the net portfolio returns that calc_net_returns forms from w, X and fees. A vector of weight vectors draws one curve per portfolio, labelled Portfolio i. The method that takes net_ret draws a return series the caller already formed. A population draws the curve of each member on one figure, labelled by the key of the member that portfolio_report uses. A member with many portfolios adds Portfolio i to its key. Each curve of a population takes kwargs, as the curve of a path does. The package extension PortfolioOptimisersPlotsExt implements the methods, and it loads after using StatsPlots.
A gapped panel reaches this figure only through the returns that the caller gives it. A prediction arity is finite already, because the fold set the Held Gap to zero once in predict. A w, X or w, pr arity computes on the matrix that the caller holds and checks nothing, and X * w is NaN at a gap even where the weight is zero. Score a gapped panel through predict(res, rd) and plot the prediction.
Arguments
w: Portfolio weights vector, or a vector of weight vectors.X: Asset returns matrix (observations × assets).fees: Transaction fees, ornothing.ts: Labels of the time axis. AReturnsResultthat carriestsreplaces the keyword with its own.compound: Compound the returns whentrue, and sum them otherwise.pr: Prior result orReturnsResult. The figure reads itsX.res: Optimisation result. The figure reads its weights, and its fees whenfeesisnothing, on its investable universe. Withoutpr, it reads the returns of the prior it was fitted on.pred: A prediction, whose return series the figure draws.ppred: A population of predictions.net_ret: Net portfolio returns, or a vector of such series.
Returns
plt::Plots.Plot: A line plot with one curve per portfolio.
Related
PortfolioOptimisers.plot_asset_cumulative_returns — Function
plot_asset_cumulative_returns(
w::VecNum,
X::MatNum,
fees::Option{<:Fees} = nothing;
ts::AbstractVector = 1:size(X, 1),
nx::AbstractVector = 1:size(X, 2),
compound::Bool = false,
N::Option{<:Number} = nothing,
kwargs...
) -> Plot
plot_asset_cumulative_returns(
w::VecNum,
pr::Pr_RR,
fees::Option{<:Fees} = nothing;
ts::AbstractVector = 1:size(pr.X, 1),
nx::AbstractVector = 1:size(pr.X, 2),
compound::Bool = false,
N::Option{<:Number} = nothing,
kwargs...
) -> Plot
plot_asset_cumulative_returns(
res::OptimisationResult[, pr::Pr_RR];
fees::Option{<:Fees} = nothing,
compound::Bool = false,
N::Option{<:Number} = nothing,
kwargs...
) -> Plot
plot_asset_cumulative_returns(pred::PredictionResult; compound, N, kwargs...) -> Plot
plot_asset_cumulative_returns(ppred::PopulationPredictionResult; compound, N, kwargs...) -> PlotPlot the cumulative contribution of each asset to the portfolio return, one line per asset.
The line of asset $i$ is cumulative_returns of its weighted return $w_i x_{t,i}$ net of its own fee, which calc_net_asset_returns forms. It is not the cumulative return of the asset alone. relevant_assets ranks the assets by $\lvert w_i \rvert$ and chooses how many lines to draw. The rest of the universe is one more line, Others, the cumulative net return of the sub-portfolio of the assets that the ranking left out. A population draws the figure of each member on one plot, and each member must be a single fold. The package extension PortfolioOptimisersPlotsExt implements the methods, and it loads after using StatsPlots.
A per-asset line keeps its gap, which the backend draws as a break, and that break is the delisting. Read against a prediction the same line is flat, because the fold set the Held Gap to zero before it formed the series. The Others line cannot keep a gap. One NaN makes every date of the sum NaN, at any weight, so it leaves out each column that is not finite throughout, through finite_columns. The line therefore describes the rest of the universe without the assets that it cannot value.
A result arity draws the investable universe of the result, and it drops the charge of a liquidation, because a liquidated asset has no column on that universe for its exit charge. plot_portfolio_cumulative_returns charges it.
Arguments
w: Portfolio weights vector.X: Asset returns matrix (observations × assets).fees: Transaction fees, ornothing.ts: Labels of the time axis. AReturnsResultthat carriestsreplaces the keyword with its own.nx: Asset names. AReturnsResultthat carriesnxreplaces the keyword with its own.compound: Compound the returns whentrue, and sum them otherwise.N: The count or the share of the lines to draw, ornothingfor the effective number of assets.relevant_assetsstates the rule.pr: Prior result orReturnsResult. The figure reads itsX.res: Optimisation result. The figure reads its weights, and its fees whenfeesisnothing, on its investable universe. Withoutpr, it reads the returns of the prior that the result was fitted on.pred: A prediction. The figure drawspred.reswithoutpr, so it reads the returns the fold was fitted on and not the returns of its test window.ppred: A population of single-fold predictions.
Returns
plt::Plots.Plot: A line plot with one line per drawn asset, and anOthersline when the count truncates.
Related
PortfolioOptimisers.plot_composition — Function
plot_composition(
w::VecNum,
nx::AbstractVector = 1:length(w);
N::Option{<:Number} = nothing,
kwargs...
) -> Plot
plot_composition(res::OptimisationResult, rd::ReturnsResult; N, kwargs...) -> Plot
plot_composition(res::OptimisationResult, pr::AbstractPriorResult; N, kwargs...) -> Plot
plot_composition(pred::PredictionResult; N, kwargs...) -> Plot
plot_composition(mpred::MultiPeriodPredictionResult; N, kwargs...) -> Plot
plot_composition(ppred::PopulationPredictionResult; N, kwargs...) -> PlotPlot the composition of a portfolio as a bar chart of its asset weights.
relevant_assets ranks the assets by $\lvert w_i \rvert$ and chooses how many bars to draw. The drawn bars keep the order of the asset axis, and the assets that the ranking left out become one more bar, Others, whose height is the signed sum of their weights. A walk-forward path and a population draw a stacked bar chart through plot_stacked_bar_composition, one bar per fold or per path, and they accept N and do not read it. The bars are the rows of prediction_weights, on the union of the asset names of the folds or of the paths, so a fold that holds other assets than the first fold draws its own assets. A path of a population takes the mean of its fold targets. The package extension PortfolioOptimisersPlotsExt implements the methods, and it loads after using StatsPlots.
Arguments
w: Portfolio weights vector.nx: Asset names.N: The count or the share of the bars to draw, ornothingfor the effective number of assets.relevant_assetsstates the rule.res: Optimisation result. The figure reads its weights on the universe of the caller.rd: Returns result. The figure reads itsnx, and numbers the assets when it has none.pr: Prior result. The figure numbers the assets and reads nothing else of it.pred: A prediction. The figure reads the weights of its result on its investable universe, under the names of the fold.mpred: A walk-forward path.ppred: A population of predictions.
Returns
plt::Plots.Plot: A bar chart, with anOthersbar when the count truncates, or a stacked bar chart for a path or a population.
Related
PortfolioOptimisers.plot_stacked_bar_composition — Function
plot_stacked_bar_composition(
w::VecNum_VecVecNum,
nx::AbstractVector = 1:(isa(w, VecVecNum) ? length(first(w)) : length(w));
kwargs...
) -> Plot
plot_stacked_bar_composition(
res_vec::AbstractVector{<:OptimisationResult},
rd::ReturnsResult;
kwargs...
) -> PlotPlot the compositions of several portfolios as a stacked bar chart, one bar per portfolio.
Each bar stacks the asset weights of one portfolio, one segment per asset. A single weight vector draws one bar. The method that takes res_vec reads the weights of each result, and the names of rd, or numbers the assets when rd has none. The package extension PortfolioOptimisersPlotsExt implements the methods, and it loads after using StatsPlots.
Arguments
w: Portfolio weights vector, or a vector of weight vectors of equal length.nx: Asset names, one per weight of a portfolio.res_vec: Optimisation results.rd: Returns result. The figure reads itsnx.
Returns
plt::Plots.Plot: A stacked bar chart.
Related
PortfolioOptimisers.plot_stacked_area_composition — Function
plot_stacked_area_composition(
w::VecNum_VecVecNum,
nx::AbstractVector = 1:(isa(w, VecVecNum) ? length(first(w)) : length(w));
kwargs...
) -> Plot
plot_stacked_area_composition(
res_vec::AbstractVector{<:OptimisationResult},
rd::ReturnsResult;
kwargs...
) -> Plot
plot_stacked_area_composition(mpred::MultiPeriodPredictionResult; N, kwargs...) -> Plot
plot_stacked_area_composition(ppred::PopulationPredictionResult; N, kwargs...) -> PlotPlot the compositions of several portfolios as a stacked area chart, one band per asset.
The horizontal axis is the position of the portfolio, and the band of an asset is its weight in each portfolio. A walk-forward path draws one position per fold, and a population one per member, whose weights are the mean of its fold weights when it is a walk-forward path. Those two methods accept N and do not read it. The package extension PortfolioOptimisersPlotsExt implements the methods, and it loads after using StatsPlots.
Arguments
w: Portfolio weights vector, or a vector of weight vectors of equal length.nx: Asset names, one per weight of a portfolio.res_vec: Optimisation results.rd: Returns result. The figure reads itsnx.mpred: A walk-forward path.ppred: A population of predictions.
Returns
plt::Plots.Plot: A stacked area chart.
Related
PortfolioOptimisers.plot_risk_contribution — Function
plot_risk_contribution(
r::BaseRM_VecBaseRM,
w::VecNum,
X::MatNum_Pr,
fees::Option{<:Fees} = nothing;
nx::AbstractVector = 1:length(w),
delta::Number = 1e-6,
marginal::Bool = false,
percentage::Bool = true,
erc::Bool = true,
N::Option{<:Number} = nothing,
sca::Option{<:Scalariser} = nothing,
kwargs...
) -> Plot
plot_risk_contribution(r, w::VecNum, rd::ReturnsResult, fees = nothing; delta, marginal, percentage, erc, N, sca, kwargs...) -> Plot
plot_risk_contribution(r, res::OptimisationResult, rd::ReturnsResult; delta, marginal, percentage, erc, N, sca, kwargs...) -> Plot
plot_risk_contribution(r, res::OptimisationResult, pr::AbstractPriorResult; nx, delta, marginal, percentage, erc, N, sca, kwargs...) -> Plot
plot_risk_contribution(r, pred::PredictionResult, fees = nothing; delta, marginal, percentage, erc, N, sca, kwargs...) -> PlotPlot the risk contribution of each asset as a bar chart.
The bars are risk_contribution of w, rescaled to shares when percentage is true, and a horizontal line marks their mean when erc is true. plot_composition draws the bars, so an N that truncates keeps the order of the asset axis and adds an Others bar. The package extension PortfolioOptimisersPlotsExt implements the methods, and it loads after using StatsPlots.
The bars decompose one number, the scalarised aggregate of r, so they sum to the aggregate and not to any one element. Under MaxScalariser and MinScalariser the decomposition is exact only where the argmax is unique. At a near tie between two scaled measures the subgradient is a set, and the bars are one admissible answer of several.
The method that takes a fold reads the target weights of the fold and the asset returns that its Held Weights record kept, and it settles the fee against the length of the fold, as predict did. Under a Weight Drift the bars are exact to first order in the drift only, for the reason risk_contribution states. A fold whose scheme set neither wd nor a DriftedWeights source keeps no record and so no asset returns.
Mathematical definition
\[\begin{align} \tilde{c}_i &= \frac{c_i}{\sum_{j=1}^{N} c_j}\,, \\ \bar{c} &= \frac{1}{N} \sum_{i=1}^{N} \tilde{c}_i\,. \end{align}\]
Where:
- $c_i$: Risk contribution of asset $i$, as
risk_contributionreturns it. - $\tilde{c}_i$: Height of the bar of asset $i$. It is $c_i$ itself when
percentageisfalse. - $\bar{c}$: Height of the reference line, the mean over every asset before any truncation. Under
percentageit is $1/N$, and whenmarginalisfalseit is the height of each bar under an equal risk contribution. - $N$: Number of assets.
Arguments
r: Risk measure, or a vector of them thatscacombines.w: Portfolio weights vector.X: Asset returns matrix (observations × assets), or a prior result.rd: Returns result. The figure reads itsXand itsnx.pr: Prior result. The figure reads itsX.fees: Transaction fees, ornothing.nx: Asset names.delta: Finite difference step ofrisk_contribution.marginal: Draw the marginal contribution whentrue, and the component contribution otherwise.percentage: Divide the contributions by their sum whentrue, so that the bars sum to one.erc: Draw the reference line whentrue.N: The count or the share of the bars to draw, ornothingfor the effective number of the contributions.relevant_assetsstates the rule.sca: Scalariser that combines the measures inr. It has no effect whenris one measure. Passres.scato draw the figure that the optimisation ran under.res: Optimisation result. The figure reads its weights and its fees on its investable universe.pred: A fold, frompredict.
Validation
delta > 0, else aDomainErroris raised.- If
Nis notnothing,N > 0, else aDomainErroris raised. - A fold carries a Held Weights record, else an
ArgumentErroris raised. - The rules of
risk_contribution.
Returns
plt::Plots.Plot: A bar chart, with the reference line whenercistrue.
Related
PortfolioOptimisers.plot_factor_risk_contribution — Function
plot_factor_risk_contribution(
r::BaseRM_VecBaseRM,
w::VecNum,
X::MatNum_Pr,
fees::Option{<:Fees} = nothing;
re::RegE_Reg = StepwiseRegression(),
rd::ReturnsResult = ReturnsResult(),
nf::Option{<:AbstractVector} = nothing,
delta::Number = 1e-6,
N::Option{<:Number} = nothing,
percentage::Bool = true,
erc::Bool = true,
sca::Option{<:Scalariser} = nothing,
kwargs...
) -> Plot
plot_factor_risk_contribution(r, res::OptimisationResult, rd::ReturnsResult; re, delta, N, percentage, erc, sca, kwargs...) -> Plot
plot_factor_risk_contribution(
r,
pred::PredictionResult,
fees = nothing;
rd::Option{<:ReturnsResult} = nothing,
re, delta, N, percentage, erc, sca, kwargs...
) -> PlotPlot the risk contribution of each factor as a bar chart.
The bars are factor_risk_contribution of w, rescaled to shares when percentage is true, and a horizontal line marks their mean when erc is true. The last bar, Off-factor, is the contribution of the part of the weights that has no exposure to any factor. It is not a regression intercept. plot_composition draws the bars, so an N that truncates keeps the order of the factor axis and adds an Others bar. The package extension PortfolioOptimisersPlotsExt implements the methods, and it loads after using StatsPlots.
The bars take the names in nf, or else in rd.nf, only when the names count the columns of the loadings. A dimension reduction regression fits fewer columns than there are factors, so its bars are numbered.
The method that takes a fold is the twin of the fold method of plot_risk_contribution. It fits the loadings on a returns result that it builds from the fold, the asset returns of its Held Weights record beside the factor block the fold carried, unless the caller gives rd, which it views at the mask of the fold. The first order caveat of that method holds here too.
Mathematical definition
\[\begin{align} \tilde{c}_k &= \frac{c_k}{\sum_{j=1}^{K+1} c_j}\,, \\ \bar{c} &= \frac{1}{K+1} \sum_{k=1}^{K+1} \tilde{c}_k\,. \end{align}\]
Where:
- $c_k$: Risk contribution of factor $k$, and of the off-factor part when $k = K + 1$, as
factor_risk_contributionreturns it. - $\tilde{c}_k$: Height of bar $k$. It is $c_k$ itself when
percentageisfalse. - $\bar{c}$: Height of the reference line, the mean over every bar before any truncation. Under
percentageit is $1/(K+1)$, the height of each bar under an equal risk contribution. - $K$: Number of factors.
Arguments
r: Risk measure, or a vector of them thatscacombines.w: Portfolio weights vector.X: Asset returns matrix (observations × assets), or a prior result.fees: Transaction fees, ornothing.re: Factor regression estimator.rd: Returns result that carries the factor returns the loadings are fitted on, and the factor names inrd.nf.nf: Factor names. They replacerd.nfwhen given.delta: Finite difference step offactor_risk_contribution.N: The count or the share of the bars to draw, ornothingfor the effective number of the contributions.relevant_assetsstates the rule.percentage: Divide the contributions by their sum whentrue, so that the bars sum to one.erc: Draw the reference line whentrue.sca: Scalariser that combines the measures inr. It has no effect whenris one measure. Passres.scato draw the figure that the optimisation ran under.res: Optimisation result. The figure reads its weights and its fees on its investable universe.pred: A fold, frompredict.
Validation
delta > 0, else aDomainErroris raised.- If
Nis notnothing,N > 0, else aDomainErroris raised. - A fold carries a Held Weights record, else an
ArgumentErroris raised. - The rules of
factor_risk_contribution.
Returns
plt::Plots.Plot: A bar chart, with the reference line whenercistrue.
Related
PortfolioOptimisers.plot_dendrogram — Function
plot_dendrogram(
clr::AbstractClusteringResult,
nx::AbstractVector = 1:length(clr.res.order);
dend_theme::Symbol = :Spectral,
kwargs...
) -> Plot
plot_dendrogram(cle::HClE_HCl, X::MatNum, nx = 1:size(X, 2); dims::Integer = 1, kwargs...) -> Plot
plot_dendrogram(cle::HClE_HCl, pr::Pr_RR, nx = 1:size(pr.X, 2); kwargs...) -> PlotPlot the dendrogram of a hierarchical clustering, with one shaded region per cluster.
The leaves follow the order of the clustering. Each cluster takes one colour of dend_theme, and its region reaches $\min(1.1 h, 1)$, where $h$ is the largest merge height inside the cluster, so the shading never rises above a height of one. The estimator arities call clusterise first. The package extension PortfolioOptimisersPlotsExt implements the methods, and it loads after using StatsPlots.
A non-investable asset is not drawn. A clustering is fitted by a plain moment estimator, which refuses a gapped sample, so the prior arity reduces itself and its names to the Investable Mask at its entry through investable_plot_view. The bare X arity computes on the matrix that the caller holds.
Arguments
clr: Clustering result.cle: Clustering estimator. It clustersX, orpr.X.X: Asset returns matrix (observations × assets).pr: Prior result orReturnsResult. A returns result that carriesnxreplaces the argument with its own.nx: Asset names.dend_theme: Colour palette of the cluster regions.dims: Dimension ofXthat holds the observations, asclusterisereads it. Only theXarity takes it. TheXof a prior or a returns result holds the observations along the rows, so the prior arity passesdims = 1.
Validation
- The rules of
clusterise.
Returns
plt::Plots.Plot: A dendrogram of 600 × 600 pixels.
Related
PortfolioOptimisers.plot_clusters — Function
plot_clusters(
clr::AbstractClusteringResult,
nx::AbstractVector = 1:size(clr.S, 1);
dend_theme::Symbol = :Spectral,
hmap_theme::Symbol = :Spectral,
color_func = x -> any(x .< 0) ? (-1, 1) : (0, 1),
line_color = :black,
line_width = 3,
kwargs...
) -> Plot
plot_clusters(cle::HClE_HCl, X::MatNum, nx = 1:size(X, 2); dims::Integer = 1, kwargs...) -> Plot
plot_clusters(cle::HClE_HCl, pr::Pr_RR, nx = 1:size(pr.X, 2); kwargs...) -> PlotPlot the similarity matrix of a clustering as a heatmap in the order of the clustering, with a dendrogram on two sides and a box round each cluster.
The heatmap always draws a correlation. When a diagonal entry of clr.S is not one, the figure rescales a copy of it to a correlation first, as plot_correlation defines it. color_func maps that correlation to the colour limits. The dendrograms shade each cluster up to its largest merge height, with no cap. The package extension PortfolioOptimisersPlotsExt implements the methods, and it loads after using StatsPlots.
A non-investable asset is not drawn, for the reason plot_dendrogram states, and the prior arity reduces to the Investable Mask at its entry through investable_plot_view.
Arguments
clr: Clustering result.cle: Clustering estimator. It clustersX, orpr.X.X: Asset returns matrix (observations × assets).pr: Prior result orReturnsResult. A returns result that carriesnxreplaces the argument with its own.nx: Asset names.dend_theme: Colour palette of the cluster regions of the dendrograms.hmap_theme: Colour gradient of the heatmap.color_func: Function that maps the correlation matrix to the colour limits(lo, hi). The default gives(-1, 1)when an entry is negative, and(0, 1)otherwise.line_color: Colour of the cluster boxes.line_width: Width of the cluster boxes.dims: Dimension ofXthat holds the observations, asclusterisereads it. Only theXarity takes it. TheXof a prior or a returns result holds the observations along the rows, so the prior arity passesdims = 1.
Validation
- The rules of
clusterise.
Returns
plt::Plots.Plot: A layout of 600 × 600 pixels, with the heatmap below one dendrogram and beside the other.
Related
PortfolioOptimisers.plot_drawdowns — Function
plot_drawdowns(
w::ArrNum,
X::MatNum,
fees::Option{<:Fees} = nothing;
slv::Option{<:Slv_VecSlv} = nothing,
ts::AbstractVector = 1:size(X, 1),
compound::Bool = false,
alpha::Number = 0.05,
kappa::Number = 0.3,
rw = nothing,
kwargs...
) -> Plot
plot_drawdowns(w, rd::ReturnsResult, fees = nothing; slv, compound, alpha, kappa, rw, kwargs...) -> Plot
plot_drawdowns(res::OptimisationResult, rd::ReturnsResult; slv, compound, alpha, kappa, rw, kwargs...) -> Plot
plot_drawdowns(pred::PredictionResult; slv, compound, alpha, kappa, rw, kwargs...) -> Plot
plot_drawdowns(mpred::MultiPeriodPredictionResult; slv, compound, alpha, kappa, rw, kwargs...) -> Plot
plot_drawdowns(ppred::PopulationPredictionResult; slv, compound, alpha, kappa, rw, kwargs...) -> Plot
plot_drawdowns(ret::VecNum; ts::AbstractVector, slv, compound, alpha, kappa, rw, kwargs...) -> PlotPlot the cumulative returns of a portfolio above its drawdown, in two panels that share the time axis.
The upper panel is cumulative_returns of the net portfolio returns. The lower panel is their drawdowns in percent, with one horizontal line for each of these measures of the returns, negated and in percent: AverageDrawdown, UlcerIndex, DrawdownatRisk, ConditionalDrawdownatRisk and MaximumDrawdown. With slv, EntropicDrawdownatRisk and RelativisticDrawdownatRisk add two more lines. Under compound each measure is its relative form, such as RelativeMaximumDrawdown. A population draws the mean of the return series of its members, which must be of one length, on the time axis of the first member. The package extension PortfolioOptimisersPlotsExt implements the methods, and it loads after using StatsPlots.
A gapped panel reaches this figure only through the returns that the caller gives it. A prediction arity is finite already, because the fold set the Held Gap to zero once in predict. A w, X or w, rd arity computes on the matrix that the caller holds and checks nothing, and X * w is NaN at a gap even where the weight is zero. Score a gapped panel through predict(res, rd) and plot the prediction.
Arguments
w: Portfolio weights.X: Asset returns matrix (observations × assets).fees: Transaction fees, ornothing.slv: Solver of the entropic and relativistic lines.nothingleaves out the two lines.ts: Labels of the time axis. A returns result or a prediction gives its own.compound: Compound the returns and use the relative drawdown measures whentrue.alpha: Significance level of the drawdown at risk lines.kappa: Deformation parameter of the relativistic line.rw: Observation weights of the average drawdown line, ornothing.res: Optimisation result. The figure reads its weights and its fees on its investable universe.pred,mpred,ppred: A prediction, a walk-forward path or a population, whose return series the figure draws.ret: Net portfolio returns.
Validation
0 < alpha < 1, else aDomainErroris raised, whether or notslvis given.0 < kappa < 1, else aDomainErroris raised, whether or notslvis given.
Returns
plt::Plots.Plot: A layout of two panels, the cumulative returns above the drawdown.
Related
PortfolioOptimisers.plot_measures — Function
plot_measures(
w::VecNum_VecVecNum,
pr::Pr_RR,
fees::Option{<:Fees} = nothing;
x::BaseRM_VecBaseRM = Variance(),
y::BaseRM_VecBaseRM = ExpectedReturn(),
z::Option{<:BaseRM_VecBaseRM} = nothing,
c::BaseRM_VecBaseRM = ExpectedReturnRiskRatio(; rk=x, rt=ArithmeticReturn(), rf=0),
slv::Option{<:Slv_VecSlv} = nothing,
factory::Bool = true,
kwargs...
) -> Plot
plot_measures(
res_vec::AbstractVector{<:OptimisationResult},
pr::Option{<:Pr_RR} = nothing;
x, y, z, c, slv, fees, factory, kwargs...
) -> Plot
plot_measures(
pred::AbstractPredictionResult;
x::BaseRM_VecBaseRM = ConditionalValueatRisk(),
y::BaseRM_VecBaseRM = MeanReturn(),
z::Option{<:BaseRM_VecBaseRM} = nothing,
c::BaseRM_VecBaseRM = MeanReturnRiskRatio(; rk = x, rt = MeanReturn(), rf = 0),
slv::Option{<:Slv_VecSlv} = nothing,
factory::Bool = true,
plt = nothing,
kwargs...
) -> PlotPlot a scatter of two or three measures over a collection of portfolios, coloured by a fourth.
Each point is one portfolio. Its coordinates are expected_risk of x, y and z, and its colour is expected_risk of c. The default colour is the ratio of the return of x to its risk. When factory is true, factory binds each measure to the prior and to slv first. The prediction arity reads the return series that the fold kept, so its defaults are measures that read a series: ConditionalValueatRisk, MeanReturn and MeanReturnRiskRatio. A prediction and a walk-forward path draw one point, and a population draws one point per member. With plt, the arity draws into that plot. The package extension PortfolioOptimisersPlotsExt implements the methods, and it loads after using StatsPlots.
Each axis takes one measure or a vector of them, and a vector becomes the one number that the axis plots. The figure names no scalariser, so a bare vector on an axis takes SumScalariser, each element weighted by its own settings.scale. A scalariser reaches an axis only through the sca field of a wrapper, ExpectedReturnRiskRatio, MeanReturnRiskRatio or NonOptimisationRiskRatio, and each axis can name its own. Those wrappers are all ratios, so the figure cannot apply a MaxScalariser to a plain vector of risks. Scalarise the vector with expected_risk and plot the numbers for that.
expected_risk reduces a Prior Result to the Investable Mask at its own entry, so a gapped prior needs no step here. A prediction arity is finite already, because the fold set the Held Gap to zero once in predict.
Arguments
w: Portfolio weights vector, or a vector of weight vectors.pr: Prior result or returns result. The result arity scores each result against its own prior whenprisnothing.fees: Transaction fees, ornothing.x: Measure of the horizontal axis, or a vector of them.y: Measure of the vertical axis, or a vector of them.z: Measure of the third axis, or a vector of them, ornothingfor a flat scatter.c: Measure of the colour, or a vector of them.slv: Solver thatfactorybinds to each measure.factory: Bind each measure throughfactorybefore the figure scores it.res_vec: Optimisation results.pred: A prediction, a walk-forward path or a population.plt: A plot to draw into, ornothingfor a new one.
Validation
- The rules of
expected_riskfor each measure.
Returns
plt::Plots.Plot: A scatter, in three dimensions whenzis given.
Related
PortfolioOptimisers.plot_histogram — Function
plot_histogram(
w::ArrNum,
X::MatNum,
fees::Option{<:Fees} = nothing;
slv::Option{<:Slv_VecSlv} = nothing,
alpha::Number = 0.05,
kappa::Number = 0.3,
rw = nothing,
points::Integer = 0,
reference::Bool = true,
kwargs...
) -> Plot
plot_histogram(w, rd::ReturnsResult, fees = nothing; slv, alpha, kappa, rw, points, reference, kwargs...) -> Plot
plot_histogram(res::OptimisationResult, rd::ReturnsResult; slv, alpha, kappa, rw, points, reference, kwargs...) -> Plot
plot_histogram(pred::PredictionResult; slv, alpha, kappa, rw, points, reference, kwargs...) -> Plot
plot_histogram(mpred::MultiPeriodPredictionResult; slv, alpha, kappa, rw, points, reference, kwargs...) -> Plot
plot_histogram(ppred::PopulationPredictionResult; slv, alpha, kappa, rw, points, reference, kwargs...) -> Plot
plot_histogram(ret::VecNum; slv, alpha, kappa, rw, points, reference, kwargs...) -> PlotPlot the histogram of the returns of a portfolio, with a vertical line for each of several statistics and an optional fitted Normal density.
The histogram is normalised to a density. Vertical lines mark, in this order: the mean $\bar{r}$, and $\bar{r}$ less the standard deviation, less the mean absolute deviation, and less the Gini mean difference; the negated value at risk, conditional value at risk and tail Gini; with slv, the negated entropic and relativistic values at risk; and the worst return. A population draws the mean of the return series of its members. The package extension PortfolioOptimisersPlotsExt implements the methods, and it loads after using StatsPlots.
The figure reads only the finite returns, as plot_exposure_distribution does. A return that is NaN or infinite is absent: the bins, the mean, the moments, every vertical line and the fitted Normal law read the finite returns, and $T$ counts them. A walk-forward fold that failed to solve has NaN weights, so its returns are absent, and the figure of a portfolio_report still draws. A series with no finite return, such as a path whose every fold failed, draws the axes alone, with no bin and no line.
A gapped panel reaches this figure only through the returns that the caller gives it. A prediction arity is finite at a gap, because the fold set the Held Gap to zero once in predict. A w, X or w, rd arity computes on the matrix that the caller holds, and X * w is NaN at a gap even where the weight is zero, so the figure drops each such row. Score a gapped panel through predict(res, rd) and plot the prediction.
Mathematical definition
\[\begin{align} P &= \begin{cases} \lceil 4 \sqrt{T} \rceil & p = 0\,, \\ p & p > 0\,, \end{cases} \\ \hat{\mu} &= \frac{1}{T} \sum_{t=1}^{T} r_t\,, \\ \hat{\sigma}^2 &= \frac{1}{T} \sum_{t=1}^{T} (r_t - \hat{\mu})^2\,. \end{align}\]
Where:
- $r_t$: Net portfolio return at observation $t$, over the finite returns only.
- $p$: The
pointskeyword. - $P$: Number of points of the grid, evenly spaced from the worst to the best return, on which the figure evaluates the Normal density.
- $\hat{\mu}$, $\hat{\sigma}^2$: Maximum likelihood mean and variance of the fitted Normal law. The divisor is $T$, so $\hat{\sigma}$ is not the standard deviation of the line, whose divisor is $T - 1$.
- $T$: Number of observations.
Arguments
w: Portfolio weights.X: Asset returns matrix (observations × assets).fees: Transaction fees, ornothing.slv: Solver of the entropic and relativistic lines.nothingleaves out the two lines.alpha: Significance level of the tail lines.kappa: Deformation parameter of the relativistic line.rw: Observation weights of the mean absolute deviation line and of the four value at risk lines (plain, conditional, entropic and relativistic), ornothing. The mean, the standard deviation, the Gini mean difference and the tail Gini lines read no weights.points: Number of points of the density grid, or0for the default.reference: Draw the fitted Normal density whentrue.res: Optimisation result. The figure reads its weights and its fees on its investable universe.pred,mpred,ppred: A prediction, a walk-forward path or a population, whose return series the figure draws.ret: Net portfolio returns.
Validation
0 < alpha < 1, else aDomainErroris raised.0 < kappa < 1, else aDomainErroris raised.points >= 0, else aDomainErroris raised.
Returns
plt::Plots.Plot: A density histogram with its vertical lines, and the Normal density whenreferenceistrue. A series with no finite return gives the axes alone.
Related
PortfolioOptimisers.plot_network — Function
plot_network(
pl::NwE_ClE_Cl,
X::MatNum,
nx::AbstractVector = 1:size(X, 2),
w::Option{<:VecNum} = nothing;
threshold::Number = 0,
kwargs...
) -> Plot
plot_network(pl, pr::Pr_RR, w::Option{<:VecNum} = nothing; nx = 1:size(pr.X, 2), threshold, kwargs...) -> Plot
plot_network(pl, res::OptimisationResult; rd::Option{<:Pr_RR} = nothing, nx = 1:length(res.w), threshold, kwargs...) -> PlotPlot the network of the assets as a graph, with GraphRecipes.graphplot.
The graph is the matrix that phylogeny_matrix fits with pl: a tree, a planar graph, or the adjacency of a clustering. An entry whose magnitude is at most threshold draws no edge. Every node has one size, unless w is given, which scales the node of asset $i$ by $\lvert w_i \rvert / \max_j \lvert w_j \rvert$. The package extension PortfolioOptimisersGraphRecipesExt implements the methods, and it loads after using GraphRecipes, StatsPlots. The other plot functions need StatsPlots alone, so a session that draws no network does not load GraphRecipes.
A non-investable asset is not drawn. The figure fits a phylogeny matrix on pr.X, and a plain moment estimator refuses a gapped sample, so the prior arity reduces itself, its names and its weights to the Investable Mask at its entry through investable_plot_view. The graph is the investable universe, and no edge of a dead asset is drawn. The bare X and ReturnsResult arities carry no moments, so no mask exists to derive, and they compute on the matrix that the caller holds.
Arguments
pl: Network or clustering estimator, or a clustering result.X: Asset returns matrix (observations × assets).nx: Asset names. AReturnsResultthat carriesnxreplaces the argument with its own.w: Portfolio weights that size the nodes, ornothingfor one size.threshold: Largest magnitude of an entry that draws no edge.pr: Prior result orReturnsResult. The figure reads itsX.res: Optimisation result. The figure reads its weights, which size the nodes, on its investable universe.rd: Prior result or returns result, ornothingfor the prior thatreswas fitted on.
Validation
- The rules of
phylogeny_matrix.
Returns
plt::Plots.Plot: A graph plot.
Related
PortfolioOptimisers.plot_centrality — Function
plot_centrality(
cte::AbstractCentralityEstimator,
X::MatNum,
nx::AbstractVector = 1:size(X, 2);
N::Option{<:Number} = nothing,
percentage::Bool = true,
kwargs...
) -> Plot
plot_centrality(cte, pr::AbstractPriorResult, nx = 1:size(pr.X, 2); N, percentage, kwargs...) -> Plot
plot_centrality(cte, rd::ReturnsResult; N, percentage, kwargs...) -> Plot
plot_centrality(cte, res::OptimisationResult, rd::ReturnsResult; N, percentage, kwargs...) -> PlotPlot the centrality score of each asset as a bar chart, sorted from the largest.
The scores are centrality_vector of X. relevant_assets chooses how many bars to draw, and the assets that it leaves out draw no bar. The figure has no Others bar. Under percentage every score is divided by the sum over all assets, so the drawn bars sum to less than one when the count truncates. The result arity reads rd alone, and the result gives only the count of the default names. The package extension PortfolioOptimisersPlotsExt implements the methods, and it loads after using StatsPlots.
A non-investable asset is not drawn. The figure fits a centrality vector on pr.X, and a plain moment estimator refuses a gapped sample, so the prior arity reduces to the Investable Mask at its entry through investable_plot_view. The axis is the investable universe. The bare X and ReturnsResult arities carry no moments, so no mask exists to derive, and they compute on the matrix that the caller holds.
Arguments
cte: Centrality estimator.X: Asset returns matrix (observations × assets).nx: Asset names.N: The count or the share of the bars to draw, ornothingfor the effective number of the scores.relevant_assetsstates the rule.percentage: Divide the scores by their sum over all assets whentrue.pr: Prior result. The figure reads itsX.rd: Returns result. The figure reads itsXand itsnx.res: Optimisation result.
Validation
- The rules of
centrality_vector.
Returns
plt::Plots.Plot: A bar chart.
Related
PortfolioOptimisers.plot_correlation — Function
plot_correlation(X::MatNum, nx::AbstractVector = 1:size(X, 1); kwargs...) -> Plot
plot_correlation(pr::AbstractPriorResult, nx = 1:size(pr.sigma, 1); kwargs...) -> Plot
plot_correlation(pr::AbstractPriorResult, rd::ReturnsResult; kwargs...) -> Plot
plot_correlation(res::OptimisationResult[, rd::ReturnsResult]; kwargs...) -> Plot
plot_correlation(pred::PredictionResult[, rd::ReturnsResult]; kwargs...) -> PlotPlot a correlation matrix as a heatmap, with no clustering and no dendrogram.
When a diagonal entry of the matrix is not one, the figure takes it for a covariance and rescales a copy of it to a correlation, whose colour limits are (-1, 1). A matrix whose diagonal is all ones is drawn unchanged, between its smallest and its largest entry. The package extension PortfolioOptimisersPlotsExt implements the methods, and it loads after using StatsPlots.
A non-investable asset of a prior that the caller gives is drawn rather than removed. It carries NaN down its row and its column of sigma, so those cells are blank, and the blank shows the gap. Its diagonal entry is NaN and not one, so the figure rescales and the colour limits stay (-1, 1), so one gap does not flatten the scale. A result arity draws the prior that the result was fitted on, which is already reduced to its investable universe, under the names of those assets.
Mathematical definition
\[\begin{align} \rho_{ij} = \frac{S_{ij}}{\sqrt{S_{ii} S_{jj}}}\,. \end{align}\]
Where:
- $S_{ij}$: Entry of the matrix that the caller gives.
- $\rho_{ij}$: Entry that the heatmap draws when a diagonal entry of $\mathbf{S}$ is not one.
Arguments
X: Covariance or correlation matrix.nx: Asset names.pr: Prior result. The figure reads itssigma.rd: Returns result. The figure reads itsnx.res: Optimisation result. The figure reads the prior it was fitted on.pred: A prediction. The figure reads the prior of its result.
Returns
plt::Plots.Plot: A heatmap.
Related
PortfolioOptimisers.plot_mu — Function
plot_mu(
mu::VecNum,
nx::AbstractVector = 1:length(mu);
N::Option{<:Number} = nothing,
kwargs...
) -> Plot
plot_mu(pr::AbstractPriorResult[, nx]; N, kwargs...) -> Plot
plot_mu(pr::AbstractPriorResult, rd::ReturnsResult; N, kwargs...) -> Plot
plot_mu(res::OptimisationResult[, rd::ReturnsResult]; N, kwargs...) -> Plot
plot_mu(pred::PredictionResult[, rd::ReturnsResult]; N, kwargs...) -> PlotPlot the expected return of each asset as a bar chart.
relevant_assets ranks the assets by $\lvert \mu_i \rvert$ and chooses how many bars to draw. The drawn bars keep the order of the asset axis, and the assets that it leaves out draw no bar. With no N, the count is the effective number of the magnitudes, so it can be smaller than the universe; pass N equal to the number of assets to draw every one. The package extension PortfolioOptimisersPlotsExt implements the methods, and it loads after using StatsPlots.
A non-investable asset of a prior that the caller gives is drawn rather than removed. It carries NaN in the moments of the prior, so its bar is blank, and that blank shows the gap. The ranking reads finite_magnitudes, so the blank never takes a top slot from a live asset, and the frame is unchanged when the count does not truncate. A result arity draws the prior that the result was fitted on, which is already reduced to its investable universe, under the names of those assets.
Arguments
mu: Expected returns vector.nx: Asset names.N: The count or the share of the bars to draw, ornothingfor the effective number of the magnitudes.relevant_assetsstates the rule.pr: Prior result. The figure reads itsmu.rd: Returns result. The figure reads itsnx.res: Optimisation result. The figure reads the prior it was fitted on.pred: A prediction. The figure reads the prior of its result.
Returns
plt::Plots.Plot: A bar chart.
Related
PortfolioOptimisers.plot_sigma — Function
plot_sigma(
sigma::MatNum,
nx::AbstractVector = 1:size(sigma, 1);
variance::Bool = false,
N::Option{<:Number} = nothing,
kwargs...
) -> Plot
plot_sigma(pr::AbstractPriorResult[, nx]; variance, N, kwargs...) -> Plot
plot_sigma(pr::AbstractPriorResult, rd::ReturnsResult; variance, N, kwargs...) -> Plot
plot_sigma(res::OptimisationResult[, rd::ReturnsResult]; variance, N, kwargs...) -> Plot
plot_sigma(pred::PredictionResult[, rd::ReturnsResult]; variance, N, kwargs...) -> PlotPlot the volatility of each asset, the square root of the diagonal of the covariance, as a bar chart.
With no N the figure draws every asset. An N is a count, $\min(\max(\lceil N \rceil, 1), M)$ for $M$ assets, of the assets with the largest values, drawn in the order of the asset axis. Unlike plot_mu, an N in (0, 1] is not a share, and it draws one bar. The package extension PortfolioOptimisersPlotsExt implements the methods, and it loads after using StatsPlots.
A non-investable asset of a prior that the caller gives is drawn rather than removed. It carries NaN on the diagonal of sigma, so its bar is blank, and that blank shows the gap. The ranking reads finite_magnitudes, so the blank never takes a top slot from a live asset, and the frame is unchanged when the count does not truncate. A result arity draws the prior that the result was fitted on, which is already reduced to its investable universe, under the names of those assets.
Arguments
sigma: Covariance matrix.nx: Asset names.variance: Draw the diagonal itself, the variances, whentrue.N: The count of the bars to draw, ornothingfor every asset.pr: Prior result. The figure reads itssigma.rd: Returns result. The figure reads itsnx.res: Optimisation result. The figure reads the prior it was fitted on.pred: A prediction. The figure reads the prior of its result.
Returns
plt::Plots.Plot: A bar chart.
Related
PortfolioOptimisers.plot_factor_loadings — Function
plot_factor_loadings(
M::MatNum,
nx::AbstractVector = 1:size(M, 1),
nf::AbstractVector = 1:size(M, 2);
kwargs...
) -> Plot
plot_factor_loadings(pr::AbstractPriorResult, nx = nothing, nf = nothing; kwargs...) -> Plot
plot_factor_loadings(pr::AbstractPriorResult, rd::ReturnsResult; kwargs...) -> Plot
plot_factor_loadings(res::OptimisationResult[, rd::ReturnsResult]; kwargs...) -> Plot
plot_factor_loadings(pred::PredictionResult[, rd::ReturnsResult]; kwargs...) -> PlotPlot the factor loadings matrix, assets by factors, as a heatmap on a diverging colour scale centred at zero.
The prior arities draw pr.rr.M, the loadings of the regression that the prior carries. The matrix arity draws M and needs no prior. The package extension PortfolioOptimisersPlotsExt implements the methods, and it loads after using StatsPlots.
A non-investable asset of a prior that the caller gives is drawn rather than removed. It carries NaN down its row of the loadings, so that row is blank cells, and the blank shows the gap. The colour limits are finite_symmetric_clim, so one gap does not flatten the scale. The gap is on the asset axis alone, so the factor axis is unaffected. A result arity draws the prior that the result was fitted on, which is already reduced to its investable universe.
Arguments
M: Loadings matrix (assets × factors).nx: Asset names, ornothingto number them.nf: Factor names, ornothingto number them.pr: Prior result that carries a factor block.rd: Returns result. The figure reads itsnxand itsnf.res: Optimisation result. The figure reads the prior it was fitted on.pred: A prediction. The figure reads the prior of its result.
Validation
pr.rris notnothing, elseassert_prior_regressionraises anIsNothingError.
Returns
plt::Plots.Plot: A heatmap.
Related
PortfolioOptimisers.plot_factor_sigma — Function
plot_factor_sigma(
f_sigma::MatNum,
nf::AbstractVector = 1:size(f_sigma, 1);
kwargs...
) -> Plot
plot_factor_sigma(pr::AbstractPriorResult, nf = nothing; kwargs...) -> Plot
plot_factor_sigma(pr::AbstractPriorResult, rd::ReturnsResult; kwargs...) -> Plot
plot_factor_sigma(res::OptimisationResult[, rd::ReturnsResult]; kwargs...) -> Plot
plot_factor_sigma(pred::PredictionResult[, rd::ReturnsResult]; kwargs...) -> PlotPlot the correlation of the factor returns as a heatmap, through plot_correlation.
The prior arities draw the factor covariance of the low order factor block that factor_plot_prior finds, rescaled to a correlation by the rule of plot_correlation. The matrix arity draws f_sigma and needs no prior. plot_factor_forecast_correlation draws the same correlation, always with the colour limits (-1, 1). The package extension PortfolioOptimisersPlotsExt implements the methods, and it loads after using StatsPlots.
The figure draws the factor axis, and a non-investable asset is on the asset axis, so a gap never reaches it. It needs neither a blank nor a reduction.
Arguments
f_sigma: Factor covariance matrix (factors × factors).nf: Factor names, ornothingto number them.pr: Prior result that carries a factor block.rd: Returns result. The figure reads itsnf.res: Optimisation result. The figure reads the prior it was fitted on.pred: A prediction. The figure reads the prior of its result.
Validation
pr.rris notnothing, elseassert_prior_regressionraises anIsNothingError. The regression and the low order factor block are present together, so the check establishes both.
Returns
plt::Plots.Plot: A heatmap.
Related
PortfolioOptimisers.plot_eigenspectrum — Function
plot_eigenspectrum(
sigma::MatNum;
N_obs::Option{<:Integer} = nothing,
reference::Bool = true,
kwargs...
) -> Plot
plot_eigenspectrum(pr::AbstractPriorResult; reference, kwargs...) -> Plot
plot_eigenspectrum(pr::AbstractPriorResult, rd::ReturnsResult; reference, kwargs...) -> Plot
plot_eigenspectrum(res::OptimisationResult[, rd::ReturnsResult]; reference, kwargs...) -> Plot
plot_eigenspectrum(pred::PredictionResult[, rd::ReturnsResult]; reference, kwargs...) -> PlotPlot the eigenvalues of a covariance or correlation matrix as a bar chart, sorted from the largest.
With a number of observations, the figure draws the edges of the Marčenko–Pastur bulk as reference lines: the upper edge always, and the lower edge when there are fewer assets than observations. An arity that takes rd reads the number of observations off rd.X. The others reach it only through the N_obs keyword, and without it they draw no line. The package extension PortfolioOptimisersPlotsExt implements the methods, and it loads after using StatsPlots.
A non-investable asset is not drawn. eigvals(Symmetric(sigma)) refuses a NaN, so the prior arity reduces to the Investable Mask at its entry through investable_plot_view, and the spectrum is the spectrum of the investable block. The bare sigma arity computes on the matrix that the caller holds, and a gap in it raises rather than reduces.
Mathematical definition
\[\begin{align} q &= \frac{N}{T}\,, \\ \bar{\sigma}^2 &= \frac{\mathrm{tr}(\mathbf{\Sigma})}{N}\,, \\ \lambda_{\pm} &= \bar{\sigma}^2 \left(1 \pm \sqrt{q}\right)^2\,. \end{align}\]
Where:
- $\mathbf{\Sigma}$: The matrix whose spectrum the figure draws.
- $N$: Number of assets.
- $T$: Number of observations.
- $q$: Ratio of the number of assets to the number of observations.
- $\bar{\sigma}^2$: Mean variance, the mean eigenvalue.
- $\lambda_{+}$, $\lambda_{-}$: Upper and lower edges of the Marčenko–Pastur bulk. The figure draws $\lambda_{-}$ only when $q < 1$.
Arguments
sigma: Covariance or correlation matrix.N_obs: Number of observations, ornothingfor no reference line.reference: Draw the reference lines whentrueand the number of observations is known.pr: Prior result. The figure reads itssigma.rd: Returns result. The figure reads the number of rows of itsX.res: Optimisation result. The figure reads the prior it was fitted on.pred: A prediction. The figure reads the prior of its result.
Validation
- Every entry of
sigmais finite, elseeigvalsraises.
Returns
plt::Plots.Plot: A bar chart, with the reference lines when they apply.
Related
PortfolioOptimisers.plot_rolling_measure — Function
plot_rolling_measure(
r::BaseRM_VecBaseRM,
w::VecNum,
X::MatNum,
fees::Option{<:Fees} = nothing;
ts::AbstractVector = 1:size(X, 1),
rolling::Integer = 0,
sca::Option{<:Scalariser} = nothing,
kwargs...
) -> Plot
plot_rolling_measure(r, w, rd::ReturnsResult, fees = nothing; rolling, sca, kwargs...) -> Plot
plot_rolling_measure(r, res::OptimisationResult, rd::ReturnsResult; rolling, sca, kwargs...) -> Plot
plot_rolling_measure(r, pred::PredictionResult; rolling, sca, kwargs...) -> Plot
plot_rolling_measure(r, mpred::MultiPeriodPredictionResult; rolling, sca, kwargs...) -> Plot
plot_rolling_measure(r, ppred::PopulationPredictionResult; rolling, sca, kwargs...) -> Plot
plot_rolling_measure(r, ret::VecNum; ts::AbstractVector, rolling, sca, kwargs...) -> PlotPlot a risk or return measure of the portfolio returns over a rolling window, against the last date of each window.
rolling_window_measure scores each window of the net portfolio returns. Each window plots one number, so a vector of measures becomes its scalarised aggregate, not several lines. A population draws the mean of the return series of its members, on the time axis of the first member. The package extension PortfolioOptimisersPlotsExt implements the methods, and it loads after using StatsPlots.
A gapped panel reaches this figure only through the returns that the caller gives it. A prediction arity is finite already, because the fold set the Held Gap to zero once in predict. A w, X or w, rd arity computes on the matrix that the caller holds and checks nothing, and X * w is NaN at a gap even where the weight is zero. Score a gapped panel through predict(res, rd) and plot the prediction.
Mathematical definition
\[\begin{align} W &= \begin{cases} \lceil \sqrt{T} \rceil & \text{rolling} = 0\,, \\ \text{rolling} & \text{otherwise}\,, \end{cases} \\ R_t &= \rho\left(r_{t-W+1}, \ldots, r_t\right)\,, \quad t = W, \ldots, T\,. \end{align}\]
Where:
- $W$: Rolling window size, in observations.
- $R_t$: Rolling risk, the risk of the window that ends at observation $t$.
- $\rho$: The measure
r, or the aggregate thatscaforms from a vector of them. - $r_t$: Net portfolio return at observation $t$.
- $T$: Number of observations.
Arguments
r: Risk or return measure, or a vector of them thatscacombines. A measure can carry its own solver, such asEntropicValueatRisk(; slv = ...).w: Portfolio weights.X: Asset returns matrix (observations × assets).fees: Transaction fees, ornothing.ts: Labels of the time axis. A returns result or a prediction gives its own.rolling: Length of the window, or0for the default.sca: Scalariser that combines the measures inr. It has no effect whenris one measure.res: Optimisation result. The figure reads its weights and its fees on its investable universe.pred,mpred,ppred: A prediction, a walk-forward path or a population, whose return series the figure draws.ret: Net portfolio returns.
Validation
rolling >= 0, else aDomainErroris raised.- $W \leq T$, else
rolling_window_measureraises aDomainError. - Each measure reads a return series, else
expected_risk_from_returnsraises anArgumentError.
Returns
plt::Plots.Plot: A line plot of $T - W + 1$ points.
Related
PortfolioOptimisers.plot_weight_stability — Function
plot_weight_stability(
mpred::MultiPeriodPredictionResult;
N::Option{<:Number} = nothing,
kwargs...
) -> Plot
plot_weight_stability(ppred::PopulationPredictionResult; N, kwargs...) -> PlotPlot the distribution of the weight of each asset over the folds of a path or the members of a population, as one box per asset.
The weights are the rows of prediction_weights: the target of each fold, or of each member, on the union of the asset names. A member that is a walk-forward path gives one weight vector, the mean of its fold targets. A fold that failed to solve, and a path that holds one, gives a row that is NaN at every name, unless the fold holds the previous weights under a Weight Drift, as prediction_weights states. That row holds no weight, so it is absent from every box, and $K$ does not count it. When no row is left, the figure draws the axes alone. relevant_assets ranks the assets by their mean absolute weight and chooses how many boxes to draw, in the order of the asset axis. The package extension PortfolioOptimisersPlotsExt implements the methods, and it loads after using StatsPlots.
Mathematical definition
\[\begin{align} m_i = \frac{1}{K} \sum_{k=1}^{K} \lvert w_{i,k} \rvert\,. \end{align}\]
Where:
- $w_{i,k}$: Weight of asset $i$ in fold or member $k$.
- $K$: Number of folds or members.
- $m_i$: Mean absolute weight of asset $i$, the key of the ranking.
Arguments
mpred: A walk-forward path.ppred: A population of predictions.N: The count or the share of the boxes to draw, ornothingfor the effective number of the mean absolute weights.relevant_assetsstates the rule.
Returns
plt::Plots.Plot: A box plot.
Related
PortfolioOptimisers.plot_cv_scores — Function
plot_cv_scores(
scores::AbstractVector{<:Number},
labels::AbstractVector = 1:length(scores);
kwargs...
) -> Plot
plot_cv_scores(
r::BaseRM_VecBaseRM,
mpred::MultiPeriodPredictionResult;
sca::Option{<:Scalariser} = nothing,
kwargs...
) -> Plot
plot_cv_scores(
r::BaseRM_VecBaseRM,
ppred::PopulationPredictionResult;
sca::Option{<:Scalariser} = nothing,
kwargs...
) -> PlotPlot the score of each fold or population member as a bar chart.
The score of a fold or a member is expected_risk of r on the return series that it kept. Each bar is one number, so a vector of measures becomes its aggregate under sca, not several bars. The package extension PortfolioOptimisersPlotsExt implements the methods, and it loads after using StatsPlots.
Arguments
scores: The scores to draw.labels: Label of each bar.r: Risk or return measure, or a vector of them thatscacombines.sca: Scalariser that combines the measures inr. It has no effect whenris one measure.mpred: A walk-forward path.ppred: A population of predictions.
Validation
- The rules of
expected_riskon a prediction.
Returns
plt::Plots.Plot: A bar chart with one bar per fold or member.
Related
PortfolioOptimisers.plot_turnover — Function
plot_turnover(
w_series::AbstractVector{<:VecNum};
ts::AbstractVector = 1:length(w_series),
kwargs...
) -> Plot
plot_turnover(mpred::MultiPeriodPredictionResult; kwargs...) -> PlotPlot the turnover of a sequence of portfolios, the $L_1$ change of the weights from one portfolio to the next.
calc_turnover computes the turnover. The first portfolio has no predecessor, so the verb answers NaN there and the figure drops it. A walk-forward path reads the target weights of each fold, not the held or drifted weights, against the last date of each fold, or against the position of the fold when the path carries no dates. The package extension PortfolioOptimisersPlotsExt implements the methods, and it loads after using StatsPlots.
Mathematical definition
\[\begin{align} \tau_k = \sum_{i=1}^{N} \lvert w_{k,i} - w_{k-1,i} \rvert\,, \quad k = 2, \ldots, K\,. \end{align}\]
Where:
- $w_{k,i}$: Weight of asset $i$ in portfolio $k$.
- $\tau_k$: Turnover into portfolio $k$.
- $K$: Number of portfolios.
- $N$: Number of assets.
Arguments
w_series: Weight vectors, one per portfolio, of equal length.ts: Label of each portfolio on the time axis.mpred: A walk-forward path.
Returns
plt::Plots.Plot: A line plot of $K - 1$ points.
Related
PortfolioOptimisers.plot_prior — Function
plot_prior(
pr::AbstractPriorResult,
nx::AbstractVector = 1:length(pr.mu);
N::Option{<:Number} = nothing,
kwargs...
) -> Plot
plot_prior(pr::AbstractPriorResult, rd::ReturnsResult; N, kwargs...) -> Plot
plot_prior(res::OptimisationResult[, rd::ReturnsResult]; N, kwargs...) -> Plot
plot_prior(pred::PredictionResult[, rd::ReturnsResult]; N, kwargs...) -> PlotPlot a prior result as three panels side by side: the expected returns, the volatilities and the correlation.
- The expected returns, through
plot_mu. - The volatilities, through
plot_sigma. - The correlation, through
plot_correlation.
N reaches the first two panels, and the two read it by their own rules: plot_mu ranks by $\lvert \mu_i \rvert$ and with no N draws the effective number of assets, while plot_sigma ranks by volatility and with no N draws every asset. So the two panels can draw different assets. The extra keywords reach the outer layout of 1800 × 500 pixels and no panel. The package extension PortfolioOptimisersPlotsExt implements the methods, and it loads after using StatsPlots.
Every panel draws, so a non-investable asset of a prior that the caller gives is drawn rather than removed. Each panel states what its blank means. A result arity draws the prior that the result was fitted on, which is already reduced to its investable universe.
Arguments
pr: Prior result. The figure reads itsmuand itssigma.nx: Asset names.N: The count or the share of the bars of the first two panels.rd: Returns result. The figure reads itsnx.res: Optimisation result. The figure reads the prior it was fitted on.pred: A prediction. The figure reads the prior of its result.
Returns
plt::Plots.Plot: A layout of three panels.
Related
PortfolioOptimisers.plot_factor_mu — Function
plot_factor_mu(
f_mu::VecNum,
nf::AbstractVector = 1:length(f_mu);
N::Option{<:Number} = nothing,
kwargs...
) -> Plot
plot_factor_mu(pr::AbstractPriorResult, nf = nothing; N, kwargs...) -> Plot
plot_factor_mu(pr::AbstractPriorResult, rd::ReturnsResult; N, kwargs...) -> Plot
plot_factor_mu(res::OptimisationResult[, rd::ReturnsResult]; N, kwargs...) -> Plot
plot_factor_mu(pred::PredictionResult[, rd::ReturnsResult]; N, kwargs...) -> PlotPlot the expected return of each factor as a bar chart.
The prior arities draw the factor expected returns of the low order factor block that factor_plot_prior finds. The vector arity draws f_mu and needs no prior. relevant_assets ranks the factors by $\lvert \mu_{f,k} \rvert$ and chooses how many bars to draw, in the order of the factor axis. The package extension PortfolioOptimisersPlotsExt implements the methods, and it loads after using StatsPlots.
The figure draws the factor axis, and a non-investable asset is on the asset axis, so a gap never reaches it. It needs neither a blank nor a reduction.
Arguments
f_mu: Factor expected returns vector.nf: Factor names, ornothingto number them.N: The count or the share of the bars to draw, ornothingfor the effective number of the magnitudes.relevant_assetsstates the rule.pr: Prior result that carries a factor block.rd: Returns result. The figure reads itsnf.res: Optimisation result. The figure reads the prior it was fitted on.pred: A prediction. The figure reads the prior of its result.
Validation
pr.rris notnothing, elseassert_prior_regressionraises anIsNothingError.
Returns
plt::Plots.Plot: A bar chart.
Related
PortfolioOptimisers.plot_benchmark — Function
plot_benchmark(
w::ArrNum,
X::MatNum,
B::VecNum_VecVecNum,
fees::Option{<:Fees} = nothing;
ts::AbstractVector = 1:size(X, 1),
nb::Option{<:AbstractVector} = nothing,
compound::Bool = false,
kwargs...
) -> Plot
plot_benchmark(w, rd::ReturnsResult, fees = nothing; compound, kwargs...) -> Plot
plot_benchmark(res::OptimisationResult, rd::ReturnsResult; compound, kwargs...) -> Plot
plot_benchmark(pred::PredictionResult; compound, kwargs...) -> Plot
plot_benchmark(mpred::MultiPeriodPredictionResult; compound, kwargs...) -> Plot
plot_benchmark(
net_ret::VecNum,
B::VecNum_VecVecNum;
ts::AbstractVector,
nb::Option{<:AbstractVector} = nothing,
compound::Bool = false,
kwargs...
) -> PlotPlot the cumulative returns of a portfolio beside those of one or more benchmarks.
Each curve is cumulative_returns of its series: the net portfolio returns as a solid line, and each benchmark as a dashed line. A benchmark without a name in nb is labelled Benchmark i. A returns result carries its benchmark in B, and the figure reads it only when it is one series. A matrix B is a benchmark per asset, and this figure does not draw it. A prediction whose series is a vector of series draws the first of them. The package extension PortfolioOptimisersPlotsExt implements the methods, and it loads after using StatsPlots.
Arguments
w: Portfolio weights.X: Asset returns matrix (observations × assets).B: Benchmark return series, or a vector of series.fees: Transaction fees, ornothing.ts: Labels of the time axis. A returns result or a prediction gives its own.nb: Benchmark names, at least one per benchmark, ornothing.compound: Compound the returns of the portfolio and of every benchmark whentrue, and sum them otherwise.rd: Returns result. The figure reads itsX,B,tsandnb.res: Optimisation result. The figure reads its weights and its fees on its investable universe.pred,mpred: A prediction or a walk-forward path, whose return series and benchmark the figure draws.net_ret: Net portfolio returns.
Validation
- The
Bof the returns result or of the prediction is notnothing, else anArgumentErroris raised.
Returns
plt::Plots.Plot: A line plot with one portfolio curve and one curve per benchmark.
Related
PortfolioOptimisers.plot_coskewness — Function
plot_coskewness(
sk::MatNum,
nx::AbstractVector = 1:size(sk, 1);
kwargs...
) -> Plot
plot_coskewness(pr::HighOrderPrior, nx = nothing; kwargs...) -> Plot
plot_coskewness(pr::HighOrderPrior, rd::ReturnsResult; kwargs...) -> Plot
plot_coskewness(res::OptimisationResult[, rd::ReturnsResult]; kwargs...) -> Plot
plot_coskewness(pred::PredictionResult[, rd::ReturnsResult]; kwargs...) -> PlotPlot the coskewness matrix, $N \times N^2$, of a HighOrderPrior as a heatmap on a diverging colour scale centred at zero.
A row is an asset and a column is a pair of assets. The column labels name the pair when there are at most ten assets, and give the position of the column otherwise, on at most about twenty ticks. The package extension PortfolioOptimisersPlotsExt implements the methods, and it loads after using StatsPlots.
A non-investable asset of a prior that the caller gives is drawn rather than removed. It carries NaN down its row and every column of a pair it belongs to, so those cells are blank, and the blank shows the gap. The colour limits are finite_symmetric_clim, so one gap does not flatten the scale. A result arity draws the prior that the result was fitted on, which is already reduced to its investable universe.
Arguments
sk: Coskewness matrix (assets × assets²).nx: Asset names, ornothingto number them.pr: High order prior result. The figure reads itssk.rd: Returns result. The figure reads itsnx.res: Optimisation result. The figure reads the prior it was fitted on.pred: A prediction. The figure reads the prior of its result.
Validation
pr.skis notnothing, else anArgumentErroris raised.- The prior of a result is a
HighOrderPrior, else anArgumentErroris raised.
Returns
plt::Plots.Plot: A heatmap.
Related
PortfolioOptimisers.plot_cokurtosis — Function
plot_cokurtosis(
kt::MatNum,
nx::AbstractVector = 1:isqrt(size(kt, 1));
heatmap::Bool = false,
reference::Bool = true,
kwargs...
) -> Plot
plot_cokurtosis(pr::HighOrderPrior, nx = nothing; heatmap, reference, kwargs...) -> Plot
plot_cokurtosis(pr::HighOrderPrior, rd::ReturnsResult; heatmap, reference, kwargs...) -> Plot
plot_cokurtosis(res::OptimisationResult[, rd::ReturnsResult]; reference, kwargs...) -> Plot
plot_cokurtosis(pred::PredictionResult[, rd::ReturnsResult]; reference, kwargs...) -> PlotPlot the eigenvalues of the cokurtosis matrix, $N^2 \times N^2$, of a HighOrderPrior as a bar chart sorted from the largest, or the matrix itself as a heatmap.
The bar chart marks the mean eigenvalue with a reference line. The heatmap carries no axis labels, so nx has no effect on either figure. A result arity passes heatmap through its extra keywords. The package extension PortfolioOptimisersPlotsExt implements the methods, and it loads after using StatsPlots.
The two figures take opposite sides of one rule, because one draws and the other computes. Under heatmap = true the figure draws. A non-investable asset keeps its rows and its columns, they are blank cells, and the colour limits are finite_symmetric_clim, so one gap does not flatten the scale. Under the default the figure computes. eigvals(Symmetric(kt)) refuses a NaN, so the prior arity reduces to the Investable Mask at its entry through investable_plot_view, and the spectrum is that of the investable block, of length $N_i^2$ for $N_i$ investable assets. The bare kt arity computes on the matrix that the caller holds, and a gap in it raises rather than reduces.
Mathematical definition
\[\begin{align} \bar{\lambda} = \frac{1}{N^2} \sum_{j=1}^{N^2} \lambda_j = \frac{\mathrm{tr}(\mathbf{K})}{N^2}\,. \end{align}\]
Where:
- $\mathbf{K}$: The cokurtosis matrix whose spectrum the figure draws.
- $\lambda_j$: Eigenvalue $j$ of $\mathbf{K}$.
- $\bar{\lambda}$: Height of the reference line, the mean eigenvalue.
- $N$: Number of assets.
Arguments
kt: Cokurtosis matrix (assets² × assets²).nx: Asset names, ornothing. Neither figure draws them.heatmap: Draw the matrix as a heatmap whentrue, and its spectrum otherwise. A heatmap is readable for a small universe only.reference: Draw the mean eigenvalue whentrue.pr: High order prior result. The figure reads itskt.rd: Returns result.res: Optimisation result. The figure reads the prior it was fitted on.pred: A prediction. The figure reads the prior of its result.
Validation
pr.ktis notnothing, else anArgumentErroris raised.- The prior of a result is a
HighOrderPrior, else anArgumentErroris raised. - Under the spectrum, every entry of
ktis finite, elseeigvalsraises.
Returns
plt::Plots.Plot: A bar chart with the reference line whenreferenceistrue, or a heatmap.
Related
PortfolioOptimisers.plot_portfolio_dashboard — Function
plot_portfolio_dashboard(
res::OptimisationResult,
rd::Pr_RR;
ts = 1:size(rd.X, 1),
nx = 1:size(rd.X, 2),
r::BaseRM_VecBaseRM = Variance(),
slv::Option{<:Slv_VecSlv} = nothing,
compound::Bool = false,
N::Option{<:Number} = nothing,
delta::Number = 1e-6,
marginal::Bool = false,
percentage::Bool = true,
alpha::Number = 0.05,
kappa::Number = 0.3,
rw = nothing,
sca::Option{<:Scalariser} = nothing,
kwargs...
) -> PlotPlot one optimisation result as four panels in a 2 × 2 layout: its composition, its cumulative returns, its risk contributions and its drawdown.
- The composition, through
plot_composition. - The cumulative returns, through
plot_portfolio_cumulative_returns. - The risk contribution of each asset under
r, throughplot_risk_contribution. - The drawdown, through
plot_drawdowns, which draws its own fixed set of drawdown measures and does not readr.
The figure reads the weights and the fees of res, the returns of rd, and the names on the investable universe of the result. A returns result replaces nx and ts with its own when it carries them. Panel 3 reads a prior whole, so a measure with an unset moment, the default Variance() among them, takes the moment from the prior, and it reads the matrix of a returns result. The extra keywords reach the outer layout of 1200 × 800 pixels and no panel. The package extension PortfolioOptimisersPlotsExt implements the method, and it loads after using StatsPlots.
Each panel takes its own side of the draw and compute rule, and this figure adds no rule of its own. The figure views the result at its Investable Mask, so every panel draws the investable universe of the result alone.
Arguments
res: Optimisation result.rd: Returns result or prior result.ts: Labels of the time axis.nx: Asset names.r: Risk measure of panel 3, or a vector of them thatscacombines.sca: Scalariser that combines the measures inr. It has no effect whenris one measure. Passres.scato match the optimisation.slv: Solver of the entropic and relativistic drawdown lines of panel 4.compound: Compound the returns of panels 2 and 4 whentrue.N: The count or the share of the bars of panels 1 and 3.delta: Finite difference step of panel 3.marginal: Draw the marginal contribution in panel 3 whentrue, and the component contribution otherwise.percentage: Divide the contributions of panel 3 by their sum whentrue.alpha: Significance level of the drawdown lines of panel 4.kappa: Deformation parameter of the relativistic line of panel 4.rw: Observation weights of the average drawdown line of panel 4, ornothing.
Validation
- The rules of
plot_risk_contributionand ofplot_drawdowns.
Returns
plt::Plots.Plot: A layout of four panels.
Related
PortfolioOptimisers.plot_cv_dashboard — Function
plot_cv_dashboard(
mpred::MultiPeriodPredictionResult;
N::Option{<:Number} = nothing,
compound::Bool = false,
kwargs...
) -> PlotPlot a walk-forward path as four panels in a 2 × 2 layout: its fold compositions, its cumulative returns, its turnover and the stability of its weights.
- The composition of each fold as a stacked bar, through
plot_composition. - The cumulative returns of the whole path as one line, through
plot_portfolio_cumulative_returns. - The turnover from one fold to the next, through
plot_turnover. - The distribution of each weight over the folds, through
plot_weight_stability.
The extra keywords reach the outer layout of 1200 × 800 pixels and no panel. The package extension PortfolioOptimisersPlotsExt implements the method, and it loads after using StatsPlots.
Every panel reads a walk-forward prediction, whose folds set their Held Gaps to zero once in predict and whose weights are full length at every fold. So the four panels share one frame over the folds, and this figure adds no rule of its own.
Arguments
mpred: A walk-forward path.N: The count or the share of the boxes of panel 4. Panel 1 accepts it and does not read it.compound: Compound the returns of panel 2 whentrue.
Returns
plt::Plots.Plot: A layout of four panels.
Related
PortfolioOptimisers.plot_efficient_frontier — Function
plot_efficient_frontier(
res_vec::AbstractVector{<:OptimisationResult},
pr::Pr_RR;
x::BaseRM_VecBaseRM = Variance(),
y::BaseRM_VecBaseRM = ExpectedReturn(),
c::BaseRM_VecBaseRM = ExpectedReturnRiskRatio(; rk=x, rt=ArithmeticReturn(), rf=0),
slv::Option{<:Slv_VecSlv} = nothing,
fees::Option{<:Fees} = nothing,
min_risk::Bool = true,
max_score::Bool = true,
factory::Bool = true,
kwargs...
) -> Plot
plot_efficient_frontier(res_vec::AbstractVector{<:OptimisationResult}, rd::ReturnsResult; kwargs...) -> Plot
plot_efficient_frontier(w::VecVecNum, pr::Pr_RR; x, y, c, slv, fees, min_risk, max_score, factory, kwargs...) -> Plot
plot_efficient_frontier(res::OptimisationResult, pr::Pr_RR; fees, kwargs...) -> Plot
plot_efficient_frontier(res::OptimisationResult, rd::ReturnsResult; fees, kwargs...) -> PlotPlot a collection of portfolios as a line ordered by risk, coloured by a score, to trace an efficient frontier.
Each point is expected_risk of x and y for one portfolio, and its colour is expected_risk of c. The default colour is the ratio of the arithmetic return to the risk of x. Under the default Variance() that is the return over the variance, not a Sharpe ratio. The line joins the points in ascending order of x. A blue star marks the portfolio of least x, and a red star the portfolio of largest c. When factory is true, factory binds each measure to the prior and to slv first. The package extension PortfolioOptimisersPlotsExt implements the methods, and it loads after using StatsPlots.
A ReturnsResult in the second position is a tag and not data. Each result is scored against the prior it was fitted on, on its own investable universe, as plot_measures scores a vector of results. A prior in that position scores every portfolio against that one prior.
Each axis takes one measure or a vector of them, and a vector becomes the one number that the axis plots. As in plot_measures the figure names no scalariser, so a bare vector on an axis takes SumScalariser, each element weighted by its own settings.scale. A scalariser reaches an axis only through the sca field of a ratio wrapper, so the figure cannot apply a MaxScalariser to a plain vector of risks. The order of the line and the two stars read the scalarised number, so a vector x orders the frontier by the aggregate and not by one measure. The axis label joins the element measures with +, whichever scalariser formed the number.
Arguments
res_vec: Optimisation results.w: Weight vectors, one per portfolio.res: One optimisation result, drawn as a frontier of one point.pr: Prior result or returns result that the portfolios are scored against.rd: Returns result, the tag that asks for the prior of each result.x: Measure of the horizontal axis, or a vector of them.y: Measure of the vertical axis, or a vector of them.c: Measure of the colour, or a vector of them.slv: Solver thatfactorybinds to each measure.fees: Transaction fees, ornothing.min_risk: Mark the portfolio of leastxwhentrue.max_score: Mark the portfolio of largestcwhentrue.factory: Bind each measure throughfactorybefore the figure scores it.
Validation
- The rules of
expected_riskfor each measure.
Returns
plt::Plots.Plot: A line plot with markers, and the stars thatmin_riskandmax_scoreask for.
Related
PortfolioOptimisers.plot_performance_summary — Function
plot_performance_summary(ps::PerformanceSummaryResult; kwargs...) -> Plot
plot_performance_summary(x::Union{AbstractArray, OptimisationResult,
AbstractPredictionResult}, args...;
ppy, alpha, compound, rf, measures, benchmark, names,
kwargs...) -> PlotPlot the performance statistics of one or more portfolios as bars, blue at a value of zero or more and red below it.
Every method but the first computes a PerformanceSummaryResult with performance_summary and draws it, so it takes every arity that verb takes. The keywords of the verb go to the summary, and every other keyword goes to the figure. The verb defines and validates the statistics, so a caller who wants the numbers and not the bars calls it directly and needs no plotting package. A prediction arity defaults benchmark to the benchmark of its rows, as performance_summary does. The package extension PortfolioOptimisersPlotsExt implements the methods, and it loads after using StatsPlots.
A summary of one entry draws one bar chart, with the eleven bars below in order, seven of them in percent, and one bar more for each extra measure. A summary of many entries draws one panel for each figure, with one bar for each entry. The label of a bar names the keys of its entry that are not nothing: the candidate, the path and the member. The excess bars are NaN, drawn empty, when the summary has no benchmark, and the turnover bar is NaN on every arity that holds no path, which is every arity but a prediction.
A gapped panel reaches this figure only through the returns that the caller gives it. A prediction arity is finite already, because the fold set the Held Gap to zero once in predict. A w, X or w, rd arity computes on the matrix that the caller holds and checks nothing, and X * w is NaN at a gap even where the weight is zero. Score a gapped panel through predict(res, rd) and plot the prediction.
Mathematical definition
\[\begin{align} \boldsymbol{v} = \left(100 R_a,\ 100 \sigma_a,\ \mathrm{SR},\ \mathrm{So},\ \mathrm{Ca},\ 100\, \mathrm{MDD},\ 100\, \mathrm{CVaR},\ 100\, \mathrm{ER},\ 100\, \mathrm{TE},\ \mathrm{IR},\ 100\, \mathrm{TO}\right)\,. \end{align}\]
Where:
- $\boldsymbol{v}$: The heights of the eleven bars of one entry, in order. The value of each extra measure follows them, with no scale.
- $R_a$, $\sigma_a$: Annualised return and annualised volatility, the fields
ann_returnandann_volatility. - $\mathrm{SR}$, $\mathrm{So}$, $\mathrm{Ca}$: Sharpe, Sortino and Calmar ratios, the fields
sharpe,sortinoandcalmar. - $\mathrm{MDD}$: Maximum drawdown, the field
max_drawdown, which is at most zero. - $\mathrm{CVaR}$: The field
cvar, the negated conditional value at risk, so its bar is negative for a loss. - $\mathrm{ER}$, $\mathrm{TE}$, $\mathrm{IR}$: Excess return, tracking error and information ratio against the benchmark, the fields
excess_ret,tracking_errorandinformation_ratio. - $\mathrm{TO}$: Turnover, the field
turnover.
Arguments
ps: The summary to draw.x,args...: The arguments ofperformance_summary: a series, weights and returns, an optimisation result and its returns, a prediction, a population, or a vector of candidates.ppy,alpha,compound,rf,measures,benchmark,names: The keywords ofperformance_summary.
Validation
- The rules of
performance_summary.
Returns
plt::Plots.Plot: A bar chart for one entry, or one panel for each figure for many entries.
Related
PortfolioOptimisers.plot_rolling_drawdowns — Function
plot_rolling_drawdowns(
w::ArrNum,
X::MatNum,
fees::Option{<:Fees} = nothing;
ts::AbstractVector = 1:size(X, 1),
rolling::Integer = 0,
compound::Bool = false,
kwargs...
) -> Plot
plot_rolling_drawdowns(w, rd::ReturnsResult, fees = nothing; rolling, compound, kwargs...) -> Plot
plot_rolling_drawdowns(res::OptimisationResult, rd::ReturnsResult; rolling, compound, kwargs...) -> Plot
plot_rolling_drawdowns(pred::PredictionResult; rolling, compound, kwargs...) -> Plot
plot_rolling_drawdowns(mpred::MultiPeriodPredictionResult; rolling, compound, kwargs...) -> Plot
plot_rolling_drawdowns(ret::VecNum; ts::AbstractVector, rolling, compound, kwargs...) -> PlotPlot the maximum drawdown of the portfolio over a rolling window, in percent, against the last date of each window.
Each window is drawn down from its own entry value. The running peak starts at the capital at the start of the window, not at the capital at inception, so a window that only rises reads zero. The package extension PortfolioOptimisersPlotsExt implements the methods, and it loads after using StatsPlots.
A gapped panel reaches this figure only through the returns that the caller gives it. A prediction arity is finite already, because the fold set the Held Gap to zero once in predict. A w, X or w, rd arity computes on the matrix that the caller holds and checks nothing, and X * w is NaN at a gap even where the weight is zero. Score a gapped panel through predict(res, rd) and plot the prediction.
Mathematical definition
\[\begin{align} W &= \begin{cases} \lceil \sqrt{T} \rceil & \text{rolling} = 0\,, \\ \text{rolling} & \text{otherwise}\,, \end{cases} \\ D_t &= 100 \min_{s = t-W+1, \ldots, t} d_{t,s}\,, \quad t = W, \ldots, T\,. \end{align}\]
Where:
- $W$: Rolling window size, in observations.
- $T$: Number of observations.
- $d_{t,s}$:
drawdownsat observation $s$ of the returns $r_{t-W+1}, \ldots, r_t$ of the window that ends at $t$, absolute or relative ascompoundselects. - $D_t$: The value that the figure draws at observation $t$, the maximum drawdown of that window in percent, at most zero.
Arguments
w: Portfolio weights.X: Asset returns matrix (observations × assets).fees: Transaction fees, ornothing.ts: Labels of the time axis. A returns result or a prediction gives its own.rolling: Length of the window, or0for the default.compound: Compound the returns and take relative drawdowns whentrue.res: Optimisation result. The figure reads its weights and its fees on its investable universe.pred,mpred: A prediction or a walk-forward path, whose return series the figure draws.ret: Net portfolio returns.
Validation
rolling >= 0, else aDomainErroris raised.- $W \leq T$, else a
DomainErroris raised.
Returns
plt::Plots.Plot: A line plot of $T - W + 1$ points.
Related
PortfolioOptimisers.plot_cs_regression_r2 — Function
plot_cs_regression_r2(csfm::CrossSectionalFactorModel; kwargs...) -> Plot
plot_cs_regression_r2(pr::AbstractPriorResult; kwargs...) -> PlotPlot the weighted cross-sectional coefficient of determination of every cross-sectional fit.
The figure draws what cs_regression_r2 returns and computes nothing of its own. A prior result gives its rr field, the block that the fit produced. The horizontal axis counts the fits of the lagged sample, so position $j$ is observation $j$ plus the lag of the block. The package extension PortfolioOptimisersPlotsExt implements the methods, and it loads after using StatsPlots.
Arguments
csfm: A cross-sectional factor model block.pr: A prior result whoserris such a block.kwargs...: Additional keyword arguments passed to the plotting backend.
Validation
pr.rris notnothing, elseassert_prior_regressionraises anIsNothingError.pr.rris aCrossSectionalFactorModel, else the verb raises aMethodError: a time-seriesRegressioncarries no exposure history.- The rules of
cs_regression_r2.
Returns
plt::Plots.Plot: A line plot with one point per fit of the lagged sample.
Related
PortfolioOptimisers.plot_cs_regression_adjusted_r2 — Function
plot_cs_regression_adjusted_r2(csfm::CrossSectionalFactorModel; kwargs...) -> Plot
plot_cs_regression_adjusted_r2(pr::AbstractPriorResult; kwargs...) -> PlotPlot the adjusted cross-sectional coefficient of determination of every cross-sectional fit.
The figure draws what cs_regression_adjusted_r2 returns and computes nothing of its own. A prior result gives its rr field, the block that the fit produced. The horizontal axis counts the fits of the lagged sample, so position $j$ is observation $j$ plus the lag of the block. The package extension PortfolioOptimisersPlotsExt implements the methods, and it loads after using StatsPlots.
Arguments
csfm: A cross-sectional factor model block.pr: A prior result whoserris such a block.kwargs...: Additional keyword arguments passed to the plotting backend.
Validation
pr.rris notnothing, elseassert_prior_regressionraises anIsNothingError.pr.rris aCrossSectionalFactorModel, else the verb raises aMethodError: a time-seriesRegressioncarries no exposure history.- The rules of
cs_regression_adjusted_r2.
Returns
plt::Plots.Plot: A line plot with one point per fit of the lagged sample.
Related
PortfolioOptimisers.plot_cs_regression_aic — Function
plot_cs_regression_aic(csfm::CrossSectionalFactorModel; kwargs...) -> Plot
plot_cs_regression_aic(pr::AbstractPriorResult; kwargs...) -> PlotPlot the Akaike information criterion of every cross-sectional fit.
The figure draws what cs_regression_aic returns and computes nothing of its own. A prior result gives its rr field, the block that the fit produced. The horizontal axis counts the fits of the lagged sample, so position $j$ is observation $j$ plus the lag of the block. The package extension PortfolioOptimisersPlotsExt implements the methods, and it loads after using StatsPlots.
Arguments
csfm: A cross-sectional factor model block.pr: A prior result whoserris such a block.kwargs...: Additional keyword arguments passed to the plotting backend.
Validation
pr.rris notnothing, elseassert_prior_regressionraises anIsNothingError.pr.rris aCrossSectionalFactorModel, else the verb raises aMethodError: a time-seriesRegressioncarries no exposure history.- The rules of
cs_regression_aic.
Returns
plt::Plots.Plot: A line plot with one point per fit of the lagged sample.
Related
PortfolioOptimisers.plot_cs_regression_bic — Function
plot_cs_regression_bic(csfm::CrossSectionalFactorModel; kwargs...) -> Plot
plot_cs_regression_bic(pr::AbstractPriorResult; kwargs...) -> PlotPlot the Bayesian information criterion of every cross-sectional fit.
The figure draws what cs_regression_bic returns and computes nothing of its own. A prior result gives its rr field, the block that the fit produced. The horizontal axis counts the fits of the lagged sample, so position $j$ is observation $j$ plus the lag of the block. The package extension PortfolioOptimisersPlotsExt implements the methods, and it loads after using StatsPlots.
Arguments
csfm: A cross-sectional factor model block.pr: A prior result whoserris such a block.kwargs...: Additional keyword arguments passed to the plotting backend.
Validation
pr.rris notnothing, elseassert_prior_regressionraises anIsNothingError.pr.rris aCrossSectionalFactorModel, else the verb raises aMethodError: a time-seriesRegressioncarries no exposure history.- The rules of
cs_regression_bic.
Returns
plt::Plots.Plot: A line plot with one point per fit of the lagged sample.
Related
PortfolioOptimisers.plot_cs_regression_t_stats — Function
plot_cs_regression_t_stats(
t::FactorDiagnosticResult;
nf::Option{<:AbstractVector} = nothing,
kwargs...
) -> Plot
plot_cs_regression_t_stats(
csfm::CrossSectionalFactorModel;
nf::Option{<:AbstractVector} = nothing,
kwargs...
) -> Plot
plot_cs_regression_t_stats(
pr::AbstractPriorResult;
nf::Option{<:AbstractVector} = nothing,
kwargs...
) -> PlotPlot the t-statistic of every factor return, one series per factor.
The figure draws what cs_regression_t_stats returns and computes nothing of its own. The series are labelled by the factor names of the axis of the answer, which cs_diagnostic_factor_names resolves, so a block that carries a family re-basis is labelled on the reduced axis. The horizontal axis counts the fits of the lagged sample. The package extension PortfolioOptimisersPlotsExt implements the methods, and it loads after using StatsPlots.
Arguments
t: The answer ofcs_regression_t_stats, or a view of it fromport_opt_view. The figure draws it and labels it with the names it carries.csfm: A cross-sectional factor model block.pr: A prior result whoserris such a block.nf: Factor names of the answer's axis.nothingreads them off the answer, and falls back to the position of the factor.kwargs...: Additional keyword arguments passed to the plotting backend.
Validation
pr.rris notnothing, elseassert_prior_regressionraises anIsNothingError.pr.rris aCrossSectionalFactorModel, else the verb raises aMethodError: a time-seriesRegressioncarries no exposure history.- The rules of
cs_regression_t_stats.
Returns
plt::Plots.Plot: A line plot with one series per factor, and one point per fit of the lagged sample in each.
Related
PortfolioOptimisers.plot_cs_regression_t_stat_exceedance_rate — Function
plot_cs_regression_t_stat_exceedance_rate(
t::FactorDiagnosticResult;
nf::Option{<:AbstractVector} = nothing,
threshold::Number = 2,
kwargs...
) -> Plot
plot_cs_regression_t_stat_exceedance_rate(
csfm::CrossSectionalFactorModel;
nf::Option{<:AbstractVector} = nothing,
threshold::Number = 2,
kwargs...
) -> Plot
plot_cs_regression_t_stat_exceedance_rate(
pr::AbstractPriorResult;
nf::Option{<:AbstractVector} = nothing,
threshold::Number = 2,
kwargs...
) -> PlotPlot the fraction of observations at which the t-statistic of each factor exceeds a threshold, one bar per factor.
The bars are what cs_regression_t_stat_exceedance_rate returns. A dashed line marks the rate that a factor of no explanatory power reaches, the one quantity the figure computes. The factors are labelled on the axis of the answer, as plot_cs_regression_t_stats labels them. The package extension PortfolioOptimisersPlotsExt implements the methods, and it loads after using StatsPlots.
Mathematical definition
\[\begin{align} q_0 = 2 \Phi(-c)\,. \end{align}\]
Where:
- $c$: The threshold,
threshold. - $\Phi$: Distribution function of the standard normal law.
- $q_0$: Height of the reference line, the probability that a standard normal t-statistic exceeds $c$ in magnitude. It is about
0.0455at the default threshold.
Arguments
t: The t-statistics ofcs_regression_t_stats, or a view of them fromport_opt_view. The figure takes the rate over them and labels it with the names they carry.csfm: A cross-sectional factor model block.pr: A prior result whoserris such a block.nf: Factor names of the answer's axis.nothingreads them off the answer, and falls back to the position of the factor.threshold: Absolute t-statistic above which an observation counts as significant.kwargs...: Additional keyword arguments passed to the plotting backend.
Validation
pr.rris notnothing, elseassert_prior_regressionraises anIsNothingError.pr.rris aCrossSectionalFactorModel, else the verb raises aMethodError: a time-seriesRegressioncarries no exposure history.- The rules of
cs_regression_t_stat_exceedance_rate.
Returns
plt::Plots.Plot: A bar chart with one bar per factor, and the reference line.
Related
PortfolioOptimisers.plot_exposure_vif — Function
plot_exposure_vif(
vif::FactorDiagnosticResult;
nf::Option{<:AbstractVector} = nothing,
kwargs...
) -> Plot
plot_exposure_vif(
csfm::CrossSectionalFactorModel;
nf::Option{<:AbstractVector} = nothing,
kwargs...
) -> Plot
plot_exposure_vif(
pr::AbstractPriorResult;
nf::Option{<:AbstractVector} = nothing,
kwargs...
) -> PlotPlot the variance inflation factor of every factor, one series per factor.
The figure draws what exposure_vif returns and computes nothing of its own. A dashed line marks 1, the value that an orthogonal design reaches. The series are labelled on the axis of the answer, as plot_cs_regression_t_stats labels them. The package extension PortfolioOptimisersPlotsExt implements the methods, and it loads after using StatsPlots.
Arguments
vif: The answer ofexposure_vif, or a view of it fromport_opt_view. The figure draws it and labels it with the names it carries.csfm: A cross-sectional factor model block.pr: A prior result whoserris such a block.nf: Factor names of the answer's axis.nothingreads them off the answer, and falls back to the position of the factor.kwargs...: Additional keyword arguments passed to the plotting backend.
Validation
pr.rris notnothing, elseassert_prior_regressionraises anIsNothingError.pr.rris aCrossSectionalFactorModel, else the verb raises aMethodError: a time-seriesRegressioncarries no exposure history.- The rules of
exposure_vif.
Returns
plt::Plots.Plot: A line plot with one series per factor, and the reference line.
Related
PortfolioOptimisers.plot_exposure_condition_number — Function
plot_exposure_condition_number(csfm::CrossSectionalFactorModel; kwargs...) -> Plot
plot_exposure_condition_number(pr::AbstractPriorResult; kwargs...) -> PlotPlot the condition number of the cross-sectional design of every observation. The package extension PortfolioOptimisersPlotsExt implements the methods, and it loads after using StatsPlots.
The figure draws what exposure_condition_number returns and computes nothing of its own. The vertical axis is logarithmic, because the condition number of a nearly collinear design is many orders of magnitude above that of a well conditioned one.
Arguments
csfm: A cross-sectional factor model block.pr: A prior result whoserris such a block.kwargs...: Additional keyword arguments passed to the plotting backend.
Validation
pr.rris notnothing, elseassert_prior_regressionraises anIsNothingError.pr.rris aCrossSectionalFactorModel, else the verb raises aMethodError: a time-seriesRegressioncarries no exposure history.- The rules of
exposure_condition_number.
Returns
plt::Plots.Plot: A line plot on a logarithmic vertical axis.
Related
PortfolioOptimisers.plot_attribution_vol_contrib — Function
plot_attribution_vol_contrib(
fa::FactorAttributionResult;
by_family::Bool = false,
rd::ReturnsResult = ReturnsResult(),
nf::Option{<:AbstractVector} = nothing,
N::Option{<:Number} = nothing,
kwargs...
) -> PlotPlot the volatility contribution of each factor, or of each factor family, as a bar chart. The package extension PortfolioOptimisersPlotsExt implements the methods, and it loads after using StatsPlots.
The plot reads one FactorAttributionResult and computes nothing. The rows it draws are fa.fbd.vol_contrib, or fa.fmbd.vol_contrib under by_family, and it selects and orders the rows it shows. A family axis is present only when the factor model block names families, so by_family = true on a Result whose fmbd is nothing raises.
Arguments
fa: Factor attribution result.by_family: Whether to draw the family axis rather than the factor axis.rd: Returns result providing the factor names throughrd.nf.nf: Factor names, one per row of the factor axis. They replacerd.nfwhen given. They have no effect underby_family, whose labels the Result carries.N: The count of the rows to draw, $\min(\max(\lceil N \rceil, 1), M)$ of the $M$ rows, ornothingfor every row. The rows are those of the largest finite magnitude of the value drawn, so aNaNrow never takes a slot from a finite one. The rows shown keep the order of the axis, and the rest are not drawn.
Validation
- If
by_familyistrue,fa.fmbdis notnothing, else anArgumentErroris raised. - If
Nis notnothing,N > 0, else aDomainErroris raised.
Returns
plt::Plots.Plot: A bar chart.
Related
PortfolioOptimisers.plot_attribution_mu_contrib — Function
plot_attribution_mu_contrib(
fa::FactorAttributionResult;
by_family::Bool = false,
rd::ReturnsResult = ReturnsResult(),
nf::Option{<:AbstractVector} = nothing,
N::Option{<:Number} = nothing,
z::Number = 1.96,
kwargs...
) -> PlotPlot the mean return contribution of each factor, or of each factor family, as a bar chart with error bars. The package extension PortfolioOptimisersPlotsExt implements the methods, and it loads after using StatsPlots.
The plot reads one FactorAttributionResult and computes nothing beyond the half-width z * se it draws. The bars are fa.fbd.mu_contrib, or fa.fmbd.mu_contrib under by_family, and the half-width of the error bar of row $k$ is $z \, \mathrm{se}_k$, from the standard errors the Result carries. A row whose standard error is NaN, such as a currency family, draws no error bar. A Result fitted without se = true carries none, and the plot then draws the bars alone.
Arguments
fa: Factor attribution result.by_family: Whether to draw the family axis rather than the factor axis.rd: Returns result providing the factor names throughrd.nf.nf: Factor names, one per row of the factor axis. They replacerd.nfwhen given. They have no effect underby_family, whose labels the Result carries.N: The count of the rows to draw, $\min(\max(\lceil N \rceil, 1), M)$ of the $M$ rows, ornothingfor every row. The rows are those of the largest finite magnitude of the value drawn, so aNaNrow never takes a slot from a finite one. The rows shown keep the order of the axis, and the rest are not drawn.z: Half-width of the error bar, in standard errors.
Validation
- If
by_familyistrue,fa.fmbdis notnothing, else anArgumentErroris raised. - If
Nis notnothing,N > 0, else aDomainErroris raised. z >= 0, else aDomainErroris raised.
Returns
plt::Plots.Plot: A bar chart, with error bars when the Result carries standard errors.
Related
PortfolioOptimisers.plot_attribution_exposure — Function
plot_attribution_exposure(
fa::FactorAttributionResult;
by_family::Bool = false,
rd::ReturnsResult = ReturnsResult(),
nf::Option{<:AbstractVector} = nothing,
N::Option{<:Number} = nothing,
kwargs...
) -> PlotPlot the portfolio's exposure to each factor, or to each factor family, as a bar chart with its spread. The package extension PortfolioOptimisersPlotsExt implements the methods, and it loads after using StatsPlots.
The plot reads one FactorAttributionResult and computes nothing. The bars are fa.fbd.exposure, or fa.fmbd.exposure under by_family, and each error bar is one standard deviation of the exposure over the observations, on either side of the bar. A predicted attribution reads one exposure and no history, so it carries no spread and the plot draws the bars alone.
Arguments
fa: Factor attribution result.by_family: Whether to draw the family axis rather than the factor axis.rd: Returns result providing the factor names throughrd.nf.nf: Factor names, one per row of the factor axis. They replacerd.nfwhen given. They have no effect underby_family, whose labels the Result carries.N: The count of the rows to draw, $\min(\max(\lceil N \rceil, 1), M)$ of the $M$ rows, ornothingfor every row. The rows are those of the largest finite magnitude of the value drawn, so aNaNrow never takes a slot from a finite one. The rows shown keep the order of the axis, and the rest are not drawn.
Validation
- If
by_familyistrue,fa.fmbdis notnothing, else anArgumentErroris raised. - If
Nis notnothing,N > 0, else aDomainErroris raised.
Returns
plt::Plots.Plot: A bar chart, with error bars when the Result carries a history of the exposure.
Related
PortfolioOptimisers.plot_attribution_mu_vs_vol — Function
plot_attribution_mu_vs_vol(
fa::FactorAttributionResult;
by_family::Bool = false,
rd::ReturnsResult = ReturnsResult(),
nf::Option{<:AbstractVector} = nothing,
N::Option{<:Number} = nothing,
kwargs...
) -> PlotPlot the mean return contribution of each factor against its volatility contribution, as a labelled scatter. The package extension PortfolioOptimisersPlotsExt implements the methods, and it loads after using StatsPlots.
The plot reads one FactorAttributionResult and computes nothing. Each point is one row of the factor axis, or of the family axis under by_family, placed at its volatility contribution and its mean return contribution. It is where a reader sees which factor paid for the risk it carried.
Arguments
fa: Factor attribution result.by_family: Whether to draw the family axis rather than the factor axis.rd: Returns result providing the factor names throughrd.nf.nf: Factor names, one per row of the factor axis. They replacerd.nfwhen given. They have no effect underby_family, whose labels the Result carries.N: The count of the rows to draw, $\min(\max(\lceil N \rceil, 1), M)$ of the $M$ rows, ornothingfor every row. The rows are those of the largest finite magnitude of the volatility contribution. The rest are not drawn.
Validation
- If
by_familyistrue,fa.fmbdis notnothing, else anArgumentErroris raised. - If
Nis notnothing,N > 0, else aDomainErroris raised.
Returns
plt::Plots.Plot: A scatter with one labelled point per drawn row.
Related
PortfolioOptimisers.plot_exposure_correlation — Function
plot_exposure_correlation(
r::FactorDiagnosticResult;
nf::Option{<:AbstractVector} = nothing,
kwargs...
) -> Plot
plot_exposure_correlation(
csfm::CrossSectionalFactorModel;
nf::Option{<:AbstractVector} = nothing,
weighting = BenchmarkWeightMetric(),
kwargs...
) -> Plot
plot_exposure_correlation(
pr::AbstractPriorResult;
nf::Option{<:AbstractVector} = nothing,
weighting = BenchmarkWeightMetric(),
kwargs...
) -> PlotPlot the time-averaged correlation between every pair of factor exposures as a heatmap.
The figure draws what exposure_correlation returns and computes nothing of its own. The colour limits are fixed at (-1, 1), so two figures of two models are read against the same scale. A pair that the verb cannot correlate is NaN, and its cell is blank. The exposure figures answer on the raw factor axis, because they read the exposure history as the panel wrote it, so the labels come from the names of the block and not from cs_diagnostic_factor_names. The package extension PortfolioOptimisersPlotsExt implements the methods, and it loads after using StatsPlots.
Arguments
r: The answer ofexposure_correlation, or a view of it fromport_opt_view. The figure draws it and labels it with the names it carries. A view by family draws the sub-block of that family.csfm: A cross-sectional factor model block.pr: A prior result whoserris such a block.nf: Factor names of the raw factor axis.nothingreads them off the answer, and falls back to the position of the factor.weighting: A member ofAbstractOrthogonalityMetric, ornothingfor equal weights. It names the weight history the block is read with.kwargs...: Additional keyword arguments passed to the plotting backend.
Validation
pr.rris notnothing, elseassert_prior_regressionraises anIsNothingError.pr.rris aCrossSectionalFactorModel, else the verb raises aMethodError: a time-seriesRegressioncarries no exposure history.- The rules of
exposure_correlation, which raises anIsNothingErrorwhen the block carries no exposure history or no weight history of the kindweightingnames.
Returns
plt::Plots.Plot: A heatmap of factors by factors.
Related
PortfolioOptimisers.plot_cumulative_exposure_ic — Function
plot_cumulative_exposure_ic(
ic::FactorDiagnosticResult;
nf::Option{<:AbstractVector} = nothing,
title::AbstractString = "Cumulative Exposure IC",
kwargs...
) -> Plot
plot_cumulative_exposure_ic(
csfm::CrossSectionalFactorModel;
nf::Option{<:AbstractVector} = nothing,
rank::Bool = true,
reduced::Bool = false,
ties::Symbol = :average,
kwargs...
) -> Plot
plot_cumulative_exposure_ic(
pr::AbstractPriorResult;
nf::Option{<:AbstractVector} = nothing,
rank::Bool = true,
reduced::Bool = false,
ties::Symbol = :average,
kwargs...
) -> PlotPlot the running sum of the information coefficient of every factor exposure, one series per factor.
The figure draws the running sum of what exposure_ic returns at a horizon of one observation, and computes nothing else of its own. An observation whose coefficient is not finite adds nothing to the sum, so one missing cross-section breaks no series. A series that rises through the sample is an exposure that forecast the return, a flat series is one that carried no forecast, and a falling series is one whose forecast had the opposite sign. The series are labelled on the raw factor axis, and on the reduced axis under reduced, as plot_cs_regression_t_stats labels them. The package extension PortfolioOptimisersPlotsExt implements the methods, and it loads after using StatsPlots.
A risk factor with an information coefficient near zero is not a bad risk factor. A risk factor is built to explain the covariance and not to predict the mean, so read plot_exposure_stability and the variance that the factor contributes before you judge one.
Mathematical definition
\[\begin{align} C_{t,k} = \sum_{s=1}^{t} \mathbb{1}\left[\mathrm{IC}_{s,k} \text{ is finite}\right] \mathrm{IC}_{s,k}\,. \end{align}\]
Where:
- $\mathrm{IC}_{s,k}$: Information coefficient of factor $k$ at observation $s$, as
exposure_icreturns it. - $C_{t,k}$: Point $t$ of the series of factor $k$.
Arguments
ic: The answer ofexposure_ic, or a view of it fromport_opt_view. The figure draws it and labels it with the names it carries. Thecsfmmethod reads it at a horizon of one observation.csfm: A cross-sectional factor model block.pr: A prior result whoserris such a block.nf: Factor names of the axis of the answer.nothingreads them off the answer, and falls back to the position of the factor.rank: Take the rank correlation whentrue, and the weighted correlation otherwise.reduced: Map the exposures through the family re-basis of the block before the correlation.ties: Rule that ranks the equal values of a cross-section.:averagegives each value of a tie the mean of the positions the tie takes, so a rank correlation does not read the order of the assets, and a constant cross-section has no rank correlation.:ordinalgives the values of a tie consecutive positions, in the order of the asset axis. The two rules give the same ranks to a cross-section with no tie. The weighted correlation reads no rank, so it ignoresties.title: Title of the figure. Thecsfmandprmethods pass one that names the method or the step.kwargs...: Additional keyword arguments passed to the plotting backend.
Validation
pr.rris notnothing, elseassert_prior_regressionraises anIsNothingError.pr.rris aCrossSectionalFactorModel, else the verb raises aMethodError: a time-seriesRegressioncarries no exposure history.- The rules of
exposure_icat a horizon of one observation.
Returns
plt::Plots.Plot: A line plot with one series per factor.
Related
PortfolioOptimisers.plot_exposure_distribution — Function
plot_exposure_distribution(
csfm::CrossSectionalFactorModel;
factor::Integer = 1,
observation::Option{<:Integer} = nothing,
nf::Option{<:AbstractVector} = nothing,
kwargs...
) -> Plot
plot_exposure_distribution(
pr::AbstractPriorResult;
factor::Integer = 1,
observation::Option{<:Integer} = nothing,
nf::Option{<:AbstractVector} = nothing,
kwargs...
) -> PlotPlot the cross-sectional distribution of one factor exposure as a histogram.
The figure draws one slice of the exposure history of the block and computes nothing of its own. observation selects one observation, and nothing pools every observation into one figure. The entries that are not finite are dropped, so the count of the figure is the coverage of the factor. The factor is named on the raw factor axis. The package extension PortfolioOptimisersPlotsExt implements the methods, and it loads after using StatsPlots.
Arguments
csfm: A cross-sectional factor model block.pr: A prior result whoserris such a block.factor: Position of the factor on the raw factor axis of the block.observation: Position of the observation, ornothingto pool every observation.nf: Factor names of the raw axis.nothingreads them off the block, and falls back to the position of the factor.kwargs...: Additional keyword arguments passed to the plotting backend.
Validation
pr.rris notnothing, elseassert_prior_regressionraises anIsNothingError.pr.rris aCrossSectionalFactorModel, else the verb raises aMethodError: a time-seriesRegressioncarries no exposure history.- The block carries an exposure history, else an
IsNothingErroris raised. factorandobservationindex the history, else aBoundsErroris raised.
Returns
plt::Plots.Plot: A histogram of the finite exposures of the slice.
Related
PortfolioOptimisers.plot_exposure_dispersion — Function
plot_exposure_dispersion(
D::FactorDiagnosticResult;
nf::Option{<:AbstractVector} = nothing,
kwargs...
) -> Plot
plot_exposure_dispersion(
csfm::CrossSectionalFactorModel;
nf::Option{<:AbstractVector} = nothing,
weighting = BenchmarkWeightMetric(),
kwargs...
) -> Plot
plot_exposure_dispersion(
pr::AbstractPriorResult;
nf::Option{<:AbstractVector} = nothing,
weighting = BenchmarkWeightMetric(),
kwargs...
) -> PlotPlot the weighted cross-sectional standard deviation of every factor exposure, one series per factor.
The figure draws what exposure_dispersion returns and computes nothing of its own. Read the series and not its level, because the level follows the standardisation the exposures were built under, and the series shows the observation at which the panel changed. The series are labelled on the raw factor axis, as plot_exposure_correlation labels them. The package extension PortfolioOptimisersPlotsExt implements the methods, and it loads after using StatsPlots.
Arguments
D: The answer ofexposure_dispersion, or a view of it fromport_opt_view. The figure draws it and labels it with the names it carries.csfm: A cross-sectional factor model block.pr: A prior result whoserris such a block.nf: Factor names of the raw factor axis.nothingreads them off the answer, and falls back to the position of the factor.weighting: A member ofAbstractOrthogonalityMetric, ornothingfor equal weights. It names the weight history the block is read with.kwargs...: Additional keyword arguments passed to the plotting backend.
Validation
pr.rris notnothing, elseassert_prior_regressionraises anIsNothingError.pr.rris aCrossSectionalFactorModel, else the verb raises aMethodError: a time-seriesRegressioncarries no exposure history.- The rules of
exposure_dispersion, which raises anIsNothingErrorwhen the block carries no exposure history or no weight history of the kindweightingnames.
Returns
plt::Plots.Plot: A line plot with one series per factor.
Related
PortfolioOptimisers.plot_exposure_stability — Function
plot_exposure_stability(
S::FactorDiagnosticResult;
nf::Option{<:AbstractVector} = nothing,
title::AbstractString = "Exposure Stability",
kwargs...
) -> Plot
plot_exposure_stability(
csfm::CrossSectionalFactorModel;
nf::Option{<:AbstractVector} = nothing,
step::Integer = 21,
weighting = BenchmarkWeightMetric(),
kwargs...
) -> Plot
plot_exposure_stability(
pr::AbstractPriorResult;
nf::Option{<:AbstractVector} = nothing,
step::Integer = 21,
weighting = BenchmarkWeightMetric(),
kwargs...
) -> PlotPlot the stability of every factor exposure, one series per factor.
The figure draws what exposure_stability returns and computes nothing of its own. The stability is a weighted correlation of the exposures at two cross-sections step observations apart, so a dashed line marks 1, the value of two cross-sections that are an exact positive affine map of each other. An exposure that keeps the order of the assets and changes their spacing stays below the line. The series are labelled on the raw factor axis, as plot_exposure_correlation labels them. The package extension PortfolioOptimisersPlotsExt implements the methods, and it loads after using StatsPlots.
Arguments
S: The answer ofexposure_stability, or a view of it fromport_opt_view. The figure draws it and labels it with the names it carries.csfm: A cross-sectional factor model block.pr: A prior result whoserris such a block.nf: Factor names of the raw factor axis.nothingreads them off the answer, and falls back to the position of the factor.step: Number of observations between the two cross-sections.weighting: A member ofAbstractOrthogonalityMetric, ornothingfor equal weights. It names the weight history the block is read with.title: Title of the figure. Thecsfmandprmethods pass one that names the method or the step.kwargs...: Additional keyword arguments passed to the plotting backend.
Validation
pr.rris notnothing, elseassert_prior_regressionraises anIsNothingError.pr.rris aCrossSectionalFactorModel, else the verb raises aMethodError: a time-seriesRegressioncarries no exposure history.- The rules of
exposure_stability:step >= 1, else aDomainErroris raised, and fewer thanstepobservations raise aDimensionMismatch.
Returns
plt::Plots.Plot: A line plot with one series per factor, and the reference line.
Related
PortfolioOptimisers.plot_factor_model_summary — Function
plot_factor_model_summary(
fs::FactorSummaryResult;
nf::Option{<:AbstractVector} = nothing,
kwargs...
) -> Plot
plot_factor_model_summary(
csfm::CrossSectionalFactorModel;
nf::Option{<:AbstractVector} = nothing,
ppy::Number = 1,
threshold::Number = 2,
step::Integer = 21,
weighting = BenchmarkWeightMetric(),
coverage_weighting = RegressionWeightMetric(),
kwargs...
) -> Plot
plot_factor_model_summary(pr::AbstractPriorResult; kwargs...) -> PlotPlot the columns of a factor model summary as a grouped bar chart, one group per column and one bar per factor. The package extension PortfolioOptimisersPlotsExt implements the methods, and it loads after using StatsPlots.
The figure draws what factor_model_summary returns and computes nothing of its own. A column the summary carries as nothing is not drawn, and the title says so, so a block with no exposure history draws its four factor return columns alone.
The columns are not on one scale, and the figure rescales none of them. Read a column against its own factors and not against the column beside it.
Arguments
fs: A factor model summary.csfm: A cross-sectional factor model block, which the figure summarises first.pr: A prior result whoserris such a block.nf: Factor names of the raw factor axis.nothingreads them off the summary, which carries the names of the block, and numbers the factors when the summary names none. A view of the summary fromport_opt_viewdraws the factors it keeps. A list of the wrong length raises aDimensionMismatch.ppy: Periods per year the summary annualises with.threshold: Absolute t-statistic the exceedance rate counts against.step: Number of observations between the two cross-sections the stability reads.weighting: TheAbstractOrthogonalityMetricthe stability reads.coverage_weighting: TheAbstractOrthogonalityMetricwhose positive weights are the universe of the coverage.kwargs...: Additional keyword arguments passed to the plotting backend.
Validation
pr.rris notnothing, elseassert_prior_regressionraises anIsNothingError.pr.rris aCrossSectionalFactorModel, else the verb raises aMethodError: a time-seriesRegressioncarries no exposure history.- The rules of
factor_model_summary.
Returns
plt::Plots.Plot: A grouped bar chart, one group per drawn column and one bar per factor.
Related
PortfolioOptimisers.plot_factor_forecast_correlation — Function
plot_factor_forecast_correlation(
f_sigma::MatNum,
nf::AbstractVector = 1:size(f_sigma, 1);
kwargs...
) -> Plot
plot_factor_forecast_correlation(
pr::AbstractPriorResult,
nf::Option{<:AbstractVector} = nothing;
kwargs...
) -> PlotPlot the forecast correlation of the factor returns as a heatmap, with the colour limits (-1, 1).
The figure reads the factor covariance of the low order factor block that factor_plot_prior finds, and always rescales a copy of it to a correlation, by the formula of plot_correlation. It is the forecast that the prior carries, and not the realised correlation of the fitted factor return series, so it answers on the factor axis of the factor prior. plot_factor_sigma draws the same correlation, and its colour limits span the entries when the matrix is already a correlation. A factor of zero variance gives a NaN row and column, drawn blank. The package extension PortfolioOptimisersPlotsExt implements the methods, and it loads after using StatsPlots.
Arguments
f_sigma: Factor covariance matrixfactors × factors.pr: A prior result that carries a factor block.nf: Factor names.nothingfalls back to the position of the factor.kwargs...: Additional keyword arguments passed to the plotting backend.
Validation
pr.rris notnothing, elseassert_prior_regressionraises anIsNothingError.
Returns
plt::Plots.Plot: A heatmap of factors by factors.
Related
PortfolioOptimisers.plot_factor_forecast_volatilities — Function
plot_factor_forecast_volatilities(
f_sigma::MatNum,
nf::AbstractVector = 1:size(f_sigma, 1);
ppy::Number = 1,
kwargs...
) -> Plot
plot_factor_forecast_volatilities(
pr::AbstractPriorResult,
nf::Option{<:AbstractVector} = nothing;
ppy::Number = 1,
kwargs...
) -> PlotPlot the forecast volatility of every factor return as a horizontal bar chart, ordered from the smallest.
The figure reads the factor covariance of the low order factor block that factor_plot_prior finds. It is the forecast that the prior carries, and not the realised volatility that factor_model_summary reports. A NaN volatility sorts last, so its bar is the top one. The package extension PortfolioOptimisersPlotsExt implements the methods, and it loads after using StatsPlots.
Mathematical definition
\[\begin{align} \sigma_k = \sqrt{p\, \Sigma_{f,kk}}\,. \end{align}\]
Where:
- $\Sigma_{f,kk}$: Diagonal entry $k$ of the factor covariance, the variance of factor $k$.
- $p$: The periods per year,
ppy. - $\sigma_k$: Length of the bar of factor $k$.
Arguments
f_sigma: Factor covariance matrixfactors × factors.pr: A prior result that carries a factor block.nf: Factor names.nothingfalls back to the position of the factor.ppy: Periods per year the volatility is annualised with.kwargs...: Additional keyword arguments passed to the plotting backend.
Validation
pr.rris notnothing, elseassert_prior_regressionraises anIsNothingError.ppy >= 0, elsesqrtraises aDomainError.
Returns
plt::Plots.Plot: A horizontal bar chart.
Related
PortfolioOptimisers.plot_factor_cumulative_returns — Function
plot_factor_cumulative_returns(
csfm::CrossSectionalFactorModel;
nf::Option{<:AbstractVector} = nothing,
compound::Bool = false,
kwargs...
) -> Plot
plot_factor_cumulative_returns(
pr::AbstractPriorResult;
nf::Option{<:AbstractVector} = nothing,
compound::Bool = false,
kwargs...
) -> PlotPlot the cumulative return of every factor, one series per factor.
The figure draws cumulative_returns of each column of the factor return history that factor_summary_returns reads: fr on the raw factor axis, or the whole reduced axis for a block that carries no fr. It is the running sum of the returns, or their running product when compound is true. The figure sets a factor return that is not finite to zero first, so that observation holds the series flat and one absent cross-section breaks no series. plot_cumulative_exposure_ic follows the same convention. The package extension PortfolioOptimisersPlotsExt implements the methods, and it loads after using StatsPlots.
Arguments
csfm: A cross-sectional factor model block.pr: A prior result whoserris such a block.nf: Factor names of the axis of the history.nothingreads them off the block, and falls back to the position of the factor.compound: Whether the cumulative series compounds.kwargs...: Additional keyword arguments passed to the plotting backend.
Validation
pr.rris notnothing, elseassert_prior_regressionraises anIsNothingError.pr.rris aCrossSectionalFactorModel, else the verb raises aMethodError: a time-seriesRegressioncarries no exposure history.csfm.csris notnothing, else anIsNothingErroris raised.
Returns
plt::Plots.Plot: A line plot with one series per factor.
Related
PortfolioOptimisers.plot_idio_calibration — Function
plot_idio_calibration(csfm::CrossSectionalFactorModel; ahead::Bool = true, kwargs...)
-> Plot
plot_idio_calibration(pr::AbstractPriorResult; ahead::Bool = true, kwargs...) -> PlotPlot the cross-sectional standard deviation of the standardised idiosyncratic returns against the observation axis. The package extension PortfolioOptimisersPlotsExt implements the methods, and it loads after using StatsPlots.
The figure draws what idio_calibration returns and computes nothing of its own. A dashed line marks the Gaussian reference of 1. A series that sits above the line is a fit whose specific risk is too small, and one that sits below it is a fit whose specific risk is too large.
Arguments
csfm: A cross-sectional factor model block.pr: A prior result whoserris such a block.ahead: Whether each idiosyncratic return is divided by the volatility estimated before it.truedivides the return of observation $t$ by the volatility of observation $t - 1$, whose estimate has not read that return, so a variance forecast that is right gives standardised returns of unit variance, and the first observation has no standardised return.falsedivides the return by the volatility of its own observation, whose estimate has read it, which pulls every standardised return toward zero and caps its size.kwargs...: Additional keyword arguments passed to the plotting backend.
Validation
pr.rris notnothing, elseassert_prior_regressionraises anIsNothingError.pr.rris aCrossSectionalFactorModel, else the verb raises aMethodError: a time-seriesRegressioncarries no exposure history.- The rules of
idio_calibration, which raises anIsNothingErrorwhen the block carries no residuals or no predicted specific variances.
Returns
plt::Plots.Plot: A line plot with the reference line.
Related
PortfolioOptimisers.plot_idio_tail_rate — Function
plot_idio_tail_rate(
csfm::CrossSectionalFactorModel;
threshold::Real = 3,
ahead::Bool = true,
kwargs...
) -> Plot
plot_idio_tail_rate(
pr::AbstractPriorResult;
threshold::Real = 3,
ahead::Bool = true,
kwargs...
) -> PlotPlot the share of assets whose standardised idiosyncratic return exceeds a threshold, against the observation axis. The package extension PortfolioOptimisersPlotsExt implements the methods, and it loads after using StatsPlots.
The figure draws what idio_tail_rate returns and computes nothing of its own. A dashed line marks the Gaussian reference $2 \Phi(-c)$, where $c$ is threshold and $\Phi$ the distribution function of the standard normal law, as plot_cs_regression_t_stat_exceedance_rate defines it. It is about 0.0027 at the default threshold. A series above the line is a fit whose standardised returns carry heavier tails than the normal law implies, which is ordinary for an equity universe.
Arguments
csfm: A cross-sectional factor model block.pr: A prior result whoserris such a block.threshold: Absolute standardised return above which an asset enters the rate.ahead: Whether each idiosyncratic return is divided by the volatility estimated before it.truedivides the return of observation $t$ by the volatility of observation $t - 1$, whose estimate has not read that return, so a variance forecast that is right gives standardised returns of unit variance, and the first observation has no standardised return.falsedivides the return by the volatility of its own observation, whose estimate has read it, which pulls every standardised return toward zero and caps its size.kwargs...: Additional keyword arguments passed to the plotting backend.
Validation
pr.rris notnothing, elseassert_prior_regressionraises anIsNothingError.pr.rris aCrossSectionalFactorModel, else the verb raises aMethodError: a time-seriesRegressioncarries no exposure history.- The rules of
idio_tail_rate, which raises anIsNothingErrorwhen the block carries no residuals or no predicted specific variances.
Returns
plt::Plots.Plot: A line plot with the reference line.
Related
PortfolioOptimisers.plot_idio_kurtosis — Function
plot_idio_kurtosis(csfm::CrossSectionalFactorModel; ahead::Bool = true, kwargs...)
-> Plot
plot_idio_kurtosis(pr::AbstractPriorResult; ahead::Bool = true, kwargs...) -> PlotPlot the cross-sectional excess kurtosis of the standardised idiosyncratic returns against the observation axis. The package extension PortfolioOptimisersPlotsExt implements the methods, and it loads after using StatsPlots.
The figure draws what idio_kurtosis returns and computes nothing of its own. A dashed line marks the Gaussian reference of 0. A positive series is a cross-section whose tails are heavier than the normal law implies.
Arguments
csfm: A cross-sectional factor model block.pr: A prior result whoserris such a block.ahead: Whether each idiosyncratic return is divided by the volatility estimated before it.truedivides the return of observation $t$ by the volatility of observation $t - 1$, whose estimate has not read that return, so a variance forecast that is right gives standardised returns of unit variance, and the first observation has no standardised return.falsedivides the return by the volatility of its own observation, whose estimate has read it, which pulls every standardised return toward zero and caps its size.kwargs...: Additional keyword arguments passed to the plotting backend.
Validation
pr.rris notnothing, elseassert_prior_regressionraises anIsNothingError.pr.rris aCrossSectionalFactorModel, else the verb raises aMethodError: a time-seriesRegressioncarries no exposure history.- The rules of
idio_kurtosis, which raises anIsNothingErrorwhen the block carries no residuals or no predicted specific variances.
Returns
plt::Plots.Plot: A line plot with the reference line.
Related
PortfolioOptimisers.plot_idio_skewness — Function
plot_idio_skewness(csfm::CrossSectionalFactorModel; ahead::Bool = true, kwargs...)
-> Plot
plot_idio_skewness(pr::AbstractPriorResult; ahead::Bool = true, kwargs...) -> PlotPlot the cross-sectional skewness of the standardised idiosyncratic returns against the observation axis. The package extension PortfolioOptimisersPlotsExt implements the methods, and it loads after using StatsPlots.
The figure draws what idio_skewness returns and computes nothing of its own. A dashed line marks the Gaussian reference of 0. A series that stays on one side of the line is a residual that carries a direction the factors did not take.
Arguments
csfm: A cross-sectional factor model block.pr: A prior result whoserris such a block.ahead: Whether each idiosyncratic return is divided by the volatility estimated before it.truedivides the return of observation $t$ by the volatility of observation $t - 1$, whose estimate has not read that return, so a variance forecast that is right gives standardised returns of unit variance, and the first observation has no standardised return.falsedivides the return by the volatility of its own observation, whose estimate has read it, which pulls every standardised return toward zero and caps its size.kwargs...: Additional keyword arguments passed to the plotting backend.
Validation
pr.rris notnothing, elseassert_prior_regressionraises anIsNothingError.pr.rris aCrossSectionalFactorModel, else the verb raises aMethodError: a time-seriesRegressioncarries no exposure history.- The rules of
idio_skewness, which raises anIsNothingErrorwhen the block carries no residuals or no predicted specific variances.
Returns
plt::Plots.Plot: A line plot with the reference line.
Related
PortfolioOptimisers.plot_idio_vol_ic — Function
plot_idio_vol_ic(csfm::CrossSectionalFactorModel; kwargs...) -> Plot
plot_idio_vol_ic(pr::AbstractPriorResult; kwargs...) -> PlotPlot the information coefficient of the predicted idiosyncratic volatility against the observation axis. The package extension PortfolioOptimisersPlotsExt implements the methods, and it loads after using StatsPlots.
The figure draws what idio_vol_ic returns and computes nothing of its own. It carries no reference line, because the series has no Gaussian reference, and a caller reads its level and its sign. A series that stays high is a fit that ranks specific risk across the assets well. The volatility predicted at one observation is scored against the return of the next, so the horizontal axis starts at the second observation.
Arguments
csfm: A cross-sectional factor model block.pr: A prior result whoserris such a block.kwargs...: Additional keyword arguments passed to the plotting backend.
Validation
pr.rris notnothing, elseassert_prior_regressionraises anIsNothingError.pr.rris aCrossSectionalFactorModel, else the verb raises aMethodError: a time-seriesRegressioncarries no exposure history.- The rules of
idio_vol_ic, which needs at least two observations.
Returns
plt::Plots.Plot: A line plot with one point per observation from the second.
Related
PortfolioOptimisers.plot_idio_vol_residual_dependence — Function
plot_idio_vol_residual_dependence(csfm::CrossSectionalFactorModel; kwargs...) -> Plot
plot_idio_vol_residual_dependence(pr::AbstractPriorResult; kwargs...) -> PlotPlot the residual dependence of the standardised idiosyncratic returns on the predicted volatility, against the observation axis. The package extension PortfolioOptimisersPlotsExt implements the methods, and it loads after using StatsPlots.
The figure draws what idio_vol_residual_dependence returns and computes nothing of its own. A dashed line marks the reference of 0, which a well calibrated fit sits on. The volatility predicted at one observation is read against the return of the next, so the horizontal axis starts at the second observation. Read it beside plot_idio_vol_ic. A fit that ranks well and leaves no residual dependence carries a high information coefficient and a dependence near 0.
Arguments
csfm: A cross-sectional factor model block.pr: A prior result whoserris such a block.kwargs...: Additional keyword arguments passed to the plotting backend.
Validation
pr.rris notnothing, elseassert_prior_regressionraises anIsNothingError.pr.rris aCrossSectionalFactorModel, else the verb raises aMethodError: a time-seriesRegressioncarries no exposure history.- The rules of
idio_vol_residual_dependence, which needs at least two observations.
Returns
plt::Plots.Plot: A line plot with one point per observation from the second, and the reference line.
Related
PortfolioOptimisers.plot_forecast_cumulative_ic — Function
plot_forecast_cumulative_ic(
fe::ForecastEvaluationResult,
w::Option{<:MatNum} = nothing;
min_count::Integer = fe.min_count,
kwargs...
) -> Plot
plot_forecast_cumulative_ic(
fe::ForecastEvaluationResult,
csfm::CrossSectionalFactorModel;
weighting = nothing,
min_count::Integer = fe.min_count,
kwargs...
) -> Plot
plot_forecast_cumulative_ic(
fes::AbstractVector{<:ForecastEvaluationResult},
w::Option{<:MatNum} = nothing;
names = nothing,
rank::Bool = true,
kwargs...
) -> Plot
plot_forecast_cumulative_ic(
fes::AbstractVector{<:ForecastEvaluationResult},
csfm::CrossSectionalFactorModel;
weighting = nothing,
names = nothing,
rank::Bool = true,
kwargs...
) -> PlotPlot the running sum of the information coefficient of a Return Forecast: both coefficients of one forecast, or one coefficient of several forecasts overlaid.
The figure draws the running sum of what forecast_ic returns. An evaluation date that carries no coefficient adds nothing to the sum, so one thin cross-section breaks no series. A series that rises through the sample is a forecast that ordered the cross-section, a flat series is one that carried no ordering, and a falling series is one whose ordering had the opposite sign. The Spearman coefficient reads no weights, so w, csfm and weighting move the Pearson series alone. The package extension PortfolioOptimisersPlotsExt implements the methods, and it loads after using StatsPlots.
The vector method is the comparison. A mean hides whether an edge was continuous or came from three dates, and a comparison of two means hides it twice. So the vector method draws one series per evaluation on the dates that the evaluations share, with a zero reference line, and the reader sees where in the sample each forecast earned its coefficient. It is the figure of which the length-2 ForecastSummaryResult is the table. It refuses evaluations that are not comparable with forecast_summary_assert_comparable, as forecast_evaluation_summary does, because two forecasts on different dates overlay nothing. It draws one coefficient, which rank names, so that a figure of four forecasts carries four series and not eight. Each evaluation reads its coefficient at its own min_count, for the reason forecast_summary_row states, and the comparability check makes it one number.
The figures of this group take the ForecastEvaluationResult, where the cross-sectional diagnostics take the block. Those verbs read a block that is already fitted, so a figure that calls one costs nothing. Here the Return Forecast history can cost a rolling refit through forecast_history, so a caller pairs once with forecast_evaluation, and every figure reads that pairing. A weighting still reaches the figure as it reaches the level-2 verbs: as a bare weight history in the second position, or as the block whose AbstractOrthogonalityMetric resolves one.
Mathematical definition
\[\begin{align} C_j = \sum_{i=1}^{j} \mathbb{1}\left[\mathrm{IC}_i \text{ is finite}\right] \mathrm{IC}_i\,. \end{align}\]
Where:
- $\mathrm{IC}_i$: Information coefficient of the forecast at evaluation date $i$, as
forecast_icreturns it. - $C_j$: Point $j$ of the series.
Arguments
fe: The evaluation to draw, fromforecast_evaluation.fes: The evaluations to overlay, at least one, fromforecast_evaluation.w: Cross-sectional weight historyobservations × assets, on the axis of the forecast, ornothingfor equal weights.csfm: A cross-sectional factor model block, whose weight historyweightingnames.weighting: A member ofAbstractOrthogonalityMetric, ornothingfor equal weights. It names the weight history the block is read with.min_count: Least number of assets a cross-section needs before a coefficient of it is reported.names: One name per evaluation, ornothingto number them.rank: Overlay the Spearman coefficient whentrue, and the Pearson coefficient otherwise.kwargs...: Additional keyword arguments passed to the plotting backend.
Validation
- The rules of
forecast_ic. - The vector method: the rules of
forecast_summary_assert_comparableandforecast_summary_names.
Returns
plt::Plots.Plot: A line plot with one series per coefficient, or one series per evaluation and a zero reference line.
Related
PortfolioOptimisers.plot_forecast_rolling_ic — Function
plot_forecast_rolling_ic(
fe::ForecastEvaluationResult,
w::Option{<:MatNum} = nothing;
rolling::Integer = 0,
min_count::Integer = fe.min_count,
kwargs...
) -> Plot
plot_forecast_rolling_ic(
fe::ForecastEvaluationResult,
csfm::CrossSectionalFactorModel;
weighting = nothing,
rolling::Integer = 0,
min_count::Integer = fe.min_count,
kwargs...
) -> PlotPlot the running mean of both information coefficients of a Return Forecast over a window.
The figure draws the mean of the last $W$ evaluation dates of what forecast_ic returns, one series per coefficient. Where plot_forecast_cumulative_ic shows what the forecast earned over the whole sample, this shows where in the sample it earned it. An evaluation date that carries no coefficient is left out of the mean of every window it falls in, so the series is the mean of the dates that scored. The first $W - 1$ points, and a window with no finite coefficient, are NaN and drawn blank. The package extension PortfolioOptimisersPlotsExt implements the methods, and it loads after using StatsPlots.
The figure takes the evaluation and not the block, for the reason plot_forecast_cumulative_ic states.
Mathematical definition
\[\begin{align} W &= \begin{cases} \lceil \sqrt{T} \rceil & \text{rolling} = 0\,, \\ \text{rolling} & \text{otherwise}\,, \end{cases} \\ m_t &= \frac{1}{\lvert F_t \rvert} \sum_{i \in F_t} \mathrm{IC}_i\,, \quad t = W, \ldots, T\,. \end{align}\]
Where:
- $T$: Number of evaluation dates,
length(fe.dates). - $W$: Rolling window size, in observations.
- $F_t$: The dates of $t - W + 1, \ldots, t$ whose coefficient is finite.
- $\mathrm{IC}_i$: Information coefficient at evaluation date $i$, as
forecast_icreturns it. - $m_t$: Point $t$ of a series.
Arguments
fe: The evaluation to draw, fromforecast_evaluation.w: Cross-sectional weight historyobservations × assets, on the axis of the forecast, ornothingfor equal weights.csfm: A cross-sectional factor model block, whose weight historyweightingnames.weighting: A member ofAbstractOrthogonalityMetric, ornothingfor equal weights. It names the weight history the block is read with.rolling: Number of evaluation dates in the window, or0for the square root of their number.min_count: Least number of assets a cross-section needs before a coefficient of it is reported.kwargs...: Additional keyword arguments passed to the plotting backend.
Validation
- $W$ lies in
1:length(fe.dates), else aDomainErroris raised. - The rules of
forecast_ic.
Returns
plt::Plots.Plot: A line plot with one series per coefficient.
Related
PortfolioOptimisers.plot_forecast_cumulative_returns — Function
plot_forecast_cumulative_returns(
fe::ForecastEvaluationResult;
kinds = (:rank, :zscore),
compound::Bool = false,
kwargs...
) -> Plot
plot_forecast_cumulative_returns(
fes::AbstractVector{<:ForecastEvaluationResult};
names = nothing,
kind::Symbol = :rank,
compound::Bool = false,
kwargs...
) -> PlotPlot the cumulative return of the books a Return Forecast states on its own: both books of one forecast, or one book of several forecasts overlaid.
The figure draws cumulative_returns of the return series of forecast_portfolio: their running sum, or their running product when compound is true. It computes nothing else of its own. The reference line of the vector method is the break-even level: zero for a running sum, and one under compound. The package extension PortfolioOptimisersPlotsExt implements the methods, and it loads after using StatsPlots.
Both books are centred and rescaled to the same gross exposure, so the two series are read against each other and against the same series of another forecast. An evaluation date whose cross-section carried no book is held flat, which is what plot_factor_cumulative_returns does to an absent factor return.
The vector method is the comparison, for the reason plot_forecast_cumulative_ic states: one series per evaluation on the dates the evaluations share, a zero reference line, and a refusal of evaluations that are not comparable with forecast_summary_assert_comparable. One book is drawn, named by kind, so that a figure of four forecasts carries four series and not eight.
The figure takes the evaluation and not the block, for the reason plot_forecast_cumulative_ic states.
Arguments
fe: The evaluation to draw, fromforecast_evaluation.fes: The evaluations to overlay, at least one, fromforecast_evaluation.kinds: The books to draw, each:rankor:zscore, asforecast_portfolio_weightsnames them.kind: The one book to overlay,:rankor:zscore.names: One name per evaluation, ornothingto number them.compound: Whether the cumulative series compounds.kwargs...: Additional keyword arguments passed to the plotting backend.
Validation
kindsis not empty, else aBoundsErroris raised.- The rules of
forecast_portfolio. - The vector method: the rules of
forecast_summary_assert_comparableandforecast_summary_names.
Returns
plt::Plots.Plot: A line plot with one series per book, or one series per evaluation and a zero reference line.
Related
PortfolioOptimisers.plot_forecast_quantile_returns — Function
plot_forecast_quantile_returns(
fe::ForecastEvaluationResult;
quantiles = (0.1,),
compound::Bool = false,
kwargs...
) -> PlotPlot the cumulative top-minus-bottom spread of a Return Forecast, one series per quantile.
The figure draws cumulative_returns of the spread series of forecast_quantile_spread: their running sum, or their running product when compound is true. It computes nothing else of its own. The package extension PortfolioOptimisersPlotsExt implements the methods, and it loads after using StatsPlots.
A spread that keeps rising as the tail narrows is a forecast whose ordering is sharpest at its ends, and one that flattens is a forecast whose ordering is spread across the whole cross-section. An evaluation date whose cross-section carried no spread is held flat.
The figure takes the evaluation and not the block, for the reason plot_forecast_cumulative_ic states.
Arguments
fe: The evaluation to draw, fromforecast_evaluation.quantiles: Tail fractions the spreads are cut at, each in(0, 0.5].compound: Whether the cumulative series compounds.kwargs...: Additional keyword arguments passed to the plotting backend.
Validation
- The rules of
forecast_quantile_spread.
Returns
plt::Plots.Plot: A line plot with one series per quantile.
Related
PortfolioOptimisers.plot_forecast_calibration — Function
plot_forecast_calibration(
fe::ForecastEvaluationResult,
w::Option{<:MatNum} = nothing;
bins::Integer = 10,
kwargs...
) -> Plot
plot_forecast_calibration(
fe::ForecastEvaluationResult,
csfm::CrossSectionalFactorModel;
weighting = nothing,
bins::Integer = 10,
kwargs...
) -> PlotPlot the calibration curve of a Return Forecast against the slope fitted through it. The package extension PortfolioOptimisersPlotsExt implements the methods, and it loads after using StatsPlots.
The figure draws the curve of forecast_calibration as a scatter of the mean realised target of each bin against the mean forecast of that bin, and lays the zero-intercept slope of the same call over it. The two answer different questions. The curve says whether the relation is a straight line, and the slope says what multiplier maps the forecast onto realised units. A curve that sits below the slope at its right end is a forecast whose largest values are the least believable.
This is the one reading of a forecast that a rescaling moves. The coefficients correlate and the books are rescaled to a fixed gross exposure, so both are invariant to a positive rescaling of the units of the forecast. The slope is not, and that is what it is for.
The figure takes the evaluation and not the block, for the reason plot_forecast_cumulative_ic states.
Arguments
fe: The evaluation to draw, fromforecast_evaluation.w: Cross-sectional weight historyobservations × assets, on the axis of the forecast, ornothingfor equal weights.csfm: A cross-sectional factor model block, whose weight historyweightingnames.weighting: A member ofAbstractOrthogonalityMetric, ornothingfor equal weights. It names the weight history the block is read with.bins: Number of quantile bins the curve is cut into.kwargs...: Additional keyword arguments passed to the plotting backend.
The weights reach the slope alone, because the curve is the unweighted mean of each bin.
Validation
- The rules of
forecast_calibration.
Returns
plt::Plots.Plot: A scatter of the curve, with the fitted slope as a dashed line.
Related
PortfolioOptimisers.plot_forecast_ic_by_holding_period — Function
plot_forecast_ic_by_holding_period(
fe::ForecastEvaluationResult,
X::MatNum,
w::Option{<:MatNum} = nothing;
n::Integer = 10,
min_count::Integer = fe.min_count,
kwargs...
) -> Plot
plot_forecast_ic_by_holding_period(
fe::ForecastEvaluationResult,
rd::ReturnsResult,
csfm::CrossSectionalFactorModel;
weighting = nothing,
n::Integer = 10,
min_count::Integer = fe.min_count,
kwargs...
) -> PlotPlot both mean information coefficients of a Return Forecast against the holding period. The package extension PortfolioOptimisersPlotsExt implements the methods, and it loads after using StatsPlots.
The figure draws two columns of the table of forecast_holding_period against its period and computes nothing of its own. A column that holds as the window lengthens is a forecast about a slow quantity, and one that falls away is a forecast whose book must be turned over to capture it.
Every row of the table is read on one date set, so the figure is internally comparable and is not comparable to the same figure at another n. A caller who compares two depths draws the deeper one.
The figure takes the evaluation and not the block, for the reason plot_forecast_cumulative_ic states. The target history is the second argument for the same reason the verb takes it, because a re-windowing needs the history the target was built from, and the evaluation carries only the matured target.
Arguments
fe: The evaluation to draw, fromforecast_evaluation.X: Target historyobservations × assets, on the axis of the forecast, fromforecast_target_history.rd: The returns data the target history is built from. It carries an Asset Panel inrd.pnl.w: Cross-sectional weight historyobservations × assets, on the axis of the forecast, ornothingfor equal weights.csfm: A cross-sectional factor model block, whose weight historyweightingnames.weighting: A member ofAbstractOrthogonalityMetric, ornothingfor equal weights. It names the weight history the block is read with.n: Number of holding periods the table reaches.min_count: Least number of assets a cross-section needs before a statistic of it is reported. It also chooses the dates that every row of the table is read on.kwargs...: Additional keyword arguments passed to the plotting backend.
Validation
- The rules of
forecast_holding_period.
Returns
plt::Plots.Plot: A line plot with one series per column, against the holding period.
Related
PortfolioOptimisers.plot_forecast_portfolio_by_holding_period — Function
plot_forecast_portfolio_by_holding_period(
fe::ForecastEvaluationResult,
X::MatNum,
w::Option{<:MatNum} = nothing;
n::Integer = 10,
min_count::Integer = fe.min_count,
ppy::Number = fe.ppy,
kwargs...
) -> Plot
plot_forecast_portfolio_by_holding_period(
fe::ForecastEvaluationResult,
rd::ReturnsResult,
csfm::CrossSectionalFactorModel;
weighting = nothing,
n::Integer = 10,
min_count::Integer = fe.min_count,
ppy::Number = fe.ppy,
kwargs...
) -> PlotPlot the annualised return and the Sharpe ratio of both books against the holding period. The package extension PortfolioOptimisersPlotsExt implements the methods, and it loads after using StatsPlots.
The figure draws four columns of the table of forecast_holding_period against its period and computes nothing of its own. It is the book-level reading of what plot_forecast_ic_by_holding_period shows at the coefficient level, and the two are read together. A coefficient that survives a longer window is only worth holding if the book built on it does too.
The four columns carry two units, so the axis is labelled Value and read column by column, which is what plot_factor_model_summary does with the same mix.
Every row of the table is read on one date set, so the figure is internally comparable and is not comparable to the same figure at another n.
The figure takes the evaluation and not the block, for the reason plot_forecast_cumulative_ic states.
Arguments
fe: The evaluation to draw, fromforecast_evaluation.X: Target historyobservations × assets, on the axis of the forecast, fromforecast_target_history.rd: The returns data the target history is built from. It carries an Asset Panel inrd.pnl.w: Cross-sectional weight historyobservations × assets, on the axis of the forecast, ornothingfor equal weights.csfm: A cross-sectional factor model block, whose weight historyweightingnames.weighting: A member ofAbstractOrthogonalityMetric, ornothingfor equal weights. It names the weight history the block is read with.n: Number of holding periods the table reaches.min_count: Least number of assets a cross-section needs before a statistic of it is reported. It also chooses the dates that every row of the table is read on.ppy: Periods per year of the annualised columns of the table. It defaults to theppyof the evaluation, so the table and the summary of one evaluation share their units.1gives the statistics per period.kwargs...: Additional keyword arguments passed to the plotting backend.
Validation
- The rules of
forecast_holding_period.
Returns
plt::Plots.Plot: A line plot with one series per column, against the holding period.
Related
PortfolioOptimisers.plot_forecast_ic_decay — Function
plot_forecast_ic_decay(
fe::ForecastEvaluationResult,
X::MatNum,
w::Option{<:MatNum} = nothing;
n::Integer = 10,
min_count::Integer = fe.min_count,
kwargs...
) -> Plot
plot_forecast_ic_decay(
fe::ForecastEvaluationResult,
rd::ReturnsResult,
csfm::CrossSectionalFactorModel;
weighting = nothing,
n::Integer = 10,
min_count::Integer = fe.min_count,
kwargs...
) -> PlotPlot both mean information coefficients of a Return Forecast against the forward window. The package extension PortfolioOptimisersPlotsExt implements the methods, and it loads after using StatsPlots.
The figure draws two columns of the table of forecast_decay against its period and computes nothing of its own. The windows are disjoint rather than cumulative, so the figure answers how long the forecast keeps forecasting. The first period is the horizon it was paired at, and a later period is the same forecast scored against a window it never saw.
Every row of the table is read on one date set, so the figure is internally comparable and is not comparable to the same figure at another n.
The figure takes the evaluation and not the block, for the reason plot_forecast_cumulative_ic states.
Arguments
fe: The evaluation to draw, fromforecast_evaluation.X: Target historyobservations × assets, on the axis of the forecast, fromforecast_target_history.rd: The returns data the target history is built from. It carries an Asset Panel inrd.pnl.w: Cross-sectional weight historyobservations × assets, on the axis of the forecast, ornothingfor equal weights.csfm: A cross-sectional factor model block, whose weight historyweightingnames.weighting: A member ofAbstractOrthogonalityMetric, ornothingfor equal weights. It names the weight history the block is read with.n: Number of forward windows the table reaches.min_count: Least number of assets a cross-section needs before a statistic of it is reported. It also chooses the dates that every row of the table is read on.kwargs...: Additional keyword arguments passed to the plotting backend.
Validation
- The rules of
forecast_decay.
Returns
plt::Plots.Plot: A line plot with one series per column, against the forward window.
Related
PortfolioOptimisers.plot_forecast_portfolio_decay — Function
plot_forecast_portfolio_decay(
fe::ForecastEvaluationResult,
X::MatNum,
w::Option{<:MatNum} = nothing;
n::Integer = 10,
min_count::Integer = fe.min_count,
ppy::Number = fe.ppy,
kwargs...
) -> Plot
plot_forecast_portfolio_decay(
fe::ForecastEvaluationResult,
rd::ReturnsResult,
csfm::CrossSectionalFactorModel;
weighting = nothing,
n::Integer = 10,
min_count::Integer = fe.min_count,
ppy::Number = fe.ppy,
kwargs...
) -> PlotPlot the annualised return and the Sharpe ratio of both books against the forward window. The package extension PortfolioOptimisersPlotsExt implements the methods, and it loads after using StatsPlots.
The figure draws four columns of the table of forecast_decay against its period and computes nothing of its own. It is the book-level reading of what plot_forecast_ic_decay shows at the coefficient level.
The four columns carry two units, so the axis is labelled Value and read column by column.
Every row of the table is read on one date set, so the figure is internally comparable and is not comparable to the same figure at another n.
The figure takes the evaluation and not the block, for the reason plot_forecast_cumulative_ic states.
Arguments
fe: The evaluation to draw, fromforecast_evaluation.X: Target historyobservations × assets, on the axis of the forecast, fromforecast_target_history.rd: The returns data the target history is built from. It carries an Asset Panel inrd.pnl.w: Cross-sectional weight historyobservations × assets, on the axis of the forecast, ornothingfor equal weights.csfm: A cross-sectional factor model block, whose weight historyweightingnames.weighting: A member ofAbstractOrthogonalityMetric, ornothingfor equal weights. It names the weight history the block is read with.n: Number of forward windows the table reaches.min_count: Least number of assets a cross-section needs before a statistic of it is reported. It also chooses the dates that every row of the table is read on.ppy: Periods per year of the annualised columns of the table. It defaults to theppyof the evaluation, so the table and the summary of one evaluation share their units.1gives the statistics per period.kwargs...: Additional keyword arguments passed to the plotting backend.
Validation
- The rules of
forecast_decay.
Returns
plt::Plots.Plot: A line plot with one series per column, against the forward window.
Related
PortfolioOptimisers.plot_forecast_factor_correlation — Function
plot_forecast_factor_correlation(
fe::ForecastEvaluationResult,
B::Arr3Num,
w::Option{<:MatNum} = nothing;
nf::Option{<:AbstractVector} = nothing,
dates::AbstractVector{<:Integer} = axes(fe.alpha, 1),
rank::Bool = false,
min_count::Integer = fe.min_count,
kwargs...
) -> Plot
plot_forecast_factor_correlation(
fe::ForecastEvaluationResult,
csfm::CrossSectionalFactorModel;
nf::Option{<:AbstractVector} = nothing,
weighting = nothing,
kwargs...
) -> Plot
plot_forecast_factor_correlation(
c::FactorDiagnosticResult;
nf::Option{<:AbstractVector} = nothing,
dates::AbstractVector{<:Integer} = axes(c.X, 1),
kwargs...
) -> PlotPlot the contemporaneous correlation of a Return Forecast with every factor exposure. The package extension PortfolioOptimisersPlotsExt implements the methods, and it loads after using StatsPlots.
The figure draws what forecast_factor_correlation returns and computes nothing of its own, one series per factor, on the rows dates names. Nothing here is forward looking, because the correlation is taken on the date the forecast is stated, so the figure says what the forecast is, not what it earned, and it is drawn on every observation by default rather than on the evaluation grid; dates = fe.dates draws the grid. A series that sits near one is a forecast that restates an exposure the risk model already holds, and the return it earns is that factor's return under another name.
A neutralised forecast does not read zero here. The cross-sectional fit that neutralises it carries no intercept, so its residual is orthogonal to its target in the uncentred sense and keeps a correlation with it.
The figure takes the evaluation and not the block, for the reason plot_forecast_cumulative_ic states.
Arguments
fe: The evaluation to draw, fromforecast_evaluation.B: Exposure historyassets × factors × observations, on the axis of the forecast.w: Cross-sectional weight historyobservations × assets, on the axis of the forecast, ornothingfor equal weights.csfm: A cross-sectional factor model block, whose exposure history and weight history are read.c: The answer of the block method offorecast_factor_correlation, or a view of it fromport_opt_view. The figure draws it and labels it with the names it carries.nf: Factor names of the axis of the answer.nothingreads them off the block for thecsfmmethod and off the answer for thecmethod, and numbers the factors for theBmethod.dates: Row indices offe.alphathe correlation is read and drawn on. The default is every observation;fe.datesreads the evaluation grid. On thecmethod,dateslabels the rows ofc.X, and its default numbers them.rank: Take the rank correlation whentrue, and the weighted correlation otherwise.weighting: A member ofAbstractOrthogonalityMetric, ornothingfor equal weights. It names the weight history the block is read with.min_count: Least number of assets a cross-section needs before a correlation of it is reported.kwargs...: Additional keyword arguments passed to the plotting backend. Thecsfmmethod passesdates,rankandmin_countthrough them to theBmethod.
Validation
- The rules of
forecast_factor_correlation.
Returns
plt::Plots.Plot: A line plot with one series per factor.
Related
PortfolioOptimisers.plot_forecast_evaluation_summary — Function
plot_forecast_evaluation_summary(fs::ForecastSummaryResult; kwargs...) -> Plot
plot_forecast_evaluation_summary(
fes::AbstractVector{<:ForecastEvaluationResult},
w::Option{<:MatNum} = nothing;
names = nothing,
bins::Integer = 10,
quantiles = nothing,
kwargs...
) -> Plot
plot_forecast_evaluation_summary(
fes::AbstractVector{<:ForecastEvaluationResult},
csfm::CrossSectionalFactorModel;
weighting = nothing,
names = nothing,
bins::Integer = 10,
quantiles = nothing,
kwargs...
) -> Plot
plot_forecast_evaluation_summary(
fe::ForecastEvaluationResult,
w::Option{<:MatNum} = nothing;
kwargs...
) -> Plot
plot_forecast_evaluation_summary(
fe::ForecastEvaluationResult,
csfm::CrossSectionalFactorModel;
kwargs...
) -> PlotPlot a ForecastSummaryResult as a grouped bar chart, one series per forecast. The package extension PortfolioOptimisersPlotsExt implements the methods, and it loads after using StatsPlots.
The figure draws the ten headline columns of the summary, with the statistic on the axis and the forecast as the series, which is the shape plot_factor_model_summary takes. The ten are both mean information coefficients and their information ratios, the annualised return and the Sharpe ratio of each book, the calibration slope and the mean coverage. A single evaluation is the length-1 case and a set of them is the comparison, as the Result is.
The quantile spread block is drawn when the summary carries one, as one bar group per quantile, and each group is the Sharpe ratio of that spread; the other columns of the block are not drawn. A summary built with no quantile carries the block as nothing, and then the block is not drawn and the title says so.
The methods that summarise do not align the evaluations, so a set of evaluations on different dates raises. Align them first with forecast_evaluation_align, or summarise them with forecast_evaluation_summary under align = true and draw the summary.
The columns carry several units, so the axis is labelled Value and read group by group. The columns the summary carries that this figure does not draw are read off the Result, which prints all of them.
Arguments
fs: The summary to draw, fromforecast_evaluation_summary.fes: The evaluations to summarise and draw, at least one.fe: One evaluation. It is drawn as the length-1 case.w: Cross-sectional weight historyobservations × assets, on the axis of the forecasts, ornothingfor equal weights.csfm: A cross-sectional factor model block, whose weight historyweightingnames.weighting: A member ofAbstractOrthogonalityMetric, ornothingfor equal weights. It names the weight history the block is read with.names: One name per evaluation, ornothingto number them.bins: Number of quantile bins the calibration curve cuts.quantiles: Tail fractions the quantile spreads are cut at, each in(0, 0.5], ornothingfor none.kwargs...: Additional keyword arguments passed to the plotting backend.
Validation
- The rules of
forecast_evaluation_summary.
Returns
plt::Plots.Plot: A grouped bar chart, one group per statistic and one bar per forecast.
Related
PortfolioOptimisers.plot_covariance_calibration — Function
plot_covariance_calibration(
cfer::CovarianceForecastEvaluationResult;
window::Integer = 50,
diagnostics = (:mahalanobis, :diagonal, :bias),
step_weighting::AbstractStepWeighting = DofStepWeighting(),
scored_steps::Bool = false,
whole_windows::Bool = false,
kwargs...
) -> Plot
plot_covariance_calibration(
cfers::AbstractVector{<:CovarianceForecastEvaluationResult};
names = nothing,
window::Integer = 50,
diagnostics = (:mahalanobis, :diagonal, :bias),
step_weighting::AbstractStepWeighting = DofStepWeighting(),
scored_steps::Bool = false,
whole_windows::Bool = false,
kwargs...
) -> PlotPlot the rolling calibration of a covariance forecast: the Mahalanobis ratio, the diagonal ratio and the bias statistic over a window of steps, with a reference line at one.
Each series is the statistic of covariance_forecast_summary, taken over the last $W$ steps of the walk-forward in place of all of them. The two ratios are means with the weights of step_weighting, as in the summary, and the bias statistic is the sample standard deviation of the standardised returns. So a window as wide as the run ends at the value of the summary under the same step_weighting. A step with no active asset adds nothing to a window. Under the defaults, the first $W - 1$ points and a window with no scored step are NaN, and the figure leaves them blank. The bias statistic needs two scored steps in its window. The package extension PortfolioOptimisersPlotsExt implements the methods, and it loads after using StatsPlots.
The default window spans a fixed number of steps, which is a fixed stretch of the walk-forward, so the figure reads two evaluations on one walk-forward over the same steps at each point. scored_steps = true makes the window hold the last $W$ scored steps instead, so it stretches over a step with no active asset, and that step draws no point. whole_windows = true starts each series at its first whole window in place of the first step. Each window rule gives a moving average, and the figure prefers neither. With step_weighting = EqualStepWeighting() and both keywords true, each series is the plain rolling mean of the scored steps, drawn from its first whole window.
An evaluation with one test portfolio draws the bias statistic of that portfolio. An evaluation with several draws the median over the portfolios, with a band from the fifth to the ninety-fifth percentile, which are the percentiles the summary gives.
The vector method is the comparison. It draws each diagnostic of each evaluation on the dates of that evaluation. The label of a series is the name of its evaluation when the figure draws one diagnostic, and the name and the diagnostic otherwise.
Mathematical definition
\[\begin{align} \bar{m}^{W}_t &= \frac{\sum_{s \in S_t} \omega_s\, m_s}{\sum_{s \in S_t} \omega_s}\,, \quad \bar{d}^{W}_t = \frac{\sum_{s \in S_t} \omega'_s\, \bar{d}_s}{\sum_{s \in S_t} \omega'_s}\,, \\ B^{W}_t &= \sqrt{\frac{1}{\lvert S_t \rvert - 1} \sum_{s \in S_t} \left(b_s - \bar{b}_t\right)^2}\,, \quad \bar{b}_t = \frac{1}{\lvert S_t \rvert} \sum_{s \in S_t} b_s\,. \end{align}\]
Where:
- $W$: Rolling window size, in observations.
- $S_t$: The scored steps of the window of point $t$: the steps of $t - W + 1, \ldots, t$ with at least one active asset, or under
scored_steps = truethe last $W$ such steps up to $t$. - $m_s$: Mahalanobis ratio of step $s$.
- $\omega_s$: Weight of step $s$ in the Mahalanobis mean, from
covariance_step_weightson the degrees of freedom oftarget_dof. - $\bar{d}_s$: Mean of the diagonal ratio over the active assets of step $s$, from
covariance_diagonal_mean. - $\omega'_s$: Weight of step $s$ in the diagonal mean, from
covariance_step_weightson the degrees of freedom oftarget_step_dof. - $b_s$: Standardised return of a test portfolio at step $s$.
- $\bar{m}^{W}_t$, $\bar{d}^{W}_t$, $B^{W}_t$: Point $t$ of the Mahalanobis, the diagonal and the bias series.
Arguments
cfer: The evaluation to draw, fromcovariance_forecast_evaluation.cfers: The evaluations to overlay, at least one, fromcovariance_forecast_evaluation.names: One name per evaluation, ornothingfor the names thatcovariance_forecast_namesgives.window: Number of steps in the window.diagnostics: The series to draw, at least one of:mahalanobis,:diagonaland:bias.step_weighting:AbstractStepWeightingthat weights each scored step in the mean of a calibration ratio and in its Gaussian band.DofStepWeighting, the default, weights a step by the degrees of freedom of its ratio, andEqualStepWeightinggives every step the same weight.scored_steps: Iffalse, the window of a point is the lastwindowsteps of the walk-forward, and a step with no active asset adds nothing to it. Iftrue, the window is the lastwindowscored steps, so it stretches over a step with no active asset, and a point sits only at a scored step.whole_windows: Iffalse, the series covers every step of the evaluation, and a point with no whole window isNaNand drawn blank. Iftrue, the series starts at its first whole window.kwargs...: Additional keyword arguments passed to the plotting backend.
Validation
- $W$ lies in
1:length(cfer.dates)for every evaluation drawn, or underscored_steps = truein1:count(>(0), cfer.n_valid). ADomainErroris thrown otherwise. - Every evaluation drawn scored at least one step, as
covariance_forecast_summaryneeds. AnIsEmptyErroris thrown otherwise, under both settings ofscored_steps. diagnosticsis not empty, and each entry is:mahalanobis,:diagonalor:bias. ADomainErroris thrown otherwise.- The vector method:
cfersis not empty, else anIsEmptyErroris thrown, and the rules ofcovariance_forecast_names.
Returns
plt::Plots.Plot: A line plot with one series per diagnostic and evaluation, and the reference line.
Related
PortfolioOptimisers.plot_covariance_qlike — Function
plot_covariance_qlike(
cfer::CovarianceForecastEvaluationResult;
window::Integer = 50,
scored_steps::Bool = false,
whole_windows::Bool = false,
kwargs...
) -> Plot
plot_covariance_qlike(
cfers::AbstractVector{<:CovarianceForecastEvaluationResult};
names = nothing,
window::Integer = 50,
scored_steps::Bool = false,
whole_windows::Bool = false,
kwargs...
) -> PlotPlot the rolling mean of the QLIKE loss of the variance of the test portfolios of a covariance forecast.
Each series is the mean portfolio QLIKE of covariance_forecast_summary, taken over the last $W$ steps of the walk-forward in place of all of them. So a window as wide as the run ends at the value of the summary. A step with no active asset adds nothing to a window. Under the defaults, the first $W - 1$ points and a window with no scored step are NaN, and the figure leaves them blank. scored_steps and whole_windows set the window and the first point, as in plot_covariance_calibration. Lower is better. The level of one loss has no fixed reference value. Only the difference between the losses of two forecasts shows which is better, so the figure draws no reference line. The package extension PortfolioOptimisersPlotsExt implements the methods, and it loads after using StatsPlots.
An evaluation with one test portfolio draws the loss of that portfolio. An evaluation with several draws the median over the portfolios, with a band from the fifth to the ninety-fifth percentile.
The vector method is the comparison. It draws one series per evaluation, on the dates of that evaluation, labelled by its name.
Mathematical definition
\[\begin{align} \bar{L}^{W}_t &= \frac{1}{\lvert S_t \rvert} \sum_{s \in S_t} L^{\mathrm{P}}_s\,. \end{align}\]
Where:
- $W$: Rolling window size, in observations.
- $S_t$: The scored steps of the window of point $t$, as
plot_covariance_calibrationstates. - $L^{\mathrm{P}}_s$: QLIKE loss of the variance of a test portfolio at step $s$, from
covariance_forecast_step. - $\bar{L}^{W}_t$: Point $t$ of the series.
Arguments
cfer: The evaluation to draw, fromcovariance_forecast_evaluation.cfers: The evaluations to overlay, at least one, fromcovariance_forecast_evaluation.names: One name per evaluation, ornothingfor the names thatcovariance_forecast_namesgives.window: Number of steps in the window.scored_steps: Iffalse, the window of a point is the lastwindowsteps of the walk-forward, and a step with no active asset adds nothing to it. Iftrue, the window is the lastwindowscored steps, so it stretches over a step with no active asset, and a point sits only at a scored step.whole_windows: Iffalse, the series covers every step of the evaluation, and a point with no whole window isNaNand drawn blank. Iftrue, the series starts at its first whole window.kwargs...: Additional keyword arguments passed to the plotting backend.
Validation
- $W$ lies in
1:length(cfer.dates)for every evaluation drawn, or underscored_steps = truein1:count(>(0), cfer.n_valid). ADomainErroris thrown otherwise. - Every evaluation drawn scored at least one step, as
covariance_forecast_summaryneeds. AnIsEmptyErroris thrown otherwise, under both settings ofscored_steps. kwargsholds nostep_weighting, because the figure weights each scored step by one and the backend drops a keyword that it does not know. AnArgumentErroris thrown otherwise.- The vector method:
cfersis not empty, else anIsEmptyErroris thrown, and the rules ofcovariance_forecast_names.
Returns
plt::Plots.Plot: A line plot with one series per evaluation.
Related
PortfolioOptimisers.plot_covariance_exceedance — Function
plot_covariance_exceedance(
cfer::CovarianceForecastEvaluationResult;
levels = (0.95, 0.99),
window::Integer = 50,
scored_steps::Bool = false,
whole_windows::Bool = false,
kwargs...
) -> Plot
plot_covariance_exceedance(
cfers::AbstractVector{<:CovarianceForecastEvaluationResult};
names = nothing,
levels = (0.95,),
window::Integer = 50,
scored_steps::Bool = false,
whole_windows::Bool = false,
kwargs...
) -> PlotPlot the rolling rate at which the Mahalanobis statistic of a covariance forecast exceeds the chi-squared quantile of each level, with a dashed line at the target rate of each level.
Each series is the exceedance rate of covariance_forecast_summary, taken over the last $W$ steps of the walk-forward in place of all of them. So a window as wide as the run ends at the value of the summary. covariance_exceedance states the statistic and its threshold. A step with no active asset adds nothing to a window. Under the defaults, the first $W - 1$ points and a window with no scored step are NaN, and the figure leaves them blank. scored_steps and whole_windows set the window and the first point, as in plot_covariance_calibration. The rate is $1 - q$ under a Gaussian null, and it rises with heavy tails as well as with a forecast that is wrong, so it compares two forecasts better than it tests one. The package extension PortfolioOptimisersPlotsExt implements the methods, and it loads after using StatsPlots.
The vector method is the comparison. It draws one series per evaluation and level, on the dates of that evaluation. The label of a series is the name of its evaluation when the figure draws one level, and the name and the level otherwise. Its default draws one level, so that a figure of four forecasts carries four series and not eight.
Mathematical definition
\[\begin{align} \bar{e}^{W}_t &= \frac{1}{\lvert S_t \rvert} \sum_{s \in S_t} e_s\,. \end{align}\]
Where:
- $W$: Rolling window size, in observations.
- $S_t$: The scored steps of the window of point $t$, as
plot_covariance_calibrationstates. - $e_s$: Exceedance indicator of step $s$ at a level, from
covariance_exceedance. - $\bar{e}^{W}_t$: Point $t$ of the series of that level.
Arguments
cfer: The evaluation to draw, fromcovariance_forecast_evaluation.cfers: The evaluations to overlay, at least one, fromcovariance_forecast_evaluation.names: One name per evaluation, ornothingfor the names thatcovariance_forecast_namesgives.levels: Confidence levels of the chi-squared quantiles, at least one.window: Number of steps in the window.scored_steps: Iffalse, the window of a point is the lastwindowsteps of the walk-forward, and a step with no active asset adds nothing to it. Iftrue, the window is the lastwindowscored steps, so it stretches over a step with no active asset, and a point sits only at a scored step.whole_windows: Iffalse, the series covers every step of the evaluation, and a point with no whole window isNaNand drawn blank. Iftrue, the series starts at its first whole window.kwargs...: Additional keyword arguments passed to the plotting backend.
Validation
- $W$ lies in
1:length(cfer.dates)for every evaluation drawn, or underscored_steps = truein1:count(>(0), cfer.n_valid). ADomainErroris thrown otherwise. - Every evaluation drawn scored at least one step, as
covariance_forecast_summaryneeds. AnIsEmptyErroris thrown otherwise, under both settings ofscored_steps. kwargsholds nostep_weighting, because the figure weights each scored step by one and the backend drops a keyword that it does not know. AnArgumentErroris thrown otherwise.levelsis not empty, and every level lies in(0, 1). ADomainErroris thrown otherwise.- The vector method:
cfersis not empty, else anIsEmptyErroris thrown, and the rules ofcovariance_forecast_names.
Returns
plt::Plots.Plot: A line plot with one series per level and evaluation, and a dashed line at each target rate.
Related
PortfolioOptimisers.default_report_figures — Function
default_report_figures() -> NamedTupleThe default figures of a Portfolio Report, as the keywords overview_figures and entry_figures of portfolio_report take them.
The result has two fields, each a vector of pairs caption => f. The fields take the names of the keywords, so the result splats into the call:
portfolio_report(preds; default_report_figures()...)A caller can add a pair to either vector, or remove one. A keyword after the splat replaces the field of the same name. Here g is a figure function of the caller:
f = default_report_figures()portfolio_report(preds; f..., entry_figures = [f.entry_figures; "Turnover" => g])overview_figures: the cumulative returns of every series of the summary on one axis, each series on its own timestamps, with one colour and one legend label for each prediction, and the risk and the return of each prediction on one scatter plot throughplot_measures.entry_figures:plot_composition,plot_drawdowns,plot_histogram, andplot_risk_contributionof aConditionalValueatRisk.
A figure function gives nothing for a prediction that it cannot draw, and the report then has no such figure. The decision is by dispatch on the type of the prediction, and never a caught error. The risk contribution needs the asset returns of a single fold, so only a PredictionResult with a Held Weights record draws it. A prediction whose optimiser gives many portfolios draws no composition, drawdown or histogram figure.
A figure of the structure of the assets, such as a dendrogram, needs a clustering estimator or a prior that a prediction does not hold, so it is not a default. A caller adds it as a pair whose function closes over that estimator. The package extension PortfolioOptimisersPlotsExt implements the method, and it loads after using StatsPlots.
Returns
figs::NamedTuple: The fieldsoverview_figuresandentry_figures, the keywords ofportfolio_report.
Related