Equity Securities

This should update now.

Computing returns

Fill me in.

VLQuantitativeFinancePackage.log_growth_matrixFunction
function log_growth_matrix(dataset::Dict{String, DataFrame}, 
            firms::Array{String,1}; Δt::Float64 = (1.0/252.0), risk_free_rate::Float64 = 0.0) -> Array{Float64,2}

The log_growth_matrix function computes the excess log growth matrix for a given set of firms where we define the log growth as:

\[ \mu_{t,t-1}(r_{f}) = \frac{1}{\Delta t} \log\left(\frac{S_{t}}{S_{t-1}}\right) - r_f\]

where $S_t$ is the volume weighted average price (units: USD/share) at time t, $\Delta t$ is the time increment (in years), and $r_f$ is the annual risk-free rate (units: 1/years) assuming continuous compounding.

Arguments

  • dataset::Dict{String, DataFrame}: A dictionary of data frames where the keys are the firm ticker symbols and the values are the data frames holding price data. We use the volume_weighted_average_price column to compute the log growth by default.
  • firms::Array{String,1}: An array of firm ticker symbols for which we want to compute the log growth matrix.
  • Δt::Float64: The time increment used to compute the log growth. The default value is 1/252, i.e., one trading day in units of years.
  • risk_free_rate::Float64: The risk-free rate used to compute the log growth. The default value is 0.0.
  • keycol::Symbol: The column in the data frame to use to compute the log growth. The default value is :volume_weighted_average_price.
  • testfirm::String: The firm ticker symbol to use to determine the number of trading days. By default, we use "AAPL".

Returns

  • Array{Float64,2}: An array of the excess log growth values for the given set of firms. The time series is the rows and the firms are the columns. The columns are ordered according to the order of the firms array.

See:

source
function log_growth_matrix(dataset::Dict{String, DataFrame}, 
            firm::String; Δt::Float64 = (1.0/252.0), risk_free_rate::Float64 = 0.0) -> Array{Float64,1}

The log_growth_matrix function computes the excess log growth matrix for a given firm where we define the log growth as:

\[ \mu_{t,t-1}(r_{f}) = \frac{1}{\Delta t} \log\left(\frac{S_{t}}{S_{t-1}}\right) - r_f\]

where $S_t$ is the volume weighted average price (units: USD/share) at time t, $\Delta t$ is the time increment (in years), and $r_f$ is the annual risk-free rate (units: 1/years) assuming continuous compounding.

Arguments

  • dataset::Dict{String, DataFrame}: A dictionary of data frames where the keys are the firm ticker symbols and the values are the data frames holding price data. We use the volume_weighted_average_price column to compute the log growth by default.
  • firm::String: The firm ticker symbol for which we want to compute the log growth matrix.
  • Δt::Float64: The time increment used to compute the log growth. The default value is 1/252, i.e., one trading day in units of years.
  • risk_free_rate::Float64: The risk-free rate used to compute the log growth. The default value is 0.0.
  • keycol::Symbol: The column in the data frame to use to compute the log growth. The default value is :volume_weighted_average_price.

Returns

  • Array{Float64,1}: An array of the excess log growth values for the given firm.

See:

source
function log_growth_matrix(dataset::DataFrame; Δt::Float64 = (1.0/252.0), risk_free_rate::Float64 = 0.0,
            keycol::Symbol = :volume_weighted_average_price) -> Array{Float64,1}

Compute the log growth matrix for a given data frame.

source
function log_growth_matrix(dataset::Array{Float64,1}, 
            Δt::Float64 = (1.0/252.0), risk_free_rate::Float64 = 0.0)::Array{Float64,1}
source
VLQuantitativeFinancePackage.typicalpriceFunction
function typicalprice(data::DataFrame) -> Array{Float64,1}

The typicalprice function computes the typical price (h+l+c)/3 for a given time frame.

Arguments

  • data::DataFrame: A data frame holding the price data. To compute the VWAP, we use the volume and open and close price fields.

Returns

  • Array{Float64,1}: An array of the typical values for the given time frame.
source

Lattice Models

VLQuantitativeFinancePackage.RealWorldBinomialProbabilityMeasureType

struct RealWorldBinomialProbabilityMeasure <: AbstractProbabilityMeasure

