Coskewness
PortfolioOptimisers.CoskewnessEstimator — Type
abstract type CoskewnessEstimator <: AbstractEstimatorAbstract supertype for all coskewness estimators.
A subtype computes the coskewness tensor of a returns matrix and the negative spectral skewness matrix V of that tensor.
The tensor is the $N \times N^{2}$ matrix of third comoments that Section 2.1 of [63] defines. That section cuts each $N \times N$ layer of the third comoment tensor and puts the layers side by side. Section 2.3 of [64] restates it. V is the negative spectral skewness matrix that Section 2 of [65] defines.
Interfaces
To add a coskewness estimator, subtype CoskewnessEstimator, keep its parameters and its observation weights in the fields of the struct, and add these methods:
Coskewness
PortfolioOptimisers.coskewness(ske::CoskewnessEstimator, X::MatNum; dims::Int = 1, mean = nothing, kwargs...) -> (MatNum, MatNum): Returns the coskewness tensor and its negative spectral skewness matrix.
Arguments
ske: Coskewness estimator.X: Data matrixobservations × assetsif thedimskeyword does not exist ordims = 1,assets × observationswhendims = 2.dims: Dimension along which the computation runs.mean: Optional precomputed centre of the data.kwargs...: More keyword arguments.
Returns
cskew::MatNum: Coskewness tensorassets x assets².V::MatNum: Negative spectral skewness matrixassets x assetsof the coskewness tensor, after the matrix processing.
Factory
PortfolioOptimisers.factory(ske::CoskewnessEstimator, w::PortfolioOptimisers.ObsWeights) -> CoskewnessEstimator: Returns a copy of the estimator that holds the new observation weights.
Arguments
ske: Coskewness estimator.w: Observation weights vectorobservations × 1.
Returns
ske::CoskewnessEstimator: A new coskewness estimator of the same type, with the new weights.
View
PortfolioOptimisers.port_opt_view(ske::CoskewnessEstimator, i) -> CoskewnessEstimator: Returns the estimator for the assets thatiselects.
Arguments
ske: Coskewness estimator.i: The index or the indices of the assets to keep.
Returns
skev: New coskewness estimator of the same type as the argument, for the new view.
Processor and factor prior
The library reads two more verbs of a coskewness estimator:
PortfolioOptimisers.coskewness_processor(ske::CoskewnessEstimator) -> Option{<:AbstractMatrixProcessingEstimator}: Optional. The matrix processing estimator that builds the negative spectral coskewnessV. The fallback givesnothing. Seecoskewness_processor.PortfolioOptimisers.coskewness_expected_returns(ske::CoskewnessEstimator) -> AbstractExpectedReturnsEstimator: The expected returns estimator of the residual moments of aHighOrderFactorPriorEstimator. It is necessary underrsd = true. The fallback refuses the type by name, and the prior calls it at construction. Seecoskewness_expected_returns.
Examples
The example below defines a minimal coskewness estimator.
julia> struct MyCoskewnessEstimator{T1} <: PortfolioOptimisers.CoskewnessEstimator w::T1 function MyCoskewnessEstimator(w::PortfolioOptimisers.Option{<:PortfolioOptimisers.ObsWeights}) PortfolioOptimisers.assert_nonempty_nonneg_finite_val(w, :w) return new{typeof(w)}(w) end endjulia> function MyCoskewnessEstimator(; w::PortfolioOptimisers.Option{<:PortfolioOptimisers.ObsWeights} = nothing) return MyCoskewnessEstimator(w) endMyCoskewnessEstimatorjulia> function PortfolioOptimisers.factory(::MyCoskewnessEstimator, w::PortfolioOptimisers.ObsWeights) return MyCoskewnessEstimator(; w = w) endjulia> function PortfolioOptimisers.port_opt_view(ske::MyCoskewnessEstimator, i) return ske endjulia> function PortfolioOptimisers.coskewness(ske::MyCoskewnessEstimator, X::PortfolioOptimisers.MatNum; dims::Int = 1, mean = nothing, kwargs...) N = size(X, 2) return zeros(N, N^2), zeros(N, N) endjulia> cskew, V = coskewness(MyCoskewnessEstimator(), [1.0 2.0; 0.3 0.7; 0.5 1.1]);julia> cskew2×4 Matrix{Float64}: 0.0 0.0 0.0 0.0 0.0 0.0 0.0 0.0julia> V2×2 Matrix{Float64}: 0.0 0.0 0.0 0.0julia> PortfolioOptimisers.factory(MyCoskewnessEstimator(), StatsBase.Weights([1, 2, 3]))MyCoskewnessEstimator w ┴ StatsBase.Weights{Int64, Int64, Vector{Int64}}: [1, 2, 3]Related
References
- [63] G. M. de Athayde and R. G. Flôres Jr. Finding a maximum skewness portfolio—a general solution to three-moments portfolio choice. Journal of Economic Dynamics and Control 28, 1335–1352 (2004). Section 2.1, page 1338.
- [64] E. Jondeau and M. Rockinger. Optimal portfolio allocation under higher moments. Notes d'Études et de Recherche 108, Banque de France (2004). Section 2.3.
- [65] D. Cajas. On the Spectral Decomposition of Portfolio Skewness and its Application to Portfolio Optimization. Available at SSRN 4540021 (2023). Section 2.
PortfolioOptimisers.Coskewness — Type
struct Coskewness{__T_me, __T_mp, __T_alg, __T_w, __T_cvg, __T_cache} <: CoskewnessEstimatorEstimates the coskewness tensor of a returns matrix, together with its negative spectral skewness matrix.
Coskewness holds a mean estimator, a matrix processing estimator and a moment algorithm. coskewness returns the two matrices as a pair. The first is the assets × assets² tensor. The second is the assets × assets matrix that negative_spectral_coskewness makes from the tensor, and it is not a processed copy of the tensor.
The tensor is the one of Section 2.1 of [63] and Section 2.3 of [64]. The library computes it with the matrix formula of Appendix A of [66]. The matrix is the negative spectral skewness matrix of Section 2 of [65]. The observation weights and the matrix processing of mp are additions of this library.
Fields
me: Expected returns estimator.
mp: Matrix processing estimator.
alg: Moment algorithm.
w: Optional observation weights vectorobservations × 1, or a concrete subtype ofDynamicAbstractWeights. Ifnothing, the computation is unweighted.
cvg: OptionalCoveragePolicy.nothingselects the reduce-and-expand path of the Coverage Universe. On that path, an asset that is not finite or not active at an observation of the window isNaNin all of the result. A policy replaces that path with available-case estimation. The fit of each cell reads the observations at which all the assets of that cell are finite and active, and each cell has its own denominator. An asset is in the result whereadmitsadmits it.
cache: Optional partial-fit state. It isnothinguntilpartial_fit!writes one. When the caller gives no data matrix, the batch verb of the estimator reads it. Each propagation channel does one thing with it.factorykeeps it unchanged, because a factory call resolves the configuration, not the sample.port_opt_viewcopies the entries of the selected assets into a new state, so the viewed estimator holds the state of those assets alone.obs_weights_viewremoves it, because a state has no slice on the observation axis. Only a type with an observation-weights field has that channel. A type with no such field falls through to the identity method, so it keeps its state. A family whose state has no exact asset slice removes it on both axes and names the reason.
Constructors
Coskewness(; me::AbstractExpectedReturnsEstimator = SimpleExpectedReturns(), mp::AbstractMatrixProcessingEstimator = MatrixProcessing(), alg::AbstractMomentAlgorithm = FullMoment(), w::Option{<:ObsWeights} = nothing, cvg::Option{<:CoveragePolicy} = nothing, cache::Option{<:AbstractPartialFitState} = nothing) -> CoskewnessKeywords correspond to the struct's fields.
Validation
- If
wis notnothing,!isempty(w). - If
cvgis aCoveragePolicy,meisnothingor aSimpleExpectedReturns, throughassert_coverage_fittable. The available-case fit centres each asset on the mean of its own observations, and on no other centre. With now, the fit folds, someholds no weights. Withw, the fit centres on the weighted mean, andwreplaces the weights ofme. AnArgumentErroris thrown otherwise.
Propagated parameters
factory passes its arguments on to these @fprop fields:
me: Recursively updated throughfactory.w: Replaced with the incomingObsWeights.cache: Carried unchanged throughfactory.
View parameters
port_opt_view takes the view of these @vprop fields at the selected indices:
me: Recursively viewed throughport_opt_view.cache: Sliced to the selected assets throughport_opt_view.
Observation weight parameters
obs_weights_view indexes these fields to the selected observations:
me: Recursively indexed throughobs_weights_view.w: Indexed to the selected observations throughobs_weights_view.cache: Dropped throughobs_weights_view, because no slice of a state exists on the observation axis.
Examples
julia> Coskewness()Coskewness me ┼ SimpleExpectedReturns │ w ┴ nothing mp ┼ MatrixProcessing │ pdm ┼ Posdef │ │ alg ┼ UnionAll: NearestCorrelationMatrix.Newton │ │ kwargs ┴ @NamedTuple{}: NamedTuple() │ dn ┼ nothing │ dt ┼ nothing │ alg ┼ nothing │ order ┴ NTuple{4, Symbol}: (:pdm, :dn, :dt, :alg) alg ┼ FullMoment() w ┼ nothing cache ┴ nothingRelated
CoskewnessEstimatorAbstractExpectedReturnsEstimatorAbstractMatrixProcessingEstimatorAbstractMomentAlgorithmnegative_spectral_coskewnessfactoryport_opt_viewobs_weights_view
References
- [63] G. M. de Athayde and R. G. Flôres Jr. Finding a maximum skewness portfolio—a general solution to three-moments portfolio choice. Journal of Economic Dynamics and Control 28, 1335–1352 (2004). Section 2.1, page 1338.
- [64] E. Jondeau and M. Rockinger. Optimal portfolio allocation under higher moments. Notes d'Études et de Recherche 108, Banque de France (2004). Section 2.3.
- [66] D. Cajas. Convex Optimization of Portfolio Kurtosis. Available at SSRN 4202967 (2022). Appendix A.
- [65] D. Cajas. On the Spectral Decomposition of Portfolio Skewness and its Application to Portfolio Optimization. Available at SSRN 4540021 (2023). Section 2.
PortfolioOptimisers.coskewness — Function
coskewness(ske::Option{<:Coskewness}, X::MatNum; dims::Int = 1,
mean = nothing, kwargs...)Computes the coskewness tensor of a dataset, and the negative spectral skewness matrix of that tensor.
The method applies the observation weights of ske.w when they are set. FullMoment takes the centred returns, and SemiMoment clips every positive deviation to zero. When the estimator is nothing, the method returns (nothing, nothing).
ske.w weights the whole estimate, so it applies to the centre and to the deviations. When mean is nothing and ske.w is not, the method sends ske.me through factory with ske.w. So ske.w replaces the weights that ske.me holds. Pass mean for a centre that ske.w does not describe.
The two returned matrices are different objects. The first is the coskewness tensor. The second is the negative spectral skewness matrix that negative_spectral_coskewness makes from the tensor.
Algorithm
The type of ske.cvg selects the method, so no branch reads the value of the policy. coverage_covariance selects the arm of a covariance in the same way.
When ske.cvg is nothing, the method takes the Coverage Universe arm. It centres the whole window on one vector. The FullMoment and the SemiMoment methods differ only in step 5.
- Orient
Xto observations × assets withdims_oriented, which validatesdims. - Refuse an inactive cell of
active_maskwithassert_finite_sample, because a plain estimator reads that cell as a non-finite return. - Resolve the observation weights
wfromske.wwithget_observation_weights. - Resolve the centre
mufromske.meandske.wwithweighted_centre, which readsmeanwhen the caller gave one. - Form the deviation matrix
Y.FullMomenttakesX .- mu, andSemiMomenttakesmin.(X .- mu, 0). - Delegate to
_coskewnesswithY,X,ske.mpandw, and return the pair it returns.
When ske.cvg is a CoveragePolicy, the method takes the available-case arm. It fits each triple on the observations at which its three assets are all finite and active, so each cell has its own denominator. The centre of each asset is the available-case mean of that asset, over its own finite and active observations. It is not a mean over the observations of the triple, because a centre for each triple needs assets³ running means. The SemiMoment arm of coverage_covariance centres each asset on its own mean for the same reason. So the arm refuses an external mean, as that arm does. The FullMoment and SemiMoment cases differ only in the clip, so they share one method through coverage_comoment_block. Neither case folds. An exact recursion for each cell at this order needs the pairwise second comoments over the observations of each triple. So the online form of an available-case coskewness refits a buffer through Online.
- Get the valid entries, the deviations from the available-case centre of each asset, and the mask of the admitted assets with
coverage_comoment_block. - Take the numerator as
transpose(Y) * zand the denominator astranspose(Mi) * zc, wherezandzcare the pairwise expansions of the zeroed deviations and of the valid mask. - Divide with
coverage_divide, and frame the refused assets down the asset axis and the pair axis withcoverage_refuse_comoment!. - Reduce the frame with
negative_spectral_coskewness, which keeps the block rule.
When ske.w holds observation weights as well, the available-case arm makes one weighted pass, because the weights describe the whole sample.
- Read the deviations, the valid entries and the admitted assets with
weighted_comoment_block. - Build the third co-moment with
weighted_comoment, and reshape it toN × N². - Frame the refused assets with
coverage_refuse_comoment!, and take the negative spectral coskewness withnegative_spectral_coskewness.
Arguments
ske: The coskewness estimator.ske.alg::FullMoment: TheFullMomentmoment algorithm gives the coskewness.ske.alg::SemiMoment: TheSemiMomentmoment algorithm gives the downside coskewness.ske::Nothing: The method returns(nothing, nothing).
X: The data matrix (observations × assets).dims: Dimension along which the computation runs.mean: The optional mean vector. When it isnothing, the method computes the centre withske.meandske.w. The available-case arm refuses a mean vector.active_mask: The active mask of the Asset Panel over the window, ornothing. The Coverage Universe arm refuses an inactive cell, as it refuses a non-finite return. The available-case arm leaves the cell out of each comoment of its asset.kwargs...: More keyword arguments. Whenske.cvgisnothing, the method passes them toget_observation_weightsand toweighted_centre. The available-case arm ignores them.
Validation
dimsis either1or2.- The available-case arm with no observation weights:
ske.meis aSimpleExpectedReturnswith no weights, andmeanisnothing. Otherwise, it raises anArgumentError.
Returns
cskew::MatNum: Coskewness tensorassets x assets².V::MatNum: Negative spectral skewness matrixassets x assetsof the coskewness tensor, after the matrix processing.
Examples
julia> using StableRNGsjulia> rng = StableRNG(123456789);julia> X = randn(rng, 10, 3);julia> cskew, V = coskewness(Coskewness(), X);julia> cskew3×9 Matrix{Float64}: -0.329646 0.0782455 0.325842 … 0.325842 -0.250881 0.16769 0.0782455 -0.236104 -0.250881 -0.250881 0.266005 0.144546 0.325842 -0.250881 0.16769 0.16769 0.144546 -0.605589julia> V3×3 Matrix{Float64}: 0.513743 -0.0452078 -0.290893 -0.0452078 0.402765 -0.0372996 -0.290893 -0.0372996 0.837701Related
coskewness(ske::WindowedCoskewness, X::MatNum; dims::Int = 1, mean = nothing, iv::Option{<:MatNum} = nothing, kwargs...)Compute coskewness over a rolling or indexed window of observations, for a matrix input.
The method selects a window of observations from X, and applies the observation weights when the estimator holds them. Then it calls the inner coskewness estimator.
Algorithm
- Resolve the window and the observation weights with
windowed_preamble. It returnsinner, a copy ofske.skethat holds the windowed weights, and the windowedX, the windowediv, and theactive_maskandestimation_maskkeywords cut to the window. - Call
coskewnessoninnerand the windowedX, and return its result. The inner estimator alone computes the value. This method changes only the observations and the weights that the inner estimator gets.
Arguments
ske: Windowed coskewness estimator.X: Data matrix of asset returns,observations × assets.dims: Dimension along which the computation runs.mean: Optional precomputed mean, passed to the inner estimator.iv: Optional implied volatility matrix. The estimator reads it only when one of its inner covariance estimators is anImpliedVolatility.kwargs...: More keyword arguments, passed to the inner estimator. The method cuts theactive_maskandestimation_maskkeywords to the window.
Returns
cskew::MatNum: Coskewness tensorassets x assets².V::MatNum: Negative spectral skewness matrixassets x assetsof the coskewness tensor, after the matrix processing.
Related
coskewness(ske::WindowedCoskewness, X::MatNum, pnl::Option{<:AssetPanel}; dims::Int = 1, mean = nothing, kwargs...)Compute coskewness over a rolling or indexed window of observations, for an Asset Panel input.
The method selects a window of observations from X, and applies the observation weights when the estimator holds them. Then it calls the inner coskewness estimator. It cuts the Asset Panel to the same observations and gives it to the inner estimator. A mask-aware inner estimator then reads the active mask of the window, and a plain one reduces to the Coverage Universe of the window.
Algorithm
- Cut
pnlto the observations of the window withwindowed_panel. - Resolve the window and the observation weights with
windowed_preamble. It returnsinner, a copy ofske.skethat holds the windowed weights, and the windowedX, the windowediv, and theactive_maskandestimation_maskkeywords cut to the window. - Call
coskewnessoninnerand the windowedXandpnl, and return its result. The inner estimator alone computes the value. This method changes only the observations and the weights that the inner estimator gets.
Arguments
ske: Windowed coskewness estimator.X: Data matrix of asset returns,observations × assets.pnl: OptionalAssetPanel. The Coverage Universe of the fit comes from its active mask. If it isnothing, the rule reads only the finiteness of the returns.dims: Dimension along which the computation runs.mean: Optional precomputed mean, passed to the inner estimator.kwargs...: More keyword arguments, passed to the inner estimator. The method cuts theiv,active_maskandestimation_maskkeywords to the window.
Returns
cskew::MatNum: Coskewness tensorassets x assets².V::MatNum: Negative spectral skewness matrixassets x assetsof the coskewness tensor, after the matrix processing.
Related
coskewness(
ske::WindowedCoskewness{<:Any, <:Any, <:Any, <:SeedWindow};
kwargs...
) -> Any
Read the coskewness from the fold of a windowed estimator under a SeedWindow.
The inner estimator holds the state of the fold, so the method reads it there.
Arguments
ske: Windowed coskewness estimator under a seed window.kwargs...: Keywords for the read of the inner estimator.
Returns
cskew::MatNum: Coskewness tensorassets x assets².V::MatNum: Negative spectral skewness matrixassets x assetsof the coskewness tensor, after the matrix processing.
Related
coskewness(
ske::Coskewness{<:Any, <:Any, <:FullMoment},
state::CoskewnessPartialFitState
) -> Tuple{Any, Any}
Reads the coskewness tensor and its negative spectral skewness matrix out of a partial-fit state.
The method of coskewness that makes the estimate from a Partial Fit State. It returns the pair the batch method returns, to machine precision, for the sample the state was fitted on.
Only the shape of that sample survives a partial fit, so the matrix processing estimator is handed a matrix of the right shape whose entries are zero. Of the shipped steps only :dn reads it, and it reads only size(X), so the two routes agree. A custom :alg step that reads the values of the sample must be run from the batch verb.
Algorithm
- Refuse a configuration the state no longer matches, with
assert_partial_fittable.factorycarries the state and replacesw, so an estimator that says weighted may hold a state fitted unweighted. The state stays on the estimator, so a caller who restoresw = nothingreads it again. - Divide the third accumulator by the observation count, giving the coskewness tensor.
- Reduce it with
negative_spectral_coskewness, underske.mpand the shape of the fitted sample.
Arguments
ske: Coskewness estimator with aFullMomentmoment algorithm.state: Partial-fit state written bypartial_fit!.
Validation
ske.wisnothingandske.meis an unweightedSimpleExpectedReturns. AnArgumentErroris thrown otherwise.
Returns
cskew::MatNum: Coskewness tensorassets x assets².V::MatNum: Negative spectral skewness matrixassets x assetsof the coskewness tensor, after the matrix processing.
Related
coskewness(ske::Coskewness) -> Any
Reads the coskewness tensor and its negative spectral skewness matrix out of the state the estimator carries.
The one-argument forwarder of coskewness. It reads ske.cache, which partial_fit! writes, and refuses an estimator that has been shown no observation.
Algorithm
- Refuse the estimator whose
cacheisnothing. - Forward to the state method of
coskewness.
Arguments
ske: Coskewness estimator.
Validation
ske.cacheis notnothing. AnArgumentErroris thrown otherwise.
Returns
cskew::MatNum: Coskewness tensorassets x assets².V::MatNum: Negative spectral skewness matrixassets x assetsof the coskewness tensor, after the matrix processing.
Related
coskewness(ske::CoskewnessEstimator) -> Any
coskewness(
ske::CoskewnessEstimator,
state::SampleBufferState
) -> Any
Reads a coskewness tensor out of a SampleBufferState, by running the batch verb over the observations the buffer holds.
The method of coskewness that makes the estimate from a Sample Buffer. An estimator wrapped in Online carries a buffer rather than a family state, so it takes no exact fold, and its estimate is whatever a batch fit over the rows the buffer holds gives — every observation folded so far when the buffer is uncapped, and the last max_history of them when it is capped. It runs no assert_partial_fittable check of its own: the batch verb answers configurations an incremental fold cannot, and a wrapper is how a caller reaches them. The buffer also holds the per-observation masks it was folded with, so the batch verb is given the mask that explains the rows and a wrapped estimator under a CoveragePolicy answers what an unwrapped one answers.
The call with no data, coskewness(ske), fills state with the state that the estimator carries, which partial_fit_cache reads out of the cache field. The call then goes to the method of coskewness for the type of that state. This is the call with no data of an estimator that has no such call of its own. A family that folds exactly has a call with no data of its own, so the default serves the estimators that fold by buffering alone, such as WindowedCoskewness.
Arguments
ske: Coskewness estimator.state: The buffer to read. The default is the state thatskecarries.
Validation
- With no
state, the estimator carries a state. AnArgumentErroris thrown otherwise.
Returns
(cskew, V)::Tuple: The coskewness tensor of the observations the buffer holds, and its negative spectral shape.
Related
coskewness(
ske::CoskewnessEstimator,
X::AbstractMatrix{<:Union{Number, AbstractJuMPScalar}},
pnl::Union{Nothing, AssetPanel};
dims,
active_mask,
kwargs...
) -> Any
The coskewness root of the Asset Panel methods of the moment verbs. It is the reduce-and-expand of Statistics.cov(ce::AbstractCovarianceEstimator, X::MatNum, pnl::Option{<:AssetPanel}; dims::Int = 1, kwargs...), which states the rule and its cost. The result is a pair, so the tensor expands at the pair index and the negative spectral skewness matrix expands as a covariance-like matrix.
Related
coskewness(
ske::Coskewness,
X::AbstractMatrix{<:Union{Number, AbstractJuMPScalar}},
pnl::Union{Nothing, AssetPanel};
dims,
kwargs...
) -> Any
Asset Panel method of coskewness for a Coskewness, which routes on its cvg field with coverage_panel_moment. The result is a pair, so the Coverage Universe route frames the tensor at the pair index and the negative spectral skewness matrix as a covariance-like matrix.
Related
References
- [63]
- G. M. de Athayde and R. G. Flôres Jr. Finding a maximum skewness portfolio—a general solution to three-moments portfolio choice. Journal of Economic Dynamics and Control 28, 1335–1352 (2004).
- [64]
- E. Jondeau and M. Rockinger. Optimal portfolio allocation under higher moments. Notes d'Études et de Recherche 108 (Banque de France, 2004).
- [65]
- D. Cajas. On the Spectral Decomposition of Portfolio Skewness and its Application to Portfolio Optimization. Available at SSRN 4540021 (2023).
- [66]
- D. Cajas. Convex Optimization of Portfolio Kurtosis. Available at SSRN 4202967 (2022).