Asset scorers
An asset scorer gives one score to each asset from the whole returns data. ScoreSelector and RedundancySelector take a scorer in their score field, in the place of a risk measure. A risk measure scores each asset on the whole training window. A scorer can score each asset over the folds of a cross-validation scheme, inside the training window of the selector.
Scores over the test windows
FoldRiskScorer evaluates a risk measure on each test window of a cross-validation scheme, and aggregates the values over the windows. One window of bad luck then does not decide the rank of an asset. Each window scores only the assets that it covers, so an asset with a gap in one window keeps its score from the other windows.
The aggregation sets the rule, and its statistic sets what the rule reduces. Value keeps the raw value of the measure, so a window of high volatility weighs more in a mean. Rank replaces each value with the rank of the asset in its window, so each window weighs the same.
PortfolioOptimisers.FoldRiskScorer — Type
struct FoldRiskScorer{__T_r, __T_sca, __T_cv, __T_agg, __T_min_folds} <: AbstractAssetScorerScores each asset with a risk measure, or with a vector of them, on each test window of a cross-validation scheme, and aggregates the values over the windows.
One window of bad luck then does not decide the rank of an asset. The score of an asset reads its own column alone, so the training rows do not change it. The scheme gives the windows only. agg sets the rule of the aggregation, and its alg sets whether it reduces the raw values with Value or the ranks with Rank.
One measure gives its raw value, with the orientation of the measure. A vector gives the oriented_score of the returns of the asset: each member is oriented so that a bigger value is better, multiplied by its scale, and then reduced through sca. The default nothing gives the sum of SumScalariser. So a vector whose members disagree on orientation gives one value, and a bigger value is better. For one measure sca is inert.
Mathematical definition
\[\begin{align} v_{i k} &= r\left(\boldsymbol{x}_{T_{k},\, i}\right)\,, \\ v_{i k} &= S\left(o_1 s_1 r_1\left(\boldsymbol{x}_{T_{k},\, i}\right), \, \ldots, \, o_n s_n r_n\left(\boldsymbol{x}_{T_{k},\, i}\right)\right)\,, \\ s_{i} &= A\left(\left\{ g_{i k} : k \in \mathcal{F}_{i} \right\}\right)\,. \end{align}\]
Where:
- $v_{i k}$: The value of asset $i$ on the test window $T_{k}$. The first line is the case of one measure, and the second line the case of a vector.
- $r$, $r_j$: The risk measure
r, or the $j$-th measure of the vectorr. - $o_j$: The orientation of $r_j$: $1$ when
bigger_is_betterholds for it, and $-1$ otherwise. - $s_j$:
scaleof $r_j$, its weight in the reduction. - $S$: The reduction
sca. - $n$: Size of the vector of risk measures.
- $\boldsymbol{x}_{T_{k},\, i}$: The returns of asset $i$ at the rows of the test window $T_{k}$.
- $T_{k}$: The $k$-th distinct test window of
split(cv, rd). - $g_{i k}$: The statistic of asset $i$ on window $T_{k}$. It is $v_{i k}$ under
Value, and the rank of $v_{i k}$ among the covered assets of the window underRank. - $\mathcal{F}_{i}$: The windows whose Coverage Universe holds asset $i$.
- $A$: The aggregation
agg. - $s_{i}$: The score of asset $i$.
The scorer evaluates each distinct window once. A CombinatorialCrossValidation split puts each test block in many splits. A count of each split weighs some blocks more than others. A MultipleRandomised split draws asset subsets. The scorer ignores them, because the score of an asset does not depend on the other assets.
A window scores only the assets of its own Coverage Universe, the assets whose return is finite and active at every row of the window. An asset with a gap in one window keeps its score from the other windows. Under Rank, a window ranks only the assets that it covers.
An asset that fewer than min_folds windows cover has the score NaN. Every selection rule and every redundancy algorithm drops a NaN score, so a selector drops that asset and the run does not stop. Inside a selector the training window is already reduced to its Coverage Universe, so the case occurs on a direct call, or with a min_folds above one.
Algorithm
- Read the orientation
bibof the values withwindow_bigger_is_better: thebigger_is_betterflag of one measure, andtruefor a vector. - Take the distinct test windows of
split(cv, rd)withdistinct_test_windows. - For each window, find the positions
liveof the covered assets withcv_live_assets. - Evaluate
ron the covered columns of the window withwindow_values, and turn the values into statistics withfold_statistic. - Collect the statistics of each asset over the windows that cover it into
stats. - Reduce the statistics of each asset that at least
min_foldswindows cover withfold_aggregate, under the orientation fromstatistic_bigger_is_better. WriteNaNat every other asset.min_folds_scoresdoes this step.
Fields
r: TheAbstractBaseRiskMeasure, or the vector of them, that scores the returns of each asset on each test window.
sca: The reduction of the oriented values of a vector of risk measures inrto one value for each asset on each window, aSca_VecToScaM, ornothing, which gives the sum ofSumScalariser. It is inert whenrholds one measure.PerCandidateis not a member, because the scorer has no stage of search scorers.
cv: Cross-validation estimator.
agg: TheAbstractFoldAggregationthat reduces the statistics of each asset over the windows.
min_folds: The smallest number of test windows that must cover an asset. An asset that fewer windows cover has the scoreNaN.
Constructors
FoldRiskScorer(; r::BaseRM_VecBaseRM, sca::Option{<:Sca_VecToScaM} = nothing, cv::CVE_Onl = KFold(), agg::AbstractFoldAggregation = MeanFoldScore(), min_folds::Integer = 1,) -> FoldRiskScorerKeywords correspond to the struct's fields.
Validation
supports_precomputed_returnsofr, or of each member of a vector, throughassert_scoreable.min_folds >= 1.
Examples
julia> rd = ReturnsResult(; nx = ["A", "B", "C"], X = [0.1 0.0 -0.2; -0.1 0.1 0.3; 0.2 0.0 -0.1; 0.0 -0.1 0.2]);julia> s = FoldRiskScorer(; r = SCM(), cv = KFold(; n = 2));julia> round.(PortfolioOptimisers.asset_scores(s, rd); digits = 4)3-element Vector{Float64}: 0.02 0.005 0.085julia> sv = FoldRiskScorer(; r = [SCM(), MeanReturn()], cv = KFold(; n = 2));julia> round.(PortfolioOptimisers.asset_scores(sv, rd); digits = 4)3-element Vector{Float64}: 0.03 -0.005 -0.035julia> PortfolioOptimisers.bigger_is_better(sv)trueThe vector orients SCM(), so the value of asset A is the negated variance plus the mean return, -0.02 + 0.05.
Related
PortfolioOptimisers.AbstractFoldStatistic — Type
abstract type AbstractFoldStatistic <: AbstractAlgorithmAbstract supertype for the statistics that one test window gives to each asset that it covers.
A FoldRiskScorer evaluates a risk measure on each test window. A statistic turns the values of one window into the numbers that an AbstractFoldAggregation then reduces over the windows. Value keeps the raw value of the measure, and Rank replaces it with its rank in the window. A statistic also states its own orientation, because a rank has an orientation of its own, and it is not that of the measure.
Interfaces
To add a statistic, subtype AbstractFoldStatistic, put every parameter of the statistic in the struct, and add the two methods below.
fold_statistic
fold_statistic(alg::MyFoldStatistic, v::VecNum, bib::Bool) -> VecNum: Turn the values of one test window into one statistic for each asset that the window covers.
Arguments
alg: The concrete statistic.v: The values of the risk measure on one test window, one entry for each asset that the window covers.bib: The orientation of the values on a test window, fromwindow_bigger_is_better: thebigger_is_betterflag of one risk measure, ortruefor a vector, whose values are oriented.
Returns
stat::VecNum: One statistic for each entry ofv, in the same order.
statistic_bigger_is_better
statistic_bigger_is_better(alg::MyFoldStatistic, bib::Bool) -> Bool: State whether a bigger statistic is better, from the orientationbibof the risk measure.
Arguments
alg: The concrete statistic.bib: The orientation of the values on a test window, fromwindow_bigger_is_better: thebigger_is_betterflag of one risk measure, ortruefor a vector, whose values are oriented.
Returns
sbib::Bool:truewhen a bigger statistic is better.
Related
PortfolioOptimisers.Value — Type
struct Value <: AbstractFoldStatisticKeeps the raw value of the risk measure on each test window.
The statistic of asset $i$ on a window is the value of the measure on that window. It has the orientation of the measure, so a fold aggregation of it is in the units of the measure. A window of high volatility then weighs more in a mean than a calm window.
Constructors
Value() -> ValueExamples
julia> PortfolioOptimisers.fold_statistic(Value(), [0.3, 0.1, 0.2], false)3-element Vector{Float64}: 0.3 0.1 0.2Related
PortfolioOptimisers.Rank — Type
struct Rank <: AbstractFoldStatisticReplaces the value of the risk measure on each test window with the percentile rank of the asset in that window.
The rank reads the orientation of the measure, so the best asset of a window takes the lowest rank, whether the measure is a risk or a reward. The rank is free of the scale of the window, so a window of high volatility weighs no more than a calm one. It is also free of the number of assets, so two windows that cover different assets give comparable ranks.
Mathematical definition
\[\begin{align} p_{i} &= \frac{n^{<}_{i} + n^{\leq}_{i}}{2 n}\,. \end{align}\]
Where:
- $p_{i}$: The rank of asset $i$ in the window, strictly inside the open unit interval.
- $n$: The number of assets that the window covers.
- $n^{<}_{i}$: The number of covered assets that are strictly better than asset $i$ under the orientation of the measure.
- $n^{\leq}_{i}$: The number of covered assets that are better than asset $i$ or equal to it, asset $i$ included.
A tie shares the average of the ranks that its members take with no tie. The best asset of a window with no tie has the rank $1 / (2 n)$, and the worst has $1 - 1 / (2 n)$. A lower rank is better, so the statistic has the orientation false.
Constructors
Rank() -> RankExamples
julia> PortfolioOptimisers.fold_statistic(Rank(), [0.3, 0.1, 0.1, 0.2], false)4-element Vector{Float64}: 0.875 0.25 0.25 0.625Related
PortfolioOptimisers.AbstractFoldAggregation — Type
abstract type AbstractFoldAggregation <: AbstractAlgorithmAbstract supertype for the rules that reduce the statistics of one asset over the test windows to one score.
A FoldRiskScorer gives each asset one statistic for each test window that covers it. The aggregation reduces those statistics to the score of the asset. Each aggregation holds an AbstractFoldStatistic in its alg field, so one rule can reduce the raw values with Value or the ranks with Rank. An aggregation keeps the orientation of its statistic. A bigger score is better exactly when a bigger statistic is better.
Interfaces
To add an aggregation, subtype AbstractFoldAggregation, give it an alg field that holds an AbstractFoldStatistic, and add the method below.
fold_aggregate
fold_aggregate(agg::MyFoldAggregation, v::VecNum, sbib::Bool) -> Number: Reduce the statistics of one asset over the windows that cover it to one score.
Arguments
agg: The concrete aggregation.v: The statistics of one asset, one entry for each window that covers it.sbib: The orientation of the statistic, fromstatistic_bigger_is_better.
Returns
s::Number: The score of the asset, with the orientationsbib.
Related
PortfolioOptimisers.MeanFoldScore — Type
struct MeanFoldScore{__T_alg} <: AbstractFoldAggregationScores an asset by the mean of its statistic over the test windows that cover it.
Fields
alg: TheAbstractFoldStatisticthat each test window gives to each asset that it covers.Valuekeeps the raw value of the risk measure, andRankkeeps the rank of the asset in the window.
Constructors
MeanFoldScore(; alg::AbstractFoldStatistic = Value(),) -> MeanFoldScoreKeywords correspond to the struct's fields.
Examples
julia> MeanFoldScore(; alg = Rank())MeanFoldScore alg ┴ Rank()Related
PortfolioOptimisers.MedianFoldScore — Type
struct MedianFoldScore{__T_alg} <: AbstractFoldAggregationScores an asset by the median of its statistic over the test windows that cover it.
One window of extreme values moves the median less than it moves the mean.
Fields
alg: TheAbstractFoldStatisticthat each test window gives to each asset that it covers.Valuekeeps the raw value of the risk measure, andRankkeeps the rank of the asset in the window.
Constructors
MedianFoldScore(; alg::AbstractFoldStatistic = Value(),) -> MedianFoldScoreKeywords correspond to the struct's fields.
Examples
julia> MedianFoldScore()MedianFoldScore alg ┴ Value()Related
PortfolioOptimisers.WorstFoldScore — Type
struct WorstFoldScore{__T_alg} <: AbstractFoldAggregationScores an asset by its worst statistic over the test windows that cover it.
The worst statistic is the largest one when a smaller statistic is better, and the smallest one when a bigger statistic is better. With Value it is the maximum of a risk and the minimum of a reward. With Rank it is the largest rank, the window in which the asset placed lowest.
Fields
alg: TheAbstractFoldStatisticthat each test window gives to each asset that it covers.Valuekeeps the raw value of the risk measure, andRankkeeps the rank of the asset in the window.
Constructors
WorstFoldScore(; alg::AbstractFoldStatistic = Value(),) -> WorstFoldScoreKeywords correspond to the struct's fields.
Examples
julia> PortfolioOptimisers.fold_aggregate(WorstFoldScore(), [0.1, 0.4, 0.2], false)0.4julia> PortfolioOptimisers.fold_aggregate(WorstFoldScore(), [0.1, 0.4, 0.2], true)0.1Related
Scores from the weights of an optimiser
WeightMassScorer runs an optimiser or a pipeline through a cross-validation scheme, and scores each asset by its mean weight or by how often it gets a weight. The score needs the whole cross-section of each fold, so no risk measure on one asset can state it.
PortfolioOptimisers.WeightMassScorer — Type
struct WeightMassScorer{__T_opt, __T_p, __T_cv, __T_tol, __T_min_folds, __T_ex} <: AbstractAssetScorerScores each asset by the mean weight, or by the selection frequency, that an optimiser gives it over the splits of a cross-validation scheme.
The score reads the whole cross-section of each fold, so no risk measure on one asset column can state it. opt is an optimisation estimator or a Pipeline. p is an optional grid of configurations, in the form that GridSearchCrossValidation takes, and the scorer pools the folds of every configuration.
Mathematical definition
\[\begin{align} m_{i} &= \frac{1}{\lvert \mathcal{K}_{i} \rvert} \sum_{(c, k) \in \mathcal{K}_{i}} w^{(c, k)}_{i}\,, \\ f_{i} &= \frac{1}{\lvert \mathcal{K}_{i} \rvert} \sum_{(c, k) \in \mathcal{K}_{i}} \mathbf{1}\left\{ \left\lvert w^{(c, k)}_{i} \right\rvert > \tau \right\}\,. \end{align}\]
Where:
- $m_{i}$: The mean weight of asset $i$, the score when
tolisnothing. - $f_{i}$: The selection frequency of asset $i$, the score when
tolis a number. - $\mathcal{K}_{i}$: The pairs of a configuration $c$ and a split $k$ whose optimisation succeeded and whose split offered asset $i$.
- $w^{(c, k)}_{i}$: The weight of asset $i$ in the portfolio that configuration $c$ fits on the training window of split $k$.
- $\tau$: The tolerance
tol.
A split offers the assets of the Coverage Universe of its training window, and also every asset that the fold made investable. A MultipleRandomised split offers only the assets of the subset that it drew. An asset that a selector inside opt drops was offered, so it counts with weight zero. An asset outside the drawn subset was not offered, so it does not count. Without this rule, an asset that a random draw seldom picks gets a low score by chance.
The scorer reads the result of each split once. Under CombinatorialCrossValidation, cross_val_predict gives a population of paths, and one split is in many paths. A failed split counts in neither the sum nor the count. The mean weight is signed, so a short position lowers it, and the frequency reads the absolute weight. A bigger score is better for both.
The scorer runs $C K$ optimisations, for $C$ configurations and $K$ splits. Inside a Pipeline under search_cross_validation, the cost multiplies again by the outer folds and the outer candidates. The scorer keeps no cache.
An asset that fewer than min_folds successful splits offered has the score NaN, and every selection rule drops it. Under MultipleRandomised, a draw of asset subsets can miss an asset completely. A selector then drops that asset only because the random draw did not offer it, and not because of its weight. More subsets in the draw make this less probable.
Algorithm
- Split
rdbycvonce, givingcvr, and find the assets that each split offers withsplit_offered. - Build the candidates of the grid with
weight_mass_candidates. - Run
cross_val_predicton each candidate over the folds ofcvr, and find the prediction of each split withsplit_prediction. The offered assets and the predictions then read the same splits, and a scheme that draws at random draws once. - Keep each prediction whose optimisation succeeded, and turn it into the record of the split with
split_weight_record. - Count the records that offered each asset.
- Return the mean of the record values of each asset that at least
min_foldsrecords offered, over those records, andNaNat every other asset.min_folds_scoresdoes this step.
Fields
opt: The optimisation estimator or thePipelinewhose weights score the assets.
p: The grid of configurations ofopt, in the form thatGridSearchCrossValidationtakes.nothingscoresoptalone.
cv: Cross-validation estimator.
tol: The tolerance of the selection frequency. A number scores the share of the splits in which the absolute weight of the asset exceeds it, andnothingscores the mean weight.
min_folds: The smallest number of successful splits that must offer an asset. An asset that fewer splits offered has the scoreNaN.
ex: Parallel execution strategy.
Constructors
WeightMassScorer(; opt::Union{OptE_TD, Pipeline}, p::Option{<:Union{MultiGSCVValType, AbstractVector}} = nothing, cv::CVE_Onl = KFold(), tol::Option{<:Real} = nothing, min_folds::Integer = 1, ex::FLoops.Transducers.Executor = FLoops.ThreadedEx(),) -> WeightMassScorerKeywords correspond to the struct's fields. p takes a vector of parameter sets whose types differ, through narrow_mixed_vector, as GridSearchCrossValidation does.
Validation
- If
tolis a number,tol >= 0. min_folds >= 1.- If
pis notnothing:!isempty(p). AnIsEmptyErroris thrown otherwise. - Every candidate of
ppasses the checks of the search: the optimiser checks for an estimator, and the hold-out check for aPipeline.
A field that takes a CountOf or a FractionOf also takes a plain number, and count_or_fraction reads an Integer as a count and any other real number as a fraction. Julia promotes the elements of a vector literal to one type before the library reads them. So ["opt.ret.ucs.alg.method.active" => [3, 5, 8], "r.alpha" => [0.05, 0.1]] is a Vector{Pair{String, Vector{Float64}}}, and the counts arrive as 3.0, 5.0 and 8.0. The field then reads them as fractions, and the check of FractionOf refuses them. State the grid in the wrappers, such as [CountOf(3), CountOf(5), FractionOf(0.2)]. A wrapper keeps its type in every container.
Examples
julia> rd = ReturnsResult(; nx = ["A", "B", "C"], X = [0.1 0.0 -0.2; -0.1 0.1 0.3; 0.2 0.0 -0.1; 0.0 -0.1 0.2]);julia> s = WeightMassScorer(; opt = InverseVolatility(), cv = KFold(; n = 2));julia> round.(PortfolioOptimisers.asset_scores(s, rd); digits = 4)3-element Vector{Float64}: 0.2834 0.5668 0.1497Related
Scores from the panel fields
PanelFieldScorer reads the asset panel of the returns data, not the returns. The value of an asset at each observation is one panel field, a sum or a product of panel fields, or a descriptor such as an EWVolumeRatio, and a statistic reduces the values over the observations to the score. A price and a volume give the median traded amount, and a ThresholdRule on it is a liquidity floor. The orientation of the score is a trait of the statistic, and the bib field can override it.
PortfolioOptimisers.PanelFieldScorer — Type
struct PanelFieldScorer{__T_fields, __T_stat, __T_bib, __T_min_obs} <: AbstractAssetScorerScores each asset by a statistic of its Panel Fields, or of a Descriptor, over the observations of the returns data.
The score reads the Asset Panel rd.pnl, not the returns. fields gives the value of an asset at each observation, in one of four forms:
- A name reads that one Panel Field. With a market capitalisation, a
ThresholdRulewith a boundlois a floor of size. - A vector of
name => coefficientpairs reads their sum.["a" => 1, "b" => -1]readsa - b. - A vector of names reads their product. With a price and a traded volume, the value is the traded amount, and a
ThresholdRuleon its median is a liquidity floor. - A Descriptor Estimator, such as an
EWVolumeRatio, reads its Descriptor throughdescriptor. A smoothed turnover or an illiquidity then becomes a score.
The first three forms are a PanelTermType. stat then reduces the values of the asset over the observations to its score.
Inside a ScoreSelector, rd is the training window, and its panel holds the observations of that window only. So the score moves with the window, and no observation after the window reaches it. A Descriptor also reads the window alone, so its recursion starts again at the first observation of each window.
Mathematical definition
\[\begin{align} v_{t i} &= \begin{cases} z^{(1)}_{t i} & \text{one name} \\ \sum_{k = 1}^{K} c_{k} z^{(k)}_{t i} & \text{a combination} \\ \prod_{k = 1}^{K} z^{(k)}_{t i} & \text{a product} \\ d_{t i} & \text{a Descriptor} \end{cases}\,, \\ s_{i} &= S\left(\left\{ v_{t i} : t \in \mathcal{O}_{i} \right\}\right)\,. \end{align}\]
Where:
- $v_{t i}$: The value of asset $i$ at observation $t$.
- $z^{(k)}_{t i}$: The value of the $k$-th Panel Field of
fieldsfor asset $i$ at observation $t$. - $c_{k}$: The coefficient of the $k$-th Panel Field of a combination.
- $K$: The number of Panel Fields in
fields. - $d_{t i}$: The Descriptor of
fieldsfor asset $i$ at observation $t$. - $\mathcal{O}_{i}$: The observations at which $v_{t i}$ is finite.
- $S$: The statistic
stat. - $s_{i}$: The score of asset $i$.
A value is NaN where the asset is outside the universe, and where a fill policy of the panel wrote one of its Panel Fields. A filled volume is not a trade, so the statistic reads only the observed values. A Descriptor is also NaN before its warm-up ends. An asset with fewer than min_obs finite values has the score NaN, and every selection rule and every redundancy algorithm drops it. An asset with no observed value then leaves the selection, and the run does not stop.
stat reads the finite values of one asset in the order of the observations, through finite_vec_to_real_measure. A measure that holds observation weights, such as MedianValue(; w), holds one weight for each observation of rd, and the function cuts them to the finite values, so each value keeps its own weight.
With bib = nothing, the orientation of the score is the orientation of its statistic, bigger_is_better of stat. A statistic of location, such as MedianValue, answers true, so a bigger traded amount is a better score. A statistic of dispersion, StdValue or VarValue, answers false, as a risk does. A plain function answers true. The orientation of a Panel Field or of a Descriptor can differ from that of the statistic: a bigger median leverage is worse, and so is a bigger median illiquidity. A Bool in bib then overrides the statistic.
Algorithm
- Read the value of each asset at each observation with
descriptor_field_values. A Descriptor Estimator gives itsdescriptor. - Count the finite values of each asset.
- Reduce the finite values of each asset that holds at least
min_obsof them withfinite_vec_to_real_measureunderstat. WriteNaNat every other asset.min_folds_scoresdoes this step.
Fields
fields: The value of an asset at each observation: aPanelTermType, which names one Panel Field, a sum or a product of Panel Fields, or a Descriptor Estimator, whose Descriptor is the value.
stat: TheVectorToScalarMeasureor the function that reduces the finite values of one asset over the observations to its score.
bib: The orientation of the score:truewhen a bigger score is better.nothingtakes thebigger_is_betterofstat.
min_obs: The smallest number of finite values that an asset must hold. An asset that holds fewer has the scoreNaN.
Constructors
PanelFieldScorer(; fields::Union{PanelTermType, AbstractDescriptorEstimator}, stat::Union{VectorToScalarMeasure, Function} = MedianValue(), bib::Option{<:Bool} = nothing, min_obs::Integer = 1,) -> PanelFieldScorerKeywords correspond to the struct's fields.
Validation
- The rules of
assert_panel_termsfor aPanelTermTypeinfields: a name is not the empty string, a combination or a product holds at least one name, no name in it is empty, and each coefficient is finite. Raises anIsEmptyErroror aDomainError. A Descriptor Estimator checks its own fields in its constructor. min_obs >= 1. Raises aDomainError.- When the scorer scores, the rules of
descriptor_field_valuesfor each Panel Field offields:rd.pnlis a time-varyingAssetPanel, and each name is aNumericPanelFieldof it. A Descriptor Estimator raises the errors of itsdescriptor.
Examples
julia> pnl = asset_panel([NumericPanelInput(; name = "close", vals = [10.0 2.0; 11.0 2.0; 12.0 NaN], alg = ForwardPanelFill()), NumericPanelInput(; name = "volume", vals = [100.0 50.0; 300.0 70.0; 200.0 60.0])]; amsk = trues(3, 2), emsk = trues(3, 2));julia> rd = ReturnsResult(; nx = ["A", "B"], X = zeros(3, 2), pnl = pnl);julia> s = PanelFieldScorer(; fields = ["close", "volume"]);julia> PortfolioOptimisers.asset_scores(s, rd)2-element Vector{Float64}: 2400.0 120.0julia> PortfolioOptimisers.bigger_is_better(s)truejulia> PortfolioOptimisers.asset_scores(PanelFieldScorer(; fields = "volume"), rd)2-element Vector{Float64}: 200.0 60.0The close of B at the third observation is a fill, so the median traded amount of B reads its first two traded amounts, 100 and 140. The median volume of B reads all three volumes.
Related
PortfolioOptimisers.bigger_is_better — Method
bigger_is_better(stat::VectorToScalarMeasure) -> Bool
bigger_is_better(stat::Union{StdValue, VarValue}) -> Bool
bigger_is_better(stat::Function) -> BoolReturn whether a bigger value of the statistic stat is a better score.
A PanelFieldScorer with bib = nothing takes the orientation of its score from its statistic. A statistic of location or of size, such as the minimum, the mean, the median, the maximum, the sum or the product, answers true: a bigger traded amount or a bigger capitalisation is better. A statistic of dispersion, StdValue or VarValue, answers false, because a dispersion is a risk, as a variance is for a risk measure. A plain function has no type that can state a trait, and it answers true.
A subtype of VectorToScalarMeasure whose smaller values are better adds a method that answers false.
Arguments
stat: The statistic.
Returns
bib::Bool:truewhen a bigger value ofstatis better.
Related
Functions
PortfolioOptimisers.fold_statistic — Method
fold_statistic(alg::Value, v::VecNum, bib::Bool) -> VecNum
fold_statistic(alg::Rank, v::VecNum, bib::Bool) -> VecNumTurn the values of a risk measure on one test window into one statistic for each covered asset.
The Value method returns v. The Rank method returns the percentile rank that the docstring of Rank defines.
Algorithm
The Rank method runs these steps:
- Orient the values with
drop_scores, so that a bigger entry ofuis a worse asset. - Sort
uintos. - For each entry of
u, count withcross_sectional_rank_countsthe entries ofsstrictly below it and those at or below it. - Divide the sum of the two counts by
2n, and return the ranks.
Arguments
alg: The statistic.v: The values of the risk measure on one test window, one entry for each covered asset.bib: The orientation of the values on a test window, fromwindow_bigger_is_better: thebigger_is_betterflag of one risk measure, ortruefor a vector, whose values are oriented.
Returns
stat::VecNum: One statistic for each entry ofv, in the same order.
Related
PortfolioOptimisers.statistic_bigger_is_better — Function
statistic_bigger_is_better(alg::Value, bib::Bool) -> Bool
statistic_bigger_is_better(alg::Rank, bib::Bool) -> BoolState whether a bigger statistic is better, from the orientation bib of the risk measure.
The Value method returns bib, because the raw value has the orientation of the measure. The Rank method returns false, because the best asset of a window takes the lowest rank.
Arguments
alg: The statistic.bib: The orientation of the values on a test window, fromwindow_bigger_is_better: thebigger_is_betterflag of one risk measure, ortruefor a vector, whose values are oriented.
Returns
sbib::Bool:truewhen a bigger statistic is better.
Related
PortfolioOptimisers.fold_aggregate — Function
fold_aggregate(agg::MeanFoldScore, v::VecNum, sbib::Bool) -> Number
fold_aggregate(agg::MedianFoldScore, v::VecNum, sbib::Bool) -> Number
fold_aggregate(agg::WorstFoldScore, v::VecNum, sbib::Bool) -> NumberReduce the statistics of one asset over the test windows that cover it to one score.
The MeanFoldScore method returns the mean of v, and the MedianFoldScore method returns its median. Neither reads sbib. The WorstFoldScore method returns the minimum of v when sbib is true, and the maximum otherwise.
Arguments
agg: The aggregation.v: The statistics of one asset, one entry for each window that covers it.sbib: The orientation of the statistic, fromstatistic_bigger_is_better.
Returns
s::Number: The score of the asset, with the orientationsbib.
Related