Immutable type that represents the real-world probability measure. This type is passed as an argument to various functions to indicate that the real-world probability measure should be used in calculations.

source
VLQuantitativeFinancePackage.RiskNeutralBinomialProbabilityMeasureType
struct RiskNeutralBinomialProbabilityMeasure <: AbstractProbabilityMeasure

Immutable type that represents the risk-neutral probability measure. This type is passed as an argument to various functions to indicate that the risk-neutral probability measure should be used in calculations.

source
VLQuantitativeFinancePackage.MyBinomialEquityPriceTreeType
mutable struct MyBinomialEquityPriceTree <: AbstractEquityPriceTreeModel

This mutable struct represents a binomial lattice model for simulating equity prices. The lattice is constructed using values for the up-factor u, down-factor d, and probability p of an up move computed using either a real-world or risk-neutral probability measure. A default (largely empty) lattice is created using a build method, and the lattice is populated using the populate function.

Required fields

  • u::Float64: The up-factor for the lattice (return for an up move during a single time step)
  • d::Float64: The down-factor for the lattice (return for a down move during a single time step)
  • p::Float64: The probability of an up move in the lattice

Optional or computed fields

  • μ::Union{Nothing,Float64}: The drift rate of the asset price (needed for option pricing)
  • T::Union{Nothing,Float64}: The time to expiration of the option contract (needed for option pricing)
  • connectivity::Union{Nothing, Dict{Int64, Array{Int64,1}}}: A dictionary that holds the connectivity of the lattice where the key is the node index and the value is an array of the connected nodes.
  • levels::Union{Nothing, Dict{Int64,Array{Int64,1}}}: A dictionary that holds the nodes on each level of the lattice where the key is the level index and the value is an array of the nodes on that level.
  • ΔT::Union{Nothing,Float64}: The time step size for a single time step in the lattice
  • data::Union{Nothing, Dict{Int64, MyBiomialLatticeEquityNodeModel}}: A dictionary that holds the lattice data for each node where nodes are modeled as MyBiomialLatticeEquityNodeModel instances.
source
VLQuantitativeFinancePackage.MyBiomialLatticeEquityNodeModelType
mutable struct MyBiomialLatticeEquityNodeModel

The MyBiomialLatticeEquityNodeModel mutable struct represents a node in a binomial lattice model for simulating equity prices. This node type is created during the initialization of a lattice model and is used to store the price, probability, intrinsic, and extrinsic values for each node.

Fields

  • price::Float64: The price of the asset at the node
  • probability::Float64: The probability of reaching the node in the binomial lattice
  • intrinsic::Union{Nothing,Float64}: The intrinsic value of the option contract at the node
  • extrinsic::Union{Nothing,Float64}: The extrinsic value of the option contract at the node
source
VLQuantitativeFinancePackage.buildMethod
function build(model::Type{MyBinomialEquityPriceTree}, data::NamedTuple) -> MyBinomialEquityPriceTree

This build method constructs an instance of the MyBinomialEquityPriceTree type using the data in a NamedTuple.

Arguments

  • model::Type{MyBinomialEquityPriceTree}: The type of model to build.
  • data::NamedTuple: The data to use to build the model.

The data::NamedTuple must contain the following keys:

  • u::Float64: The up-factor for the lattice (return for an up move during a single time step)
  • d::Float64: The down-factor for the lattice (return for a down move during a single time step)
  • p::Float64: The probability of an up move in the lattice

The other properties of the MyBinomialEquityPriceTree model are set to nothing by default and are populated during the construction of the model using the populate method.

source
VLQuantitativeFinancePackage.populateMethod
function populate(model::MyBinomialEquityPriceTree; 
            Sₒ::Float64 = 100.0, h::Int = 1) -> MyBinomialEquityPriceTree

The populate function initializes a MyBinomialEquityPriceTree model with share prices and probabilities for each node in a lattice of height h.

Arguments

  • model::MyBinomialEquityPriceTree: An instance of the MyBinomialEquityPriceTree type constructed using the corresponding build function.
  • Sₒ::Float64 = 100.0: The initial price of the equity at time 0. Default value is 100.0 dollars per share.
  • h::Int = 1: The height of the binomial price tree. Default value is 1.

