Plotting: private API

PortfolioOptimisers.relevant_assets — Function
relevant_assets(
    w::AbstractVector{<:Union{Number, AbstractJuMPScalar}},
    M::Integer
) -> Tuple{Any, Any}
relevant_assets(
    w::AbstractVector{<:Union{Number, AbstractJuMPScalar}},
    M::Integer,
    N_opt::Union{Nothing, Number}
) -> Tuple{Any, Any}

Rank the entries of a per-asset vector by magnitude, and choose how many of them a top-N figure draws.

The ranking reads finite_magnitudes, so a non-finite entry ranks as a zero, below every live entry, and among the zeros by position. The count reads the shares of the magnitudes, so it does not change when w is scaled, so daily and annual expected returns of one universe give one count. A figure that draws the full axis when the count does not truncate keeps its frame.

Mathematical definition

\[\begin{align} p_i &= \frac{m_i}{\sum_{j=1}^{M} m_j}\,, \\ N_{\mathrm{eff}} &= \left(\sum_{i=1}^{M} p_i^2\right)^{-1}\,, \\ N &= \begin{cases} \min\left\{k : \sum_{j=1}^{k} p_{(j)} > 1 - n\right\} & 0 < n \leq 1\,, \\ \min\left(\max\left(\lceil n \rceil, 1\right), M\right) & \text{otherwise}\,. \end{cases} \end{align}\]

Where:

  • $m_i$: Magnitude of entry $i$, $\lvert w_i \rvert$ when $w_i$ is finite and zero otherwise.
  • $p_i$: Share of entry $i$ in the total magnitude, and $p_{(j)}$ the $j$-th largest share.
  • $N_{\mathrm{eff}}$: Effective number of entries. It lies in $[1, M]$, and it is $M$ when every magnitude is equal.
  • $n$: The count or the share that the caller gives, or $N_{\mathrm{eff}}$ when the caller gives none. A value in $(0, 1]$ is a share: $N$ is the least number of the largest entries whose share exceeds $1 - n$, so $n = 0.1$ keeps more than 90 % of the magnitude.
  • $N$: The number of entries the figure draws.
  • $M$: The number of entries.

Algorithm

  1. Map w to its finite magnitudes, abs_w.
  2. Sort abs_w in descending order, stably, giving the ranking idx.
  3. Divide abs_w by its sum, giving the shares abs_w_norm.
  4. Take N_eff as N_opt, or as number_effective_assets of abs_w_norm when N_opt is nothing.
  5. When N_eff is NaN, which it is when every magnitude is zero, take N = M.
  6. When 0 < N_eff ≤ 1, take N as the first k at which the cumulative share cw of abs_w_norm[idx] exceeds 1 - N_eff, or M when none does.
  7. Otherwise take N = clamp(ceil(Int, N_eff), 1, M).

Arguments

  • w: The per-asset vector the figure ranks by, such as a weight, an expected return, a centrality score or a mean absolute weight.
  • M: The number of entries, the largest count.
  • N_opt: The count or the share that the caller gives, or nothing for the effective number.

Returns

  • N::Int: The number of entries to draw.
  • idx::Vector{Int}: The ranking of every entry, largest magnitude first. The first N entries are the ones to draw.

Related

source
PortfolioOptimisers.finite_magnitudes — Function
finite_magnitudes(
    v::AbstractVector{<:Union{Number, AbstractJuMPScalar}}
) -> Any

Take the ranking magnitudes of a per-asset vector, with a non-finite entry ranked as a zero.

A figure that shows the top assets sorts by the size of a per-asset number. A non-investable asset carries NaN in that number, and NaN sorts first under rev = true, so a blank bar would take the top slot from a live asset. The same NaN makes every reduction of the ranking NaN: sum(v) and dot(v, v) are both NaN, and ceil(Int, NaN) throws an InexactError.

Mapping a non-finite entry to zero settles the three for a vector with at least one live entry. The entry ranks below every non-zero entry, it counts for nothing, and the frame is unchanged when the count does not truncate. A vector whose entries are all finite ranks exactly as its absolute values do. A vector with no non-zero finite entry gives all zeros, and relevant_assets then draws every entry.

Arguments

  • v: A per-asset number the figure ranks by, such as an expected return, a volatility, a centrality score or a weight.

