Prices result
Types
A new type of price data subtypes AbstractPricesResult, has the fields X and pnl, and adds a method of port_opt_view.
PortfolioOptimisers.AbstractPricesResult — Type
abstract type AbstractPricesResult <: AbstractResultAbstract supertype for all price-level data result types.
Every concrete type that holds price-level data subtypes AbstractPricesResult. PricesResult is the member the library builds. The fold generation of cross-validation, the pipeline and the price-level preprocessing steps dispatch on this supertype, as they dispatch on AbstractReturnsResult for returns-level data. No check enforces the interface below.
Interfaces
To implement a new price-level data type that a pipeline and a cross-validation fold can read, subtype AbstractPricesResult with these fields:
X: The asset prices, aTimeSeries.TimeArrayofobservations × assets. Fold generation reads its timestamps and its row count, and asset subset sampling reads its column count.pnl: AnAssetPanelover the assets ofX, ornothing. Fold generation reads it together withXto find the assets that hold data.
Then implement the following method:
port_opt_view
port_opt_view(pr::MyPricesResult, i, j = :) -> MyPricesResult: Returnpron the observations atiand the assets atj.
A subtype that carries a panel subselects it together with X. A subtype that implements no method gets the fallback, which throws an ArgumentError.
Arguments
pr: The price-level data of the new type.i: Indices or timestamps of the observations to keep.j: Indices of the assets to keep.
Returns
pr::MyPricesResult: A value of the same type that holds only the selected observations and assets.
Related
PortfolioOptimisers.PricesResult — Type
struct PricesResult{__T_X, __T_F, __T_B, __T_E, __T_iv, __T_ivpa, __T_pnl, __T_span} <: AbstractPricesResultHolds asset prices with optional factor, benchmark, Exogenous Series and implied volatility series, each a TimeSeries.TimeArray.
It is the price-level counterpart of ReturnsResult. The price-level preprocessing steps and prices_to_returns take it as input, and port_opt_view cuts it into the timestamp windows of pipeline cross-validation.
The asset price series X is the master clock. port_opt_view selects observation windows on X, and each other series keeps its rows at the timestamps that X keeps.
The Exogenous Series E holds level series that belong to no asset, for example a Currency Excess Index. price_ingestion aligns it by timestamp to the clock of X, and prices_to_returns converts it with the return rule of the assets. Its column names are the names that ReturnsResult carries in ne.
The AssetPanel pnl and the Listing Span span hold no timestamps, so no timestamp aligns them. A Panel Field can be a 3-dimensional array, a static panel has no observation axis, and a span can be two integers per asset. Their axes run parallel to X by position instead. The asset axis follows TimeSeries.colnames(X), and the observation axis of a time-varying panel follows TimeSeries.timestamp(X) row for row. A routine that drops an asset or an observation from X must drop it from pnl and span in the same step. port_opt_view does this: it views the panel with its own method, and the span with listing_span_view, and MissingDataFilter and prices_to_returns do it too.
Fields
X: Asset prices,observations × assets. It is the master clock of every timestamp window.
F: Optional factor prices,observations × factors.
B: Optional benchmark prices,observations × 1orobservations × assets.
E: Optional Exogenous Series,observations × series: level series that belong to no asset, such as a Currency Excess Index.prices_to_returnsconverts them to the Exogenous Series of theReturnsResult.
iv: Optional implied volatilities,observations × assets. An absent value isNaN, andImpliedVolatilityremoves the asset from its fit.
ivpa: Implied volatility risk premium adjustment, a positive number that every asset shares, or a vector of positive numbers with one entry per asset.
pnl: OptionalAssetPanelthat holds the Panel Fields of the universe and its two universe masks. It is not aTimeArray, and its axes run parallel toXby position.
span: Optional Listing Span,observations × assets, that states which assets are listed at each observation of the price clock. Its axes run parallel toXby position. It is aPortfolioOptimisers.ListingSpanwhenPriceIngestionderives it by the Span Rule, and any otherAbstractMatrix{Bool}when a caller states their own listing calendar. It isnothingwhen the ingestion layer did not build thePricesResult.
Constructors
PricesResult(; X::TimeSeries.TimeArray, F::Option{<:TimeSeries.TimeArray} = nothing, B::Option{<:TimeSeries.TimeArray} = nothing, E::Option{<:TimeSeries.TimeArray} = nothing, iv::Option{<:TimeSeries.TimeArray} = nothing, ivpa::Option{<:Num_VecNum} = nothing, pnl::Option{<:AssetPanel} = nothing, span::Option{<:AbstractMatrix{Bool}} = nothing,) -> PricesResultKeywords correspond to the struct's fields.
PricesResult is an entry point of integer data. A time array X, F, B, E or iv with an integer element type converts once to its floating-point type through float_if_integer, so every kernel downstream reads floating-point data. Every other element type stays.
Validation
!isempty(X), andallunique(TimeSeries.timestamp(X)).- If
Fis notnothing:!isempty(F). - If
Bis notnothing:!isempty(B), andsize(values(B), 2) in (1, size(values(X), 2)). - If
Eis notnothing:!isempty(E). - If
ivis notnothing:!isempty(iv),size(values(iv), 2) == size(values(X), 2), and every present value is finite and non-negative. An absent value isNaN, ormissingon aPricesResultbuilt by hand. Seeassert_nonneg_where_present. - If
ivpais notnothing:!isempty(ivpa),all(isfinite, ivpa)andall(x -> x > 0, ivpa). Ifivpais a vector:length(ivpa) == size(values(X), 2). - If
pnlis notnothing: its asset axis has the lengthsize(values(X), 2), and the observation axis of a time-varying panel has the lengthsize(values(X), 1). Seecheck_asset_panel. - If
spanis notnothing:size(span) == size(values(X)).
An empty series or an empty ivpa raises an IsEmptyError. A repeated timestamp raises an ArgumentError. A wrong width or a wrong shape raises a DimensionMismatch. A value outside its domain raises a DomainError.
Examples
julia> X = TimeArray(Date(2020, 1, 1):Day(1):Date(2020, 1, 3), [100.0 101.0; 102.0 103.0; 104.0 105.0], ["A", "B"]);julia> pr = PricesResult(; X = X);julia> size(values(pr.X))(3, 2)Related
Functions
PortfolioOptimisers.port_opt_view — Method
port_opt_view(
pr::PricesResult,
_::Colon,
_::Colon
) -> PricesResult
Return the PricesResult on the observation window i and the assets j of the asset price series X.
Indexing a TimeArray copies its rows, so X, F, B, E and iv of the result are copies. ivpa, the Asset Panel and the Listing Span of the result can share memory with pr, and the call with two Colons returns pr itself.
The asset price series is the master clock. i selects rows of X, and the factor, benchmark, Exogenous Series and implied volatility series keep their rows at the timestamps that X keeps. The rows come back in clock order whatever the order of i, and a timestamp of i that X does not hold selects no row. j selects asset columns in the order it gives them, and its default is :. So a call that gives only i is an observation window over the whole universe.
The timestamps of i must compare with the timestamps of X, see assert_timestamp_type. A Date window of DateTime prices selects the observations at midnight. A DateTime window of zoned prices is refused with an error that names i.
The first index selects observations here. The two-argument method of ReturnsResult selects assets, so i names a different axis on the two types.
Algorithm
The method that Julia selects is the algorithm. The timestamp methods do the work, and the integer method sends the call to them.
iandjare bothColon: returnpritself. No view is built.iis a vector of timestamps andjis aColon: giveiin a form that indexesX, withclock_selection. AVectorin the element type of the timestamps ofXpasses as it is, and another type goes throughtimestamp_positions. Then indexX,F,B,Eandivby the timestampsi. Recover the rows of a time-varying Asset Panel from the kept timestamps withfeature_row_indices, and view the panel on that observation axis withport_opt_view. A static panel has no observation axis and ignores the row index. View the Listing Span at the same timestamps withlisting_span_view. Passivpathrough unchanged, because the asset index does not reach it. Rebuild thePricesResult.iis a vector of timestamps andjis one asset position, one asset name, or a vector of asset positions or asset names:- Replace
iwith the timestamps ofXthat it selects, as in step 2. Resolve the asset names ofjto positions in the column names ofXwithlabel_positions. One positionnbecomesn:n, and one name becomes a vector of one position, so the view keeps its matrix shape. Positions pass through. - Index
Xby the timestampsi, then keep the asset columnsj. - Index
FandEby the timestampsialone.jis an asset index, and the factors and the Exogenous Series are separate axes, so every column of each stays. - Index
Bby the timestampsi. Keep its columnsjwhenBholds one column per asset, and keep its single column otherwise. The test reads the width ofB, because a shared benchmark has only one column to give. - Index
ivby the timestampsiand the asset columnsj, and viewivpaatj. - Recover the rows of a time-varying Asset Panel with
feature_row_indices. View the panel at those rows and the assetsjwithport_opt_view, and give it the asset names. It then also cuts the label axis of a tensor Panel Field whose labels are the asset names, seefeatures_are_assets. - View the Listing Span at the kept timestamps and the assets
jwithlisting_span_view. - Rebuild the
PricesResult.
- Replace
iis one integer, integer indices, a range, aColonor one timestamp, andjis one integer, one asset name, integer indices, a range, aColonor asset names: find the positions ofiwithtimestamp_positions, read the timestamps ofXat them, and call step 2 or step 3 with them. One integerngives the positionsn:n, and one timestamp gives the position of the one observation at it. A call such asport_opt_view(pr, 2:3)reaches this method. A timestamp or a vector of timestamps injreaches it too, and step 3 refuses it with the message oflabel_positions, as the view of aReturnsResultdoes.Any other call on an
AbstractPricesResult: throw anArgumentErrorthat names the type of each index argument, the keyword arguments, and the two call shapes of the interface. A call with three indices or with a keyword argument reaches this step. So does a subtype that implements no method.
Arguments
pr: APricesResultobject.i: Observation window into the rows ofpr.X. Either integer positions (oneInteger, anAbstractVector{<:Integer}, anAbstractRange, or aColon), or timestamps (oneDates.AbstractTime, or anAbstractVector{<:Dates.AbstractTime}). One integer and one timestamp select one observation, and the view keeps its matrix shape.j: Asset window into the columns ofpr.X. One integer, integer indices, anAbstractRange, one asset name, a vector of asset names, orColonfor the whole universe. One integer and one name select one asset, and the view keeps its matrix shape. AColonkeeps every asset column ofX,Bandiv, and passesivpathrough unchanged.
Validation
- A window that keeps no row raises the
IsEmptyErrorof thePricesResultconstructor. - The timestamps of
icompare with the timestamps ofX. Raises anArgumentError. Seeassert_timestamp_type. Xholds the timestampi, wheniis one timestamp. Raises anArgumentError. Seetimestamp_positions.- Every asset name of
jis a column name ofX. Raises anArgumentError. Seelabel_positions. - A call shape that step 5 takes raises an
ArgumentError.
Returns
new_pr::PricesResult: The price data on the selected observations and assets. It ispritself wheniandjare bothColons.
Examples
julia> X = TimeArray(Date(2020, 1, 1):Day(1):Date(2020, 1, 3), [100.0 101.0; 102.0 103.0; 104.0 105.0], ["A", "B"]);julia> pr = PricesResult(; X = X);julia> pv = PortfolioOptimisers.port_opt_view(pr, 2:3);julia> first(timestamp(pv.X))2020-01-02julia> size(values(pv.X))(2, 2)julia> colnames(PortfolioOptimisers.port_opt_view(pr, 2:3, ["B"]).X)1-element Vector{Symbol}: :BRelated