Returns

  • MyBinomialEquityPriceTree: An updated instance of the MyBinomialEquityPriceTree type with the share prices and probabilities computed for each node in the lattice.

Node data is stored in the data field of the model (as MyBiomialLatticeEquityNodeModel instances), and the connectivity of the lattice is stored in the connectivity field. See the MyBinomialEquityPriceTree type for more information on the tree.

source
VLQuantitativeFinancePackage.RealWorldGeneralProbabilityMeasureType

struct RealWorldGeneralProbabilityMeasure <: AbstractProbabilityMeasure

Immutable type that represents the real-world probability measure for a n-ary tree. This type is passed as an argument to various functions to indicate that the real-world probability measure should be used in calculations.

source
VLQuantitativeFinancePackage.MyGeneralAdjacencyRecombiningCommodityPriceTreeType
mutable struct  MyGeneralAdjacencyRecombiningCommodityPriceTree <: AbstractPriceTreeModel

The MyGeneralAdjacencyRecombiningCommodityPriceTree type is a model of a commodity price tree that uses an dictionary to store the price data. This model stores the connectivity information between nodes.

Fields

  • data::Union{Nothing, Dict{Int64,NamedTuple}} - A dictionary that stores the price data and path informationfor the tree.
  • connectivity::Dict{Int64,Array{Int64,1}} - A dictionary that stores the connectivity information between nodes.
source
VLQuantitativeFinancePackage.buildMethod
function build(type::Type{MyGeneralAdjacencyRecombiningCommodityPriceTree}, data::NamedTuple) -> MyGeneralAdjacencyRecombiningCommodityPriceTree

Builds an MyGeneralAdjacencyRecombiningCommodityPriceTree model given the data in the NamedTuple. This method builds the connectivity of the tree. To compute the price at each node, use the populate! method.

Arguments

  • type::Type{MyGeneralAdjacencyRecombiningCommodityPriceTree}: The type of the model to build.
  • data::NamedTuple: The data to use to build the model.

The data NamedTuple must contain the following fields:

  • h::Int64: The height of the tree.
  • price::Float64: The price at the root node.
  • u::Float64: The price increase factor.
  • d::Float64: The price decrease factor.

Returns

  • MyGeneralAdjacencyRecombiningCommodityPriceTree: the price tree model holding the computed price data.
source
VLQuantitativeFinancePackage.populateMethod
populate(model::MyGeneralAdjacencyRecombiningCommodityPriceTree, price::Float64, Δ::Array{Float64,1})

This function populates the price tree model with the given price and price change factors. This method updates the model in place.

Arguments

  • model::MyGeneralAdjacencyRecombiningCommodityPriceTree: The price tree model to populate.
  • price::Float64: The initial price to set at the root of the tree.
  • Δ::Array{Float64,1}: The array of price change factors for each level of the tree.
source

Short cut syntax for data-driven binomial trees

We provide a short-cut syntax to estimate the values of the $(u, d, p)$ parameters of a binomial tree model using historical data. The short-cut syntax allows the user to specify a probability measure, the time step in the data, and the historical growth rate data required to estimate the parameters.

For example, to estimate the expected $(\bar{u}, \bar{d}, \bar{p})$ parameters of using historical growth data for a single-asset with time-step $\Delta{t}$ assuming a real-world probability measure, the user can use the following code:

(ū,d̄,p̄) = (RealWorldBinomialProbabilityMeasure())(growth_rate_array; Δt = Δt);

Geometric Brownian Motion

VLQuantitativeFinancePackage.buildMethod
function build(model::Type{MyGeometricBrownianMotionEquityModel}, data::NamedTuple) -> MyGeometricBrownianMotionEquityModel

This build method constructs an instance of the MyGeometricBrownianMotionEquityModel type using the data in a NamedTuple.

Arguments

  • model::Type{MyGeometricBrownianMotionEquityModel}: The type of model to build.
  • data::NamedTuple: The data to use to build the model.

The data::NamedTuple must contain the following keys:

  • μ::Float64: The drift of the process.
  • σ::Float64: The volatility of the process.
source
VLQuantitativeFinancePackage.buildMethod
function build(model::Type{MyMultipleAssetGeometricBrownianMotionEquityModel}, data::NamedTuple) -> MyMultipleAssetGeometricBrownianMotionEquityModel

