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) -> nothing

Check 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, or nothing.
  • csr: The nested cross-sectional regression result, or nothing.
  • K: Number of factors on the reduced axis, the column count of L, or of M when L is unset.

Validation

  • csr is not nothing. Raises an IsNothingError.
  • !isempty(fx), and size(fx, 1) == size(csr.f, 1).
  • size(csr.f, 2) + size(fx, 2) == K.

Returns

  • nothing.

Related

source
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, or nothing.
  • N: Number of assets the model carries.

Validation

  • !isempty(esigma).
  • length(esigma) == N when esigma is a vector.
  • esigma is square, and size(esigma, 1) == N, when esigma is a matrix.

Returns

  • nothing.

Related

source
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, or nothing.
  • i: Indices of the assets to select.

Returns

  • esigma::Option{<:VecNum_MatNum}: A view over the selected assets, or nothing when 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.0

Related

source
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, or nothing.
  • N: Number of assets the block carries.
  • sym: Name of the field, for the error message.

Validation

  • !isempty(x), and length(x) == N.

Returns

  • nothing.

Related

source
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, or nothing.
  • rr: The loadings block the field was read from, which the raise reports.

Validation

  • !isnothing(esigma), raising an IsNothingError.

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.2

Related

source
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, or nothing.
  • 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 of A, or nothing when A is absent.

Related

source
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, or nothing.
  • b: Observation count of the second history, or nothing.
  • 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

source
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 history assets × factors × observations, or nothing.
  • 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

source
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, or nothing.
  • N: Number of assets the model carries.

Validation

  • size(csr.eps, 2) == N.

Returns

  • nothing.

Related

source
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, or nothing.
  • N: Number of assets the model carries.

Validation

Returns

  • nothing.

Related

source
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, or nothing.
  • T: The number of rows that the key describes, or nothing when the block does not state it.
  • sym: The name of the field that holds key, for the error message.

Validation

  • assert_row_key_length on key and T.
  • 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

source
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, or nothing when the block does not state it.
  • sym: The name of the field that holds key, for the error message.

Validation

  • When T is an integer, length(key) == T. Raises a DimensionMismatch.

Returns

  • nothing.

Related

source
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, or nothing.

Returns

  • T::Option{<:Integer}: length(key), or nothing.

Related

source
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, or nothing.
  • ts: Timestamp of each block row, or nothing.
  • csr: The cross-sectional fit of the block, or nothing.

Validation

  • When idx or ts is present, csr is present. Raises an ArgumentError.
  • assert_row_key_part on idx and on ts, with the size(csr.f, 1) rows of the fit.

Returns

  • nothing.

Related

source
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: true when L is set, so the raw factor axis of M is a linear image of the re-based one and a factor covariance stated on it is singular; false when 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))true

Related

source
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.

  1. i is not a LabelGroup: return label_positions of nf and i. One integer n gives n:n.
  2. i is a LabelGroup and fam is nothing: throw.
  3. i is a LabelGroup: return the positions of the entries of fam that equal the group, and throw when there is none.

Arguments

  • nf: Name of each factor on the factor axis of the answer, or nothing when 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, or nothing when the block labels no family. A view selects the factors of one family with a LabelGroup.
  • i: The factor index of the view: one integer, positions, a range, a Colon, one name, a vector of names, or a LabelGroup.

Validation

  • nf is not nothing when i is a vector of names. Raises an ArgumentError.
  • Every name of i is in nf. Raises an ArgumentError that suggests the nearest name.
  • fam is not nothing when i is a LabelGroup. Raises an ArgumentError.
  • At least one entry of fam is the group of i. Raises an ArgumentError that suggests the nearest family.

Returns

  • pos: The positions of the selected factors, or i unchanged.

Related

source
PortfolioOptimisers.factor_table_fields — Function
factor_table_fields(r::AbstractResult, i) -> Tuple

Return 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

  1. Turn i into positions on the factor axis with factor_axis_positions.
  2. View each field at those positions with nothing_scalar_array_view, which keeps a scalar and nothing unchanged.

Arguments

  • r: A per-factor table.
  • i: The factor index: positions, a range, a Colon, a vector of names, or a LabelGroup.

Validation

Returns

  • fields::Tuple: One entry per field of r, in the order of the fields.

Related

source
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

  1. Map the labels onto the whole reduced axis with the two-argument cs_diagnostic_factor_names.
  2. 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, or nothing.

Returns

  • labels::Option{<:Vector{String}}: The labels of the design axis, or nothing when labels is nothing.

Related

source
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

source