Returns

  • m::Vector: A new vector, $\lvert v_i \rvert$ at every finite entry and zero at every other.

Related

source
PortfolioOptimisers.finite_symmetric_clim — Function
finite_symmetric_clim(
    A::AbstractMatrix{<:Union{Number, AbstractJuMPScalar}}
) -> Tuple{Any, Any}

Take the symmetric colour limits of a heatmap over its finite entries alone.

maximum(abs, A) is NaN when any entry of A is, and a NaN colour limit paints every cell one colour. A drawn plot of a Prior Result keeps the full universe, so it does meet a NaN, because a non-investable asset carries one down its row and its column. The limits are therefore taken over the finite entries, and the blank cell is drawn against the scale the live cells set.

Arguments

  • A: The matrix the heatmap draws.

Validation

  • A is not empty, else maximum raises an ArgumentError.

Returns

  • clim::Tuple: (-c, c), where c is the largest finite absolute entry of A, or zero when A holds no finite non-zero entry.

Related

source
PortfolioOptimisers.finite_columns — Function
finite_columns(
    X::AbstractMatrix{<:Union{Number, AbstractJuMPScalar}},
    idx::AbstractVector{<:Integer}
) -> Vector

Keep the columns of idx whose column of X is finite throughout.

A figure that draws one line per asset keeps a gapped asset, and the break in its line is the delisting. A figure that sums several assets into one aggregate line cannot. A single NaN in the sum makes every date of it NaN, at any weight, even the zero weight that an optimiser gives a non-investable asset. Such a series draws nothing at all, so the aggregate excludes the asset instead of carrying it.

The rule reads the column rather than a mask, because the aggregate is formed from a returns matrix the caller holds and no prior travels with it.

Arguments

  • X: The matrix whose columns the aggregate would sum (observations × assets), such as asset returns.
  • idx: Column indices the aggregate would sum.

Validation

  • Every entry of idx indexes a column of X, else a BoundsError is raised.

Returns

  • keep::VecInt: The entries of idx whose column of X holds no non-finite entry, in the order of idx.

Related

source
PortfolioOptimisers.factor_plot_prior — Function
factor_plot_prior(pr::AbstractPriorResult)
factor_plot_prior(pr::HighOrderPrior)

Return the low order factor prior whose mu and sigma a factor figure draws.

A prior result that carries a factor block keeps its low order factor moments in fpr. A HighOrderPrior is the exception. Its own fpr field holds the factor co-moments, and that field is nothing when the estimator formed none, although the prior it wraps still carries the low order factor block. The method for it falls back to the wrapped prior, so a factor figure draws the same block on both prior results.

Arguments

Returns

  • fpr: The factor prior. Its mu is the vector of factor expected returns, and its sigma is the factor covariance matrix.

Related

source
PortfolioOptimisers.investable_plot_view — Function
investable_plot_view(
    pr::AbstractPriorResult,
    nx::Option{<:AbstractVector} = nothing,
    w::Option{<:VecNum} = nothing,
    imsk::BitVector = investable_mask(pr)
)
investable_plot_view(pr::AbstractPriorResult, nx, w, imsk::Nothing)
investable_plot_view(
    rd::AbstractReturnsResult,
    nx::Option{<:AbstractVector} = nothing,
    w::Option{<:VecNum} = nothing
)

Reduce a prior result, the axis names and the weights a computed figure draws to the Investable Mask.

A drawn plot keeps the frame. A heatmap or a bar chart of a Prior Result shows the full universe, and the backend leaves a blank cell and a missing bar where the asset is not investable. A computed plot has no such option. eigvals(Symmetric(sigma)) refuses a NaN, and a phylogeny or a centrality score is fitted by a plain moment estimator, which refuses one too. Such a figure reduces here instead, and it draws the investable universe alone.

The reduction is the one port_opt_view the prior's owner already writes, so a new block cannot be forgotten and the reduced pr.X carries no dead column. The names and the weights are on the asset axis, so they take the mask directly.

A ReturnsResult carries no moments, so no mask exists to derive and it passes through. So one function states the reduction once, and dispatch decides whether it happens.