This build method constructs an instance of the MyMultipleAssetGeometricBrownianMotionEquityModel type using the data in a NamedTuple.

Arguments

  • model::Type{MyMultipleAssetGeometricBrownianMotionEquityModel}: The type of model to build.
  • data::NamedTuple: The data to use to build the model.

The data::NamedTuple must contain the following keys:

  • μ::Array{Float64,1}: Array of drift rates for each asset.
  • A::Array{Float64,2}: Cholesky decomposition of the covariance matrix of the process.
source
VLQuantitativeFinancePackage.sampleMethod
sample(model::MyGeometricBrownianMotionEquityModel, data::NamedTuple; 
    number_of_paths::Int64 = 100) -> Array{Float64,2}

The sample function simulates the geometric Brownian motion model for a single equity using the analytical solution. The model is defined by the parameters μ and σ which are the drift and volatility of the equity return, respectively. The simulation is performed over a time interval T and the initial price of the equity is Sₒ. The function returns a matrix of size (number_of_time_steps, number_of_paths + 1) where each row represents a single path of the equity price over time.

Arguments

  • model::MyGeometricBrownianMotionEquityModel: An instance of the MyGeometricBrownianMotionEquityModel type which models the geometric Brownian motion for the equity.
  • data::NamedTuple: A named tuple that contains the data for the simulation.

The data::NamedTuple must contain the following keys:

  • T₁::Float64: The start time of the simulation.
  • T₂::Float64: The end time of the simulation.
  • Δt::Float64: The time increment for the simulation.
  • Sₒ::Float64: The initial price of the equity.

Returns

  • Array{Float64,2}: A matrix of size (number_of_time_steps, number_of_paths + 1) where each row represents a single path of the equity price over time. The first column contains the time values.

Optional Arguments

  • number_of_paths::Int64 = 100: The number of paths to simulate. Default value is 100 paths.
source
VLQuantitativeFinancePackage.sampleMethod
sample(model::MyMultipleAssetGeometricBrownianMotionEquityModel, data::NamedTuple; 
    number_of_paths::Int64 = 100) -> Dict{Int64, Array{Float64,2}}

The sample function simulates the geometric Brownian motion model for multiple equities using the analytical solution.

Arguments

  • model::MyMultipleAssetGeometricBrownianMotionEquityModel: An instance of the MyMultipleAssetGeometricBrownianMotionEquityModel type which models the geometric Brownian motion for multiple equities.
  • data::NamedTuple: A named tuple that contains the data for the simulation.

The data::NamedTuple must contain the following keys:

  • T₁::Float64: The start time of the simulation.
  • T₂::Float64: The end time of the simulation.
  • Δt::Float64: The time increment for the simulation.
  • Sₒ::Array{Float64,1}: The initial prices of the equities.

Returns

  • Dict{Int64, Array{Float64,2}}: A dictionary of simulations where the key is the path index and the value is a matrix of size (number_of_time_steps, number_of_assets + 1) where each row represents a time step, and columns represents an asset price. The first column contains the time values.
source
VLQuantitativeFinancePackage.sample_endpointMethod
sample_endpoint(model::MyGeometricBrownianMotionEquityModel, data::NamedTuple; 
    number_of_paths::Int64 = 100) -> Array{Float64,1}

The sample_endpoint function simulates the geometric Brownian motion model for a single equity using the analytical solution at time T.

Arguments

  • model::MyGeometricBrownianMotionEquityModel: An instance of the MyGeometricBrownianMotionEquityModel type which models the geometric Brownian motion for the equity.
  • data::NamedTuple: A named tuple that contains the data for the simulation.

The data::NamedTuple must contain the following keys:

  • T::Float64: The time at which to sample the equity price.
  • Sₒ::Float64: The initial price of the equity at time 0.

Returns

  • Array{Float64,1}: An array of size number_of_paths that contains the equity price at time T.

Optional Arguments

  • number_of_paths::Int64 = 100: The number of paths to simulate. Default value is 100 paths.
source

Advanced Stochastic Pricing and Return Models

VLQuantitativeFinancePackage.MyOrnsteinUhlenbeckModelType
mutable struct MyOrnsteinUhlenbeckModel <: AbstractAssetModel

