Cross-Sectional Factor Model: private API
Functions
PortfolioOptimisers.assert_observed_factor_returns — Function
assert_observed_factor_returns(fx::Nothing, csr, K::Integer) -> nothing
assert_observed_factor_returns(fx::MatNum, csr, K::Integer) -> nothingCheck the observed factor returns of a CrossSectionalFactorModel against the fit and the factor axis.
The observed factors are the trailing columns of the reduced axis, after the factors that the fit estimated. So csr.f and fx together fill the reduced axis, row for row, and every consumer that reads the two side by side with cross_sectional_factor_returns meets one matrix of the width of the loadings. A block with no observed factor takes the method over Nothing.
Arguments
fx: The observed factor returns,observations × factors, ornothing.csr: The nested cross-sectional regression result, ornothing.K: Number of factors on the reduced axis, the column count ofL, or ofMwhenLis unset.
Validation
csris notnothing. Raises anIsNothingError.!isempty(fx), andsize(fx, 1) == size(csr.f, 1).size(csr.f, 2) + size(fx, 2) == K.
Returns
nothing.
Related
PortfolioOptimisers.assert_idiosyncratic_covariance — Function
assert_idiosyncratic_covariance(esigma::Nothing, N::Integer)
assert_idiosyncratic_covariance(esigma::VecNum, N::Integer)
assert_idiosyncratic_covariance(esigma::MatNum, N::Integer)Check the idiosyncratic covariance of a CrossSectionalFactorModel against the asset count N.
The idiosyncratic covariance takes either of two shapes, and the shape is the dispatch rather than a branch: a vector holds the idiosyncratic variances alone, and a matrix holds the full covariance an idiosyncratic correlation threshold produces. An absent covariance is checked by the method over Nothing, so no caller writes an isnothing test.
Arguments
esigma: Idiosyncratic covariance, a vector of variances, a square matrix, ornothing.N: Number of assets the model carries.
Validation
!isempty(esigma).length(esigma) == Nwhenesigmais a vector.esigmais square, andsize(esigma, 1) == N, whenesigmais a matrix.
Returns
nothing.
Related
PortfolioOptimisers.idiosyncratic_covariance_view — Function
idiosyncratic_covariance_view(esigma::Nothing, i)
idiosyncratic_covariance_view(esigma::VecNum, i)
idiosyncratic_covariance_view(esigma::MatNum, i)Return a view of an idiosyncratic covariance, selecting only the assets indexed by i.
The shape is the dispatch, as it is in assert_idiosyncratic_covariance: a vector of variances is indexed once, and a full covariance matrix is indexed on both of its axes, which keeps the selected block square.
Arguments
esigma: Idiosyncratic covariance, a vector of variances, a square matrix, ornothing.i: Indices of the assets to select.
Returns
esigma::Option{<:VecNum_MatNum}: A view over the selected assets, ornothingwhen the model carries no idiosyncratic covariance.
Examples
julia> PortfolioOptimisers.idiosyncratic_covariance_view([1.0, 2.0, 3.0], [1, 3])2-element view(::Vector{Float64}, [1, 3]) with eltype Float64: 1.0 3.0julia> PortfolioOptimisers.idiosyncratic_covariance_view([1.0 0.0; 0.0 2.0], [2])1×1 view(::Matrix{Float64}, [2], [2]) with eltype Float64: 2.0Related
PortfolioOptimisers.assert_idiosyncratic_count — Function
assert_idiosyncratic_count(x::Nothing, N::Integer, sym::Symbol)
assert_idiosyncratic_count(x::VecNum, N::Integer, sym::Symbol)Check a per-asset count of a loadings block, edof or ediv, against the asset count N.
The count is a vector with one entry per asset, or nothing when the fit recorded none. The method over Nothing accepts the absent count, so no caller writes an isnothing test. The check reads the length alone. An entry that is not finite or not positive is a valid record of a short fit, and the consumer that reads the count refuses it.
Arguments
x: The count, ornothing.N: Number of assets the block carries.sym: Name of the field, for the error message.
Validation
!isempty(x), andlength(x) == N.
Returns
nothing.
Related
PortfolioOptimisers.idiosyncratic_variances — Method
idiosyncratic_variances(rr::AbstractLoadingsRegressionResult)
idiosyncratic_variances(esigma::VecNum, rr::AbstractLoadingsRegressionResult)
idiosyncratic_variances(esigma::MatNum, rr::AbstractLoadingsRegressionResult)
idiosyncratic_variances(esigma::Nothing, rr::Regression)
idiosyncratic_variances(esigma::Nothing, rr::CrossSectionalFactorModel)Read the idiosyncratic variance vector off a loadings block, whatever shape the block stores it in.
Both members of AbstractLoadingsRegressionResult carry esigma under one name, and both admit the two shapes: a vector of variances, or a full covariance. A consumer that needs the variances alone — an AbstractUncertaintySetEstimator that weights the cross-section by the inverse idiosyncratic variance is the first one — asks for them here rather than testing the shape at its own site.
The shape is the dispatch, as it is in assert_idiosyncratic_covariance and idiosyncratic_covariance_view. The one-argument entry reads the field and forwards it beside the block, so the two refusals name the block they came from: a Regression is filled by the prior that lifts the factor moments, so its message names rsd, and a CrossSectionalFactorModel is filled by its own fit, so its message names the field.
There is no fallback. A block that carries no idiosyncratic covariance cannot answer, and an answer of ones or of zeros is a different weighting rather than a missing one.
Arguments
esigma: Idiosyncratic covariance, a vector of variances, a square matrix, ornothing.rr: The loadings block the field was read from, which the raise reports.
Validation
!isnothing(esigma), raising anIsNothingError.
Returns
esigma::VecNum: The idiosyncratic variances, one per asset. A vector comes back unchanged, and a matrix comes back as its diagonal.
Examples
julia> re = Regression(; M = [1.0 2.0; 3.0 4.0], esigma = [0.1, 0.2]);julia> PortfolioOptimisers.idiosyncratic_variances(re)2-element Vector{Float64}: 0.1 0.2Related
PortfolioOptimisers.cs_history_assets — Function
cs_history_assets(A::Nothing, N::Integer, sym::Symbol)
cs_history_assets(A::MatNum, N::Integer, sym::Symbol)Check the asset axis of an optional per-asset history of a CrossSectionalFactorModel, and return its observation count.
A per-asset history holds one row per observation and one column per asset, so the asset axis is the second one. The count comes back so that the caller pins the observation axis of two histories against each other with assert_cs_history_obs and needs no isnothing test of its own.
Arguments
A: A per-asset history, ornothing.N: Number of assets the model carries.sym: Name of the field, which the raise reports.
Validation
!isempty(A).size(A, 2) == N.
Returns
T::Option{<:Integer}: The observation count ofA, ornothingwhenAis absent.
Related
PortfolioOptimisers.assert_cs_history_obs — Function
assert_cs_history_obs(a::Option{<:Integer}, b::Option{<:Integer}, asym::Symbol, bsym::Symbol)
assert_cs_history_obs(a::Integer, b::Integer, asym::Symbol, bsym::Symbol)Check that two per-asset histories of a CrossSectionalFactorModel agree on the observation axis.
A history that the model does not carry constrains nothing, so the pair is checked only when cs_history_assets returned a count for both.
Arguments
a: Observation count of the first history, ornothing.b: Observation count of the second history, ornothing.asym: Name of the first field, which the raise reports.bsym: Name of the second field, which the raise reports.
Validation
a == b, when both counts are present.
Returns
nothing.
Related
PortfolioOptimisers.assert_exposure_history — Function
assert_exposure_history(Ms::Nothing, N::Integer, K::Integer)
assert_exposure_history(Ms::Arr3Num, N::Integer, K::Integer)Check the exposure history of a CrossSectionalFactorModel against the asset count N and the factor count K.
The exposure history holds one slice per observation, and a slice has the shape of the loadings matrix, so its first and second axes are the asset axis and the factor axis. The observation axis is the last axis, so the slice of one observation is contiguous.
Arguments
Ms: An exposure historyassets × factors × observations, ornothing.N: Number of assets the model carries.K: Number of raw factors the model carries.
Validation
!isempty(Ms).size(Ms, 1) == N.size(Ms, 2) == K.
Returns
nothing.
Related
PortfolioOptimisers.assert_cs_regression_assets — Function
assert_cs_regression_assets(csr::Nothing, N::Integer)
assert_cs_regression_assets(csr::CrossSectionalRegression, N::Integer)Check the asset axis of the fit a CrossSectionalFactorModel nests against the asset count N.
The residuals of a CrossSectionalRegression hold one row per observation and one column per asset, so the asset axis is the second one, as it is for every per-asset history of the model.
Arguments
csr: The nested cross-sectional regression result, ornothing.N: Number of assets the model carries.
Validation
size(csr.eps, 2) == N.
Returns
nothing.
Related
PortfolioOptimisers.assert_return_forecast_assets — Function
assert_return_forecast_assets(rf::Nothing, N::Integer)
assert_return_forecast_assets(rf::AbstractReturnForecastResult, N::Integer)Check the Return Forecast of a CrossSectionalFactorModel against the asset count N.
A model carries the Return Forecast its prior fitted, or nothing, and the absent case is the method over Nothing. The check reads the two fields every member of the family answers, mu and hist, and never the member's own fields, so a new member needs no new method here.
Arguments
rf: Return Forecast Result, ornothing.N: Number of assets the model carries.
Validation
length(rf.mu) == N.- The rules of
cs_history_assetsonrf.hist.
Returns
nothing.
Related
PortfolioOptimisers.assert_row_key_part — Function
assert_row_key_part(key::Nothing, T, sym::Symbol)
assert_row_key_part(key::VecInt, T::Option{<:Integer}, sym::Symbol)
assert_row_key_part(key::VecDate, T::Option{<:Integer}, sym::Symbol)Check one part of the row key of a factor model block.
A row key names the observation of the returns data that each row of a factor model block describes. It has two parts: the position of each row in the returns data that the prior read, and the timestamp of each row. CrossSectionalFactorModel and Regression carry both parts, and each one checks them with this function. A factor_attribution of a cross-validation reads the key in the order of time, so each part must increase strictly.
Arguments
key: The positions or the timestamps of the rows, ornothing.T: The number of rows that the key describes, ornothingwhen the block does not state it.sym: The name of the field that holdskey, for the error message.
Validation
assert_row_key_lengthonkeyandT.- The entries of a vector of positions are positive and increase strictly. Raises an
ArgumentError. - The entries of a vector of timestamps increase strictly. Raises an
ArgumentError.
Returns
nothing.
Related
PortfolioOptimisers.assert_row_key_length — Function
assert_row_key_length(key::AbstractVector, T::Option{<:Integer}, sym::Symbol)Check that one part of a row key has one entry for each row that it describes.
Arguments
key: The positions or the timestamps of the rows.T: The number of rows that the key describes, ornothingwhen the block does not state it.sym: The name of the field that holdskey, for the error message.
Validation
- When
Tis an integer,length(key) == T. Raises aDimensionMismatch.
Returns
nothing.
Related
PortfolioOptimisers.row_key_length — Function
row_key_length(key::Nothing)
row_key_length(key::AbstractVector)Return the number of rows that one part of a row key describes, or nothing when the part is absent.
A block that states no row count of its own, such as a Regression, checks the timestamps of its key against the length of its positions. This function gives that length.
Arguments
key: The positions or the timestamps of the rows, ornothing.
Returns
T::Option{<:Integer}:length(key), ornothing.
Related
PortfolioOptimisers.assert_cs_block_rows — Function
assert_cs_block_rows(idx::Option{<:VecInt}, ts::Option{<:VecDate},
csr::Option{<:CrossSectionalRegression})Check the row key of a CrossSectionalFactorModel against its fit.
The row key names the observation of the returns data that each row of the block describes. idx holds the position of each row in the returns data that the prior read, and ts holds its timestamp. A key describes the rows of the fit, so a block that carries a key carries a fit, and the key has one entry for each row of the fit.
Arguments
idx: Position of each block row in the returns data, ornothing.ts: Timestamp of each block row, ornothing.csr: The cross-sectional fit of the block, ornothing.
Validation
- When
idxortsis present,csris present. Raises anArgumentError. assert_row_key_partonidxand onts, with thesize(csr.f, 1)rows of the fit.
Returns
nothing.
Related
PortfolioOptimisers.has_family_rebasis — Method
has_family_rebasis(csfm::CrossSectionalFactorModel) -> Bool
State whether the model was fitted in a re-based factor family.
L and fcb are present together and absent together, and the pair is present exactly when a Factor Family was re-based before the fit. The answer is therefore the presence of L, read with getfield rather than through property access: the swap(L, M) rule of CrossSectionalFactorModel makes csfm.L return csfm.M when L is unset, so a property read would answer true for every model.
Arguments
csfm: A cross-sectional factor model result.
Returns
val::Bool:truewhenLis set, so the raw factor axis ofMis a linear image of the re-based one and a factor covariance stated on it is singular;falsewhen the fit ran in the raw basis.
Examples
julia> PortfolioOptimisers.has_family_rebasis(CrossSectionalFactorModel(; M = [1.0 2.0; 3.0 4.0], b = [0.1, 0.2]))falsejulia> fcb = FactorFamilyBasis(; fnm = ["f"], fi = [[1, 2]], di = [2], ratios = reshape([1.0], 1, 1), K = 2);julia> PortfolioOptimisers.has_family_rebasis(CrossSectionalFactorModel(; M = [1.0 2.0; 3.0 4.0], L = reshape([1.0, 2.0], 2, 1), b = [0.1, 0.2], fcb = fcb))trueRelated
PortfolioOptimisers.factor_axis_positions — Function
factor_axis_positions(nf::Option{<:VecStr}, fam::Option{<:VecStr}, i) -> Union{typeof(i), UnitRange{Int}, Vector{Int}}
factor_axis_positions(nf::Option{<:VecStr}, fam::Nothing, i::LabelGroup) -> Union{}
factor_axis_positions(nf::Option{<:VecStr}, fam::VecStr, i::LabelGroup) -> Vector{Int}Turn the factor index of a view of a diagnostic answer into positions on its factor axis.
A position vector, a range and a Colon pass through. A name and a vector of names go through label_positions, which refuses a name it cannot find. One integer becomes a range of one position through label_positions, so the answer keeps its factor axis. A LabelGroup selects every factor whose family label is the group, in the order of the axis.
Algorithm
The method that Julia selects is the algorithm.
iis not aLabelGroup: returnlabel_positionsofnfandi. One integerngivesn:n.iis aLabelGroupandfamisnothing: throw.iis aLabelGroup: return the positions of the entries offamthat equal the group, and throw when there is none.
Arguments
nf: Name of each factor on the factor axis of the answer, ornothingwhen the block names no factor. The axis is the one that the verb answers on, raw or reduced.fam: Family label of each factor on the factor axis of the answer, ornothingwhen the block labels no family. A view selects the factors of one family with aLabelGroup.i: The factor index of the view: one integer, positions, a range, aColon, one name, a vector of names, or aLabelGroup.
Validation
nfis notnothingwheniis a vector of names. Raises anArgumentError.- Every name of
iis innf. Raises anArgumentErrorthat suggests the nearest name. famis notnothingwheniis aLabelGroup. Raises anArgumentError.- At least one entry of
famis the group ofi. Raises anArgumentErrorthat suggests the nearest family.
Returns
pos: The positions of the selected factors, oriunchanged.
Related
PortfolioOptimisers.factor_table_fields — Function
factor_table_fields(r::AbstractResult, i) -> TupleReturn every field of a per-factor table, cut to the factors that i selects.
A per-factor table is a Result whose fields are vectors with one entry per factor, scalars, or nothing, and which carries the names nf and the family labels fam of its factors. The answer is in the order of the fields, so the positional constructor of the table takes it.
Algorithm
- Turn
iinto positions on the factor axis withfactor_axis_positions. - View each field at those positions with
nothing_scalar_array_view, which keeps a scalar andnothingunchanged.
Arguments
r: A per-factor table.i: The factor index: positions, a range, aColon, a vector of names, or aLabelGroup.
Validation
- The rules of
factor_axis_positions.
Returns
fields::Tuple: One entry per field ofr, in the order of the fields.
Related
PortfolioOptimisers.cs_design_labels — Function
cs_design_labels(csfm::CrossSectionalFactorModel, labels::Option{<:VecStr})Map labels of the raw factor axis onto the design axis of the cross-sectional regression.
The design axis is the reduced axis less the observed factors, which cs_diagnostic_factor_names states. The labels are the names or the family labels of the raw axis.
Algorithm
- Map the labels onto the whole reduced axis with the two-argument
cs_diagnostic_factor_names. - Drop the last
size(csfm.fx, 2)entries when the block carries observed factor returns.
Arguments
csfm: A cross-sectional factor model block.labels: The names or the family labels of the raw factor axis, ornothing.
Returns
labels::Option{<:Vector{String}}: The labels of the design axis, ornothingwhenlabelsisnothing.
Related
PortfolioOptimisers.cs_design_result — Function
cs_design_result(csfm::CrossSectionalFactorModel, X::AbstractArray)Wrap the answer of a regression diagnostic of a block in a FactorDiagnosticResult on the design axis.
The last dimension of X is the factor axis. The names and the family labels are those of the design axis, from cs_design_labels.
Arguments
csfm: A cross-sectional factor model block.X: The answer of the diagnostic, with the factors on its last dimension.
Returns
r::FactorDiagnosticResult: The answer with the labels of its factor axis.
Related