No diagnostic is emitted. A figure is a drawing rather than a number a caller acts on, and the docstring of each computed plot says that a non-investable asset is not drawn.

Algorithm

  1. Return the three arguments unchanged when pr is a returns result.
  2. Derive the Investable Mask once with investable_mask, the default of the last slot.
  3. Return the three unchanged when every asset is investable, the nothing method.
  4. Otherwise return a port_opt_view of the prior at findall(imsk), and the views of the names and the weights at the mask.

Arguments

  • pr: Prior result, or ReturnsResult.
  • nx: Asset names of the axis, or nothing.
  • w: Portfolio weights the figure sizes by, or nothing.
  • imsk: The Investable Mask of pr, or nothing when every asset is investable. The default is investable_mask(pr).

Validation

  • At least one asset is investable, else investable_mask raises an IsEmptyError.
  • nx and w have one entry per asset, else the view raises a BoundsError.

Returns

  • (pr, nx, w): The three reduced to the Investable Mask, or unchanged.

Related

source
PortfolioOptimisers.attribution_plot_axis — Function
attribution_plot_axis(fa::FactorAttributionResult, by_family::Bool, rd::ReturnsResult,
                      nf::Option{<:AbstractVector})

Return the axis of a FactorAttributionResult a plot draws, and the labels of its rows.

The four attribution plots share one choice: the factor axis or the family axis, and where the labels of that axis come from. The family axis carries its own labels, because they are derived from the block. The factor axis carries none, because the factor names are carried input, so they come from nf, else from rd.nf, else from the position of the row.

Arguments

  • fa: Factor attribution result.
  • by_family: Whether to draw the family axis rather than the factor axis.
  • rd: Returns result that gives the factor names through rd.nf. It has no effect on the family axis.
  • nf: Factor names. They replace rd.nf when given, and they have no effect on the family axis. Nothing checks that they count the rows.

Validation

  • If by_family is true, fa.fmbd is not nothing, else an ArgumentError is raised.

Returns

  • bd::AttributionBreakdown: The axis the plot draws.
  • labels::AbstractVector: The label of each row of that axis.

Related

source
PortfolioOptimisers.plot_extension — Function
plot_extension(
    _::typeof(plot_network)
) -> Tuple{Symbol, String}

The package extension that implements the plot function f, and the packages that load it.

PortfolioOptimisersGraphRecipesExt implements plot_network, and it loads after using GraphRecipes, StatsPlots. PortfolioOptimisersPlotsExt implements every other plot function, and it loads after using StatsPlots. GraphRecipes serves one function, and it brings methods that invalidate much of the compiled code of the caller, so the package loads it for that function alone.

Arguments

  • f: The plot function.

Returns

  • (ext, packages)::Tuple{Symbol, String}: The name of the extension module, and the packages of the using line that loads it, separated by commas.

Related

source
PortfolioOptimisers.plots_extension_hint — Function
plots_extension_hint(
    io::IO,
    exc::MethodError,
    argtypes,
    kwargs
)

Error hint that names the package extension of a plot function with no method.

A package extension implements each plot function of the package, and it loads only after its trigger packages load. A caller who calls a plot function before then gets a MethodError that names no package. The package registers this hint for MethodError in PortfolioOptimisers.__init__, and the hint names the extension that plot_extension gives and the using line that loads it.

A function is a plot function when the package owns it and holds no method of it. The package holds a method of each of its other functions, so the test of the plot file checks that the extension of each function that the rule selects implements it.

Algorithm

  1. In the method with four arguments, which the error display calls, read the extension of the function of exc with plot_extension, and read loaded with Base.get_extension. Pass it to the method with three arguments.
  2. Read f, the function of exc. Return nothing when loaded is true.
  3. Return nothing when the package does not own f, or when the package holds a method of f.
  4. Print one line that names the extension, the name of f, and the using line that loads the extension.

Arguments

  • io: The stream that the error display prints the hint to.
  • exc: The error to explain.
  • argtypes: The types of the positional arguments of the failed call. The hint does not read them.
  • kwargs: The keyword arguments of the failed call. The hint does not read them.
  • loaded: true when the extension of the function of exc is loaded. The hint then prints nothing, because the MethodError comes from a wrong argument and not from a missing extension.

Returns

  • nothing.

Related

source