A mutable struct that represents a Ornstein-Uhlenbeck process. An instance of MyOrnsteinUhlenbeckModel is configured and constructed using a corresponding build method.

Fields

  • μ::Function: The price drift function (long term price level)
  • σ::Function: The price volatility function
  • θ::Function: The mean reversion function. This function determines how quickly the price reverts to the long-term mean.
source
VLQuantitativeFinancePackage.MyHestonModelType
mutable struct MyHestonModel <: AbstractAssetModel

A mutable struct that represents the Heston model. An instance of MyHestonModel is configured and constructed using a corresponding build method.

Fields

  • μ::Function: Drift function takes the state matrix X and time t and returns a scalar, i.e., $\mu:X\times{t}\rightarrow\mathbb{R}$
  • κ::Function: Mean reversion function
  • θ::Function: Long-run volatility function
  • ξ::Function: Volatility of volatility function
  • Σ::Array{Float64,2}: Covariance matrix between the asset price and the volatility process
source
VLQuantitativeFinancePackage.buildMethod
function build(modeltype::Type{MyOrnsteinUhlenbeckModel}, data::NamedTuple) -> MyOrnsteinUhlenbeckModel

This method builds an instance of the MyOrnsteinUhlenbeckModel type using the data in a NamedTuple.

Arguments

  • modeltype::Type{MyOrnsteinUhlenbeckModel}: The type of model to build.
  • data::NamedTuple: The data to use to build the model.

The data::NamedTuple argument must contain the following keys:

  • μ::Float64: The long-term mean of the process.
  • σ::Float64: The volatility of the process.
  • θ::Float64: The mean reversion rate of the process.
source
VLQuantitativeFinancePackage.buildMethod
function build(model::Type{MyHestonModel}, data::NamedTuple) -> MyHestonModel

This build method constructs an instance of the MyHestonModel type using the data in a NamedTuple.

Arguments

  • model::Type{MyHestonModel}: The type of model to build.
  • data::NamedTuple: The data to use to build the model.

The data::NamedTuple must contain the following keys:

  • μ::Function: The long-term mean of the process.
  • κ::Function: The mean reversion rate of the process.
  • θ::Function: The volatility of the process.
  • ξ::Function: The volatility of the volatility of the process.
  • Σ::Array{Float64,2}: The covariance matrix of the process.
source
VLQuantitativeFinancePackage.solveMethod
function solve(model::AbstractAssetModel, tspan::NamedTuple, initialconditions::AbstractArray; 
            method::AbstractStochasticSolverModel = EulerMaruyamaMethod(), N::Int64 = 100)::Tuple

The solve function is used to solve a stochastic asset model. The function takes a model, time span, initial conditions, method, and number of paths as input and returns a tuple of time and state arrays. The method argument is used to specify the method used to solve the model. The N argument is used to specify the number of paths to simulate. The function uses the Euler-Maruyama method as the default method to solve the model.

Arguments

  • model::AbstractAssetModel: The asset model to solve.
  • tspan::NamedTuple: The time span to solve the model over. The NamedTuple should have the fields start, stop, and step.
  • initialconditions::AbstractArray: The initial conditions for the model.
  • method::AbstractStochasticSolverModel = EulerMaruyamaMethod(): The method used to solve the model. Default is Euler-Maruyama.
  • N::Int64 = 100: The number of paths to simulate. Default is 100 paths.

Return

  • Tuple: A tuple of time and state arrays (more than one with multidimensional models) where the rows are the time steps and the columns are the paths.
source

Structured State-Space Models

Update this section with some groooovy text.

VLQuantitativeFinancePackage.MySisoLegSHippoModelType
mutable struct MySisoLegSHippoModel <: AbstractAssetModel

A mutable struct that represents a single-input, single-output (SISO) linear time-invariant (LTI) system that used the Leg-S parameterization. An instance of MySisoLegSHippoModel is configuired and constructed using a corresponding build method.

Fields

  • Â::Array{Float64,2}: Discretized state matrix of the system  ∈ ℝ^(n x n) where n is the number of hidden states
  • B̂::Array{Float64,1}: Discretized input matrix of the system B̂ ∈ ℝ^n x 1
  • Ĉ::Array{Float64,1}: Discretized output matrix of the system Ĉ ∈ ℝ^1 x n
  • D̂::Array{Float64,1}: Discretized feedforward matrix of the system D̂ ∈ ℝ^1 x 1
  • n::Int: Number of hidden states in the system
  • Xₒ::Array{Float64,1}: Initial conditions of the system
source
VLQuantitativeFinancePackage.buildMethod
function build(modeltype::Type{MySisoLegSHippoModel}, data::NamedTuple) -> MySisoLegSHippoModel

This build method constructs an instance of the MySisoLegSHippoModel type using the data in a NamedTuple. This implementation uses the bilinear method to discretize the model, where the A and B matrices are computed using the Leg-S parameterization.

Arguments

  • modeltype::Type{MySisoLegSHippoModel}: The type of model to build.
  • data::NamedTuple: The data to use to build the model.

The data::NamedTuple must contain the following keys:

  • number_of_hidden_states::Int64: The number of hidden states in the model.
  • Δt::Float64: The time step size used to discretize the model (constant).
  • uₒ::Array{Float64,1}: The initial input to the model.
  • C::Array{Float64,1}: The output matrix of the model.
source
VLQuantitativeFinancePackage.solveMethod
function solve(model::MySisoLegSHippoModel, tspan::NamedTuple, signal::Array{Float64}) -> Tuple

The solve function solves the single input single output (SISO) HiPPO model using the Leg-S parameterization and bilinear discretization. The function returns the time array, the hidden state array and the output array.

Arguments

  • model::MySisoLegSHippoModel: A model struct that defines the HiPPO model, see MySisoLegSHippoModel for details on the model struct.
  • tspan::NamedTuple: A named tuple that defines the time span for the simulation. The named tuple should have the fields start, stop and step.
  • signal::Array{Float64}: An array of input signals to the model.

Returns

  • Tuple: A tuple of the time array T, hidden state array X and the output array Y.
source
VLQuantitativeFinancePackage.predictionMethod
function prediction(model::MySisoLegSHippoModel, tspan::NamedTuple, signal::Array{Float64,1}; L::Int64 = 10) -> Tuple

The prediction function predicts the output of the single input single output (SISO) HiPPO model given a signal vector using the Leg-S parameterization and bilinear discretization. The function returns the time array, the hidden state array and the output array.

Arguments

  • model::MySisoLegSHippoModel: A model struct that defines the HiPPO model, see MySisoLegSHippoModel for details on the model struct.
  • tspan::NamedTuple: A named tuple that defines the time span for the simulation. The named tuple should have the fields start, stop and step.
  • signal::Array{Float64}: An array of input signals to the model.
  • S::Int64: Circular buffer size used by the prediction function. The default value is 10 steps. After L steps, the input signal is reset to the first signal value.
  • B::Float64: A threshold value used to reset the hidden states. The default value is 40.0.
  • α::Float64: A scaling factor used to check the output value. The default value is 0.25.
  • β::Float64: A scaling factor used to reset the hidden states. The default value is 0.10.

Returns

  • Tuple: A tuple of the time array T, hidden state array X and the output array Y.
source
VLQuantitativeFinancePackage.estimate_hippo_parametersMethod
function estimate_hippo_parameters(model::MySisoLegSHippoModel, tspan::NamedTuple, signal::Array{Float64};
    method = LBFGS()) -> Array{Float64}

The estimate_hippo_parameters function estimates the C-matrix of the single input single output (SISO) Leg-S bilinear discretized HiPPO model. The Optim.jl package is used to minimize the squared error loss between the estimated and observed model output. The function returns the estimated parameters.

Arguments

  • model::MySisoLegSHippoModel: A model struct that defines the HiPPO model, see MySisoLegSHippoModel for details on the model struct.
  • tspan::NamedTuple: A named tuple that defines the time span for the simulation. The named tuple should have the fields start, stop and step.
  • signal::Array{Float64}: An array of input signals to the model.
  • method::AbstractOptimizer: An optimizer to use for the optimization problem. The default optimizer is the LBFGS routine of the Optim.jl.

Returns

  • Array{Float64}: An array of estimated parameters for the C-matrix of the HiPPO model
source