licenses
sequencelengths 1
3
| version
stringclasses 677
values | tree_hash
stringlengths 40
40
| path
stringclasses 1
value | type
stringclasses 2
values | size
stringlengths 2
8
| text
stringlengths 25
67.1M
| package_name
stringlengths 2
41
| repo
stringlengths 33
86
|
---|---|---|---|---|---|---|---|---|
[
"MIT"
] | 0.3.2 | 728c49a9de6ffe78fceb7bcba3b53db070fa5532 | code | 2305 |
function simulate!(X_cu, mcProcess::SubordinatedBrownianMotion, mcBaseData::CudaMonteCarloConfig, T::numb) where {numb <: Number}
Nsim = mcBaseData.Nsim
Nstep = mcBaseData.Nstep
drift = mcProcess.drift * T / Nstep
sigma = mcProcess.sigma
ChainRulesCore.@ignore_derivatives @assert T > 0
type_sub = typeof(Float32(quantile(mcProcess.subordinator_, 0.5)))
dt_s = CuArray{type_sub}(undef, Nsim)
dt_s_cpu = Array{type_sub}(undef, Nsim)
isDualZero = drift * sigma * zero(eltype(dt_s)) * 0
@views fill!(X_cu[:, 1], isDualZero) #more efficient than @views X_cu[:, 1] .= isDualZero
Z = CuArray{typeof(get_rng_type(isDualZero))}(undef, Nsim)
θ = mcProcess.θ
@inbounds for i = 1:Nstep
# SUBORDINATED BROWNIAN MOTION (dt_s=time change)
rand!(mcBaseData.parallelMode.rng, mcProcess.subordinator_, dt_s_cpu)
dt_s .= cu(dt_s_cpu)
randn!(CUDA.CURAND.default_rng(), Z)
@views @. X_cu[:, i+1] = X_cu[:, i] + drift + θ * dt_s + sigma * sqrt(dt_s) * Z
end
return
end
function simulate!(X_cu, mcProcess::SubordinatedBrownianMotion, mcBaseData::CudaAntitheticMonteCarloConfig, T::numb) where {numb <: Number}
Nsim = mcBaseData.Nsim
Nstep = mcBaseData.Nstep
drift = mcProcess.drift
sigma = mcProcess.sigma
ChainRulesCore.@ignore_derivatives @assert T > 0
type_sub = typeof(Float32(quantile(mcProcess.subordinator_, 0.5)))
Nsim_2 = div(Nsim, 2)
dt_s = CuArray{type_sub}(undef, Nsim_2)
dt_s_cpu = Array{type_sub}(undef, Nsim_2)
isDualZero = drift * sigma * zero(eltype(dt_s)) * 0
@views fill!(X_cu[:, 1], isDualZero) #more efficient than @views X_cu[:, 1] .= isDualZero
X_cu_p = view(X_cu, 1:Nsim_2, :)
X_cu_m = view(X_cu, (Nsim_2+1):Nsim, :)
Z = CuArray{typeof(get_rng_type(isDualZero))}(undef, Nsim_2)
θ = mcProcess.θ
@inbounds for i = 1:Nstep
randn!(CUDA.CURAND.default_rng(), Z)
# SUBORDINATED BROWNIAN MOTION (dt_s=time change)
rand!(mcBaseData.parallelMode.rng, mcProcess.subordinator_, dt_s_cpu)
dt_s .= cu(dt_s_cpu)
@views @. X_cu_p[:, i+1] = X_cu_p[:, i] + drift + θ * dt_s + sigma * sqrt(dt_s) * Z
@views @. X_cu_m[:, i+1] = X_cu_m[:, i] + drift + θ * dt_s - sigma * sqrt(dt_s) * Z
end
return
end
| FinancialMonteCarlo | https://github.com/rcalxrc08/FinancialMonteCarlo.jl.git |
|
[
"MIT"
] | 0.3.2 | 728c49a9de6ffe78fceb7bcba3b53db070fa5532 | code | 1119 | import Base.+;
const MarketDataSet = Dict{String, AbstractMonteCarloProcess};
export MarketDataSet;
#Link an underlying to a single name model
function →(x::String, y::AbstractMonteCarloProcess)
out = MarketDataSet(x => y)
return out
end
#Link an multiname underlying to a multi variate model
function →(x::String, y::NDimensionalMonteCarloProcess)
sep = findfirst("_", x)
ChainRulesCore.@ignore_derivatives @assert !isnothing(sep) "Nvariate process must follow the format: INDEX1_INDEX2"
len_ = length(y.models)
sep = split(x, "_")
ChainRulesCore.@ignore_derivatives @assert len_ == length(sep)
out = MarketDataSet(x => y)
return out
end
#Joins two different MarketDataSet s
function +(x::MarketDataSet, y::MarketDataSet)
out = copy(x)
y_keys = keys(y)
for y_key in y_keys
ChainRulesCore.@ignore_derivatives @assert !(haskey(out, y_key) || any(out_el -> any(out_el_sub -> out_el_sub == y_key, split(out_el, "_")), keys(out)) || any(y_key_el -> haskey(out, y_key_el), split(y_key, "_"))) "check keys"
out[y_key] = y[y_key]
end
return out
end
| FinancialMonteCarlo | https://github.com/rcalxrc08/FinancialMonteCarlo.jl.git |
|
[
"MIT"
] | 0.3.2 | 728c49a9de6ffe78fceb7bcba3b53db070fa5532 | code | 2847 | import Base.+;
import Base.*;
import Base.-;
import Base./;
const Position = Dict{AbstractPayoff, Number};
# "sum" AbstractPayoff s
function +(x::AbstractPayoff, y::AbstractPayoff)
out = Position(x => 1.0)
if haskey(out, y)
out[x] = 2.0
else
out[y] = 1.0
end
return out
end
# "sum" Position and AbstractPayoff
function +(x::Position, y::AbstractPayoff)
out = copy(x)
if haskey(out, y)
out[y] += 1.0
else
out[y] = 1.0
end
return out
end
# "sum" Position s
function +(x::Position, y::Position)
out = copy(x)
y_keys = keys(y)
for y_key in y_keys
if haskey(out, y_key)
out[y_key] += y[y_key]
else
out[y_key] = y[y_key]
end
end
return out
end
# scalar multiplication
function *(x::Position, y::Number)
out = copy(x)
for a in keys(out)
out[a] *= y
end
return out
end
# scalar multiplication
function *(x::AbstractPayoff, y::Number)
return Position(x => y)
end
*(y::Number, out::AbstractPayoff) = out * y;
*(y::Number, out::Position) = out * y;
/(out::AbstractPayoff, y::Number) = out * (1.0 / y);
/(out::Position, y::Number) = out * (1.0 / y);
+(y::AbstractPayoff, out::Position) = out + y;
-(x::AbstractPayoff) = return -1 * x;
-(x::Position) = return -1 * x;
-(y::AbstractPayoff, out::AbstractPayoff) = y + (-1 * out);
-(y::AbstractPayoff, out::Position) = y + (-1 * out);
-(y::Position, out::AbstractPayoff) = y + (-1 * out);
-(y::Position, out::Position) = y + (-1 * out);
#+(x::AbstractPayoff,y::Tuple{AbstractPayoff,AbstractPayoff,typeof(+)})=(x,y,+)
#+(x::Position,AbstractPayoff)
import Base.hash;
import Base.isequal;
# Needed for Dict
hash(x::Payoff) where {Payoff <: AbstractPayoff} = sum(hash(get_parameters(x))) + hash(string(Payoff))
isequal(x::Payoff1, y::Payoff2) where {Payoff1 <: AbstractPayoff, Payoff2 <: AbstractPayoff} = hash(x) == hash(y)
# Overload for show
import Base.show;
function show(io::IO, p::Position)
keys_ = collect(keys(p))
for idx_ in eachindex(keys_)
key_ = keys_[idx_]
val_ = p[key_]
iszero(val_) ? continue : nothing
if typeof(val_) <: Real
if (idx_ != 1)
val_ > 0.0 ? print(io, +) : print(io, -)
end
if (abs(val_) != 1.0)
idx_ != 1 ? print(io, abs(val_)) : print(io, val_)
print(io, *)
print(io, key_)
else
idx_ == 1 && val_ < 0.0 ? print(io, -) : nothing
print(io, key_)
end
else
if (idx_ != 1)
print(io, +)
end
print(io, "(")
print(io, val_)
print(io, ")")
print(io, *)
print(io, key_)
end
end
#println("")
end
| FinancialMonteCarlo | https://github.com/rcalxrc08/FinancialMonteCarlo.jl.git |
|
[
"MIT"
] | 0.3.2 | 728c49a9de6ffe78fceb7bcba3b53db070fa5532 | code | 2313 | import Base.+;
#Strategies Implementation
const Portfolio = Dict{String, Position};
#Link an underlying name to a Position
function →(x::String, y::Position)
out = Portfolio(x => y)
return out
end
#Link an underlying name to a SingleNamePayoff
function →(x::String, y::SingleNamePayoff)
sep = findfirst("_", x)
ChainRulesCore.@ignore_derivatives @assert isnothing(sep) "NO UNDERSCORE ALLOWED IN SINGLE NAME OPTIONS"
return x → (1.0 * y)
end
#Link an underlying name to a BasketPayoff
function →(x::String, y::BasketPayoff)
sep = findfirst("_", x)[1]
ChainRulesCore.@ignore_derivatives @assert !isnothing(sep) "Bivariate payoff underlying must follow the format: INDEX1_INDEX2"
return x → (1.0 * y)
end
#Join Portfolio s
function +(x::Portfolio, y::Portfolio)
out = copy(x)
y_keys = keys(y)
for y_key in y_keys
if haskey(out, y_key)
out[y_key] = out[y_key] + y[y_key]
else
out[y_key] = y[y_key]
end
end
return out
end
#Overload for display
import Base.Multimedia.display;
function display(p::Portfolio)
keys_ = keys(p)
for key_ in keys_
print(key_)
print(" => ")
print(p[key_])
end
println("")
end
#Overload for extraction, output needs particular shape.
function extract_option_from_portfolio(x::String, dict_::Portfolio)
keys_ = keys(dict_)
out = Position()
out_vec = Position[]
ap_keys = String[]
for key_ in keys_
if ((x == key_) || (any(z -> z == key_, split(x, "_"))))
out = dict_[key_]
push!(out_vec, out)
push!(ap_keys, key_)
end
end
if (length(out_vec) == 1) && (x == ap_keys[1])
return out
else
str_v = split(x, "_")
X = compute_indices(length(str_v))
#tmp_map=Dict( str_v .=> collect(1:length(str_v)))
tmp_map_rev = Dict(collect(1:length(str_v)) .=> str_v)
out__ = Array{Position}(undef, length(X))
for i_ = 1:length(X)
idx_ = X[i_]
str_underlv = [tmp_map_rev[idx_2] for idx_2 in idx_]
str_underl = join(str_underlv, "_")
if (haskey(dict_, str_underl))
out__[i_] = dict_[str_underl]
end
end
return out__
end
end
| FinancialMonteCarlo | https://github.com/rcalxrc08/FinancialMonteCarlo.jl.git |
|
[
"MIT"
] | 0.3.2 | 728c49a9de6ffe78fceb7bcba3b53db070fa5532 | code | 229 | ####### Payoffs definition
## Engines
include("engines/general_european_engine.jl")
include("engines/general_american_engine.jl")
include("engines/general_path_dependent_engine.jl")
include("engines/general_bermudan_engine.jl")
| FinancialMonteCarlo | https://github.com/rcalxrc08/FinancialMonteCarlo.jl.git |
|
[
"MIT"
] | 0.3.2 | 728c49a9de6ffe78fceb7bcba3b53db070fa5532 | code | 2991 | ## Payoffs
abstract type AbstractPayoff{numtype <: Number} end
struct ControlVariates{abstractPayoff <: AbstractPayoff{<:Number}, abstractMonteCarloConfiguration <: AbstractMonteCarloConfiguration, abstractMonteCarloMethod <: AbstractMonteCarloMethod} <: AbstractMonteCarloMethod
variate::abstractPayoff
conf_variate::abstractMonteCarloConfiguration
curr_method::abstractMonteCarloMethod
function ControlVariates(variate::T1, conf_variate::abstractMonteCarloConfiguration, curr_method::abstractMonteCarloMethod = StandardMC()) where {T1 <: AbstractPayoff{<:Number}, abstractMonteCarloConfiguration <: AbstractMonteCarloConfiguration, abstractMonteCarloMethod <: AbstractMonteCarloMethod}
return new{T1, abstractMonteCarloConfiguration, abstractMonteCarloMethod}(variate, conf_variate, curr_method)
end
end
abstract type SingleNamePayoff{numtype <: Number} <: AbstractPayoff{numtype} end
abstract type EuropeanPayoff{numtype <: Number} <: SingleNamePayoff{numtype} end
abstract type AmericanPayoff{numtype <: Number} <: SingleNamePayoff{numtype} end
abstract type BermudanPayoff{numtype <: Number} <: SingleNamePayoff{numtype} end
abstract type PathDependentPayoff{numtype <: Number} <: SingleNamePayoff{numtype} end
abstract type BarrierPayoff{numtype <: Number} <: PathDependentPayoff{numtype} end
abstract type AsianPayoff{numtype <: Number} <: PathDependentPayoff{numtype} end
#No multiple inheritance, sigh
abstract type BasketPayoff{numtype <: Number} <: AbstractPayoff{numtype} end
abstract type EuropeanBasketPayoff{numtype <: Number} <: BasketPayoff{numtype} end
abstract type AmericanBasketPayoff{numtype <: Number} <: BasketPayoff{numtype} end
abstract type BarrierBasketPayoff{numtype <: Number} <: BasketPayoff{numtype} end
abstract type AsianBasketPayoff{numtype <: Number} <: BasketPayoff{numtype} end
function maturity(x::abstractPayoff) where {abstractPayoff <: AbstractPayoff{<:Number}}
return x.T
end
"""
General Interface for Payoff computation from MonteCarlo paths
Payoff=payoff(S,optionData,rfCurve,T1=optionData.T)
Where:
S = Paths of the Underlying.
optionData = Datas of the Option.
rfCurve = Datas of the Risk Free Curve.
T1 =Final Time of Spot Simulation (default equals Time to Maturity of the option)[Optional, default to optionData.T]
Payoff = payoff of the Option.
"""
function payoff(::AbstractMatrix, ::AbstractPayoff, ::AbstractZeroRateCurve, ::AbstractMonteCarloConfiguration, T1::Number = 0.0)
error("Function used just for documentation")
end
function payoff(S::Array{Array{num, 2}, 1}, optionData::SingleNamePayoff, rfCurve::abstractZeroRateCurve, mcBaseData::AbstractMonteCarloConfiguration, T1::num2 = optionData.T) where {abstractZeroRateCurve <: AbstractZeroRateCurve, num <: Number, num2 <: Number}
#switch to only in julia 1.4
ChainRulesCore.@ignore_derivatives @assert length(S) == 1
return payoff(S[1], optionData, rfCurve, mcBaseData, T1)
end
| FinancialMonteCarlo | https://github.com/rcalxrc08/FinancialMonteCarlo.jl.git |
|
[
"MIT"
] | 0.3.2 | 728c49a9de6ffe78fceb7bcba3b53db070fa5532 | code | 780 | ####### Payoffs definition
### Spot
include("payoffs/spot.jl")
### European Payoffs
include("payoffs/forward.jl")
include("payoffs/european_option.jl")
include("payoffs/binary_european_option.jl")
### Barrier Payoffs
include("payoffs/barrier_do_option.jl")
include("payoffs/barrier_di_option.jl")
include("payoffs/barrier_uo_option.jl")
include("payoffs/barrier_ui_option.jl")
include("payoffs/double_barrier_option.jl")
### American Payoffs
include("payoffs/american_option.jl")
include("payoffs/binary_american_option.jl")
### Path Dependent Payoffs
include("payoffs/bermudan_option.jl")
### Asian Payoffs
include("payoffs/asian_fixed_strike_option.jl")
include("payoffs/asian_floating_strike_option.jl")
### Basket Payoffs
include("payoffs/basket/n_european_option.jl")
| FinancialMonteCarlo | https://github.com/rcalxrc08/FinancialMonteCarlo.jl.git |
|
[
"MIT"
] | 0.3.2 | 728c49a9de6ffe78fceb7bcba3b53db070fa5532 | code | 2171 |
function payoff(S1::AbstractMatrix{num}, amPayoff::AmericanPayoff, rfCurve::abstractZeroRateCurve, mcBaseData::AbstractMonteCarloConfiguration, T1::num2 = maturity(amPayoff)) where {abstractZeroRateCurve <: AbstractZeroRateCurve, num <: Number, num2 <: Number}
T = amPayoff.T
NStep = mcBaseData.Nstep
Nsim = mcBaseData.Nsim
index1 = round(Int, T / T1 * NStep) + 1
S = collect(S1[:, 1:index1])
Nstep = index1 - 1
r = rfCurve.r
dt = T / Nstep
# initialize vectors
exerciseTimes = (Nstep) .* ones(Int64, Nsim)
df_exerciseTimes = [exp(-integral(r, dt * j_)) for j_ = 0:NStep]
#define payout
phi(Sti::numtype_) where {numtype_ <: Number} = payout(Sti, amPayoff)
#compute payout
@views V = @. phi(S[:, end])
# Backward Procedure
s_type = eltype(S)
b_type = typeof(zero(eltype(S)) + zero(eltype(V)))
A_2 = Matrix{s_type}(undef, 3, 3)
Btilde = Array{b_type}(undef, 3)
alpha = Array{b_type}(undef, 3)
@inbounds for j = Nstep:-1:2
@views Tmp = @. phi(S[:, j])
inMoneyIndexes = findall(Tmp .> 0.0)
if !isempty(inMoneyIndexes)
@views S_I = S[inMoneyIndexes, j]
#- Linear Regression on Quadratic Form
A = Matrix{eltype(A_2)}(undef, length(S_I), 3)
@views @. A[:, 1] = 1
@views @. A[:, 2] = S_I
@views @. A[:, 3] = S_I^2
b = [V[j_] * df_exerciseTimes[exerciseTimes[j_]-j+1] for j_ in inMoneyIndexes]
A_2 .= A' * A
LuMat = lu!(A_2)
Btilde .= A' * b
alpha .= LuMat \ Btilde
#alpha=A\b;
#Continuation Value
CV = A * alpha
#-- Intrinsic Value
@views IV = Tmp[inMoneyIndexes]
#----------
# Find premature exercise times
Index = findall(IV .> CV)
@views exercisePositions = inMoneyIndexes[Index]
# Update the outputs
@views @. V[exercisePositions] = IV[Index]
@views @. exerciseTimes[exercisePositions] = j - 1
end
end
Out = @. V * df_exerciseTimes[exerciseTimes+1]
return Out
end
| FinancialMonteCarlo | https://github.com/rcalxrc08/FinancialMonteCarlo.jl.git |
|
[
"MIT"
] | 0.3.2 | 728c49a9de6ffe78fceb7bcba3b53db070fa5532 | code | 2180 |
function payoff(S1::AbstractMatrix{num}, bmPayoff::BermudanPayoff, rfCurve::abstractZeroRateCurve, mcBaseData::AbstractMonteCarloConfiguration, T1::num2 = maturity(bmPayoff)) where {abstractZeroRateCurve <: AbstractZeroRateCurve, num <: Number, num2 <: Number}
T_opt = bmPayoff.T_ex
T = maturity(bmPayoff)
NStep = mcBaseData.Nstep
Nsim = mcBaseData.Nsim
index1 = round(Int, T / T1 * NStep) + 1
S = collect(S1[:, 1:index1])
Nstep = index1 - 1
r = rfCurve.r
dt = T / Nstep
# initialize
exerciseTimes = Nstep .* ones(Nsim)
phi(Sti::numtype_) where {numtype_ <: Number} = payout(Sti, bmPayoff)
idx_opt = round.(Int, T_opt ./ dt)
@views V = phi.(S[:, end]) #payoff
# Backward Procedure
for j in reverse(idx_opt)
@views Tmp = phi.(S[:, j])
inMoneyIndexes = findall(Tmp .> 0.0)
if !isempty(inMoneyIndexes)
#S_I=S[inMoneyIndexes,j];
S_I = view(S, inMoneyIndexes, j)
#-- Intrinsic Value
@views IV = Tmp[inMoneyIndexes]
#-- Continuation Value
#- Linear Regression on Quadratic Form
A = [ones(length(S_I)) S_I S_I .^ 2]
#@views b=V[inMoneyIndexes].*exp.(-r*dt*(exerciseTimes[inMoneyIndexes].-j));
@views b = V[inMoneyIndexes] .* exp.(-[integral(r, dt * (exerciseTime - j + 1)) for exerciseTime in exerciseTimes[inMoneyIndexes]])
#@views b = V[inMoneyIndexes] .* exp.(-1.0*integral.(r, dt .* (exerciseTimes[inMoneyIndexes]. - j + 1)))
#MAT=A'*A;
LuMat = lu(A' * A)
Btilde = A' * b
alpha = LuMat \ Btilde
#alpha=A\b;
#Continuation Value
CV = A * alpha
#----------
# Find premature exercise times
Index = findall(IV .> CV)
@views exercisePositions = inMoneyIndexes[Index]
# Update the outputs
@views V[exercisePositions] = IV[Index]
@views exerciseTimes[exercisePositions] .= j - 1
end
end
Out = V .* exp.(-[integral(r, dt * exerciseTime) for exerciseTime in exerciseTimes])
return Out
end
| FinancialMonteCarlo | https://github.com/rcalxrc08/FinancialMonteCarlo.jl.git |
|
[
"MIT"
] | 0.3.2 | 728c49a9de6ffe78fceb7bcba3b53db070fa5532 | code | 547 |
function payoff(S::AbstractMatrix{num}, euPayoff::EuropeanPayoff, rfCurve::abstractZeroRateCurve, mcBaseData::AbstractMonteCarloConfiguration, T1::num2 = maturity(euPayoff)) where {abstractZeroRateCurve <: AbstractZeroRateCurve, num <: Number, num2 <: Number}
r = rfCurve.r
T = euPayoff.T
NStep = mcBaseData.Nstep
index1 = round(UInt, T / T1 * NStep) + 1
@views ST = S[:, index1]
phi(Sti::numtype_) where {numtype_ <: Number} = payout(Sti, euPayoff)
payoff2 = @. phi(ST)
return payoff2 * exp(-integral(r, T))
end
| FinancialMonteCarlo | https://github.com/rcalxrc08/FinancialMonteCarlo.jl.git |
|
[
"MIT"
] | 0.3.2 | 728c49a9de6ffe78fceb7bcba3b53db070fa5532 | code | 636 |
function payoff(S::AbstractMatrix{num}, payoff_::PathDependentPayoff, rfCurve::abstractZeroRateCurve, mcBaseData::AbstractMonteCarloConfiguration, T1::num2 = maturity(payoff_)) where {abstractZeroRateCurve <: AbstractZeroRateCurve, num <: Number, num2 <: Number}
r = rfCurve.r
T = payoff_.T
Nsim = mcBaseData.Nsim
NStep = mcBaseData.Nstep
index1 = round(Int, T / T1 * NStep) + 1
@inbounds f(S::abstractArray) where {abstractArray <: AbstractArray{num_}} where {num_ <: Number} = payout(S, payoff_)
@inbounds payoff2 = [f(view(S, i, 1:index1)) for i = 1:Nsim]
return payoff2 * exp(-integral(r, T))
end
| FinancialMonteCarlo | https://github.com/rcalxrc08/FinancialMonteCarlo.jl.git |
|
[
"MIT"
] | 0.3.2 | 728c49a9de6ffe78fceb7bcba3b53db070fa5532 | code | 1197 | """
Struct for Standard American Option
amOption=AmericanOption(T::num1,K::num2,isCall::Bool=true) where {num1 <: Number,num2 <: Number}
Where:
T = Time to maturity of the Option.
K = Strike Price of the Option.
isCall = true for CALL, false for PUT.
"""
struct AmericanOption{num1 <: Number, num2 <: Number, numtype <: Number} <: AmericanPayoff{numtype}
T::num1
K::num2
isCall::Bool
function AmericanOption(T::num1, K::num2, isCall::Bool = true) where {num1 <: Number, num2 <: Number}
ChainRulesCore.@ignore_derivatives @assert T > 0 "Time to Maturity must be positive"
ChainRulesCore.@ignore_derivatives @assert K > 0 "Strike Price must be positive"
zero_typed = ChainRulesCore.@ignore_derivatives zero(num1) + zero(num2)
return new{num1, num2, typeof(zero_typed)}(T, K, isCall)
end
end
export AmericanOption;
function payout(Sti::numtype_, amPayoff::AmericanOption) where {numtype_ <: Number}
iscall = ChainRulesCore.@ignore_derivatives ifelse(amPayoff.isCall, Int8(1), Int8(-1))
zero_typed = ChainRulesCore.@ignore_derivatives zero(Sti) * amPayoff.K
return max(iscall * (Sti - amPayoff.K), zero_typed)
end
| FinancialMonteCarlo | https://github.com/rcalxrc08/FinancialMonteCarlo.jl.git |
|
[
"MIT"
] | 0.3.2 | 728c49a9de6ffe78fceb7bcba3b53db070fa5532 | code | 1273 | """
Struct for Asian Fixed Strike Option
asOption=AsianFixedStrikeOption(T::num1,K::num2,isCall::Bool=true) where {num1 <: Number,num2 <: Number}
Where:
T = Time to maturity of the Option.
K = Strike Price of the Option.
isCall = true for CALL, false for PUT.
"""
struct AsianFixedStrikeOption{num1 <: Number, num2 <: Number, numtype <: Number} <: AsianPayoff{numtype}
T::num1
K::num2
isCall::Bool
function AsianFixedStrikeOption(T::num1, K::num2, isCall::Bool = true) where {num1 <: Number, num2 <: Number}
ChainRulesCore.@ignore_derivatives @assert T > 0 "Time to Maturity must be positive"
ChainRulesCore.@ignore_derivatives @assert K > 0 "Strike Price must be positive"
zero_typed = ChainRulesCore.@ignore_derivatives zero(num1) + zero(num2)
return new{num1, num2, typeof(zero_typed)}(T, K, isCall)
end
end
export AsianFixedStrikeOption;
function payout(S::abstractArray, opt_::AsianFixedStrikeOption) where {abstractArray <: AbstractArray{num_}} where {num_ <: Number}
iscall = ChainRulesCore.@ignore_derivatives ifelse(opt_.isCall, Int8(1), Int8(-1))
zero_typed = ChainRulesCore.@ignore_derivatives zero(eltype(S)) * opt_.K
return max(iscall * (mean(S) - opt_.K), zero_typed)
end
| FinancialMonteCarlo | https://github.com/rcalxrc08/FinancialMonteCarlo.jl.git |
|
[
"MIT"
] | 0.3.2 | 728c49a9de6ffe78fceb7bcba3b53db070fa5532 | code | 942 | """
Struct for Asian Floating Strike Option
asOption=AsianFloatingStrikeOption(T::num1,isCall::Bool=true) where {num1 <: Number}
Where:
T = Time to maturity of the Option.
isCall = true for CALL, false for PUT.
"""
struct AsianFloatingStrikeOption{num <: Number} <: AsianPayoff{num}
T::num
isCall::Bool
function AsianFloatingStrikeOption(T::num, isCall::Bool = true) where {num <: Number}
ChainRulesCore.@ignore_derivatives @assert T > 0 "Time to Maturity must be positive"
return new{num}(T, isCall)
end
end
export AsianFloatingStrikeOption;
function payout(S::abstractArray, opt_::AsianFloatingStrikeOption) where {abstractArray <: AbstractArray{num_}} where {num_ <: Number}
iscall = ChainRulesCore.@ignore_derivatives ifelse(opt_.isCall, Int8(1), Int8(-1))
zero_typed = ChainRulesCore.@ignore_derivatives zero(eltype(S))
return max(iscall * (S[end] - mean(S)), zero_typed)
end
| FinancialMonteCarlo | https://github.com/rcalxrc08/FinancialMonteCarlo.jl.git |
|
[
"MIT"
] | 0.3.2 | 728c49a9de6ffe78fceb7bcba3b53db070fa5532 | code | 1635 | """
Struct for Barrier Down and In Option
barOption=BarrierOptionDownIn(T::num1,K::num2,barrier::num3,isCall::Bool=true) where {num1 <: Number,num2 <: Number,num3 <: Number}
Where:
T = Time to maturity of the Option.
K = Strike Price of the Option.
barrier = Down Barrier of the Option.
isCall = true for CALL, false for PUT.
"""
struct BarrierOptionDownIn{num1 <: Number, num2 <: Number, num3 <: Number, numtype <: Number} <: BarrierPayoff{numtype}
T::num1
K::num2
barrier::num3
isCall::Bool
function BarrierOptionDownIn(T::num1, K::num2, barrier::num3, isCall::Bool = true) where {num1 <: Number, num2 <: Number, num3 <: Number}
ChainRulesCore.@ignore_derivatives @assert T > 0 "Time to Maturity must be positive"
ChainRulesCore.@ignore_derivatives @assert K > 0 "Strike Price must be positive"
ChainRulesCore.@ignore_derivatives @assert barrier > 0 "Barrier must be positive"
zero_typed = ChainRulesCore.@ignore_derivatives zero(num1) + zero(num2) + zero(num3)
return new{num1, num2, num3, typeof(zero_typed)}(T, K, barrier, isCall)
end
end
export BarrierOptionDownIn;
function payout(S::abstractArray, barrierPayoff::BarrierOptionDownIn) where {abstractArray <: AbstractArray{num_}} where {num_ <: Number}
iscall = ChainRulesCore.@ignore_derivatives ifelse(barrierPayoff.isCall, Int8(1), Int8(-1))
zero_typed = ChainRulesCore.@ignore_derivatives zero(eltype(S)) * barrierPayoff.K * barrierPayoff.barrier
return max(iscall * (S[end] - barrierPayoff.K), zero_typed) * !(findfirst(x -> x < barrierPayoff.barrier, S) === nothing)
end
| FinancialMonteCarlo | https://github.com/rcalxrc08/FinancialMonteCarlo.jl.git |
|
[
"MIT"
] | 0.3.2 | 728c49a9de6ffe78fceb7bcba3b53db070fa5532 | code | 1647 | """
Struct for Barrier Down and Out Option
barOption=BarrierOptionDownOut(T::num1,K::num2,barrier::num3,isCall::Bool=true) where {num1 <: Number,num2 <: Number,num3 <: Number}
Where:
T = Time to maturity of the Option.
K = Strike Price of the Option.
barrier = Down Barrier of the Option.
isCall = true for CALL, false for PUT.
"""
struct BarrierOptionDownOut{num1 <: Number, num2 <: Number, num3 <: Number, numtype <: Number} <: BarrierPayoff{numtype}
T::num1
K::num2
barrier::num3
isCall::Bool
function BarrierOptionDownOut(T::num1, K::num2, barrier::num3, isCall::Bool = true) where {num1 <: Number, num2 <: Number, num3 <: Number}
ChainRulesCore.@ignore_derivatives @assert T > 0 "Time to Maturity must be positive"
ChainRulesCore.@ignore_derivatives @assert K > 0 "Strike Price must be positive"
ChainRulesCore.@ignore_derivatives @assert barrier > 0 "Barrier must be positive"
zero_typed = ChainRulesCore.@ignore_derivatives zero(num1) + zero(num2) + zero(num3)
return new{num1, num2, num3, typeof(zero_typed)}(T, K, barrier, isCall)
end
end
export BarrierOptionDownOut;
function payout(S::abstractArray, barrierPayoff::BarrierOptionDownOut) where {abstractArray <: AbstractArray{num_}} where {num_ <: Number}
iscall = ChainRulesCore.@ignore_derivatives ifelse(barrierPayoff.isCall, Int8(1), Int8(-1))
zero_typed = ChainRulesCore.@ignore_derivatives zero(eltype(S)) * barrierPayoff.K * barrierPayoff.barrier
return @views max(iscall * (S[end] - barrierPayoff.K), zero_typed) * (findfirst(x -> x < barrierPayoff.barrier, S) === nothing)
end
| FinancialMonteCarlo | https://github.com/rcalxrc08/FinancialMonteCarlo.jl.git |
|
[
"MIT"
] | 0.3.2 | 728c49a9de6ffe78fceb7bcba3b53db070fa5532 | code | 1621 | """
Struct for Barrier Up and In Option
barOption=BarrierOptionUpIn(T::num1,K::num2,barrier::num3,isCall::Bool=true) where {num1 <: Number,num2 <: Number,num3 <: Number}
Where:
T = Time to maturity of the Option.
K = Strike Price of the Option.
barrier = Up Barrier of the Option.
isCall = true for CALL, false for PUT.
"""
struct BarrierOptionUpIn{num1 <: Number, num2 <: Number, num3 <: Number, numtype <: Number} <: BarrierPayoff{numtype}
T::num1
K::num2
barrier::num3
isCall::Bool
function BarrierOptionUpIn(T::num1, K::num2, barrier::num3, isCall::Bool = true) where {num1 <: Number, num2 <: Number, num3 <: Number}
ChainRulesCore.@ignore_derivatives @assert T > 0 "Time to Maturity must be positive"
ChainRulesCore.@ignore_derivatives @assert K > 0 "Strike Price must be positive"
ChainRulesCore.@ignore_derivatives @assert barrier > 0 "Barrier must be positive"
zero_typed = ChainRulesCore.@ignore_derivatives zero(num1) + zero(num2) + zero(num3)
return new{num1, num2, num3, typeof(zero_typed)}(T, K, barrier, isCall)
end
end
export BarrierOptionUpIn;
function payout(S::abstractArray, barrierPayoff::BarrierOptionUpIn) where {abstractArray <: AbstractArray{num_}} where {num_ <: Number}
iscall = ChainRulesCore.@ignore_derivatives ifelse(barrierPayoff.isCall, Int8(1), Int8(-1))
zero_typed = ChainRulesCore.@ignore_derivatives zero(eltype(S)) * barrierPayoff.K * barrierPayoff.barrier
return max(iscall * (S[end] - barrierPayoff.K), zero_typed) * !(findfirst(x -> x > barrierPayoff.barrier, S) === nothing)
end
| FinancialMonteCarlo | https://github.com/rcalxrc08/FinancialMonteCarlo.jl.git |
|
[
"MIT"
] | 0.3.2 | 728c49a9de6ffe78fceb7bcba3b53db070fa5532 | code | 1626 | """
Struct for Barrier Up and Out Option
barOption=BarrierOptionUpOut(T::num1,K::num2,barrier::num3,isCall::Bool=true) where {num1 <: Number,num2 <: Number,num3 <: Number}
Where:
T = Time to maturity of the Option.
K = Strike Price of the Option.
barrier = Up Barrier of the Option.
isCall = true for CALL, false for PUT.
"""
struct BarrierOptionUpOut{num1 <: Number, num2 <: Number, num3 <: Number, numtype <: Number} <: BarrierPayoff{numtype}
T::num1
K::num2
barrier::num3
isCall::Bool
function BarrierOptionUpOut(T::num1, K::num2, barrier::num3, isCall::Bool = true) where {num1 <: Number, num2 <: Number, num3 <: Number}
ChainRulesCore.@ignore_derivatives @assert T > 0 "Time to Maturity must be positive"
ChainRulesCore.@ignore_derivatives @assert K > 0 "Strike Price must be positive"
ChainRulesCore.@ignore_derivatives @assert barrier > 0 "Barrier must be positive"
zero_typed = ChainRulesCore.@ignore_derivatives zero(num1) + zero(num2) + zero(num3)
return new{num1, num2, num3, typeof(zero_typed)}(T, K, barrier, isCall)
end
end
export BarrierOptionUpOut;
function payout(S::abstractArray, barrierPayoff::BarrierOptionUpOut) where {abstractArray <: AbstractArray{num_}} where {num_ <: Number}
iscall = ChainRulesCore.@ignore_derivatives ifelse(barrierPayoff.isCall, Int8(1), Int8(-1))
zero_typed = ChainRulesCore.@ignore_derivatives zero(eltype(S)) * barrierPayoff.K * barrierPayoff.barrier
return max(iscall * (S[end] - barrierPayoff.K), zero_typed) * (findfirst(x -> x > barrierPayoff.barrier, S) === nothing)
end
| FinancialMonteCarlo | https://github.com/rcalxrc08/FinancialMonteCarlo.jl.git |
|
[
"MIT"
] | 0.3.2 | 728c49a9de6ffe78fceb7bcba3b53db070fa5532 | code | 1294 | """
Struct for Standard Bermudan Option
bmOption=BermudanOption(T::AbstractArray{num1},K::num2,isCall::Bool=true) where {num1 <: Number,num2 <: Number}
Where:
T = Time to maturity of the Option.
K = Strike Price of the Option.
isCall = true for CALL, false for PUT.
"""
struct BermudanOption{num1 <: Number, num2 <: Number, numtype <: Number} <: BermudanPayoff{numtype}
T::num1
T_ex::Array{num1}
K::num2
isCall::Bool
function BermudanOption(T::AbstractArray{num1}, K::num2, isCall::Bool = true) where {num1 <: Number, num2 <: Number}
ChainRulesCore.@ignore_derivatives @assert minimum(T) > 0 "Times to Maturity must be positive"
ChainRulesCore.@ignore_derivatives @assert K > 0 "Strike Price must be positive"
ChainRulesCore.@ignore_derivatives @assert issorted(T) "Times to Maturity must be sorted"
zero_typed = ChainRulesCore.@ignore_derivatives zero(num1) + zero(num2)
return new{num1, num2, typeof(zero_typed)}(T[end], T, K, isCall)
end
end
export BermudanOption;
function payout(Sti::numtype_, bmPayoff::BermudanOption) where {numtype_ <: Number}
iscall = ChainRulesCore.@ignore_derivatives ifelse(bmPayoff.isCall, Int8(1), Int8(-1))
return max((Sti - bmPayoff.K) * iscall, zero(numtype_))
end
| FinancialMonteCarlo | https://github.com/rcalxrc08/FinancialMonteCarlo.jl.git |
|
[
"MIT"
] | 0.3.2 | 728c49a9de6ffe78fceb7bcba3b53db070fa5532 | code | 1181 | """
Struct for Binary American Option
binAmOption=BinaryAmericanOption(T::num1,K::num2,isCall::Bool=true) where {num1 <: Number,num2 <: Number}
Where:
T = Time to maturity of the Option.
K = Strike Price of the Option.
isCall = true for CALL, false for PUT.
"""
struct BinaryAmericanOption{num1 <: Number, num2 <: Number, numtype <: Number} <: AmericanPayoff{numtype}
T::num1
K::num2
isCall::Bool
function BinaryAmericanOption(T::num1, K::num2, isCall::Bool = true) where {num1 <: Number, num2 <: Number}
ChainRulesCore.@ignore_derivatives @assert T > 0 "Time to Maturity must be positive"
ChainRulesCore.@ignore_derivatives @assert K > 0 "Strike Price must be positive"
zero_typed = ChainRulesCore.@ignore_derivatives zero(num1) + zero(num2)
return new{num1, num2, typeof(zero_typed)}(T, K, isCall)
end
end
export BinaryAmericanOption;
function payout(Sti::numtype_, amPayoff::BinaryAmericanOption) where {numtype_ <: Number}
iscall = ChainRulesCore.@ignore_derivatives ifelse(amPayoff.isCall, Int8(1), Int8(-1))
return ifelse((Sti - amPayoff.K) * iscall > 0.0, one(numtype_), zero(numtype_))
end
| FinancialMonteCarlo | https://github.com/rcalxrc08/FinancialMonteCarlo.jl.git |
|
[
"MIT"
] | 0.3.2 | 728c49a9de6ffe78fceb7bcba3b53db070fa5532 | code | 1345 | """
Struct for Binary European Option
binOption=BinaryEuropeanOption(T::num1,K::num2,isCall::Bool=true) where {num1 <: Number,num2 <: Number}
Where:
T = Time to maturity of the Option.
K = Strike Price of the Option.
isCall = true for CALL, false for PUT.
"""
struct BinaryEuropeanOption{num1 <: Number, num2 <: Number, numtype <: Number} <: EuropeanPayoff{numtype}
T::num1
K::num2
isCall::Bool
function BinaryEuropeanOption(T::num1, K::num2, isCall::Bool = true) where {num1 <: Number, num2 <: Number}
ChainRulesCore.@ignore_derivatives @assert T > 0 "Time to Maturity must be positive"
ChainRulesCore.@ignore_derivatives @assert K > 0 "Strike Price must be positive"
zero_typed = ChainRulesCore.@ignore_derivatives zero(num1) + zero(num2)
return new{num1, num2, typeof(zero_typed)}(T, K, isCall)
end
end
export BinaryEuropeanOption;
function payout_untyped(ST::numtype_, euPayoff::BinaryEuropeanOption) where {numtype_ <: Number}
iscall = ChainRulesCore.@ignore_derivatives ifelse(euPayoff.isCall, Int8(1), Int8(-1))
res = ifelse((ST - 1) * iscall > 0, one(numtype_), zero(numtype_))
return res
end
function payout(ST::numtype_, euPayoff::BinaryEuropeanOption) where {numtype_ <: Number}
K = euPayoff.K
return payout_untyped(ST / K, euPayoff)
end
| FinancialMonteCarlo | https://github.com/rcalxrc08/FinancialMonteCarlo.jl.git |
|
[
"MIT"
] | 0.3.2 | 728c49a9de6ffe78fceb7bcba3b53db070fa5532 | code | 1912 | """
Struct for Double Barrier Option
dbOption=DoubleBarrierOption(T::num1,K::num2,D::num3,U::num4,isCall::Bool=true) where {num1 <: Number,num2 <: Number,num3 <: Number,num4 <: Number}
Where:
T = Time to maturity of the Option.
K = Strike Price of the Option.
D = Low Barrier of the Option.
U = Up Barrier of the Option.
isCall = true for CALL, false for PUT.
"""
struct DoubleBarrierOption{num1 <: Number, num2 <: Number, num3 <: Number, num4 <: Number, numtype <: Number} <: BarrierPayoff{numtype}
T::num1
K::num2
D::num3
U::num4
isCall::Bool
function DoubleBarrierOption(T::num1, K::num2, D::num3, U::num4, isCall::Bool = true) where {num1 <: Number, num2 <: Number, num3 <: Number, num4 <: Number}
ChainRulesCore.@ignore_derivatives @assert T > 0 "Time to Maturity must be positive"
ChainRulesCore.@ignore_derivatives @assert K > 0 "Strike Price must be positive"
ChainRulesCore.@ignore_derivatives @assert D > 0 "Low Barrier must be positive"
ChainRulesCore.@ignore_derivatives @assert U > D "High Barrier must be positive and greater then Low barrier"
zero_typed = ChainRulesCore.@ignore_derivatives zero(num1) + zero(num2) + zero(num3) + zero(num4)
return new{num1, num2, num3, num4, typeof(zero_typed)}(T, K, D, U, isCall)
end
end
export DoubleBarrierOption;
function payout(S::abstractArray, barrierPayoff::DoubleBarrierOption) where {abstractArray <: AbstractArray{num_}} where {num_ <: Number}
iscall = ChainRulesCore.@ignore_derivatives ifelse(barrierPayoff.isCall, Int8(1), Int8(-1))
zero_typed = ChainRulesCore.@ignore_derivatives zero(eltype(S)) * barrierPayoff.K * barrierPayoff.U * barrierPayoff.D
return max(iscall * (S[end] - barrierPayoff.K), zero_typed) * (findfirst(x -> x < barrierPayoff.D, S) === nothing) * (findfirst(x -> x > barrierPayoff.U, S) === nothing)
end
| FinancialMonteCarlo | https://github.com/rcalxrc08/FinancialMonteCarlo.jl.git |
|
[
"MIT"
] | 0.3.2 | 728c49a9de6ffe78fceb7bcba3b53db070fa5532 | code | 1346 | """
Struct for European Option
euOption=EuropeanOption(T::num1,K::num2,isCall::Bool=true) where {num1 <: Number,num2 <: Number}
Where:
T = Time to maturity of the Option.
K = Strike Price of the Option.
isCall = true for CALL, false for PUT.
"""
struct EuropeanOption{num1 <: Number, num2 <: Number, numtype <: Number} <: EuropeanPayoff{numtype}
T::num1
K::num2
isCall::Bool
function EuropeanOption(T::num1, K::num2, isCall::Bool = true) where {num1 <: Number, num2 <: Number}
ChainRulesCore.@ignore_derivatives @assert T > 0 "Time to Maturity must be positive"
ChainRulesCore.@ignore_derivatives @assert K > 0 "Strike Price must be positive"
zero_typed = ChainRulesCore.@ignore_derivatives zero(num1) + zero(num2)
return new{num1, num2, typeof(zero_typed)}(T, K, isCall)
end
end
export EuropeanOption;
function payout_untyped(ST::numtype_, euPayoff::EuropeanOption) where {numtype_ <: Number}
iscall = ChainRulesCore.@ignore_derivatives ifelse(euPayoff.isCall, Int8(1), Int8(-1))
zero_typed = ChainRulesCore.@ignore_derivatives zero(ST)
return max(iscall * (ST - 1), zero_typed)
end
function payout(ST::numtype_, euPayoff::EuropeanOption) where {numtype_ <: Number}
K = euPayoff.K
result = K * payout_untyped(ST / K, euPayoff)
return result
end
| FinancialMonteCarlo | https://github.com/rcalxrc08/FinancialMonteCarlo.jl.git |
|
[
"MIT"
] | 0.3.2 | 728c49a9de6ffe78fceb7bcba3b53db070fa5532 | code | 800 | """
Class for Dispatching Forward Payoff
forward=Forward(T::num) where {num <: Number}
Where:
T = Time to maturity of the Forward.
"""
struct Forward{num <: Number} <: EuropeanPayoff{num}
T::num
function Forward(T::num) where {num <: Number}
ChainRulesCore.@ignore_derivatives @assert T > 0 "Time to Maturity must be positive"
return new{num}(T)
end
end
export Forward;
function payoff(S::AbstractMatrix{num}, optionData::Forward, rfCurve::AbstractZeroRateCurve, mcBaseData::AbstractMonteCarloConfiguration, T1::num2 = maturity(optionData)) where {num <: Number, num2 <: Number}
r = rfCurve.r
T = optionData.T
NStep = mcBaseData.Nstep
index1 = round(Int, T / T1 * NStep) + 1
@views ST = S[:, index1]
return ST * exp(-integral(r, T))
end
| FinancialMonteCarlo | https://github.com/rcalxrc08/FinancialMonteCarlo.jl.git |
|
[
"MIT"
] | 0.3.2 | 728c49a9de6ffe78fceb7bcba3b53db070fa5532 | code | 570 | """
Class for Dispatching Spot Payoff
spot=Spot()
"""
struct Spot <: EuropeanPayoff{Float16}
function Spot()
return new()
end
end
export Spot;
function payoff(S::AbstractMatrix{num}, optionData::Spot, ::ZeroRate, ::AbstractMonteCarloConfiguration, T1::num2 = maturity(optionData)) where {num <: Number, num2 <: Number}
S0_vec = S[:, 1]
return S0_vec
end
function pricer(mcProcess::BaseProcess, ::AbstractZeroRateCurve, ::MonteCarloConfiguration, ::Spot)
return mcProcess.underlying.S0
end
function maturity(::Spot)
return 0.0
end
| FinancialMonteCarlo | https://github.com/rcalxrc08/FinancialMonteCarlo.jl.git |
|
[
"MIT"
] | 0.3.2 | 728c49a9de6ffe78fceb7bcba3b53db070fa5532 | code | 1710 | """
Struct for European Option
euOption=EuropeanOptionND(T::num1,K::num2,isCall::Bool=true) where {num1 <: Number,num2 <: Number}
Where:
T = Time to maturity of the Option.
K = Strike Price of the Option.
isCall = true for CALL, false for PUT.
"""
struct EuropeanOptionND{num1 <: Number, num2 <: Number, numtype <: Number} <: EuropeanBasketPayoff{numtype}
T::num1
K::num2
isCall::Bool
function EuropeanOptionND(T::num1, K::num2, isCall::Bool = true) where {num1 <: Number, num2 <: Number}
ChainRulesCore.@ignore_derivatives @assert T > 0 "Time to Maturity must be positive"
ChainRulesCore.@ignore_derivatives @assert K > 0 "Strike Price must be positive"
zero_typed = ChainRulesCore.@ignore_derivatives zero(num1) + zero(num2)
return new{num1, num2, typeof(zero_typed)}(T, K, isCall)
end
end
export EuropeanOptionND;
function payoff(S::Array{abstractMatrix}, euPayoff::EuropeanOptionND, rfCurve::abstractZeroRateCurve, mcBaseData::AbstractMonteCarloConfiguration, T1::num2 = maturity(euPayoff)) where {abstractMatrix <: AbstractMatrix, num2 <: Number, abstractZeroRateCurve <: AbstractZeroRateCurve}
r = rfCurve.r
T = euPayoff.T
iscall = ChainRulesCore.@ignore_derivatives ifelse(euPayoff.isCall, Int8(1), Int8(-1))
NStep = mcBaseData.Nstep
index1 = round(Int, T / T1 * NStep) + 1
K = euPayoff.K
#ST_all=[ sum(x_i[j,index1] for x_i in S) for j in 1:Nsim]
# ST_all = S[1][:, index1]
# for i = 2:length(S)
# ST_all += S[i][:, index1]
# end
ST_all = sum(S[i][:, index1] for i = 1:length(S))
payoff2 = max.(iscall * (ST_all .- K), 0.0)
return payoff2 * exp(-integral(r, T))
end
| FinancialMonteCarlo | https://github.com/rcalxrc08/FinancialMonteCarlo.jl.git |
|
[
"MIT"
] | 0.3.2 | 728c49a9de6ffe78fceb7bcba3b53db070fa5532 | code | 3183 | ########### Curve Section
using Dictionaries
const DictTypeInternal = Dictionaries.Dictionary
const CurveType = DictTypeInternal{num1, num2} where {num1 <: Number, num2 <: Number}
function extract_keys(x::CurveType{num1, num2}) where {num1 <: Number, num2 <: Number}
return sort(collect(keys(x)))
end
function extract_values(x::CurveType{num1, num2}) where {num1 <: Number, num2 <: Number}
T_d = collect(keys(x))
idx_ = sortperm(T_d)
return collect(values(x))[idx_]
end
function Curve(r_::Array{num1}, T::num2) where {num1 <: Number, num2 <: Number}
r = DictTypeInternal{num2, num1}()
Nstep = length(r_) - 1
dt = T / Nstep
for i = 1:length(r_)
insert!(r, (i - 1) * dt, r_[i])
end
return r
end
function Curve(r_::Array{num1}, T::Array{num2}) where {num1 <: Number, num2 <: Number}
ChainRulesCore.@ignore_derivatives @assert length(r_) == length(T)
ChainRulesCore.@ignore_derivatives @assert T == sort(T)
r = DictTypeInternal{num2, num1}()
for i = 1:length(r_)
insert!(r, T[i], r_[i])
end
return r
end
function ImpliedCurve(r_::Array{num1}, T::Array{num2}) where {num1 <: Number, num2 <: Number}
ChainRulesCore.@ignore_derivatives @assert length(r_) == length(T)
ChainRulesCore.@ignore_derivatives @assert length(r_) >= 1
ChainRulesCore.@ignore_derivatives @assert T == sort(T)
r = DictTypeInternal{num2, num1}()
insert!(r, 0.0, 0.0)
insert!(r, T[1], r_[1] * 2.0)
prec_r = r_[1] * 2.0
for i = 2:length(r_)
tmp_r = (r_[i] * T[i] - r_[i-1] * T[i-1]) * 2 / (T[i] - T[i-1]) - prec_r
insert!(r, T[i], tmp_r)
prec_r = tmp_r
end
return r
end
function ImpliedCurve(r_::Array{num1}, T::num2) where {num1 <: Number, num2 <: Number}
N = length(r_)
dt_ = T / N
t_ = collect(dt_:dt_:T)
return ImpliedCurve(r_, t_)
end
function incremental_integral(x::CurveType{num1, num2}, t::Number, dt::Number) where {num1 <: Number, num2 <: Number}
T = extract_keys(x)
r = extract_values(x)
return internal_definite_integral(t + dt, T, r) - internal_definite_integral(t, T, r)
end
using Interpolations
function internal_definite_integral(x::num, T::Array{num1}, r::Array{num2}) where {num <: Number, num1 <: Number, num2 <: Number}
ChainRulesCore.@ignore_derivatives @assert length(T) == length(r)
if x == 0.0
return 0.0
end
ChainRulesCore.@ignore_derivatives @assert x >= 0.0
idx_ = findlast(y -> y < x, T)
out = sum([(r[i] + r[i+1]) * 0.5 * (T[i+1] - T[i]) for i = 1:(idx_-1)])
if x <= T[end]
itp = linear_interpolation([T[idx_], T[idx_+1]], [r[idx_], r[idx_+1]], extrapolation_bc = Flat())
out = out + (r[idx_] + itp(x)) * 0.5 * (x - T[idx_])
else
#continuation
out = out + (r[idx_] + r[idx_-1]) * 0.5 * (x - T[idx_])
end
return out
end
function integral(r::DictTypeInternal{num1, num2}, t::Number) where {num1 <: Number, num2 <: Number}
T = extract_keys(r)
values = extract_values(r)
return internal_definite_integral(t, T, values)
end
integral(x::num1, t::num2) where {num1 <: Number, num2 <: Number} = x * t;
### end curve section
| FinancialMonteCarlo | https://github.com/rcalxrc08/FinancialMonteCarlo.jl.git |
|
[
"MIT"
] | 0.3.2 | 728c49a9de6ffe78fceb7bcba3b53db070fa5532 | code | 1597 | function oper(+)
@eval import Base.$+
@eval function $+(r::DictTypeInternal{num1, num2}, d::DictTypeInternal{num1, num3}) where {num1 <: Number, num2 <: Number, num3 <: Number}
T_r = extract_keys(r)
T_d = extract_keys(d)
if (length(T_d) > length(T_r))
return $+(d, r)
end
d_complete = complete_curve(T_r, d)
val_type = typeof(zero(num2) + zero(num3))
out = DictTypeInternal{num1, val_type}()
for t in T_r
insert!(out, t, $+(r[t], d_complete[t]))
end
return out
end
@eval function $+(r::DictTypeInternal{num1, num2}, d::num3) where {num1 <: Number, num2 <: Number, num3 <: Number}
return $+.(r, d)
end
end
function oper2(+)
@eval import Base.$+
@eval function $+(d::num3, r::DictTypeInternal{num1, num2}) where {num1 <: Number, num2 <: Number, num3 <: Number}
return $+(r, d)
end
end
import Base.-
function -(d::num3, r::DictTypeInternal{num1, num2}) where {num1 <: Number, num2 <: Number, num3 <: Number}
return +(-1 * r, d)
end
oper(Symbol(+))
oper(Symbol(-))
oper(Symbol(/))
oper(Symbol(*))
oper2(Symbol(*))
oper2(Symbol(+))
function complete_curve(T::Array{num}, d::DictTypeInternal{num1, num2}) where {num <: Number, num1 <: Number, num2 <: Number}
T_d = extract_keys(d)
idx_ = sortperm(T_d)
T_d = T_d[idx_]
d_val = extract_values(d)
d_val = d_val[idx_]
out = DictTypeInternal{num1, num2}()
itp = linear_interpolation(T_d, d_val)
for t in T
insert!(out, t, itp(t))
end
return out
end
| FinancialMonteCarlo | https://github.com/rcalxrc08/FinancialMonteCarlo.jl.git |
|
[
"MIT"
] | 0.3.2 | 728c49a9de6ffe78fceb7bcba3b53db070fa5532 | code | 3976 |
abstract type AbstractMonteCarloConfiguration end
struct MonteCarloConfiguration{num1 <: Integer, num2 <: Integer, abstractMonteCarloMethod <: AbstractMonteCarloMethod, baseMode <: BaseMode} <: AbstractMonteCarloConfiguration
Nsim::num1
Nstep::num2
monteCarloMethod::abstractMonteCarloMethod
parallelMode::baseMode
init_rng::Bool
function MonteCarloConfiguration(Nsim::num1, Nstep::num2, seed::Number) where {num1 <: Integer, num2 <: Integer}
return MonteCarloConfiguration(Nsim, Nstep, StandardMC(), SerialMode(seed))
end
function MonteCarloConfiguration(Nsim::num1, Nstep::num2, monteCarloMethod::abstractMonteCarloMethod = StandardMC(), seed::Number = 0) where {num1 <: Integer, num2 <: Integer, abstractMonteCarloMethod <: AbstractMonteCarloMethod}
return MonteCarloConfiguration(Nsim, Nstep, monteCarloMethod, SerialMode(Int64(seed), MersenneTwister()))
end
function MonteCarloConfiguration(Nsim::num1, Nstep::num2, parallelMethod::baseMode) where {num1 <: Integer, num2 <: Integer, baseMode <: BaseMode}
return MonteCarloConfiguration(Nsim, Nstep, StandardMC(), parallelMethod)
end
#Most General, no default argument
function GeneralMonteCarloConfiguration(Nsim::num1, Nstep::num2, monteCarloMethod::abstractMonteCarloMethod, parallelMethod::baseMode, init_rng::Bool = true) where {num1 <: Integer, num2 <: Integer, abstractMonteCarloMethod <: AbstractMonteCarloMethod, baseMode <: BaseMode}
ChainRulesCore.@ignore_derivatives @assert Nsim > zero(num1) "Number of Simulations must be positive"
ChainRulesCore.@ignore_derivatives @assert Nstep > zero(num2) "Number of Steps must be positive"
return new{num1, num2, abstractMonteCarloMethod, baseMode}(Nsim, Nstep, monteCarloMethod, parallelMethod, init_rng)
end
function MonteCarloConfiguration(Nsim::num1, Nstep::num2, monteCarloMethod::abstractMonteCarloMethod, parallelMethod::baseMode, init_rng::Bool) where {num1 <: Integer, num2 <: Integer, abstractMonteCarloMethod <: AbstractMonteCarloMethod, baseMode <: BaseMode}
ChainRulesCore.@ignore_derivatives @assert Nsim > zero(num1) "Number of Simulations must be positive"
ChainRulesCore.@ignore_derivatives @assert Nstep > zero(num2) "Number of Steps must be positive"
return GeneralMonteCarloConfiguration(Nsim, Nstep, monteCarloMethod, parallelMethod, init_rng)
end
function MonteCarloConfiguration(Nsim::num1, Nstep::num2, monteCarloMethod::abstractMonteCarloMethod, parallelMethod::baseMode) where {num1 <: Integer, num2 <: Integer, abstractMonteCarloMethod <: AbstractMonteCarloMethod, baseMode <: BaseMode}
return GeneralMonteCarloConfiguration(Nsim, Nstep, monteCarloMethod, parallelMethod)
end
function MonteCarloConfiguration(Nsim::num1, Nstep::num2, monteCarloMethod::AntitheticMC, parallelMethod::baseMode = SerialMode()) where {num1 <: Integer, num2 <: Integer, baseMode <: BaseMode}
ChainRulesCore.@ignore_derivatives @assert iseven(Nsim) "Antithetic support only even number of simulations"
return GeneralMonteCarloConfiguration(Nsim, Nstep, monteCarloMethod, parallelMethod)
end
end
SerialMonteCarloConfig = MonteCarloConfiguration{num1, num2, num3, ser_mode} where {num1 <: Integer, num2 <: Integer, num3 <: FinancialMonteCarlo.AbstractMonteCarloMethod, ser_mode <: FinancialMonteCarlo.SerialMode{rng_}} where {rng_ <: Random.AbstractRNG}
SerialAntitheticMonteCarloConfig = MonteCarloConfiguration{num1, num2, num3, ser_mode} where {num1 <: Integer, num2 <: Integer, num3 <: FinancialMonteCarlo.AntitheticMC, ser_mode <: FinancialMonteCarlo.SerialMode{rng_}} where {rng_ <: Random.AbstractRNG}
SerialSobolMonteCarloConfig = MonteCarloConfiguration{num1, num2, num3, ser_mode} where {num1 <: Integer, num2 <: Integer, num3 <: FinancialMonteCarlo.SobolMode, ser_mode <: FinancialMonteCarlo.SerialMode{rng_}} where {rng_ <: Random.AbstractRNG}
export MonteCarloConfiguration;
| FinancialMonteCarlo | https://github.com/rcalxrc08/FinancialMonteCarlo.jl.git |
|
[
"MIT"
] | 0.3.2 | 728c49a9de6ffe78fceb7bcba3b53db070fa5532 | code | 727 | #Parallel Modes
abstract type BaseMode end
struct SerialMode{rngType <: Random.AbstractRNG} <: BaseMode
seed::Int64
rng::rngType
function SerialMode(seed::num = 0, rng::rngType = MersenneTwister()) where {num <: Integer, rngType <: Random.AbstractRNG}
return new{rngType}(Int64(seed), rng)
end
end
abstract type ParallelMode <: BaseMode end
#Numerical Modes, keyholes for modes different than Monte Carlo
abstract type AbstractMethod end
abstract type AbstractMonteCarloMethod <: AbstractMethod end
struct StandardMC <: AbstractMonteCarloMethod end
struct AntitheticMC <: AbstractMonteCarloMethod end
struct SobolMode <: AbstractMonteCarloMethod end
struct PrescribedMC <: AbstractMonteCarloMethod end
| FinancialMonteCarlo | https://github.com/rcalxrc08/FinancialMonteCarlo.jl.git |
|
[
"MIT"
] | 0.3.2 | 728c49a9de6ffe78fceb7bcba3b53db070fa5532 | code | 93 | get_rng_type(::T) where {T <: AbstractFloat} = zero(T);
get_rng_type(::Any) = zero(Float64);
| FinancialMonteCarlo | https://github.com/rcalxrc08/FinancialMonteCarlo.jl.git |
|
[
"MIT"
] | 0.3.2 | 728c49a9de6ffe78fceb7bcba3b53db070fa5532 | code | 258 | abstract type AbstractSimResult end
struct SimResult{num_ <: Number, num_2 <: Number, time_array <: AbstractArray{num_}, sim_matrix <: AbstractMatrix{num_2}} <: AbstractSimResult
times::time_array
sim_result::sim_matrix
initial_value::num_2
end
| FinancialMonteCarlo | https://github.com/rcalxrc08/FinancialMonteCarlo.jl.git |
|
[
"MIT"
] | 0.3.2 | 728c49a9de6ffe78fceb7bcba3b53db070fa5532 | code | 1202 | ###########Underlying Types
#Abstract
abstract type AbstractUnderlying end
#Scalar dividend
struct UnderlyingScalar{num <: Number, num2 <: Number} <: AbstractUnderlying
S0::num
d::num2
function UnderlyingScalar(S0::num_, d::num_2 = 0.0) where {num_ <: Number, num_2 <: Number}
ChainRulesCore.@ignore_derivatives @assert S0 >= zero(num_) "Underlying starting value must be positive"
return new{num_, num_2}(S0, d)
end
end
#Curve dividend
struct UnderlyingVec{num <: Number, num2 <: Number, num3 <: Number} <: AbstractUnderlying
S0::num
d::CurveType{num2, num3}
function UnderlyingVec(S0::num_, d::CurveType{num2, num3}) where {num_ <: Number, num2 <: Number, num3 <: Number}
ChainRulesCore.@ignore_derivatives @assert S0 >= zero(num_) "Underlying starting value must be positive"
return new{num_, num2, num3}(S0, d)
end
end
#Common Constructors
function Underlying(S0::num_, d::CurveType{num2, num3}) where {num_ <: Number, num2 <: Number, num3 <: Number}
return UnderlyingVec(S0, d)
end
function Underlying(S0::num_, d::num_2 = 0.0) where {num_ <: Number, num_2 <: Number}
return UnderlyingScalar(S0, d)
end
export Underlying;
| FinancialMonteCarlo | https://github.com/rcalxrc08/FinancialMonteCarlo.jl.git |
|
[
"MIT"
] | 0.3.2 | 728c49a9de6ffe78fceb7bcba3b53db070fa5532 | code | 1100 | ###########Zero Rate Curve Types
#Abstract
abstract type AbstractZeroRateCurve end
#Scalar
struct ZeroRate{T2 <: Number} <: AbstractZeroRateCurve
r::T2
function ZeroRate(r::T2) where {T2 <: Number}
return new{T2}(r)
end
end
#Curve
struct ZeroRateCurve{num1 <: Number, num2 <: Number} <: AbstractZeroRateCurve
r::CurveType{num1, num2}
function ZeroRateCurve(r_::Array{num1}, T::num2) where {num1 <: Number, num2 <: Number}
new{num2, num1}(Curve(r_, T))
end
function ZeroRateCurve(r_::CurveType{num1, num2}) where {num1 <: Number, num2 <: Number}
new{num2, num1}(r_)
end
end
#Common Constructors
function ZeroRate(r_::Array{num1}, T::num2) where {num1 <: Number, num2 <: Number}
return ZeroRateCurve(r_, T)
end
function ImpliedZeroRate(r_::Array{num1}, T::num2) where {num1 <: Number, num2 <: Number}
return ZeroRateCurve(ImpliedCurve(r_, T))
end
function ImpliedZeroRate(r_::Array{num1}, T::Array{num2}) where {num1 <: Number, num2 <: Number}
return ZeroRateCurve(ImpliedCurve(r_, T))
end
export ZeroRateCurve;
export ZeroRate;
| FinancialMonteCarlo | https://github.com/rcalxrc08/FinancialMonteCarlo.jl.git |
|
[
"MIT"
] | 0.3.2 | 728c49a9de6ffe78fceb7bcba3b53db070fa5532 | code | 810 | using FinancialMonteCarlo
path1 = joinpath(dirname(pathof(FinancialMonteCarlo)), "..", "test")
test_listTmp = readdir(path1);
BlackList = ["REQUIRE", "runtests.jl", "Project.toml", "Manifest.toml", "cuda", "af", "wip", "test_black_rev_diff.jl", "test_black_pre.jl"];
func_scope(x::String) = include(x);
return nothing;
test_list = [test_element for test_element in test_listTmp if !any(x -> x == test_element, BlackList)]
println("Running tests:\n")
for (current_test, i) in zip(test_list, 1:length(test_list))
println("------------------------------------------------------------")
println(" * $(current_test) *")
func_scope(joinpath(path1, current_test))
println("------------------------------------------------------------")
if (i < length(test_list))
println("")
end
end
| FinancialMonteCarlo | https://github.com/rcalxrc08/FinancialMonteCarlo.jl.git |
|
[
"MIT"
] | 0.3.2 | 728c49a9de6ffe78fceb7bcba3b53db070fa5532 | code | 4915 | using Test, FinancialMonteCarlo;
@show "Black Scholes Model"
S0 = 100.0;
K = 100.0;
r = 0.02;
T = 1.0;
d = 0.01;
D = 90.0;
Nsim = 10000;
Nstep = 30;
sigma = 0.2;
mc = MonteCarloConfiguration(Nsim, Nstep);
mc1 = MonteCarloConfiguration(Nsim, Nstep, FinancialMonteCarlo.AntitheticMC());
toll = 0.8
rfCurve = ZeroRate(r);
FwdData = Forward(T)
@test FinancialMonteCarlo.get_parameters(FwdData)[1] == T
EUData = EuropeanOption(T, K)
EUBin = BinaryEuropeanOption(T, K)
AMData = AmericanOption(T, K)
AmBin = BinaryEuropeanOption(T, K)
BarrierData = BarrierOptionDownOut(T, K, D)
AsianFloatingStrikeData = AsianFloatingStrikeOption(T)
AsianFixedStrikeData = AsianFixedStrikeOption(T, K)
Model = BlackScholesProcess(0.1, Underlying(S0, d));
param_ = FinancialMonteCarlo.get_parameters(Model)
@test param_[1] == 0.1
Model = FinancialMonteCarlo.set_parameters!(Model, [sigma])
@test Model.σ == sigma
display(Model)
@show spot = pricer(Model, rfCurve, mc, Spot());
@show FwdPrice = pricer(Model, rfCurve, mc, FwdData);
@show EuPrice = pricer(Model, rfCurve, mc, EUData);
@show EuBinPrice = pricer(Model, rfCurve, mc, EUBin);
@show AmPrice = pricer(Model, rfCurve, mc, AMData);
@show AmBinPrice = pricer(Model, rfCurve, mc, AmBin);
@show BarrierPrice = pricer(Model, rfCurve, mc, BarrierData);
@show AsianPrice1 = pricer(Model, rfCurve, mc, AsianFloatingStrikeData);
@show AsianPrice2 = pricer(Model, rfCurve, mc, AsianFixedStrikeData);
@test abs(FwdPrice - 99.1078451563562) < toll
@test abs(EuPrice - 8.43005524824866) < toll
@test abs(AmPrice - 8.450489415187354) < toll
@test abs(BarrierPrice - 7.5008664470880735) < toll
@test abs(AsianPrice1 - 4.774451704549382) < toll
@show FwdPrice = pricer(Model, rfCurve, mc1, FwdData);
@show EuPrice = pricer(Model, rfCurve, mc1, EUData);
@show AmPrice = pricer(Model, rfCurve, mc1, AMData);
@show BarrierPrice = pricer(Model, rfCurve, mc1, BarrierData);
@show AsianPrice1 = pricer(Model, rfCurve, mc1, AsianFloatingStrikeData);
@show AsianPrice2 = pricer(Model, rfCurve, mc1, AsianFixedStrikeData);
tollanti = 0.6;
@test abs(FwdPrice - 99.1078451563562) < tollanti
@test abs(EuPrice - 8.43005524824866) < tollanti
@test abs(AmPrice - 8.450489415187354) < tollanti
@test abs(BarrierPrice - 7.5008664470880735) < tollanti
@test abs(AsianPrice1 - 4.774451704549382) < tollanti
EUDataPut = EuropeanOption(T, K, false)
AMDataPut = AmericanOption(T, K, false)
BarrierDataPut = BarrierOptionDownOut(T, K, D, false)
AsianFloatingStrikeDataPut = AsianFloatingStrikeOption(T, false)
AsianFixedStrikeDataPut = AsianFixedStrikeOption(T, K, false)
@show EuPrice = pricer(Model, rfCurve, mc, EUDataPut);
@show AmPrice = pricer(Model, rfCurve, mc, AMDataPut);
@show BarrierPrice = pricer(Model, rfCurve, mc, BarrierDataPut);
@show AsianPrice1 = pricer(Model, rfCurve, mc, AsianFloatingStrikeDataPut);
@show AsianPrice2 = pricer(Model, rfCurve, mc, AsianFixedStrikeDataPut);
tollPut = 0.6;
@test abs(FwdPrice - 99.1078451563562) < tollPut
@test abs(EuPrice - 7.342077422567968) < tollPut
@test abs(AmPrice - 7.467065889603365) < tollPut
@test abs(BarrierPrice - 0.29071929104261723) < tollPut
@test abs(AsianPrice1 - 4.230547012372306) < tollPut
@test abs(AsianPrice2 - 4.236220218194027) < tollPut
@test_throws(AssertionError, MonteCarloConfiguration(Nsim + 1, Nstep, FinancialMonteCarlo.AntitheticMC()));
mc1 = MonteCarloConfiguration(Nsim, Nstep, FinancialMonteCarlo.AntitheticMC());
@test variance(Model, rfCurve, mc, EUDataPut) > variance(Model, rfCurve, mc1, EUDataPut);
@test prod(variance(Model, rfCurve, mc, [EUDataPut, AMDataPut]) .>= variance(Model, rfCurve, mc1, [EUDataPut, AMDataPut]));
IC1 = confinter(Model, rfCurve, mc, EUDataPut);
IC2 = confinter(Model, rfCurve, mc1, EUDataPut, 0.99);
L1 = IC1[2] - IC1[1]
L2 = IC2[2] - IC2[1]
@test L1 > L2
IC1 = confinter(Model, rfCurve, mc, [EUDataPut, AMDataPut]);
IC2 = confinter(Model, rfCurve, mc1, [EUDataPut, AMDataPut], 0.99);
L1 = IC1[2][2] - IC1[2][1]
L2 = IC2[2][2] - IC2[2][1]
@test L1 > L2
############## Complete Options
EUDataBin = BinaryEuropeanOption(T, K)
BinAMData = BinaryAmericanOption(T, K)
BarrierDataDI = BarrierOptionDownIn(T, K, D)
BarrierDataUI = BarrierOptionUpIn(T, K, D)
BarrierDataUO = BarrierOptionUpOut(T, K, D)
BermData = BermudanOption(collect(0.2:0.1:T), K);
doubleBarrierOptionDownOut = DoubleBarrierOption(T, K, K / 10.0, 1.2 * K)
@show BarrierPrice = pricer(Model, rfCurve, mc, BarrierDataDI);
@show BarrierPrice = pricer(Model, rfCurve, mc, BarrierDataUI);
@show BarrierPrice = pricer(Model, rfCurve, mc, BarrierDataUO);
@show BermPrice = pricer(Model, rfCurve, mc, BermData);
@show AmBinPrice = pricer(Model, rfCurve, mc, BinAMData);
@show EuBinPrice = pricer(Model, rfCurve, mc, EUDataBin);
@show doubleBarrier = pricer(Model, rfCurve, mc, doubleBarrierOptionDownOut);
@show "Test Black Scholes Parameters"
@test_throws(AssertionError, BlackScholesProcess(-sigma, Underlying(S0, d)))
| FinancialMonteCarlo | https://github.com/rcalxrc08/FinancialMonteCarlo.jl.git |
|
[
"MIT"
] | 0.3.2 | 728c49a9de6ffe78fceb7bcba3b53db070fa5532 | code | 1649 | using Test, FinancialMonteCarlo, Statistics;
@show "Black Scholes Model"
S0 = 100.0;
K = 100.0;
r = [0.00, 0.02];
T = 1.0;
d = FinancialMonteCarlo.Curve([0.019, 0.019, 0.02], T);
D = 90.0;
Nsim = 100000;
Nstep = 30;
sigma = 0.2;
mc = MonteCarloConfiguration(Nsim, Nstep);
mc1 = MonteCarloConfiguration(Nsim, Nstep, FinancialMonteCarlo.AntitheticMC());
toll = 1.8
rfCurve = ZeroRate(r, T);
FwdData = Forward(T)
EUData = EuropeanOption(T, K)
EUBin = BinaryEuropeanOption(T, K)
AMData = AmericanOption(T, K)
AmBin = BinaryEuropeanOption(T, K)
BarrierData = BarrierOptionDownOut(T, K, D)
AsianFloatingStrikeData = AsianFloatingStrikeOption(T)
AsianFixedStrikeData = AsianFixedStrikeOption(T, K)
Model = BlackScholesProcess(sigma, Underlying(S0, d));
display(Model)
@show FwdPrice = pricer(Model, rfCurve, mc1, FwdData);
@show FwdPrice = pricer(Model, rfCurve, mc, FwdData);
@show EuPrice = pricer(Model, rfCurve, mc, EUData);
@show EuBinPrice = pricer(Model, rfCurve, mc, EUBin);
@show AmPrice = pricer(Model, rfCurve, mc, AMData);
@show AmBinPrice = pricer(Model, rfCurve, mc, AmBin);
@show BarrierPrice = pricer(Model, rfCurve, mc, BarrierData);
@show AsianPrice1 = pricer(Model, rfCurve, mc, AsianFloatingStrikeData);
@show AsianPrice2 = pricer(Model, rfCurve, mc, AsianFixedStrikeData);
@test abs(FwdPrice - 99.1078451563562) < toll
@test abs(EuPrice - 8.43005524824866) < toll
@test abs(AmPrice - 8.450489415187354) < toll
@test abs(BarrierPrice - 7.5008664470880735) < toll
@test abs(AsianPrice1 - 4.774451704549382) < toll
@show "Test Black Scholes Parameters"
@test_throws(AssertionError, BlackScholesProcess(-sigma, Underlying(S0, d)))
| FinancialMonteCarlo | https://github.com/rcalxrc08/FinancialMonteCarlo.jl.git |
|
[
"MIT"
] | 0.3.2 | 728c49a9de6ffe78fceb7bcba3b53db070fa5532 | code | 1882 | using Test, FinancialMonteCarlo, DualNumbers;
@show "Black Scholes Model"
S0 = 100.0;
K = 100.0;
r = 0.02;
T = 1.0;
d = 0.01;
D = 90.0;
Nsim = 10000;
Nstep = 30;
sigma = dual(0.2, 1.0);
mc = MonteCarloConfiguration(Nsim, Nstep);
mc1 = MonteCarloConfiguration(Nsim, Nstep, FinancialMonteCarlo.AntitheticMC());
toll = 0.8
rfCurve = ZeroRate(r);
FwdData = Forward(T)
EUData = EuropeanOption(T, K)
AMData = AmericanOption(T, K)
BarrierData = BarrierOptionDownOut(T, K, D)
AsianFloatingStrikeData = AsianFloatingStrikeOption(T)
AsianFixedStrikeData = AsianFixedStrikeOption(T, K)
Model = BlackScholesProcess(sigma, Underlying(S0, d));
@show FwdPrice = pricer(Model, rfCurve, mc, FwdData);
@show EuPrice = pricer(Model, rfCurve, mc, EUData);
@show AmPrice = pricer(Model, rfCurve, mc, AMData);
@show BarrierPrice = pricer(Model, rfCurve, mc, BarrierData);
@show AsianPrice1 = pricer(Model, rfCurve, mc, AsianFloatingStrikeData);
@show AsianPrice2 = pricer(Model, rfCurve, mc, AsianFixedStrikeData);
@test abs(FwdPrice - 99.1078451563562) < toll
@test abs(EuPrice - 8.43005524824866) < toll
@test abs(AmPrice - 8.450489415187354) < toll
@test abs(BarrierPrice - 7.5008664470880735) < toll
@test abs(AsianPrice1 - 4.774451704549382) < toll
@show FwdPrice = pricer(Model, rfCurve, mc1, FwdData);
@show EuPrice = pricer(Model, rfCurve, mc1, EUData);
@show AmPrice = pricer(Model, rfCurve, mc1, AMData);
@show BarrierPrice = pricer(Model, rfCurve, mc1, BarrierData);
@show AsianPrice1 = pricer(Model, rfCurve, mc1, AsianFloatingStrikeData);
@show AsianPrice2 = pricer(Model, rfCurve, mc1, AsianFixedStrikeData);
tollanti = 0.6;
@test abs(FwdPrice - 99.1078451563562) < tollanti
@test abs(EuPrice - 8.43005524824866) < tollanti
@test abs(AmPrice - 8.450489415187354) < tollanti
@test abs(BarrierPrice - 7.5008664470880735) < tollanti
@test abs(AsianPrice1 - 4.774451704549382) < tollanti
| FinancialMonteCarlo | https://github.com/rcalxrc08/FinancialMonteCarlo.jl.git |
|
[
"MIT"
] | 0.3.2 | 728c49a9de6ffe78fceb7bcba3b53db070fa5532 | code | 786 | using FinancialMonteCarlo, ForwardDiff;
@show "Black Scholes Model"
S0 = 100.0;
K = 100.0;
r = 0.02;
T = 1.0;
d = 0.01;
D = 90.0;
Nsim = 10000;
Nstep = 30;
sigma = 0.2
mc = MonteCarloConfiguration(Nsim, Nstep);
mc1 = MonteCarloConfiguration(Nsim, Nstep, FinancialMonteCarlo.AntitheticMC());
toll = 0.8
rfCurve = ZeroRate(r);
FwdData = Forward(T)
EUData = EuropeanOption(T, K)
AMData = AmericanOption(T, K)
BarrierData = BarrierOptionDownOut(T, K, D)
AsianFloatingStrikeData = AsianFloatingStrikeOption(T)
AsianFixedStrikeData = AsianFixedStrikeOption(T, K)
Model = BlackScholesProcess(sigma, Underlying(S0, d));
f(x::Vector) = pricer(BlackScholesProcess(x[1], Underlying(x[2], d)), ZeroRate(r), mc, EUData);
x = Float64[sigma, S0]
g = x -> ForwardDiff.gradient(f, x);
@show g(x)
| FinancialMonteCarlo | https://github.com/rcalxrc08/FinancialMonteCarlo.jl.git |
|
[
"MIT"
] | 0.3.2 | 728c49a9de6ffe78fceb7bcba3b53db070fa5532 | code | 1856 | using Test, FinancialMonteCarlo, ForwardDiff;
@show "Black Scholes Model"
S0 = 100.0;
K = 100.0;
r = 0.02;
T = 1.0;
d = 0.01;
D = 90.0;
Nsim = 10000;
Nstep = 30;
sigma = ForwardDiff.Dual{Float64}(0.2, 1.0)
mc = MonteCarloConfiguration(Nsim, Nstep);
mc1 = MonteCarloConfiguration(Nsim, Nstep, FinancialMonteCarlo.AntitheticMC());
toll = 0.8
rfCurve = ZeroRate(r);
FwdData = Forward(T)
EUData = EuropeanOption(T, K)
AMData = AmericanOption(T, K)
BarrierData = BarrierOptionDownOut(T, K, D)
AsianFloatingStrikeData = AsianFloatingStrikeOption(T)
AsianFixedStrikeData = AsianFixedStrikeOption(T, K)
Model = BlackScholesProcess(sigma, Underlying(S0, d));
@show FwdPrice = pricer(Model, rfCurve, mc, FwdData);
@show EuPrice = pricer(Model, rfCurve, mc, EUData);
@show AmPrice = pricer(Model, rfCurve, mc, AMData);
@show BarrierPrice = pricer(Model, rfCurve, mc, BarrierData);
@show AsianPrice1 = pricer(Model, rfCurve, mc, AsianFloatingStrikeData);
@show AsianPrice2 = pricer(Model, rfCurve, mc, AsianFixedStrikeData);
@test abs(FwdPrice - 99.1078451563562) < toll
@test abs(EuPrice - 8.43005524824866) < toll
@test abs(BarrierPrice - 7.5008664470880735) < toll
@test abs(AsianPrice1 - 4.774451704549382) < toll
@show FwdPrice = pricer(Model, rfCurve, mc1, FwdData);
@show EuPrice = pricer(Model, rfCurve, mc1, EUData);
@show AmPrice = pricer(Model, rfCurve, mc1, AMData);
@show BarrierPrice = pricer(Model, rfCurve, mc1, BarrierData);
@show AsianPrice1 = pricer(Model, rfCurve, mc1, AsianFloatingStrikeData);
@show AsianPrice2 = pricer(Model, rfCurve, mc1, AsianFixedStrikeData);
tollanti = 0.6;
@test abs(FwdPrice - 99.1078451563562) < tollanti
@test abs(EuPrice - 8.43005524824866) < tollanti
@test abs(AmPrice - 8.450489415187354) < tollanti
@test abs(BarrierPrice - 7.5008664470880735) < tollanti
@test abs(AsianPrice1 - 4.774451704549382) < tollanti
| FinancialMonteCarlo | https://github.com/rcalxrc08/FinancialMonteCarlo.jl.git |
|
[
"MIT"
] | 0.3.2 | 728c49a9de6ffe78fceb7bcba3b53db070fa5532 | code | 678 | using FinancialMonteCarlo, Distributed
S0 = 100.0;
K = 100.0;
r = 0.02;
T = 1.0;
d = 0.01;
D = 90.0;
Nsim = 10000;
Nstep = 30;
sigma = 0.2;
mc = MonteCarloConfiguration(Nsim, Nstep, FinancialMonteCarlo.MultiProcess());
toll = 1.0;
rfCurve = ZeroRate(r);
FwdData = Forward(T)
EUData = EuropeanOption(T, K)
AMData = AmericanOption(T, K)
BarrierData = BarrierOptionDownOut(T, K, D)
AsianFloatingStrikeData = AsianFloatingStrikeOption(T)
AsianFixedStrikeData = AsianFixedStrikeOption(T, K)
Model = BlackScholesProcess(sigma, Underlying(S0, d));
EuPrice = pricer(Model, rfCurve, mc, EUData);
pricer(Model, rfCurve, mc, [EUData, EUData]);
@test abs(EuPrice - 8.43005524824866) < toll | FinancialMonteCarlo | https://github.com/rcalxrc08/FinancialMonteCarlo.jl.git |
|
[
"MIT"
] | 0.3.2 | 728c49a9de6ffe78fceb7bcba3b53db070fa5532 | code | 673 | using FinancialMonteCarlo, Test
S0 = 100.0;
K = 100.0;
r = 0.02;
T = 1.0;
d = 0.01;
D = 90.0;
Nsim = 10000;
Nstep = 30;
sigma = 0.2;
mc = MonteCarloConfiguration(Nsim, Nstep, FinancialMonteCarlo.MultiThreading());
toll = 1.0;
rfCurve = ZeroRate(r);
FwdData = Forward(T)
EUData = EuropeanOption(T, K)
AMData = AmericanOption(T, K)
BarrierData = BarrierOptionDownOut(T, K, D)
AsianFloatingStrikeData = AsianFloatingStrikeOption(T)
AsianFixedStrikeData = AsianFixedStrikeOption(T, K)
Model = BlackScholesProcess(sigma, Underlying(S0, d));
EuPrice = pricer(Model, rfCurve, mc, EUData);
pricer(Model, rfCurve, mc, [EUData, EUData]);
@test abs(EuPrice - 8.43005524824866) < toll | FinancialMonteCarlo | https://github.com/rcalxrc08/FinancialMonteCarlo.jl.git |
|
[
"MIT"
] | 0.3.2 | 728c49a9de6ffe78fceb7bcba3b53db070fa5532 | code | 4581 | using Test, FinancialMonteCarlo;
@show "Black Scholes Model"
S0 = 100.0;
K = 100.0;
r = 0.02;
T = 1.0;
d = 0.01;
D = 90.0;
Nsim = 1000;
Nstep = 30;
sigma = 0.2;
mc = MonteCarloConfiguration(Nsim, Nstep, FinancialMonteCarlo.PrescribedMC());
mc1 = MonteCarloConfiguration(Nsim, Nstep, FinancialMonteCarlo.AntitheticMC());
toll = 0.8
rfCurve = ZeroRate(r);
FwdData = Forward(T)
EUData = EuropeanOption(T, K)
EUBin = BinaryEuropeanOption(T, K)
AMData = AmericanOption(T, K)
AmBin = BinaryEuropeanOption(T, K)
BarrierData = BarrierOptionDownOut(T, K, D)
AsianFloatingStrikeData = AsianFloatingStrikeOption(T)
AsianFixedStrikeData = AsianFixedStrikeOption(T, K)
Model = BlackScholesProcess(sigma, Underlying(S0, d));
display(Model)
@show FwdPrice = pricer(Model, rfCurve, mc, FwdData);
@show EuPrice = pricer(Model, rfCurve, mc, EUData);
@show EuBinPrice = pricer(Model, rfCurve, mc, EUBin);
@show AmPrice = pricer(Model, rfCurve, mc, AMData);
@show AmBinPrice = pricer(Model, rfCurve, mc, AmBin);
@show BarrierPrice = pricer(Model, rfCurve, mc, BarrierData);
@show AsianPrice1 = pricer(Model, rfCurve, mc, AsianFloatingStrikeData);
@show AsianPrice2 = pricer(Model, rfCurve, mc, AsianFixedStrikeData);
@test abs(FwdPrice - 99.1078451563562) < toll
@test abs(EuPrice - 8.43005524824866) < toll
@test abs(AmPrice - 8.450489415187354) < toll
@test abs(BarrierPrice - 7.5008664470880735) < toll
@test abs(AsianPrice1 - 4.774451704549382) < toll
@show FwdPrice = pricer(Model, rfCurve, mc1, FwdData);
@show EuPrice = pricer(Model, rfCurve, mc1, EUData);
@show AmPrice = pricer(Model, rfCurve, mc1, AMData);
@show BarrierPrice = pricer(Model, rfCurve, mc1, BarrierData);
@show AsianPrice1 = pricer(Model, rfCurve, mc1, AsianFloatingStrikeData);
@show AsianPrice2 = pricer(Model, rfCurve, mc1, AsianFixedStrikeData);
tollanti = 0.6;
@test abs(FwdPrice - 99.1078451563562) < tollanti
@test abs(EuPrice - 8.43005524824866) < tollanti
@test abs(AmPrice - 8.450489415187354) < tollanti
@test abs(BarrierPrice - 7.5008664470880735) < tollanti
@test abs(AsianPrice1 - 4.774451704549382) < tollanti
EUDataPut = EuropeanOption(T, K, false)
AMDataPut = AmericanOption(T, K, false)
BarrierDataPut = BarrierOptionDownOut(T, K, D, false)
AsianFloatingStrikeDataPut = AsianFloatingStrikeOption(T, false)
AsianFixedStrikeDataPut = AsianFixedStrikeOption(T, K, false)
@show EuPrice = pricer(Model, rfCurve, mc, EUDataPut);
@show AmPrice = pricer(Model, rfCurve, mc, AMDataPut);
@show BarrierPrice = pricer(Model, rfCurve, mc, BarrierDataPut);
@show AsianPrice1 = pricer(Model, rfCurve, mc, AsianFloatingStrikeDataPut);
@show AsianPrice2 = pricer(Model, rfCurve, mc, AsianFixedStrikeDataPut);
tollPut = 0.6;
@test abs(FwdPrice - 99.1078451563562) < tollPut
@test abs(EuPrice - 7.342077422567968) < tollPut
@test abs(AmPrice - 7.467065889603365) < tollPut
@test abs(BarrierPrice - 0.29071929104261723) < tollPut
@test abs(AsianPrice1 - 4.230547012372306) < tollPut
@test abs(AsianPrice2 - 4.236220218194027) < tollPut
@test_throws(AssertionError, MonteCarloConfiguration(Nsim + 1, Nstep, FinancialMonteCarlo.AntitheticMC()));
mc1 = MonteCarloConfiguration(Nsim, Nstep, FinancialMonteCarlo.AntitheticMC());
@test variance(Model, rfCurve, mc, EUDataPut) > variance(Model, rfCurve, mc1, EUDataPut);
@test prod(variance(Model, rfCurve, mc, [EUDataPut, AMDataPut]) .>= variance(Model, rfCurve, mc1, [EUDataPut, AMDataPut]));
IC1 = confinter(Model, rfCurve, mc, EUDataPut);
IC2 = confinter(Model, rfCurve, mc1, EUDataPut, 0.99);
L1 = IC1[2] - IC1[1]
L2 = IC2[2] - IC2[1]
@test L1 > L2
IC1 = confinter(Model, rfCurve, mc, [EUDataPut, AMDataPut]);
IC2 = confinter(Model, rfCurve, mc1, [EUDataPut, AMDataPut], 0.99);
L1 = IC1[2][2] - IC1[2][1]
L2 = IC2[2][2] - IC2[2][1]
@test L1 > L2
############## Complete Options
EUDataBin = BinaryEuropeanOption(T, K)
BinAMData = BinaryAmericanOption(T, K)
BarrierDataDI = BarrierOptionDownIn(T, K, D)
BarrierDataUI = BarrierOptionUpIn(T, K, D)
BarrierDataUO = BarrierOptionUpOut(T, K, D)
doubleBarrierOptionDownOut = DoubleBarrierOption(T, K, K / 10.0, 1.2 * K)
@show BarrierPrice = pricer(Model, rfCurve, mc, BarrierDataDI);
@show BarrierPrice = pricer(Model, rfCurve, mc, BarrierDataUI);
@show BarrierPrice = pricer(Model, rfCurve, mc, BarrierDataUO);
@show AmBinPrice = pricer(Model, rfCurve, mc, BinAMData);
@show EuBinPrice = pricer(Model, rfCurve, mc, EUDataBin);
@show doubleBarrier = pricer(Model, rfCurve, mc, doubleBarrierOptionDownOut);
@show "Test Black Scholes Parameters"
@test_throws(AssertionError, BlackScholesProcess(-sigma, Underlying(S0, d)))
| FinancialMonteCarlo | https://github.com/rcalxrc08/FinancialMonteCarlo.jl.git |
|
[
"MIT"
] | 0.3.2 | 728c49a9de6ffe78fceb7bcba3b53db070fa5532 | code | 1194 | using FinancialMonteCarlo, ReverseDiff;
@show "Black Scholes Model"
S0 = 100.0;
K = 100.0;
r = 0.02;
T = 1.0;
d = 0.01;
D = 90.0;
Nsim = 10000;
Nstep = 30;
sigma = 0.2
mc = MonteCarloConfiguration(Nsim, Nstep);
mc1 = MonteCarloConfiguration(Nsim, Nstep, FinancialMonteCarlo.AntitheticMC());
toll = 0.8
rfCurve = ZeroRate(r);
Model = BlackScholesProcess(sigma, Underlying(S0, d));
x = Float64[sigma, S0, r, d, T]
@show ReverseDiff.gradient(x -> pricer(BlackScholesProcess(x[1]), ZeroRate(x[2], x[3], x[4]), mc, Forward(x[5])), x)
@show ReverseDiff.gradient(x -> pricer(BlackScholesProcess(x[1]), ZeroRate(x[2], x[3], x[4]), mc, EuropeanOption(x[5], K)), x)
@show ReverseDiff.gradient(x -> pricer(BlackScholesProcess(x[1]), ZeroRate(x[2], x[3], x[4]), mc, AmericanOption(x[5], K)), x)
@show ReverseDiff.gradient(x -> pricer(BlackScholesProcess(x[1]), ZeroRate(x[2], x[3], x[4]), mc, BarrierOptionDownOut(x[5], K, D)), x)
@show ReverseDiff.gradient(x -> pricer(BlackScholesProcess(x[1]), ZeroRate(x[2], x[3], x[4]), mc, AsianFloatingStrikeOption(x[5])), x)
@show ReverseDiff.gradient(x -> pricer(BlackScholesProcess(x[1]), ZeroRate(x[2], x[3], x[4]), mc, AsianFixedStrikeOption(x[5], K)), x)
| FinancialMonteCarlo | https://github.com/rcalxrc08/FinancialMonteCarlo.jl.git |
|
[
"MIT"
] | 0.3.2 | 728c49a9de6ffe78fceb7bcba3b53db070fa5532 | code | 1457 | using Test, FinancialMonteCarlo;
@show "Black Scholes Model"
S0 = 100.0;
K = 100.0;
r = 0.02;
T = 1.0;
d = 0.01;
d_ = FinancialMonteCarlo.Curve([0.009999, 0.01], T);
D = 90.0;
Nsim = 10000;
Nstep = 30;
sigma = 0.2;
mc = MonteCarloConfiguration(Nsim, Nstep, FinancialMonteCarlo.SobolMode());
toll = 0.8
spotData1 = ZeroRate(r);
FwdData = Forward(T)
EUData = EuropeanOption(T, K)
EUBin = BinaryEuropeanOption(T, K)
AMData = AmericanOption(T, K)
AmBin = BinaryEuropeanOption(T, K)
BarrierData = BarrierOptionDownOut(T, K, D)
AsianFloatingStrikeData = AsianFloatingStrikeOption(T)
AsianFixedStrikeData = AsianFixedStrikeOption(T, K)
Model = BlackScholesProcess(sigma, Underlying(S0, d));
display(Model)
@show FwdPrice = pricer(Model, spotData1, mc, FwdData);
@show EuPrice = pricer(Model, spotData1, mc, EUData);
@show EuBinPrice = pricer(Model, spotData1, mc, EUBin);
@show AmPrice = pricer(Model, spotData1, mc, AMData);
@show AmBinPrice = pricer(Model, spotData1, mc, AmBin);
@show BarrierPrice = pricer(Model, spotData1, mc, BarrierData);
@show AsianPrice1 = pricer(Model, spotData1, mc, AsianFloatingStrikeData);
@test abs(FwdPrice - 99.1078451563562) < toll
@test abs(EuPrice - 8.43005524824866) < toll
@test abs(AmPrice - 8.450489415187354) < toll
@test abs(BarrierPrice - 7.5008664470880735) < toll
@test abs(AsianPrice1 - 4.774451704549382) < toll
@show FwdPrice = pricer(BlackScholesProcess(sigma, Underlying(S0, d_)), spotData1, mc, FwdData);
| FinancialMonteCarlo | https://github.com/rcalxrc08/FinancialMonteCarlo.jl.git |
|
[
"MIT"
] | 0.3.2 | 728c49a9de6ffe78fceb7bcba3b53db070fa5532 | code | 1904 | using Test, FinancialMonteCarlo, TaylorSeries;
@show "Black Scholes Model"
S0 = 100.0;
K = 100.0;
r = 0.02;
T = 1.0;
d = 0.01;
D = 90.0;
Nsim = 10000;
Nstep = 30;
sigma = taylor_expand(identity,0.2,order=3);
mc = MonteCarloConfiguration(Nsim, Nstep);
mc1 = MonteCarloConfiguration(Nsim, Nstep, FinancialMonteCarlo.AntitheticMC());
toll = 0.8
rfCurve = ZeroRate(r);
FwdData = Forward(T)
EUData = EuropeanOption(T, K)
AMData = AmericanOption(T, K)
BarrierData = BarrierOptionDownOut(T, K, D)
AsianFloatingStrikeData = AsianFloatingStrikeOption(T)
AsianFixedStrikeData = AsianFixedStrikeOption(T, K)
Model = BlackScholesProcess(sigma, Underlying(S0, d));
@show FwdPrice = pricer(Model, rfCurve, mc, FwdData);
@show EuPrice = pricer(Model, rfCurve, mc, EUData);
@show AmPrice = pricer(Model, rfCurve, mc, AMData);
@show BarrierPrice = pricer(Model, rfCurve, mc, BarrierData);
@show AsianPrice1 = pricer(Model, rfCurve, mc, AsianFloatingStrikeData);
@show AsianPrice2 = pricer(Model, rfCurve, mc, AsianFixedStrikeData);
@test abs(FwdPrice - 99.1078451563562) < toll
@test abs(EuPrice - 8.43005524824866) < toll
@test abs(AmPrice - 8.450489415187354) < toll
@test abs(BarrierPrice - 7.5008664470880735) < toll
@test abs(AsianPrice1 - 4.774451704549382) < toll
@show FwdPrice = pricer(Model, rfCurve, mc1, FwdData);
@show EuPrice = pricer(Model, rfCurve, mc1, EUData);
@show AmPrice = pricer(Model, rfCurve, mc1, AMData);
@show BarrierPrice = pricer(Model, rfCurve, mc1, BarrierData);
@show AsianPrice1 = pricer(Model, rfCurve, mc1, AsianFloatingStrikeData);
@show AsianPrice2 = pricer(Model, rfCurve, mc1, AsianFixedStrikeData);
tollanti = 0.6;
@test abs(FwdPrice - 99.1078451563562) < tollanti
@test abs(EuPrice - 8.43005524824866) < tollanti
@test abs(AmPrice - 8.450489415187354) < tollanti
@test abs(BarrierPrice - 7.5008664470880735) < tollanti
@test abs(AsianPrice1 - 4.774451704549382) < tollanti
| FinancialMonteCarlo | https://github.com/rcalxrc08/FinancialMonteCarlo.jl.git |
|
[
"MIT"
] | 0.3.2 | 728c49a9de6ffe78fceb7bcba3b53db070fa5532 | code | 693 | using FinancialMonteCarlo, VectorizedRNG
S0 = 100.0;
K = 100.0;
r = 0.02;
T = 1.0;
d = 0.01;
D = 90.0;
Nsim = 10000;
Nstep = 30;
sigma = 0.2;
mc = MonteCarloConfiguration(Nsim, Nstep, FinancialMonteCarlo.SerialMode(10, local_rng()));
toll = 1.0;
rfCurve = ZeroRate(r);
FwdData = Forward(T)
EUData = EuropeanOption(T, K)
AMData = AmericanOption(T, K)
BarrierData = BarrierOptionDownOut(T, K, D)
AsianFloatingStrikeData = AsianFloatingStrikeOption(T)
AsianFixedStrikeData = AsianFixedStrikeOption(T, K)
Model = BlackScholesProcess(sigma, Underlying(S0, d));
EuPrice = pricer(Model, rfCurve, mc, EUData);
pricer(Model, rfCurve, mc, [EUData, EUData]);
@test abs(EuPrice - 8.43005524824866) < toll | FinancialMonteCarlo | https://github.com/rcalxrc08/FinancialMonteCarlo.jl.git |
|
[
"MIT"
] | 0.3.2 | 728c49a9de6ffe78fceb7bcba3b53db070fa5532 | code | 579 | using FinancialMonteCarlo, Test;
@show "Test Parameters"
S0 = 100.0;
K = 100.0;
r = 0.02;
Tneg = -1.0;
d = 0.01;
T = -Tneg;
Nsim = 10000;
Nstep = 30;
mc1 = MonteCarloConfiguration(Nsim, Nstep, FinancialMonteCarlo.AntitheticMC());
rfCurve2 = ZeroRate([0.00, 0.02], T);
sigma = 0.2;
McConfig = MonteCarloConfiguration(Nsim, Nstep);
rfCurve = ZeroRate(r);
@show "Test Brownian Motion Parameters"
drift = 0.0
@test_throws(AssertionError, BrownianMotion(-sigma, drift))
@test_throws(AssertionError, BrownianMotion(-sigma, rfCurve2.r))
S=simulate(BrownianMotion(0.2, 0.01),mc1,1.0);
| FinancialMonteCarlo | https://github.com/rcalxrc08/FinancialMonteCarlo.jl.git |
|
[
"MIT"
] | 0.3.2 | 728c49a9de6ffe78fceb7bcba3b53db070fa5532 | code | 1021 | using FinancialMonteCarlo
S0 = 100.0;
K = 100.0;
r = 0.02;
T = 1.0;
d = 0.01;
D = 90.0;
Nsim = 10000;
Nstep = 300;
sigma = 0.2;
variate_ = FinancialMonteCarlo.ControlVariates(Forward(T), MonteCarloConfiguration(1000, 100))
variate_2 = FinancialMonteCarlo.ControlVariates(AsianFloatingStrikeOption(T), MonteCarloConfiguration(1000, 100))
mc = MonteCarloConfiguration(Nsim, Nstep, variate_);
mc2 = MonteCarloConfiguration(Nsim, Nstep, variate_2);
mc1 = MonteCarloConfiguration(Nsim, Nstep);
toll = 1e-3;
spotData1 = ZeroRate(r);
FwdData = Forward(T)
EUData = EuropeanOption(T, K)
AMData = AmericanOption(T, K)
BarrierData = BarrierOptionDownOut(T, K, D)
AsianFloatingStrikeData = AsianFloatingStrikeOption(T)
AsianFixedStrikeData = AsianFixedStrikeOption(T, K)
Model = BlackScholesProcess(sigma, Underlying(S0, d));
AsianPrice1 = pricer(Model, spotData1, mc, AsianFloatingStrikeData);
AsianPrice2 = pricer(Model, spotData1, mc, AsianFixedStrikeData);
AsianPrice2 = pricer(Model, spotData1, mc2, AsianFixedStrikeData);
| FinancialMonteCarlo | https://github.com/rcalxrc08/FinancialMonteCarlo.jl.git |
|
[
"MIT"
] | 0.3.2 | 728c49a9de6ffe78fceb7bcba3b53db070fa5532 | code | 2448 | using Test, FinancialMonteCarlo, DualNumbers;
@show "Black Scholes Model"
S0 = 100.0;
K = 100.0;
r = 0.02;
T = 1.0;
d = 0.01;
D = 90.0;
underlying_name = "ENJ"
underlying_name_2 = "ABPL"
underlying_ = underlying_name * "_" * underlying_name_2 * "_TESL"
Nsim = 10000;
Nstep = 30;
sigma = 0.2;
mc = MonteCarloConfiguration(Nsim, Nstep);
mc1 = MonteCarloConfiguration(Nsim, Nstep, FinancialMonteCarlo.AntitheticMC());
toll = 0.8
rfCurve = ZeroRate(r);
FwdData = Forward(T)
EUData = EuropeanOptionND(T, K)
AMData = AmericanOption(T, K)
BarrierData = BarrierOptionDownOut(T, K, D)
AsianFloatingStrikeData = AsianFloatingStrikeOption(T)
AsianFixedStrikeData = AsianFixedStrikeOption(T, K)
Model_enj = BlackScholesProcess(sigma, Underlying(S0, d));
Model_abpl = BlackScholesProcess(sigma, Underlying(S0, d));
Model_tesl = BlackScholesProcess(sigma, Underlying(S0, d));
rho_1 = [1.0 0.0 0.1; 0.0 1.0 0.0; 0.1 0.0 1.0];
Model = GaussianCopulaNVariateProcess(rho_1, Model_enj, Model_abpl, Model_tesl)
display(Model)
mktdataset = underlying_ → Model
mktdataset_1 = underlying_name → Model_enj
portfolio_ = [EUData];
portfolio = underlying_ → EUData
portfolio_1 = underlying_name → AMData
price_mkt = FinancialMonteCarlo.delta(mktdataset, rfCurve, mc, portfolio, underlying_name, 1e-7)
price_mkt_1 = FinancialMonteCarlo.delta(mktdataset_1, rfCurve, mc, portfolio_1, underlying_name, 1e-7)
Model_enj_dual = BlackScholesProcess(sigma, Underlying(dual(S0, 1.0), d));
Model_dual = GaussianCopulaNVariateProcess(rho_1, Model_enj_dual, Model_abpl, Model_tesl)
mktdataset_dual = underlying_ → Model_dual
mktdataset_1_dual = underlying_name → Model_enj_dual
price_mkt_dual = pricer(mktdataset_dual, rfCurve, mc, portfolio)
price_mkt_1_dual = pricer(mktdataset_1_dual, rfCurve, mc, portfolio_1)
@test(abs(price_mkt_dual.epsilon - price_mkt) < 1e-4)
@test(abs(price_mkt_1_dual.epsilon - price_mkt_1) < 1e-4)
@test(abs(price_mkt_1_dual.epsilon - FinancialMonteCarlo.delta(Model_enj, rfCurve, mc, AMData, 1e-7)) < 1e-4)
@test(abs(price_mkt_1_dual.epsilon - FinancialMonteCarlo.delta(Model_enj, rfCurve, mc, AMData * 1.0, 1e-7)) < 1e-4)
@test(abs(price_mkt_1_dual.epsilon - FinancialMonteCarlo.delta(Model_enj, rfCurve, mc, [AMData], 1e-7)[1]) < 1e-4)
@test_throws(AssertionError, FinancialMonteCarlo.delta(mktdataset_1, rfCurve, mc, portfolio_1, underlying_, 1e-7))
@test(FinancialMonteCarlo.delta(mktdataset_1, rfCurve, mc, portfolio_1, "ciao", 1e-7) == 0.0)
| FinancialMonteCarlo | https://github.com/rcalxrc08/FinancialMonteCarlo.jl.git |
|
[
"MIT"
] | 0.3.2 | 728c49a9de6ffe78fceb7bcba3b53db070fa5532 | code | 1149 | using Test, FinancialMonteCarlo, DifferentialEquations;
@show "Differential Equation Junctor"
Nsim = 10000;
Nstep = 30;
toll = 0.8;
mc = MonteCarloConfiguration(Nsim, Nstep);
S0 = 100.0
K = 100.0;
D = 90.0;
r = 0.02
sigma = 0.2
T = 1.0;
d = 0.01;
# Drift
dr_(u, p, t) = (r - d) * u
# Diffusion
g_1(u, p, t) = sigma * u
# Time Window
tspan = (0.0, T)
# Definition of the SDE
prob = SDEProblem(dr_, g_1, S0, tspan)
monte_prob = EnsembleProblem(prob)
rfCurve = ZeroRate(r);
model = FinancialMonteCarlo.MonteCarloDiffEqModel(monte_prob, Underlying(S0, d))
FwdData = Forward(T)
EUData = EuropeanOption(T, K)
AMData = AmericanOption(T, K)
BarrierData = BarrierOptionDownOut(T, K, D)
AsianFloatingStrikeData = AsianFloatingStrikeOption(T)
AsianFixedStrikeData = AsianFixedStrikeOption(T, K)
@show FwdPrice = pricer(model, rfCurve, mc, FwdData);
@show EuPrice = pricer(model, rfCurve, mc, EUData);
@show AmPrice = pricer(model, rfCurve, mc, AMData);
@show BarrierPrice = pricer(model, rfCurve, mc, BarrierData);
@show AsianPrice1 = pricer(model, rfCurve, mc, AsianFloatingStrikeData);
@show AsianPrice2 = pricer(model, rfCurve, mc, AsianFixedStrikeData);
| FinancialMonteCarlo | https://github.com/rcalxrc08/FinancialMonteCarlo.jl.git |
|
[
"MIT"
] | 0.3.2 | 728c49a9de6ffe78fceb7bcba3b53db070fa5532 | code | 1882 | using Test, FinancialMonteCarlo, DifferentialEquations, Random;
@show "Differential Equation Junctor"
Nsim = 10000;
Nstep = 30;
toll = 0.8;
mc = MonteCarloConfiguration(Nsim, Nstep);
mc1 = MonteCarloConfiguration(Nsim, Nstep, FinancialMonteCarlo.AntitheticMC());
S0 = 100.0
K = 100.0;
D = 90.0;
r = 0.02
sigma = 0.2
T = 1.0;
d = 0.01;
u0 = 0.0;
p1 = 0.3;
lam = 5.0;
lamp = 30.0;
lamm = 20.0;
#Drift
dr_(u, p, t) = (r - d - sigma^2 / 2.0 - lam * (p1 / (lamp - 1) - (1 - p1) / (lamm + 1)))
#Diffusion
g_1(u, p, t) = sigma
#Time Window
tspan = (0.0, T)
rate(u, p, t) = lam * T
affect!(integrator) = (integrator.u = integrator.u + ((rand(mc.parallelMode.rng) < p1) ? randexp(mc.parallelMode.rng) / lamp : -randexp(mc.parallelMode.rng) / lamm))
jump = ConstantRateJump(rate, affect!)
#Definition of the SDE
prob = SDEProblem(dr_, g_1, u0, tspan)
jump_prob = JumpProblem(prob, Direct(), jump, rng = mc.parallelMode.rng)
monte_prob = EnsembleProblem(jump_prob)
rfCurve = ZeroRate(r);
func(x) = S0 * exp(x);
model = FinancialMonteCarlo.MonteCarloDiffEqModel(monte_prob, func, Underlying(S0, d))
FwdData = Forward(T)
EUData = EuropeanOption(T, K)
AMData = AmericanOption(T, K)
BarrierData = BarrierOptionDownOut(T, K, D)
AsianFloatingStrikeData = AsianFloatingStrikeOption(T)
AsianFixedStrikeData = AsianFixedStrikeOption(T, K)
@show FwdPrice = pricer(model, rfCurve, mc, FwdData);
@show EuPrice = pricer(model, rfCurve, mc, EUData);
@show AmPrice = pricer(model, rfCurve, mc, AMData);
@show BarrierPrice = pricer(model, rfCurve, mc, BarrierData);
@show AsianPrice1 = pricer(model, rfCurve, mc, AsianFloatingStrikeData);
@show AsianPrice2 = pricer(model, rfCurve, mc, AsianFixedStrikeData);
@test abs(FwdPrice - 98.8436678850961) < toll
Tneg = -T;
tspanNeg = (0.0, Tneg)
probNeg = SDEProblem(dr_, g_1, u0, tspanNeg, rng = mc.parallelMode.rng)
monte_probNeg = EnsembleProblem(probNeg)
| FinancialMonteCarlo | https://github.com/rcalxrc08/FinancialMonteCarlo.jl.git |
|
[
"MIT"
] | 0.3.2 | 728c49a9de6ffe78fceb7bcba3b53db070fa5532 | code | 857 | using Test, FinancialMonteCarlo;
@show "Black Scholes Model"
S0 = 100.0;
K = 100.0;
r = 0.02;
T = 1.0;
d = 0.01;
D = 90.0;
Nsim = 10000;
Nstep = 30;
sigma = 0.2;
mc = MonteCarloConfiguration(Nsim, Nstep);
mc1 = MonteCarloConfiguration(Nsim, Nstep, FinancialMonteCarlo.AntitheticMC());
toll = 0.8
rfCurve = ZeroRate(r);
FwdData = Forward(T)
EUData = EuropeanOption(T, K)
EUBin = BinaryEuropeanOption(T, K)
AMData = AmericanOption(T, K)
AmBin = BinaryEuropeanOption(T, K)
BarrierData = BarrierOptionDownOut(T, K, D)
AsianFloatingStrikeData = AsianFloatingStrikeOption(T)
AsianFixedStrikeData = AsianFixedStrikeOption(T, K)
Model = BlackScholesProcess(sigma, Underlying(S0, d));
display(Model)
ST = FinancialMonteCarlo.distribution(Model, rfCurve, mc, T);
@show FwdPrice = exp(-r * T) * sum(ST) / length(ST);
@test abs(FwdPrice - 99.1078451563562) < toll
| FinancialMonteCarlo | https://github.com/rcalxrc08/FinancialMonteCarlo.jl.git |
|
[
"MIT"
] | 0.3.2 | 728c49a9de6ffe78fceb7bcba3b53db070fa5532 | code | 501 | using FinancialMonteCarlo, Test
@show "Test Parameters"
S0 = 100.0;
K = 100.0;
r = 0.02;
Tneg = -1.0;
T = -Tneg;
d = 0.01;
Nsim = 10000;
Nstep = 30;
sigma = 0.2;
McConfig = MonteCarloConfiguration(Nsim, Nstep);
toll = 0.8;
rfCurve2 = ZeroRate([0.00, 0.02], T);
rfCurve = ZeroRate(r);
@show "Test Geometric Brownian Motion Parameters"
drift = 0.0
@test_throws(AssertionError, GeometricBrownianMotion(-sigma, drift, 1.0))
@test_throws(AssertionError, GeometricBrownianMotion(-sigma, rfCurve2.r, 1.0))
| FinancialMonteCarlo | https://github.com/rcalxrc08/FinancialMonteCarlo.jl.git |
|
[
"MIT"
] | 0.3.2 | 728c49a9de6ffe78fceb7bcba3b53db070fa5532 | code | 2230 | using Test, FinancialMonteCarlo;
@show "HestonModel"
S0 = 100.0;
K = 100.0;
r = 0.02;
T = 1.0;
d = 0.01;
D = 90.0;
Nsim = 10000;
Nstep = 30;
sigma = 0.2;
sigma_zero = 0.2;
kappa = 0.01;
theta = 0.03;
lambda = 0.01;
rho_ = 0.0;
mc = MonteCarloConfiguration(Nsim, Nstep);
mc1 = MonteCarloConfiguration(Nsim, Nstep, FinancialMonteCarlo.AntitheticMC());
toll = 0.8;
rfCurve = ZeroRate(r);
FwdData = Forward(T)
EUData = EuropeanOption(T, K)
AMData = AmericanOption(T, K)
BarrierData = BarrierOptionDownOut(T, K, D)
AsianData1 = AsianFloatingStrikeOption(T)
AsianData2 = AsianFixedStrikeOption(T, K)
Model = HestonProcess(sigma, sigma_zero, lambda, kappa, rho_, theta, Underlying(S0, d));
@show FwdPrice = pricer(Model, rfCurve, mc, FwdData);
@show EuPrice = pricer(Model, rfCurve, mc, EUData);
@show AmPrice = pricer(Model, rfCurve, mc, AMData);
@show BarrierPrice = pricer(Model, rfCurve, mc, BarrierData);
@show AsianPrice1 = pricer(Model, rfCurve, mc, AsianData1);
@show AsianPrice2 = pricer(Model, rfCurve, mc, AsianData2);
@test abs(FwdPrice - 98.8790717426047) < toll
@test abs(EuPrice - 7.9813557592924) < toll
@test abs(BarrierPrice - 7.006564636309922) < toll
@test abs(AsianPrice1 - 4.242256952013707) < toll
@show FwdPrice = pricer(Model, rfCurve, mc1, FwdData);
@show EuPrice = pricer(Model, rfCurve, mc1, EUData);
@show AmPrice = pricer(Model, rfCurve, mc1, AMData);
@show BarrierPrice = pricer(Model, rfCurve, mc1, BarrierData);
@show AsianPrice1 = pricer(Model, rfCurve, mc1, AsianData1);
@show AsianPrice2 = pricer(Model, rfCurve, mc1, AsianData2);
tollanti = 0.8
@test abs(FwdPrice - 98.8790717426047) < tollanti
@test abs(EuPrice - 7.9813557592924) < tollanti
@test abs(BarrierPrice - 7.006564636309922) < tollanti
@test abs(AsianPrice1 - 4.242256952013707) < tollanti
@test_throws(AssertionError, HestonProcess(-sigma, sigma_zero, lambda, kappa, rho_, theta, Underlying(S0, d)))
@test_throws(AssertionError, HestonProcess(sigma, -sigma_zero, lambda, kappa, rho_, theta, Underlying(S0, d)))
@test_throws(AssertionError, HestonProcess(sigma, sigma_zero, lambda, kappa, -5.0, theta, Underlying(S0, d)))
@test_throws(AssertionError, HestonProcess(sigma, sigma_zero, 1e-16, 1e-16, rho_, theta, Underlying(S0, d)))
| FinancialMonteCarlo | https://github.com/rcalxrc08/FinancialMonteCarlo.jl.git |
|
[
"MIT"
] | 0.3.2 | 728c49a9de6ffe78fceb7bcba3b53db070fa5532 | code | 922 | using Test, FinancialMonteCarlo;
@show "HestonModel"
S0 = 100.0;
K = 100.0;
r = [0.02; 0.02];
T = 1.0;
d = 0.01;
D = 90.0;
Nsim = 10000;
Nstep = 30;
sigma = 0.2;
sigma_zero = 0.2;
kappa = 0.01;
theta = 0.03;
lambda = 0.01;
rho_ = 0.0;
mc = MonteCarloConfiguration(Nsim, Nstep);
mc1 = MonteCarloConfiguration(Nsim, Nstep, FinancialMonteCarlo.AntitheticMC());
toll = 0.8;
rfCurve = ZeroRate(r, T);
FwdData = Forward(T)
EUData = EuropeanOption(T, K)
AMData = AmericanOption(T, K)
BarrierData = BarrierOptionDownOut(T, K, D)
AsianData1 = AsianFloatingStrikeOption(T)
AsianData2 = AsianFixedStrikeOption(T, K)
Model = HestonProcess(sigma, sigma_zero, lambda, kappa, rho_, theta, Underlying(S0, d));
@show FwdPrice = pricer(Model, rfCurve, mc, FwdData);
@test abs(FwdPrice - 98.72567723404445) < toll
@show FwdPrice = pricer(Model, rfCurve, mc1, FwdData);
tollanti = 0.8
@test abs(FwdPrice - 98.72567723404445) < tollanti
| FinancialMonteCarlo | https://github.com/rcalxrc08/FinancialMonteCarlo.jl.git |
|
[
"MIT"
] | 0.3.2 | 728c49a9de6ffe78fceb7bcba3b53db070fa5532 | code | 1812 | using Test, FinancialMonteCarlo, DualNumbers;
@show "HestonModel"
S0 = 100.0;
K = 100.0;
r = 0.02;
T = 1.0;
d = 0.01;
D = 90.0;
Nsim = 10000;
Nstep = 30;
sigma = 0.2;
sigma_zero = dual(0.2, 1.0);
kappa = 0.01;
theta = 0.03;
lambda = 0.01;
rho_ = 0.0;
mc = MonteCarloConfiguration(Nsim, Nstep);
mc1 = MonteCarloConfiguration(Nsim, Nstep, FinancialMonteCarlo.AntitheticMC());
toll = 0.8;
rfCurve = ZeroRate(r);
FwdData = Forward(T)
EUData = EuropeanOption(T, K)
AMData = AmericanOption(T, K)
BarrierData = BarrierOptionDownOut(T, K, D)
AsianData1 = AsianFloatingStrikeOption(T)
AsianData2 = AsianFixedStrikeOption(T, K)
Model = HestonProcess(sigma, sigma_zero, lambda, kappa, rho_, theta, Underlying(S0, d));
@show FwdPrice = pricer(Model, rfCurve, mc, FwdData);
@show EuPrice = pricer(Model, rfCurve, mc, EUData);
@show AmPrice = pricer(Model, rfCurve, mc, AMData);
@show BarrierPrice = pricer(Model, rfCurve, mc, BarrierData);
@show AsianPrice1 = pricer(Model, rfCurve, mc, AsianData1);
@show AsianPrice2 = pricer(Model, rfCurve, mc, AsianData2);
@test abs(FwdPrice - 98.8790717426047) < toll
@test abs(EuPrice - 7.9813557592924) < toll
@test abs(BarrierPrice - 7.006564636309922) < toll
@test abs(AsianPrice1 - 4.242256952013707) < toll
@show FwdPrice = pricer(Model, rfCurve, mc1, FwdData);
@show EuPrice = pricer(Model, rfCurve, mc1, EUData);
@show AmPrice = pricer(Model, rfCurve, mc1, AMData);
@show BarrierPrice = pricer(Model, rfCurve, mc1, BarrierData);
@show AsianPrice1 = pricer(Model, rfCurve, mc1, AsianData1);
@show AsianPrice2 = pricer(Model, rfCurve, mc1, AsianData2);
tollanti = 0.8
@test abs(FwdPrice - 98.8790717426047) < tollanti
@test abs(EuPrice - 7.9813557592924) < tollanti
@test abs(BarrierPrice - 7.006564636309922) < tollanti
@test abs(AsianPrice1 - 4.242256952013707) < tollanti
| FinancialMonteCarlo | https://github.com/rcalxrc08/FinancialMonteCarlo.jl.git |
|
[
"MIT"
] | 0.3.2 | 728c49a9de6ffe78fceb7bcba3b53db070fa5532 | code | 1415 | using Test, FinancialMonteCarlo;
@show "HestonModel"
S0 = 100.0;
K = 100.0;
r = 0.02;
T = 1.0;
d = 0.01;
D = 90.0;
Nsim = 10000;
Nstep = 30;
sigma = 0.2;
sigma_zero = 0.2;
kappa = 0.01;
theta = 0.03;
lambda = 0.01;
rho_ = 0.0;
mc = MonteCarloConfiguration(Nsim, Nstep, FinancialMonteCarlo.SobolMode());
mc1 = MonteCarloConfiguration(Nsim, Nstep, FinancialMonteCarlo.AntitheticMC());
toll = 0.8;
rfCurve = ZeroRate(r);
FwdData = Forward(T)
EUData = EuropeanOption(T, K)
AMData = AmericanOption(T, K)
BarrierData = BarrierOptionDownOut(T, K, D)
AsianData1 = AsianFloatingStrikeOption(T)
AsianData2 = AsianFixedStrikeOption(T, K)
Model = HestonProcess(sigma, sigma_zero, lambda, kappa, rho_, theta, Underlying(S0, d));
@show FwdPrice = pricer(Model, rfCurve, mc, FwdData);
@show EuPrice = pricer(Model, rfCurve, mc, EUData);
@show AmPrice = pricer(Model, rfCurve, mc, AMData);
@show BarrierPrice = pricer(Model, rfCurve, mc, BarrierData);
@show AsianPrice1 = pricer(Model, rfCurve, mc, AsianData1);
@show AsianPrice2 = pricer(Model, rfCurve, mc, AsianData2);
@test abs(FwdPrice - 98.8790717426047) < toll
@test abs(EuPrice - 7.9813557592924) < toll
@test abs(BarrierPrice - 7.006564636309922) < toll
@test abs(AsianPrice1 - 4.242256952013707) < toll
@show FwdPrice = pricer(Model, FinancialMonteCarlo.ImpliedZeroRate([0.01], [0.5]), MonteCarloConfiguration(Nsim, Nstep, FinancialMonteCarlo.SobolMode()), FwdData); | FinancialMonteCarlo | https://github.com/rcalxrc08/FinancialMonteCarlo.jl.git |
|
[
"MIT"
] | 0.3.2 | 728c49a9de6ffe78fceb7bcba3b53db070fa5532 | code | 2211 | using Test, FinancialMonteCarlo;
@show "KouModel"
S0 = 100.0;
K = 100.0;
r = 0.02;
T = 1.0;
d = 0.01;
D = 90.0;
Nsim = 10000;
Nstep = 30;
sigma = 0.2;
p = 0.3;
lam = 5.0;
lamp = 30.0;
lamm = 20.0;
mc = MonteCarloConfiguration(Nsim, Nstep);
mc1 = MonteCarloConfiguration(Nsim, Nstep, FinancialMonteCarlo.AntitheticMC());
toll = 0.8;
rfCurve = ZeroRate(r);
FwdData = Forward(T)
EUData = EuropeanOption(T, K)
AMData = AmericanOption(T, K)
BarrierData = BarrierOptionDownOut(T, K, D)
AsianData1 = AsianFloatingStrikeOption(T)
AsianData2 = AsianFixedStrikeOption(T, K)
Model = KouProcess(sigma, lam, p, lamp, lamm, Underlying(S0, d));
@show FwdPrice = pricer(Model, rfCurve, mc, FwdData);
@show EuPrice = pricer(Model, rfCurve, mc, EUData);
@show AmPrice = pricer(Model, rfCurve, mc, AMData);
@show BarrierPrice = pricer(Model, rfCurve, mc, BarrierData);
@show AsianPrice1 = pricer(Model, rfCurve, mc, AsianData1);
@show AsianPrice2 = pricer(Model, rfCurve, mc, AsianData2);
@test abs(FwdPrice - 99.41332633109904) < toll
@test abs(EuPrice - 10.347332240535199) < toll
@test abs(BarrierPrice - 8.860123655599818) < toll
@test abs(AsianPrice1 - 5.81798437145069) < toll
@show FwdPrice = pricer(Model, rfCurve, mc1, FwdData);
@show EuPrice = pricer(Model, rfCurve, mc1, EUData);
@show AmPrice = pricer(Model, rfCurve, mc1, AMData);
@show BarrierPrice = pricer(Model, rfCurve, mc1, BarrierData);
@show AsianPrice1 = pricer(Model, rfCurve, mc1, AsianData1);
@show AsianPrice2 = pricer(Model, rfCurve, mc1, AsianData2);
tollanti = 0.8
@test abs(FwdPrice - 99.41332633109904) < tollanti
@test abs(EuPrice - 10.347332240535199) < tollanti
@test abs(BarrierPrice - 8.860123655599818) < tollanti
@test abs(AsianPrice1 - 5.81798437145069) < tollanti
@show "Test Kou Parameters"
@test_throws(AssertionError, KouProcess(-sigma, lam, p, lamp, lamm, Underlying(S0, d)))
@test_throws(AssertionError, KouProcess(sigma, -lam, p, lamp, lamm, Underlying(S0, d)))
@test_throws(AssertionError, KouProcess(sigma, lam, -p, lamp, lamm, Underlying(S0, d)))
@test_throws(AssertionError, KouProcess(sigma, lam, p, -lamp, lamm, Underlying(S0, d)))
@test_throws(AssertionError, KouProcess(sigma, lam, p, lamp, -lamm, Underlying(S0, d)))
| FinancialMonteCarlo | https://github.com/rcalxrc08/FinancialMonteCarlo.jl.git |
|
[
"MIT"
] | 0.3.2 | 728c49a9de6ffe78fceb7bcba3b53db070fa5532 | code | 1777 | using Test, DualNumbers, FinancialMonteCarlo
@show "KouModel"
S0 = 100.0;
K = 100.0;
r = 0.02;
T = 1.0;
d = 0.01;
D = 90.0;
Nsim = 10000;
Nstep = 30;
sigma = dual(0.2, 1.0);
#sigma=0.2;
p = 0.3;
lam = 5.0;
lamp = 30.0;
lamm = 20.0;
mc = MonteCarloConfiguration(Nsim, Nstep);
mc1 = MonteCarloConfiguration(Nsim, Nstep, FinancialMonteCarlo.AntitheticMC());
toll = 0.8;
rfCurve = ZeroRate(r);
FwdData = Forward(T)
EUData = EuropeanOption(T, K)
AMData = AmericanOption(T, K)
BarrierData = BarrierOptionDownOut(T, K, D)
AsianData1 = AsianFloatingStrikeOption(T)
AsianData2 = AsianFixedStrikeOption(T, K)
Model = KouProcess(sigma, lam, p, lamp, lamm, Underlying(S0, d));
@show FwdPrice = pricer(Model, rfCurve, mc, FwdData);
@show EuPrice = pricer(Model, rfCurve, mc, EUData);
@show AmPrice = pricer(Model, rfCurve, mc, AMData);
@show BarrierPrice = pricer(Model, rfCurve, mc, BarrierData);
@show AsianPrice1 = pricer(Model, rfCurve, mc, AsianData1);
@show AsianPrice2 = pricer(Model, rfCurve, mc, AsianData2);
@test abs(FwdPrice - 99.41332633109904) < toll
@test abs(EuPrice - 10.347332240535199) < toll
@test abs(BarrierPrice - 8.860123655599818) < toll
@test abs(AsianPrice1 - 5.81798437145069) < toll
@show FwdPrice = pricer(Model, rfCurve, mc1, FwdData);
@show EuPrice = pricer(Model, rfCurve, mc1, EUData);
@show AmPrice = pricer(Model, rfCurve, mc1, AMData);
@show BarrierPrice = pricer(Model, rfCurve, mc1, BarrierData);
@show AsianPrice1 = pricer(Model, rfCurve, mc1, AsianData1);
@show AsianPrice2 = pricer(Model, rfCurve, mc1, AsianData2);
tollanti = 0.8
@test abs(FwdPrice - 99.41332633109904) < tollanti
@test abs(EuPrice - 10.347332240535199) < tollanti
@test abs(BarrierPrice - 8.860123655599818) < tollanti
@test abs(AsianPrice1 - 5.81798437145069) < tollanti
| FinancialMonteCarlo | https://github.com/rcalxrc08/FinancialMonteCarlo.jl.git |
|
[
"MIT"
] | 0.3.2 | 728c49a9de6ffe78fceb7bcba3b53db070fa5532 | code | 1919 | using Test, FinancialMonteCarlo;
@show "LogNormalMixture Model"
S0 = 100.0;
K = 100.0;
r = 0.02;
T = 1.0;
d = 0.01;
D = 90.0;
Nsim = 10000;
Nstep = 30;
sigma = [0.2, 0.2];
lam = Float64[0.999999999];
mc = MonteCarloConfiguration(Nsim, Nstep);
mc1 = MonteCarloConfiguration(Nsim, Nstep, FinancialMonteCarlo.AntitheticMC());
toll = 0.8
rfCurve = ZeroRate(r);
FwdData = Forward(T)
EUData = EuropeanOption(T, K)
AMData = AmericanOption(T, K)
BarrierData = BarrierOptionDownOut(T, K, D)
AsianFloatingStrikeData = AsianFloatingStrikeOption(T)
AsianFixedStrikeData = AsianFixedStrikeOption(T, K)
Model = LogNormalMixture(sigma, lam, Underlying(S0, d));
param_ = FinancialMonteCarlo.get_parameters(Model)
Model = FinancialMonteCarlo.set_parameters!(Model, param_)
display(Model)
# @test_throws(AssertionError, FinancialMonteCarlo.set_parameters!(Model, [1, 4]))
@show FwdPrice = pricer(Model, rfCurve, mc, FwdData);
@show EuPrice = pricer(Model, rfCurve, mc, EUData);
@show AmPrice = pricer(Model, rfCurve, mc, AMData);
@show BarrierPrice = pricer(Model, rfCurve, mc, BarrierData);
@show AsianPrice1 = pricer(Model, rfCurve, mc, AsianFloatingStrikeData);
@show AsianPrice2 = pricer(Model, rfCurve, mc, AsianFixedStrikeData);
@test abs(FwdPrice - 99.1078451563562) < toll
@test abs(EuPrice - 8.43005524824866) < toll
@test abs(AmPrice - 8.450489415187354) < toll
@test abs(BarrierPrice - 7.5008664470880735) < toll
@test abs(AsianPrice1 - 4.774451704549382) < toll
@show "Test LogNormalMixture Parameters"
eta = [0.2, 0.2]
lam11 = [0.9999]
@test_throws(AssertionError, LogNormalMixture(-0.2 * ones(3), 0.1 * ones(2), Underlying(S0, d)))
@test_throws(AssertionError, LogNormalMixture(0.2 * ones(3), -0.1 * ones(2), Underlying(S0, d)))
@test_throws(AssertionError, LogNormalMixture(0.2 * ones(3), ones(2), Underlying(S0, d)))
@test_throws(AssertionError, LogNormalMixture(0.2 * ones(3), 0.2 * ones(3), Underlying(S0, d)))
| FinancialMonteCarlo | https://github.com/rcalxrc08/FinancialMonteCarlo.jl.git |
|
[
"MIT"
] | 0.3.2 | 728c49a9de6ffe78fceb7bcba3b53db070fa5532 | code | 1868 | using Test, FinancialMonteCarlo;
@show "MertonProcess"
S0 = 100.0;
K = 100.0;
r = 0.02;
T = 1.0;
d = 0.01;
D = 90.0;
Nsim = 10000;
Nstep = 30;
sigma = 0.2;
lam = 5.0;
mu1 = 0.03;
sigma1 = 0.02;
mc = MonteCarloConfiguration(Nsim, Nstep);
mc1 = MonteCarloConfiguration(Nsim, Nstep, FinancialMonteCarlo.AntitheticMC());
toll = 0.8;
rfCurve = ZeroRate(r);
FwdData = Forward(T)
EUData = EuropeanOption(T, K)
AMData = AmericanOption(T, K)
BarrierData = BarrierOptionDownOut(T, K, D)
AsianData = AsianFloatingStrikeOption(T)
Model = MertonProcess(sigma, lam, mu1, sigma1, Underlying(S0, d));
@show FwdPrice = pricer(Model, rfCurve, mc, FwdData);
@show EuPrice = pricer(Model, rfCurve, mc, EUData);
@show AmPrice = pricer(Model, rfCurve, mc, AMData);
@show BarrierPrice = pricer(Model, rfCurve, mc, BarrierData);
@show AsianPrice = pricer(Model, rfCurve, mc, AsianData);
@test abs(FwdPrice - 99.1188767166039) < toll
@test abs(EuPrice - 9.084327245917533) < toll
@test abs(BarrierPrice - 7.880881290426765) < toll
@test abs(AsianPrice - 5.129020349580892) < toll
@show FwdPrice = pricer(Model, rfCurve, mc1, FwdData);
@show EuPrice = pricer(Model, rfCurve, mc1, EUData);
@show AmPrice = pricer(Model, rfCurve, mc1, AMData);
@show BarrierPrice = pricer(Model, rfCurve, mc1, BarrierData);
@show AsianPrice = pricer(Model, rfCurve, mc1, AsianData);
tollanti = 0.6;
@test abs(FwdPrice - 99.1188767166039) < tollanti
@test abs(EuPrice - 9.084327245917533) < tollanti
@test abs(BarrierPrice - 7.880881290426765) < tollanti
@test abs(AsianPrice - 5.129020349580892) < tollanti
@show "Test Merton Parameters"
@test_throws(AssertionError, MertonProcess(-sigma, lam, mu1, sigma1, Underlying(S0, d)))
@test_throws(AssertionError, MertonProcess(sigma, lam, mu1, -sigma1, Underlying(S0, d)))
@test_throws(AssertionError, MertonProcess(sigma, -lam, mu1, sigma1, Underlying(S0, d)))
| FinancialMonteCarlo | https://github.com/rcalxrc08/FinancialMonteCarlo.jl.git |
|
[
"MIT"
] | 0.3.2 | 728c49a9de6ffe78fceb7bcba3b53db070fa5532 | code | 1904 | using Test, FinancialMonteCarlo;
@show "NormalInverseGaussianProcess"
S0 = 100.0;
K = 100.0;
r = 0.02;
T = 1.0;
d = 0.01;
D = 90.0;
Nsim = 10000;
Nstep = 30;
sigma = 0.2;
theta1 = 0.01;
k1 = 0.03;
mc = MonteCarloConfiguration(Nsim, Nstep);
mc1 = MonteCarloConfiguration(Nsim, Nstep, FinancialMonteCarlo.AntitheticMC());
toll = 0.8;
rfCurve = ZeroRate(r);
FwdData = Forward(T)
EUData = EuropeanOption(T, K)
AMData = AmericanOption(T, K)
BarrierData = BarrierOptionDownOut(T, K, D)
AsianData = AsianFloatingStrikeOption(T)
Model = NormalInverseGaussianProcess(sigma, theta1, k1, Underlying(S0, d));
@show FwdPrice = pricer(Model, rfCurve, mc, FwdData);
@show EuPrice = pricer(Model, rfCurve, mc, EUData);
@show AmPrice = pricer(Model, rfCurve, mc, AMData);
@show BarrierPrice = pricer(Model, rfCurve, mc, BarrierData);
@show AsianPrice = pricer(Model, rfCurve, mc, AsianData);
@test abs(FwdPrice - 99.16322764791194) < toll
@test abs(EuPrice - 8.578451710277706) < toll
@test abs(BarrierPrice - 7.561814171846508) < toll
@test abs(AsianPrice - 4.86386704425551) < toll
@show FwdPrice = pricer(Model, rfCurve, mc1, FwdData);
@show EuPrice = pricer(Model, rfCurve, mc1, EUData);
@show AmPrice = pricer(Model, rfCurve, mc1, AMData);
@show BarrierPrice = pricer(Model, rfCurve, mc1, BarrierData);
@show AsianPrice = pricer(Model, rfCurve, mc1, AsianData);
tollanti = 0.8;
@test abs(FwdPrice - 99.16322764791194) < tollanti
@test abs(EuPrice - 8.578451710277706) < tollanti
@test abs(BarrierPrice - 7.561814171846508) < tollanti
@test abs(AsianPrice - 4.86386704425551) < tollanti
@show "Test NIG Parameters"
@test_throws(AssertionError, NormalInverseGaussianProcess(-sigma, theta1, k1, Underlying(S0, d)))
@test_throws(AssertionError, NormalInverseGaussianProcess(sigma, theta1, -k1, Underlying(S0, d)))
@test_throws(AssertionError, NormalInverseGaussianProcess(sigma, 10000.0, k1, Underlying(S0, d)))
| FinancialMonteCarlo | https://github.com/rcalxrc08/FinancialMonteCarlo.jl.git |
|
[
"MIT"
] | 0.3.2 | 728c49a9de6ffe78fceb7bcba3b53db070fa5532 | code | 2277 | using Test, FinancialMonteCarlo, DualNumbers;
@show "Black Scholes Model"
S0 = 100.0;
K = 100.0;
r = 0.02;
T = 1.0;
d = 0.01;
D = 90.0;
underlying_name = "ENJ"
Nsim = 10000;
Nstep = 30;
sigma = 0.2;
mc = MonteCarloConfiguration(Nsim, Nstep);
mc1 = MonteCarloConfiguration(Nsim, Nstep, FinancialMonteCarlo.AntitheticMC());
toll = 0.8
rfCurve = ZeroRate(r);
FwdData = Forward(T)
EUData = EuropeanOption(T, K)
AMData = AmericanOption(T, K)
BarrierData = BarrierOptionDownOut(T, K, D)
AsianFloatingStrikeData = AsianFloatingStrikeOption(T)
AsianFixedStrikeData = AsianFixedStrikeOption(T, K)
Model = BlackScholesProcess(sigma, Underlying(S0, d));
display(Model)
port_ = EUData * 2.0 + FwdData - FwdData / 2.0 - FwdData;
port_ = port_ * 2.0;
port_ = 2.0 * port_;
display(port_)
print(port_)
display(FwdData)
display(-FwdData)
print(FwdData)
print(-FwdData)
display(Forward(dual(T, 1.0)))
display(-Forward(dual(T, 1.0)))
print(Forward(dual(T, 1.0)))
print(-Forward(dual(T, 1.0)))
display(Forward(dual(T, 1.0)) + EUData)
display(-Forward(dual(T, 1.0)) + EUData)
print(Forward(dual(T, 1.0)) + EUData)
print(-Forward(dual(T, 1.0)) + EUData)
display(Forward(dual(T, 1.0)) - EUData)
display(-Forward(dual(T, 1.0)) - EUData)
print(Forward(dual(T, 1.0)) - EUData)
print(-Forward(dual(T, 1.0)) - EUData)
fwd = Forward(dual(T, 1.0)) * 1.0
fwd = 1.0 * Forward(dual(T, 1.0))
ok = FwdData - fwd;
display(fwd)
print(fwd)
fwd = 1.0 * fwd
fwd = fwd * 1.0
fwd = fwd / 1.0
fwd = -fwd
fwd = Forward(dual(T, 1.0)) * dual(1.0, 1.0) + EUData * 2.0 + AMData
display(fwd)
print(fwd)
fwd = -Forward(dual(T, 1.0)) * dual(1.0, 1.0) + EUData * 2.0 + AMData
display(fwd)
print(fwd)
mktdataset = underlying_name → Model
portfolio_ = [FwdData; EUData; AMData; BarrierData; AsianFloatingStrikeData; AsianFixedStrikeData; Spot()];
portfolio = underlying_name → FwdData
portfolio += underlying_name → EUData
portfolio += underlying_name → AMData
portfolio += underlying_name → Spot()
portfolio += underlying_name → BarrierData
portfolio += underlying_name → AsianFloatingStrikeData
portfolio += underlying_name → AsianFixedStrikeData
display(portfolio)
price_mkt = pricer(mktdataset, rfCurve, mc, portfolio)
price_old = sum(pricer(Model, rfCurve, mc, portfolio_))
@test abs(price_mkt - price_old) < 1e-8
| FinancialMonteCarlo | https://github.com/rcalxrc08/FinancialMonteCarlo.jl.git |
|
[
"MIT"
] | 0.3.2 | 728c49a9de6ffe78fceb7bcba3b53db070fa5532 | code | 991 | using Test, FinancialMonteCarlo;
@show "Black Scholes Model"
S0 = 100.0;
K = 100.0;
r = 0.02;
T = 1.0;
d = 0.01;
D = 90.0;
underlying_name = "ENJ"
underlying_name_2 = "ABPL"
underlying_ = underlying_name * "_" * underlying_name_2
Nsim = 10000;
Nstep = 30;
sigma = 0.2;
mc = MonteCarloConfiguration(Nsim, Nstep);
toll = 0.8
rfCurve = ZeroRate(r);
EUData = EuropeanOptionND(T, K)
Model_enj = BlackScholesProcess(sigma, Underlying(S0, d));
Model_abpl = BlackScholesProcess(sigma, Underlying(S0, d));
Model = GaussianCopulaNVariateProcess(Model_enj, Model_abpl, 0.4)
@test GaussianCopulaNVariateProcess(Model_enj, Model_abpl).rho == GaussianCopulaNVariateProcess(Model_enj, Model_abpl, 0.0).rho
display(Model)
FinancialMonteCarlo.get_parameters(Model)
mktdataset = underlying_ → Model
portfolio_ = [EUData];
portfolio = underlying_ → EUData
price_mkt = pricer(mktdataset, rfCurve, mc, portfolio)
price_old = pricer(Model, rfCurve, mc, EUData)
@test abs(price_mkt - price_old) < 1e-8
| FinancialMonteCarlo | https://github.com/rcalxrc08/FinancialMonteCarlo.jl.git |
|
[
"MIT"
] | 0.3.2 | 728c49a9de6ffe78fceb7bcba3b53db070fa5532 | code | 1434 | using Test, FinancialMonteCarlo;
@show "Black Scholes Model"
S0 = 100.0;
K = 100.0;
r = 0.02;
T = 1.0;
d = 0.01;
D = 90.0;
underlying_name = "ENJ"
underlying_name_2 = "ABPL"
underlying_ = underlying_name * "_" * underlying_name_2
Nsim = 10000;
Nstep = 30;
sigma = 0.2;
mc = MonteCarloConfiguration(Nsim, Nstep);
mc1 = MonteCarloConfiguration(Nsim, Nstep, FinancialMonteCarlo.AntitheticMC());
toll = 0.8
rfCurve = ZeroRate(r);
FwdData = Forward(T)
EUData = EuropeanOption(T, K)
AMData = AmericanOption(T, K)
BarrierData = BarrierOptionDownOut(T, K, D)
AsianFloatingStrikeData = AsianFloatingStrikeOption(T)
AsianFixedStrikeData = AsianFixedStrikeOption(T, K)
Model_enj = BlackScholesProcess(sigma, Underlying(S0, d));
Model_abpl = BlackScholesProcess(sigma, Underlying(S0, d));
Model_n = BlackScholesProcess(sigma, Underlying(S0, d));
Model1 = GaussianCopulaNVariateLogProcess(Model_enj, Model_abpl)
Model = GaussianCopulaNVariateLogProcess(Model_enj, Model_abpl, 0.0)
@test Model1.rho == Model.rho
display(Model)
mktdataset = underlying_ → Model
mktdataset_2 = underlying_name → Model_enj
mktdataset += "notneeded" → Model_n
portfolio = underlying_name → 1.0 * EUData
portfolio += underlying_name → 1.0 * AMData
portfolio += underlying_name → -1.0 * (-1.0) * BarrierData
price_mkt = pricer(mktdataset, rfCurve, mc, portfolio)
price_old = pricer(mktdataset_2, rfCurve, mc, portfolio)
@test abs(price_mkt - price_old) < 1e-8
| FinancialMonteCarlo | https://github.com/rcalxrc08/FinancialMonteCarlo.jl.git |
|
[
"MIT"
] | 0.3.2 | 728c49a9de6ffe78fceb7bcba3b53db070fa5532 | code | 1243 | using Test, FinancialMonteCarlo;
@show "Black Scholes Model"
S0 = 100.0;
K = 100.0;
r = 0.02;
T = 1.0;
d = 0.01;
D = 90.0;
underlying_name = "ENJ"
underlying_name_2 = "ABPL"
underlying_ = underlying_name * "_" * underlying_name_2 * "_TESL"
Nsim = 10000;
Nstep = 30;
sigma = 0.2;
mc = MonteCarloConfiguration(Nsim, Nstep);
mc1 = MonteCarloConfiguration(Nsim, Nstep, FinancialMonteCarlo.AntitheticMC());
toll = 0.8
rfCurve = ZeroRate(r);
FwdData = Forward(T)
EUData = EuropeanOptionND(T, K)
AMData = AmericanOption(T, K)
BarrierData = BarrierOptionDownOut(T, K, D)
AsianFloatingStrikeData = AsianFloatingStrikeOption(T)
AsianFixedStrikeData = AsianFixedStrikeOption(T, K)
Model_enj = BlackScholesProcess(sigma, Underlying(S0, d));
Model_abpl = BlackScholesProcess(sigma, Underlying(S0, d));
Model_tesl = BlackScholesProcess(sigma, Underlying(S0, d));
rho_1 = [1.0 0.0 0.0; 0.0 1.0 0.0; 0.0 0.0 1.0];
Model = GaussianCopulaNVariateProcess(rho_1, Model_enj, Model_abpl, Model_tesl)
display(Model)
mktdataset = underlying_ → Model
portfolio_ = [EUData];
portfolio = underlying_ → EUData
price_mkt = pricer(mktdataset, rfCurve, mc, portfolio)
price_old = sum(pricer(Model, rfCurve, mc, portfolio_))
@test abs(price_mkt - price_old) < 1e-8
| FinancialMonteCarlo | https://github.com/rcalxrc08/FinancialMonteCarlo.jl.git |
|
[
"MIT"
] | 0.3.2 | 728c49a9de6ffe78fceb7bcba3b53db070fa5532 | code | 1493 | using Test, FinancialMonteCarlo;
@show "Black Scholes Model"
S0 = 100.0;
K = 100.0;
r = 0.02;
T = 1.0;
d = 0.01;
D = 90.0;
underlying_name = "ENJ"
underlying_name_2 = "ABPL"
underlying_ = underlying_name * "_" * underlying_name_2 * "_TESL"
Nsim = 10000;
Nstep = 30;
sigma = 0.2;
mc = MonteCarloConfiguration(Nsim, Nstep);
mc1 = MonteCarloConfiguration(Nsim, Nstep, FinancialMonteCarlo.AntitheticMC());
toll = 0.8
rfCurve = ZeroRate(r);
FwdData = Forward(T)
EUData = EuropeanOptionND(T, K)
AMData = AmericanOption(T, K)
BarrierData = BarrierOptionDownOut(T, K, D)
AsianFloatingStrikeData = AsianFloatingStrikeOption(T)
AsianFixedStrikeData = AsianFixedStrikeOption(T, K)
Model_enj = BlackScholesProcess(sigma, Underlying(S0, d));
Model_abpl = BlackScholesProcess(sigma, Underlying(S0, d));
Model_tesl = BlackScholesProcess(sigma, Underlying(S0, d));
rho_1 = [1.0 0.0 0.1; 0.0 1.0 0.0; 0.1 0.0 1.0];
Model2 = GaussianCopulaNVariateLogProcess(Model_enj, Model_abpl, Model_tesl)
Model = GaussianCopulaNVariateLogProcess(rho_1, Model_enj, Model_abpl, Model_tesl)
display(Model)
mktdataset = underlying_ → Model
mktdataset2 = underlying_ → Model2
portfolio_ = [EUData];
portfolio = underlying_ → EUData
price_mkt = pricer(mktdataset, rfCurve, mc, portfolio)
price_mkt2 = pricer(mktdataset2, rfCurve, mc, portfolio)
price_old = sum(pricer(Model, rfCurve, mc, portfolio_))
@test_throws(AssertionError, BlackScholesProcess(-sigma, Underlying(S0, d)))
@test abs(price_mkt - price_old) < 1e-8
| FinancialMonteCarlo | https://github.com/rcalxrc08/FinancialMonteCarlo.jl.git |
|
[
"MIT"
] | 0.3.2 | 728c49a9de6ffe78fceb7bcba3b53db070fa5532 | code | 1312 | using FinancialMonteCarlo, ReverseDiff;
@show "Black Scholes Model"
S0 = 100.0;
K = 100.0;
r = 0.02;
T = 1.0;
d = 0.01;
D = 90.0;
Nsim = 100;
Nstep = 30;
sigma = 0.2;
p = 0.3;
lam = 5.0;
lamp = 30.0;
lamm = 20.0;
mc = MonteCarloConfiguration(Nsim, Nstep);
mc1 = MonteCarloConfiguration(Nsim, Nstep, FinancialMonteCarlo.AntitheticMC());
toll = 0.8;
rfCurve = ZeroRate(r);
Model = BlackScholesProcess(sigma, Underlying(S0, d));
x = Float64[sigma, S0, r, d, T]
@show ReverseDiff.gradient(x -> pricer(BlackScholesProcess(x[1], Underlying(x[2], x[4])), ZeroRate(x[3]), mc, Forward(x[5])), x)
@show ReverseDiff.gradient(x -> pricer(BlackScholesProcess(x[1], Underlying(x[2], x[4])), ZeroRate(x[3]), mc, EuropeanOption(x[5], K)), x)
@show ReverseDiff.gradient(x -> pricer(BlackScholesProcess(x[1], Underlying(x[2], x[4])), ZeroRate(x[3]), mc, AmericanOption(x[5], K)), x)
@show ReverseDiff.gradient(x -> pricer(BlackScholesProcess(x[1], Underlying(x[2], x[4])), ZeroRate(x[3]), mc, BarrierOptionDownOut(x[5], K, D)), x)
@show ReverseDiff.gradient(x -> pricer(BlackScholesProcess(x[1], Underlying(x[2], x[4])), ZeroRate(x[3]), mc, AsianFloatingStrikeOption(x[5])), x)
@show ReverseDiff.gradient(x -> pricer(BlackScholesProcess(x[1], Underlying(x[2], x[4])), ZeroRate(x[3]), mc, AsianFixedStrikeOption(x[5], K)), x)
| FinancialMonteCarlo | https://github.com/rcalxrc08/FinancialMonteCarlo.jl.git |
|
[
"MIT"
] | 0.3.2 | 728c49a9de6ffe78fceb7bcba3b53db070fa5532 | code | 1465 | using Test, FinancialMonteCarlo, DualNumbers;
@show "Black Scholes Model"
S0 = 100.0;
K = 100.0;
T = 1.0;
d = 0.01;
D = 90.0;
Nsim = 10000;
Nstep = 30;
sigma = 0.2;
mc = MonteCarloConfiguration(Nsim, Nstep);
dr__ = 1e-7;
mc1 = MonteCarloConfiguration(Nsim, Nstep, FinancialMonteCarlo.AntitheticMC());
toll = 0.8
der_toll = 1e-2;
rfCurve = ZeroRate(dual(0.02, 1.0));
rfCurve1 = ZeroRate(0.02);
FwdData = Forward(T)
EUData = EuropeanOption(T, K)
AMData = AmericanOption(T, K)
BarrierData = BarrierOptionDownOut(T, K, D)
AsianFloatingStrikeData = AsianFloatingStrikeOption(T)
AsianFixedStrikeData = AsianFixedStrikeOption(T, K)
Model = BlackScholesProcess(sigma, Underlying(S0, d));
@show EuPrice = pricer(Model, rfCurve, mc, EUData);
@show EuPrice_der = rho(Model, rfCurve1, mc, EUData, dr__);
@show AmPrice = pricer(Model, rfCurve, mc, AMData);
@show AmPrice_der = rho(Model, rfCurve1, mc, AMData, dr__);
@test abs(EuPrice - 8.43005524824866) < toll
@test abs(EuPrice.epsilon - EuPrice_der) < der_toll
@test abs(AmPrice - 8.450489415187354) < toll
@test abs(AmPrice.epsilon - AmPrice_der) < der_toll
@show EuPrice = pricer(Model, rfCurve, mc1, EUData);
@show EuPrice_der = rho(Model, rfCurve1, mc1, EUData, dr__);
@show EuPrice_der_vec = rho(Model, rfCurve1, mc1, [EUData], dr__)[1];
tollanti = 0.6;
@test abs(EuPrice - 8.43005524824866) < tollanti
@test abs(EuPrice.epsilon - EuPrice_der) < der_toll
@test abs(EuPrice.epsilon - EuPrice_der_vec) < der_toll
| FinancialMonteCarlo | https://github.com/rcalxrc08/FinancialMonteCarlo.jl.git |
|
[
"MIT"
] | 0.3.2 | 728c49a9de6ffe78fceb7bcba3b53db070fa5532 | code | 1988 | using Test, FinancialMonteCarlo;
@show "ShiftedLogNormalMixture Model"
S0 = 100.0;
K = 100.0;
r = 0.02;
T = 1.0;
d = 0.01;
D = 90.0;
Nsim = 10000;
Nstep = 30;
sigma = [0.2, 0.2];
lam = Float64[0.999999999];
mc = MonteCarloConfiguration(Nsim, Nstep);
mc1 = MonteCarloConfiguration(Nsim, Nstep, FinancialMonteCarlo.AntitheticMC());
toll = 0.8
rfCurve = ZeroRate(r);
FwdData = Forward(T)
EUData = EuropeanOption(T, K)
AMData = AmericanOption(T, K)
BarrierData = BarrierOptionDownOut(T, K, D)
AsianFloatingStrikeData = AsianFloatingStrikeOption(T)
AsianFixedStrikeData = AsianFixedStrikeOption(T, K)
Model = ShiftedLogNormalMixture(sigma, lam, 0.0, Underlying(S0, d));
param_ = FinancialMonteCarlo.get_parameters(Model)
Model = FinancialMonteCarlo.set_parameters!(Model, param_)
display(Model)
# @test_throws(AssertionError, FinancialMonteCarlo.set_parameters!(Model, [1, 2]))
@show FwdPrice = pricer(Model, rfCurve, mc, FwdData);
@show EuPrice = pricer(Model, rfCurve, mc, EUData);
@show AmPrice = pricer(Model, rfCurve, mc, AMData);
@show BarrierPrice = pricer(Model, rfCurve, mc, BarrierData);
@show AsianPrice1 = pricer(Model, rfCurve, mc, AsianFloatingStrikeData);
@show AsianPrice2 = pricer(Model, rfCurve, mc, AsianFixedStrikeData);
@test abs(FwdPrice - 99.1078451563562) < toll
@test abs(EuPrice - 8.43005524824866) < toll
@test abs(AmPrice - 8.450489415187354) < toll
@test abs(BarrierPrice - 7.5008664470880735) < toll
@test abs(AsianPrice1 - 4.774451704549382) < toll
@show "Test LogNormalMixture Parameters"
eta = [0.2, 0.2]
lam11 = [0.9999]
@test_throws(AssertionError, ShiftedLogNormalMixture(-0.2 * ones(3), 0.1 * ones(2), 0.0, Underlying(S0, d)))
@test_throws(AssertionError, ShiftedLogNormalMixture(0.2 * ones(3), -0.1 * ones(2), 0.0, Underlying(S0, d)))
@test_throws(AssertionError, ShiftedLogNormalMixture(0.2 * ones(3), ones(2), 0.0, Underlying(S0, d)))
@test_throws(AssertionError, ShiftedLogNormalMixture(0.2 * ones(3), 0.2 * ones(3), 0.0, Underlying(S0, d)))
| FinancialMonteCarlo | https://github.com/rcalxrc08/FinancialMonteCarlo.jl.git |
|
[
"MIT"
] | 0.3.2 | 728c49a9de6ffe78fceb7bcba3b53db070fa5532 | code | 3974 | using FinancialMonteCarlo, Test
@show "Test Structs Building"
S0 = 100.0;
K = 100.0;
Kneg = -100.0;
r = 0.02;
T = 1.0;
Tneg = -1.0;
d = 0.01;
D = 90.0;
Nsim = 10000;
Nstep = 30;
sigma = 0.2;
theta1 = 0.01;
k1 = 0.03;
sigma1 = 0.02;
underlying_name = "ENJ"
mc = MonteCarloConfiguration(Nsim, Nstep, 1);
mc2 = MonteCarloConfiguration(Nsim, Nstep, FinancialMonteCarlo.SerialMode(1));
mc1 = MonteCarloConfiguration(Nsim, Nstep, FinancialMonteCarlo.AntitheticMC());
toll = 0.8;
Model_enj = BlackScholesProcess(sigma, Underlying(S0, d));
Model_abpl = BlackScholesProcess(sigma, Underlying(S0, d));
FinancialMonteCarlo.Curve([0.0, 0.1], [0.0, 0.1]);
Model = GaussianCopulaNVariateProcess(Model_enj, Model_abpl, 0.0)
param_ = FinancialMonteCarlo.get_parameters(Model_abpl);
# @test_throws(AssertionError, FinancialMonteCarlo.set_parameters!(Model_abpl, [1, 2, 3, 4]))
port_ = "eni_aap" → Model;
rfCurve = ZeroRate(r);
rfCurve2 = ZeroRate([0.00, 0.02], T);
@test_throws(AssertionError, port_ + port_)
@test_throws(AssertionError, underlying_name → Model)
@test_throws(AssertionError, Underlying(-S0, rfCurve2.r))
@test_throws(AssertionError, "c_i" → Forward(1.0))
@test_throws(AssertionError, Underlying(-S0))
@test_throws(AssertionError, EuropeanOptionND(-1.0, 1.0))
@test_throws(AssertionError, EuropeanOptionND(1.0, -1.0))
@test_throws(AssertionError, MonteCarloConfiguration(-Nsim, Nstep))
@test_throws(AssertionError, MonteCarloConfiguration(Nsim + 1, Nstep, FinancialMonteCarlo.AntitheticMC()));
@test_throws(AssertionError, MonteCarloConfiguration(Nsim, -Nstep))
#####################################################################
#Payoff Structs Test: Negative TTM
@test_throws(AssertionError, Forward(Tneg));
@test_throws(AssertionError, EuropeanOption(Tneg, K));
@test_throws(AssertionError, AmericanOption(Tneg, K));
@test_throws(AssertionError, BermudanOption([Tneg], K));
@test_throws(AssertionError, BinaryAmericanOption(Tneg, K));
@test_throws(AssertionError, BinaryEuropeanOption(Tneg, K));
@test_throws(AssertionError, BarrierOptionDownOut(Tneg, K, D));
@test_throws(AssertionError, BarrierOptionUpOut(Tneg, K, D));
@test_throws(AssertionError, BarrierOptionUpIn(Tneg, K, D));
@test_throws(AssertionError, BarrierOptionDownIn(Tneg, K, D));
@test_throws(AssertionError, AsianFloatingStrikeOption(Tneg));
@test_throws(AssertionError, AsianFixedStrikeOption(Tneg, K));
@test_throws(AssertionError, DoubleBarrierOption(Tneg, K, K * 10, D));
# Negative Strike and Barriers
@test_throws(AssertionError, EuropeanOption(T, Kneg));
@test_throws(AssertionError, AmericanOption(T, Kneg));
@test_throws(AssertionError, BermudanOption([T], Kneg));
@test_throws(AssertionError, BinaryEuropeanOption(T, Kneg));
@test_throws(AssertionError, BinaryAmericanOption(T, Kneg));
@test_throws(AssertionError, AsianFixedStrikeOption(T, Kneg));
@test_throws(AssertionError, BarrierOptionDownOut(T, Kneg, D));
@test_throws(AssertionError, BarrierOptionDownOut(T, K, Kneg));
@test_throws(AssertionError, BarrierOptionDownIn(T, Kneg, D));
@test_throws(AssertionError, BarrierOptionDownIn(T, K, Kneg));
@test_throws(AssertionError, BarrierOptionUpIn(T, Kneg, D));
@test_throws(AssertionError, BarrierOptionUpIn(T, K, Kneg));
@test_throws(AssertionError, BarrierOptionUpOut(T, Kneg, D));
@test_throws(AssertionError, BarrierOptionUpOut(T, K, Kneg));
@test_throws(AssertionError, DoubleBarrierOption(T, K, K, Kneg));
@test_throws(AssertionError, DoubleBarrierOption(T, Kneg, K, K));
@test_throws(AssertionError, DoubleBarrierOption(T, K, Kneg, K));
@test FinancialMonteCarlo.maturity(Spot()) == 0.0
@test 2.0 * EuropeanOption(T, K) == EuropeanOption(T, K) + 1.0 * EuropeanOption(T, K)
@test 2.0 * EuropeanOption(T, K) == EuropeanOption(T, K) + EuropeanOption(T, K)
########
import FinancialMonteCarlo.AbstractPayoff
struct tmptype2 <: FinancialMonteCarlo.AbstractPayoff{Float64}
T::Float64
end
@test_throws(ErrorException, payoff([1.0 1.0; 1.0 1.0], tmptype2(1.0), rfCurve, mc1));
| FinancialMonteCarlo | https://github.com/rcalxrc08/FinancialMonteCarlo.jl.git |
|
[
"MIT"
] | 0.3.2 | 728c49a9de6ffe78fceb7bcba3b53db070fa5532 | code | 624 | using FinancialMonteCarlo, Distributions, Test;
@show "Test Parameters"
S0 = 100.0;
r = 0.02;
d = 0.01;
T = 1.0;
Nsim = 100;
Nstep = 30;
sigma = 0.2;
McConfig = MonteCarloConfiguration(Nsim, Nstep);
mc1 = MonteCarloConfiguration(Nsim, Nstep, FinancialMonteCarlo.AntitheticMC());
rfCurve = ZeroRate(r);
rfCurve2 = ZeroRate([0.00, 0.02], T);
@show "Test Subordinated Brownian Motion Parameters"
drift = 0.0;
@test_throws(AssertionError, SubordinatedBrownianMotion(-sigma, drift, 0.01, InverseGaussian(1.0, 1.0)))
@test_throws(AssertionError, SubordinatedBrownianMotion(-sigma, rfCurve2.r, 0.01, InverseGaussian(1.0, 1.0)))
| FinancialMonteCarlo | https://github.com/rcalxrc08/FinancialMonteCarlo.jl.git |
|
[
"MIT"
] | 0.3.2 | 728c49a9de6ffe78fceb7bcba3b53db070fa5532 | code | 1966 | using Test, FinancialMonteCarlo, RandomNumbers;
@show "VarianceGammaProcess"
S0 = 100.0;
K = 100.0;
r = 0.02;
T = 1.0;
d = 0.01;
D = 90.0;
Nsim = 10000;
Nstep = 30;
sigma = 0.2;
theta1 = 0.01;
k1 = 0.03;
mc = MonteCarloConfiguration(Nsim, Nstep, FinancialMonteCarlo.SerialMode(1, RandomNumbers.Xorshifts.Xoroshiro128Plus()));
mc1 = MonteCarloConfiguration(Nsim, Nstep, FinancialMonteCarlo.AntitheticMC());
toll = 0.8;
rfCurve = ZeroRate(r);
FwdData = Forward(T)
EUData = EuropeanOption(T, K)
AMData = AmericanOption(T, K)
BarrierData = BarrierOptionDownOut(T, K, D)
AsianData = AsianFloatingStrikeOption(T)
Model = VarianceGammaProcess(sigma, theta1, k1, Underlying(S0, d));
@show FwdPrice = pricer(Model, rfCurve, mc, FwdData);
@show EuPrice = pricer(Model, rfCurve, mc, EUData);
@show AmPrice = pricer(Model, rfCurve, mc, AMData);
@show BarrierPrice = pricer(Model, rfCurve, mc, BarrierData);
@show AsianPrice = pricer(Model, rfCurve, mc, AsianData);
@test abs(FwdPrice - 99.09861035102614) < toll
@test abs(EuPrice - 8.368903690692187) < toll
@test abs(BarrierPrice - 7.469024475794258) < toll
@test abs(AsianPrice - 4.779663836736272) < toll
@show FwdPrice = pricer(Model, rfCurve, mc1, FwdData);
@show EuPrice = pricer(Model, rfCurve, mc1, EUData);
@show AmPrice = pricer(Model, rfCurve, mc1, AMData);
@show BarrierPrice = pricer(Model, rfCurve, mc1, BarrierData);
@show AsianPrice = pricer(Model, rfCurve, mc1, AsianData);
@test abs(FwdPrice - 99.09861035102614) < toll
@test abs(EuPrice - 8.368903690692187) < toll
@test abs(BarrierPrice - 7.469024475794258) < toll
@test abs(AsianPrice - 4.779663836736272) < toll
print(Model);
println("");
@show "Test Variance Gamma Parameters"
@test_throws(AssertionError, VarianceGammaProcess(-sigma, theta1, k1, Underlying(S0, d)))
@test_throws(AssertionError, VarianceGammaProcess(sigma, theta1, -k1, Underlying(S0, d)))
@test_throws(AssertionError, VarianceGammaProcess(sigma, 10000.0, k1, Underlying(S0, d)))
| FinancialMonteCarlo | https://github.com/rcalxrc08/FinancialMonteCarlo.jl.git |
|
[
"MIT"
] | 0.3.2 | 728c49a9de6ffe78fceb7bcba3b53db070fa5532 | code | 1672 | using Test, FinancialMonteCarlo, Statistics;
@show "Black Scholes Model"
S0 = 100.0;
K = 100.0;
r = [0.00, 0.02];
T = 1.0;
d = FinancialMonteCarlo.Curve([0.0, 0.02], T);
d2 = FinancialMonteCarlo.Curve([0.0, 0.01, 0.02], T);
D = 90.0;
Nsim = 10000;
Nstep = 30;
sigma = 0.2;
theta1 = 0.01;
k1 = 0.03;
mc = MonteCarloConfiguration(Nsim, Nstep);
mc1 = MonteCarloConfiguration(Nsim, Nstep, FinancialMonteCarlo.AntitheticMC());
toll = 0.8;
rfCurve = FinancialMonteCarlo.ImpliedZeroRate(r, T);
rfCurve2 = ZeroRate(r, T);
FwdData = Forward(T)
EUData = EuropeanOption(T, K)
EUBin = BinaryEuropeanOption(T, K)
AMData = AmericanOption(T, K)
AmBin = BinaryEuropeanOption(T, K)
BarrierData = BarrierOptionDownOut(T, K, D)
AsianFloatingStrikeData = AsianFloatingStrikeOption(T)
AsianFixedStrikeData = AsianFixedStrikeOption(T, K)
Model = VarianceGammaProcess(sigma, theta1, k1, Underlying(S0, d));
Model2 = VarianceGammaProcess(sigma, theta1, k1, Underlying(S0, d2));
display(Model)
@show FwdPrice = pricer(Model, ZeroRate(r[end]), mc, FwdData);
@show FwdPrice = pricer(Model, rfCurve, mc, FwdData);
@show FwdPrice = pricer(Model, rfCurve2, mc, FwdData);
@show FwdPrice = pricer(Model2, rfCurve, mc, FwdData);
@show FwdPrice = pricer(Model, rfCurve, mc1, FwdData);
@show EuPrice = pricer(Model, rfCurve, mc, EUData);
@show EuBinPrice = pricer(Model, rfCurve, mc, EUBin);
@show AmPrice = pricer(Model, rfCurve, mc, AMData);
@show AmBinPrice = pricer(Model, rfCurve, mc, AmBin);
@show BarrierPrice = pricer(Model, rfCurve, mc, BarrierData);
@show AsianPrice1 = pricer(Model, rfCurve, mc, AsianFloatingStrikeData);
@show AsianPrice2 = pricer(Model, rfCurve, mc, AsianFixedStrikeData);
| FinancialMonteCarlo | https://github.com/rcalxrc08/FinancialMonteCarlo.jl.git |
|
[
"MIT"
] | 0.3.2 | 728c49a9de6ffe78fceb7bcba3b53db070fa5532 | code | 2068 | using Test, DualNumbers, FinancialMonteCarlo
@show "VarianceGammaProcess"
S0 = 100.0;
K = 100.0;
r = 0.02;
T = 1.0;
d = 0.01;
D = 90.0;
Nsim = 10000;
Nstep = 30;
sigma = dual(0.2, 1.0);
theta1 = 0.01;
k1 = 0.03;
sigma1 = 0.02;
mc = MonteCarloConfiguration(Nsim, Nstep);
mc1 = MonteCarloConfiguration(Nsim, Nstep, FinancialMonteCarlo.AntitheticMC());
mc2 = MonteCarloConfiguration(Nsim, Nstep, FinancialMonteCarlo.SobolMode());
toll = 0.8;
rfCurve = ZeroRate(r);
FwdData = Forward(T)
EUData = EuropeanOption(T, K)
AMData = AmericanOption(T, K)
BarrierData = BarrierOptionDownOut(T, K, D)
AsianData = AsianFloatingStrikeOption(T)
Model = VarianceGammaProcess(sigma, theta1, k1, Underlying(S0, d));
@show FwdPrice = pricer(Model, rfCurve, mc, FwdData);
@show EuPrice = pricer(Model, rfCurve, mc, EUData);
@show AmPrice = pricer(Model, rfCurve, mc, AMData);
@show BarrierPrice = pricer(Model, rfCurve, mc, BarrierData);
@show AsianPrice = pricer(Model, rfCurve, mc, AsianData);
@test abs(FwdPrice - 99.09861035102614) < toll
@test abs(EuPrice - 8.368903690692187) < toll
@test abs(BarrierPrice - 7.469024475794258) < toll
@test abs(AsianPrice - 4.779663836736272) < toll
@show FwdPrice = pricer(Model, rfCurve, mc1, FwdData);
@show EuPrice = pricer(Model, rfCurve, mc1, EUData);
@show AmPrice = pricer(Model, rfCurve, mc1, AMData);
@show BarrierPrice = pricer(Model, rfCurve, mc1, BarrierData);
@show AsianPrice = pricer(Model, rfCurve, mc1, AsianData);
@test abs(FwdPrice - 99.09861035102614) < toll
@test abs(EuPrice - 8.368903690692187) < toll
@test abs(BarrierPrice - 7.469024475794258) < toll
@test abs(AsianPrice - 4.779663836736272) < toll
@show FwdPrice = pricer(Model, rfCurve, mc2, FwdData);
# @show FwdPrice = pricer(VarianceGammaProcess(sigma, theta1, k1, Underlying(S0, FinancialMonteCarlo.Curve([0.009999, 0.01], T))), FinancialMonteCarlo.ImpliedZeroRate([0.01], [1.0]), mc2, FwdData);
# @show FwdPrice = pricer.([VarianceGammaProcess(sigma, theta1, k1, Underlying(S0, FinancialMonteCarlo.Curve([0.009999, 0.01], T))), Model], rfCurve, mc2, FwdData); | FinancialMonteCarlo | https://github.com/rcalxrc08/FinancialMonteCarlo.jl.git |
|
[
"MIT"
] | 0.3.2 | 728c49a9de6ffe78fceb7bcba3b53db070fa5532 | code | 3114 | using Test, FinancialMonteCarlo,CUDA;
@show "Black Scholes Model"
S0=100.0;
K=100.0;
r=0.02;
T=1.0;
d=0.01;
D=90.0;
Nsim=10000;
Nstep=30;
sigma=0.2;
mc=MonteCarloConfiguration(Nsim,Nstep,FinancialMonteCarlo.CudaMode());
toll=0.8
rfCurve=ZeroRate(r);
FwdData=Forward(T)
EUData=EuropeanOption(T,K)
AMData=AmericanOption(T,K)
BarrierData=BarrierOptionDownOut(T,K,D)
AsianFloatingStrikeData=AsianFloatingStrikeOption(T)
AsianFixedStrikeData=AsianFixedStrikeOption(T,K)
Model=BlackScholesProcess(sigma,Underlying(S0,d));
display(Model)
@show FwdPrice=pricer(Model,rfCurve,mc,FwdData);
@show EuPrice=pricer(Model,rfCurve,mc,EUData);
@show AmPrice=pricer(Model,rfCurve,mc,AMData);
@show BarrierPrice=pricer(Model,rfCurve,mc,BarrierData);
@show AsianPrice1=pricer(Model,rfCurve,mc,AsianFloatingStrikeData);
@show AsianPrice2=pricer(Model,rfCurve,mc,AsianFixedStrikeData);
@test abs(FwdPrice-99.1078451563562)<toll
@test abs(EuPrice-8.43005524824866)<toll
@test abs(AmPrice-8.450489415187354)<toll
@test abs(BarrierPrice-7.5008664470880735)<toll
@test abs(AsianPrice1-4.774451704549382)<toll
@show FwdPrice=pricer(Model,rfCurve,mc1,FwdData);
@show EuPrice=pricer(Model,rfCurve,mc1,EUData);
@show AmPrice=pricer(Model,rfCurve,mc1,AMData);
@show BarrierPrice=pricer(Model,rfCurve,mc1,BarrierData);
@show AsianPrice1=pricer(Model,rfCurve,mc1,AsianFloatingStrikeData);
@show AsianPrice2=pricer(Model,rfCurve,mc1,AsianFixedStrikeData);
tollanti=0.6;
@test abs(FwdPrice-99.1078451563562)<tollanti
@test abs(EuPrice-8.43005524824866)<tollanti
@test abs(AmPrice-8.450489415187354)<tollanti
@test abs(BarrierPrice-7.5008664470880735)<tollanti
@test abs(AsianPrice1-4.774451704549382)<tollanti
EUDataPut=EuropeanOption(T,K,false)
AMDataPut=AmericanOption(T,K,false)
BarrierDataPut=BarrierOptionDownOut(T,K,D,false)
AsianFloatingStrikeDataPut=AsianFloatingStrikeOption(T,false)
AsianFixedStrikeDataPut=AsianFixedStrikeOption(T,K,false)
@show EuPrice=pricer(Model,rfCurve,mc,EUDataPut);
@show AmPrice=pricer(Model,rfCurve,mc,AMDataPut);
@show BarrierPrice=pricer(Model,rfCurve,mc,BarrierDataPut);
@show AsianPrice1=pricer(Model,rfCurve,mc,AsianFloatingStrikeDataPut);
@show AsianPrice2=pricer(Model,rfCurve,mc,AsianFixedStrikeDataPut);
tollPut=0.6;
@test abs(FwdPrice-99.1078451563562)<tollPut
@test abs(EuPrice-7.342077422567968)<tollPut
@test abs(AmPrice-7.467065889603365)<tollPut
@test abs(BarrierPrice-0.29071929104261723)<tollPut
@test abs(AsianPrice1-4.230547012372306)<tollPut
@test abs(AsianPrice2-4.236220218194027)<tollPut
@test variance(Model,rfCurve,mc,EUDataPut)>variance(Model,rfCurve,mc1,EUDataPut);
@test prod(variance(Model,rfCurve,mc,[EUDataPut,AMDataPut]).>=variance(Model,rfCurve,mc1,[EUDataPut,AMDataPut]));
##############################################################
IC1=confinter(Model,rfCurve,mc,EUDataPut,0.99);
IC2=confinter(Model,rfCurve,mc1,EUDataPut,0.99);
L1=IC1[2]-IC1[1]
L2=IC2[2]-IC2[1]
@test L1>L2
IC1=confinter(Model,rfCurve,mc,[EUDataPut,AMDataPut],0.99);
IC2=confinter(Model,rfCurve,mc1,[EUDataPut,AMDataPut],0.99);
L1=IC1[2][2]-IC1[2][1]
L2=IC2[2][2]-IC2[2][1]
@test L1>L2 | FinancialMonteCarlo | https://github.com/rcalxrc08/FinancialMonteCarlo.jl.git |
|
[
"MIT"
] | 0.3.2 | 728c49a9de6ffe78fceb7bcba3b53db070fa5532 | code | 1015 | using Test, FinancialMonteCarlo,Statistics;
@show "Black Scholes Model"
S0=100.0;
K=100.0;
r=[0.00,0.02];
T=1.0;
d=0.01;
D=90.0;
Nsim=100000;
Nstep=30;
sigma=0.2;
mc=MonteCarloConfiguration(Nsim,Nstep);
toll=0.8
rfCurve=ZeroRate(r,T);
FwdData=Forward(T)
EUData=EuropeanOption(T,K)
EUBin=BinaryEuropeanOption(T,K)
AMData=AmericanOption(T,K)
AmBin=BinaryEuropeanOption(T,K)
BarrierData=BarrierOptionDownOut(T,K,D)
AsianFloatingStrikeData=AsianFloatingStrikeOption(T)
AsianFixedStrikeData=AsianFixedStrikeOption(T,K)
Model=BlackScholesProcess(sigma,Underlying(S0,d));
display(Model)
@show FwdPrice=pricer(Model,rfCurve,mc,FwdData);
@show EuPrice=pricer(Model,rfCurve,mc,EUData);
@show EuBinPrice=pricer(Model,rfCurve,mc,EUBin);
@show AmPrice=pricer(Model,rfCurve,mc,AMData);
@show AmBinPrice=pricer(Model,rfCurve,mc,AmBin);
@show BarrierPrice=pricer(Model,rfCurve,mc,BarrierData);
@show AsianPrice1=pricer(Model,rfCurve,mc,AsianFloatingStrikeData);
@show AsianPrice2=pricer(Model,rfCurve,mc,AsianFixedStrikeData); | FinancialMonteCarlo | https://github.com/rcalxrc08/FinancialMonteCarlo.jl.git |
|
[
"MIT"
] | 0.3.2 | 728c49a9de6ffe78fceb7bcba3b53db070fa5532 | code | 584 | using Test, FinancialMonteCarlo,Statistics;
@show "Black Scholes Model"
S0=100.0;
K=100.0;
r=[0.00,0.02];
T=1.0;
d=0.01;
r=0.02;
D=90.0;
Nsim=100000;
Nstep=30;
sigma=0.2;
mc=MonteCarloConfiguration(Nsim,Nstep);
toll=0.8
rfCurve=ZeroRate(r);
FwdData=Forward(T)
EUData=EuropeanOption(T,K)
Model_base=BrownianMotion(sigma,r-d-sigma*sigma*0.5,Underlying(0.0,0.0))
S=S0.*exp.(simulate(Model_base,mc,T));
Payoff=exp(-FinancialMonteCarlo.integral(r,T))*S[:,end];
@show Price=mean(Payoff)
Model=BlackScholesProcess(sigma,Underlying(S0,d));
@show FwdPrice=pricer(Model,rfCurve,mc,FwdData); | FinancialMonteCarlo | https://github.com/rcalxrc08/FinancialMonteCarlo.jl.git |
|
[
"MIT"
] | 0.3.2 | 728c49a9de6ffe78fceb7bcba3b53db070fa5532 | code | 1058 | using Test, FinancialMonteCarlo;
@show "Black Scholes Model"
S0=100.0;
K=100.0;
r=0.02;
T=1.0;
d=0.01;
D=90.0;
underlying_name="ENJ"
underlying_name_2="ABPL"
underlying_=underlying_name*"_"*underlying_name_2*"_TESL"
Nsim=10000;
Nstep=30;
sigma=0.2;
mc=MonteCarloConfiguration(Nsim,Nstep);
mc1=MonteCarloConfiguration(Nsim,Nstep,FinancialMonteCarlo.AntitheticMC());
toll=0.8
rfCurve=ZeroRate(r);
FwdData=Forward(T)
EUData=EuropeanOptionND(T,K)
AMData=AmericanOption(T,K)
BarrierData=BarrierOptionDownOut(T,K,D)
AsianFloatingStrikeData=AsianFloatingStrikeOption(T)
AsianFixedStrikeData=AsianFixedStrikeOption(T,K)
Model_enj=BlackScholesProcess(sigma,Underlying(S0,d));
Model_abpl=BlackScholesProcess(sigma,Underlying(S0,d));
Model_tesl=BlackScholesProcess(sigma,Underlying(S0,d));
rho=[1.0 0.0 0.0; 0.0 1.0 0.0; 0.0 0.0 1.0];
Model=GaussianCopulaNVariateProcess(rho,Model_enj,Model_abpl,Model_tesl)
###############
p=EuropeanOption(1.0,70.0)+Forward(1.0)
p2=3.0*p;
port_=Array{typeof(p)}(undef,7)
port_[1]=p
port_[2]=p2
pricer(Model,rfCurve,mc,port_) | FinancialMonteCarlo | https://github.com/rcalxrc08/FinancialMonteCarlo.jl.git |
|
[
"MIT"
] | 0.3.2 | 728c49a9de6ffe78fceb7bcba3b53db070fa5532 | code | 694 | using FinancialMonteCarlo,Nabla;
@show "Black Scholes Model"
S0=100.0;
K=100.0;
r=0.02;
T=1.0;
d=0.01;
D=90.0;
Nsim=10000;
Nstep=30;
sigma=0.2
mc=MonteCarloConfiguration(Nsim,Nstep);
toll=0.8
rfCurve=ZeroRate(S0,r,d);
FwdData=Forward(T)
EUData=EuropeanOption(T,K)
AMData=AmericanOption(T,K)
BarrierData=BarrierOptionDownOut(T,K,D)
AsianFloatingStrikeData=AsianFloatingStrikeOption(T)
AsianFixedStrikeData=AsianFixedStrikeOption(T,K)
Model=BlackScholesProcess(sigma);
#f__(x) = pricer(BlackScholesProcess(x[1]),ZeroRate(x[2],x[3],d),mc,EUData);
f__(x) = pricer(BlackScholesProcess(x[1]),ZeroRate(x[2],x[3],d),mc,FwdData);
#x=Float64[sigma,S0]
x=Float64[sigma,S0,r]
gradient(x -> f__(x), x)
| FinancialMonteCarlo | https://github.com/rcalxrc08/FinancialMonteCarlo.jl.git |
|
[
"MIT"
] | 0.3.2 | 728c49a9de6ffe78fceb7bcba3b53db070fa5532 | code | 807 | using FinancialMonteCarlo,Zygote;
@show "Black Scholes Model"
S0=100.0;
K=100.0;
r=0.02;
T=1.0;
d=0.01;
D=90.0;
Nsim=100;
Nstep=3;
sigma=0.2
mc=MonteCarloConfiguration(Nsim,Nstep);
toll=0.8
rfCurve=ZeroRate(r);
FwdData=Forward(T)
EUData=EuropeanOption(T,K)
AMData=AmericanOption(T,K)
BarrierData=BarrierOptionDownOut(T,K,D)
AsianFloatingStrikeData=AsianFloatingStrikeOption(T)
AsianFixedStrikeData=AsianFixedStrikeOption(T,K)
Model=BlackScholesProcess(sigma,Underlying(S0,d));
#f__(x) = pricer(BlackScholesProcess(x[1]),ZeroRate(x[2],x[3],d),mc,EUData);
#f__(x) = pricer(BlackScholesProcess(x[1],Underlying(x[2],d)),ZeroRate(x[3]),mc,FwdData);
f__(x) = sum(simulate(BlackScholesProcess(x[1],Underlying(x[2],d)),ZeroRate(x[3]),mc,T));
#x=Float64[sigma,S0]
x=Float64[sigma,S0,r]
gradient(x -> f__(x), x)
| FinancialMonteCarlo | https://github.com/rcalxrc08/FinancialMonteCarlo.jl.git |
|
[
"MIT"
] | 0.3.2 | 728c49a9de6ffe78fceb7bcba3b53db070fa5532 | code | 3665 | #Number Type (just sigma tested) ---> Model type ----> Mode ---> zero rate type
using Test, DualNumbers, FinancialMonteCarlo, VectorizedRNG, JLD2
rebase = false;
sigma_dual = dual(0.2, 1.0);
sigma_no_dual = 0.2;
suite_num = Dict{String, Number}()
und = Underlying(100.0, 0.01);
p = 0.3;
lam = 5.0;
lamp = 30.0;
lamm = 20.0;
mu1 = 0.03;
sigma1 = 0.02;
sigma_zero = 0.2;
kappa = 0.01;
theta = 0.03;
lambda = 0.01;
rho = 0.0;
theta1 = 0.01;
k1 = 0.03;
sigma1 = 0.02;
T = 1.0;
K = 100.0;
Nsim = 10_000;
Nstep = 30;
std_mc = MonteCarloConfiguration(Nsim, Nstep);
anti_mc = MonteCarloConfiguration(Nsim, Nstep, FinancialMonteCarlo.AntitheticMC());
sobol_mc = MonteCarloConfiguration(Nsim, Nstep, FinancialMonteCarlo.SobolMode());
cv_mc = MonteCarloConfiguration(Nsim, Nstep, FinancialMonteCarlo.ControlVariates(Forward(T), MonteCarloConfiguration(100, 3)));
cv_mc_2 = MonteCarloConfiguration(Nsim, Nstep, FinancialMonteCarlo.ControlVariates(AsianFloatingStrikeOption(T), MonteCarloConfiguration(100, 3)));
vect_mc = MonteCarloConfiguration(Nsim, Nstep, FinancialMonteCarlo.SerialMode(10, local_rng()));
mc_modes = [std_mc, anti_mc, sobol_mc, cv_mc, cv_mc_2, vect_mc]
r = 0.02;
r_prev = 0.019999;
D = 60;
lam_vec = Float64[0.99];
zr_scalar = ZeroRate(r);
zr_imp = FinancialMonteCarlo.ImpliedZeroRate([r_prev, r], 2.0);
eur_opt_ = EuropeanOption(T, K);
EUBin = BinaryEuropeanOption(T, K)
AMData = AmericanOption(T, K)
AmBin = BinaryEuropeanOption(T, K)
BarrierData = BarrierOptionDownOut(T, K, D)
AsianFloatingStrikeData = AsianFloatingStrikeOption(T)
AsianFixedStrikeData = AsianFixedStrikeOption(T, K)
BinAMData = BinaryAmericanOption(T, K)
BarrierDataDI = BarrierOptionDownIn(T, K, D)
BarrierDataUI = BarrierOptionUpIn(T, K, D)
BarrierDataUO = BarrierOptionUpOut(T, K, D)
BermData = BermudanOption(collect(0.2:0.1:T), K);
doubleBarrierOptionDownOut = DoubleBarrierOption(T, K, K / 10.0, 1.2 * K)
opt_vec = [eur_opt_, EUBin, AMData, AmBin, BarrierData, AsianFloatingStrikeData, AsianFixedStrikeData, BinAMData, BarrierDataDI, BarrierDataUO, BermData, doubleBarrierOptionDownOut];
bs(sigma) = BlackScholesProcess(sigma, und)
kou(sigma) = KouProcess(sigma, lam, p, lamp, lamm, und);
hest(sigma) = HestonProcess(sigma, sigma_zero, lambda, kappa, rho, theta, und);
vg(sigma) = VarianceGammaProcess(sigma, theta1, k1, und)
merton(sigma) = MertonProcess(sigma, lambda, mu1, sigma1, und)
nig(sigma) = NormalInverseGaussianProcess(sigma, theta1, k1, und);
log_mixture(sigma) = LogNormalMixture([sigma, 0.2], lam_vec, und);
shift_mixture(sigma) = ShiftedLogNormalMixture([sigma, 0.2], lam_vec, 0.0, und);
create_str_lam(x...) = join([string(typeof(y)) for y in x], "_");
for sigma in Number[sigma_no_dual, sigma_dual]
for model_ in [bs(sigma), kou(sigma), hest(sigma), vg(sigma), merton(sigma), nig(sigma), log_mixture(sigma), shift_mixture(sigma)]
for mode_ in mc_modes
for zero_ in [zr_scalar, zr_imp]
for opt in opt_vec
key_tmp1 = create_str_lam(sigma, model_, mode_.monteCarloMethod, mode_.parallelMode.rng, zero_, opt)
result = pricer(model_, zero_, mode_, opt)
@assert !isnan(result) "Result for provided simulation is nan $(result) $(key_tmp1)\n"
suite_num[key_tmp1] = result
end
end
end
end
end
OUTPUT = joinpath(@__DIR__, "test_results.jld2")
if rebase
save(OUTPUT, suite_num)
end
suite_num_old_results = load(OUTPUT)
toll = 0.4
for key_tmp in unique([collect(keys(suite_num_old_results)); collect(keys(suite_num))])
@test abs(suite_num[key_tmp] - suite_num_old_results[key_tmp]) < toll
end | FinancialMonteCarlo | https://github.com/rcalxrc08/FinancialMonteCarlo.jl.git |
|
[
"MIT"
] | 0.3.2 | 728c49a9de6ffe78fceb7bcba3b53db070fa5532 | code | 3170 | #Number Type (just sigma tested) ---> Model type ----> Mode ---> zero rate type
using Test, DualNumbers, FinancialMonteCarlo, JLD2, CUDA
rebase = false;
sigma_dual = dual(0.2, 1.0);
sigma_no_dual = 0.2;
suite_num = Dict{String, Number}()
und = Underlying(100.0, 0.01);
p = 0.3;
lam = 5.0;
lamp = 30.0;
lamm = 20.0;
mu1 = 0.03;
sigma1 = 0.02;
sigma_zero = 0.2;
kappa = 0.01;
theta = 0.03;
lambda = 0.01;
rho = 0.0;
theta1 = 0.01;
k1 = 0.03;
sigma1 = 0.02;
T = 1.0;
K = 100.0;
Nsim = 10_000;
Nstep = 30;
mc = MonteCarloConfiguration(Nsim, Nstep, FinancialMonteCarlo.CudaMode());
mc_2 = MonteCarloConfiguration(Nsim, Nstep, FinancialMonteCarlo.AntitheticMC(), FinancialMonteCarlo.CudaMode());
r = 0.02;
r_prev = 0.019999;
D = 60;
lam_vec = Float64[0.99];
zr_scalar = ZeroRate(r);
zr_imp = FinancialMonteCarlo.ImpliedZeroRate([r_prev, r], 2.0);
eur_opt_ = EuropeanOption(T, K);
EUBin = BinaryEuropeanOption(T, K)
AMData = AmericanOption(T, K)
AmBin = BinaryEuropeanOption(T, K)
BarrierData = BarrierOptionDownOut(T, K, D)
AsianFloatingStrikeData = AsianFloatingStrikeOption(T)
AsianFixedStrikeData = AsianFixedStrikeOption(T, K)
BinAMData = BinaryAmericanOption(T, K)
BarrierDataDI = BarrierOptionDownIn(T, K, D)
BarrierDataUI = BarrierOptionUpIn(T, K, D)
BarrierDataUO = BarrierOptionUpOut(T, K, D)
BermData = BermudanOption(collect(0.2:0.1:T), K);
doubleBarrierOptionDownOut = DoubleBarrierOption(T, K, K / 10.0, 1.2 * K)
bs(sigma) = BlackScholesProcess(sigma, und)
kou(sigma) = KouProcess(sigma, lam, p, lamp, lamm, und);
hest(sigma) = HestonProcess(sigma, sigma_zero, lambda, kappa, rho, theta, und);
vg(sigma) = VarianceGammaProcess(sigma, theta1, k1, und)
merton(sigma) = MertonProcess(sigma, lambda, mu1, sigma1, und)
nig(sigma) = NormalInverseGaussianProcess(sigma, theta1, k1, und);
log_mixture(sigma) = LogNormalMixture([sigma, 0.2], lam_vec, und);
shift_mixture(sigma) = ShiftedLogNormalMixture([sigma, 0.2], lam_vec, 0.0, und);
create_str_lam(x...) = join([string(typeof(y)) for y in x], "_");
for sigma in Number[sigma_no_dual, sigma_dual]
for model_ in [bs(sigma), kou(sigma), hest(sigma), vg(sigma), merton(sigma), nig(sigma), log_mixture(sigma), shift_mixture(sigma)]
for mode_ in [mc, mc_2]
for zero_ in [zr_scalar, zr_imp]
for opt in [eur_opt_, EUBin, AMData, AmBin, BarrierData, AsianFloatingStrikeData, AsianFixedStrikeData, BinAMData, BarrierDataDI, BarrierDataUO, BermData, doubleBarrierOptionDownOut]
key_tmp1 = create_str_lam(sigma, model_, mode_.monteCarloMethod, mode_.parallelMode.rng, zero_, opt)
result = pricer(model_, zero_, mode_, opt)
@assert !isnan(result) "Result for provided simulation is nan $(key_tmp1)"
suite_num[key_tmp1] = result
end
end
end
end
end
OUTPUT = joinpath(@__DIR__, "test_results_cuda.jld2")
if rebase
save(OUTPUT, suite_num)
end
suite_num_old_results = load(OUTPUT)
toll = 1.0
for key_tmp in unique([collect(keys(suite_num_old_results)); collect(keys(suite_num))])
@test abs(suite_num[key_tmp] - suite_num_old_results[key_tmp]) < toll
end | FinancialMonteCarlo | https://github.com/rcalxrc08/FinancialMonteCarlo.jl.git |
|
[
"MIT"
] | 0.3.2 | 728c49a9de6ffe78fceb7bcba3b53db070fa5532 | docs | 4200 | # FinancialMonteCarlo.jl <img src="etc/logo.png" width="40">
[](https://rcalxrc08.gitlab.io/FinancialMonteCarlo.jl/)
[](https://gitlab.com/rcalxrc08/FinancialMonteCarlo.jl/commits/master) [](https://codecov.io/gl/rcalxrc08/FinancialMonteCarlo.jl)
##### This is a Julia package containing some useful Financial function for Pricing and Risk Management for Equity products.
It currently contains the following capabilities:
- Support for the following Single Name Models:
- Black Scholes
- Kou
- Merton
- Normal Inverse Gaussian
- Variance Gamma
- Heston
- LogNormal Mixture
- Shifted LogNormal Mixture
- Support for Multivariate processes through Gaussian Copula
- Support for non costant zero rates and dividends
- Support for the following Option families:
- European Options
- Barrier Options
- Asian Options
- Bermudan Options (Using Longstaff-Schwartz)
- American Options (Using Longstaff-Schwartz)
- Partial Support for the following Parallelization:
- CUDA using [CUDA.jl](https://github.com/JuliaGPU/CUDA.jl)
- Thread based (Native julia)
- Process based (Native julia)
It also supports the pricing directly from the definition of the Stochastic Differential Equation, using the package [DifferentiatialEquations.jl](https://github.com/JuliaDiffEq/DifferentialEquations.jl).
Currently supports [DualNumbers.jl](https://github.com/JuliaDiff/DualNumbers.jl), [HyperDualNumbers.jl](https://github.com/JuliaDiff/HyperDualNumbers.jl), [TaylorSeries.jl](https://github.com/JuliaDiff/TaylorSeries.jl), [ForwardDiff.jl](https://github.com/JuliaDiff/ForwardDiff.jl) and [ReverseDiff.jl](https://github.com/JuliaDiff/ReverseDiff.jl)
for Automatic Differentiation (where it makes sense).
## How to Install
To install the package simply type on the Julia REPL the following:
```julia
] add FinancialMonteCarlo
```
## How to Test
After the installation, to test the package type on the Julia REPL the following:
```julia
] test FinancialMonteCarlo
```
## Hello World: Pricing European Call Option in Black Scholes Model
The following example shows how to price a european call option with underlying varying according to the Black Scholes Model, given the volatility:
```julia
#Import the Package
using FinancialMonteCarlo;
#Define Spot Datas
S0=100.0;
K=100.0;
r=0.02;
T=1.0;
d=0.01;
D=90.0;
#Define FinancialMonteCarlo Parameters
Nsim=10000;
Nstep=30;
#Define Model Parameters
σ=0.2;
#Build the Structs
mcConfig=MonteCarloConfiguration(Nsim,Nstep); #Configurator
zeroRate=ZeroRate(r);
underlying=Underlying(S0,d); #Underlying relative data
#Define The Option
EU_payoff=EuropeanOption(T,K)
#Define the Model
Model=BlackScholesProcess(σ,underlying);
#Price
@show EuPrice=pricer(Model,zeroRate,mcConfig,EU_payoff);
```
## Curve Support
Non constant zero rates and dividend are managed.
An implied curve is built at time zero, such implied curve is able to return the right implied zero/dividend at a given time,
Without the need to carry the integral structure of the curve.
No support for multicurrency.
## Contracts Algebra
Contracts that refer to the same underlying can be sum togheter in order to build a "new instrument".
In this sense assuming the same underlying, the set of contracts form a vectorial space over "Real" Numbers.
## Market Data and Multivariate Support
A market data set is a dictionary containing all of the process for which we have a view (or a model). ( "KEY" => MODEL)
The portofolio is a dictionary as well but it carries the structure of the portfolio. ( "KEY" => CONTRACTS_ON_MODEL)
## Keep in mind
There are few things that you should keep in mind when using this library:
- First Order Automatic Differentiation is enabled for any kind of option, also for such that there is no sense (e.g. Binary, Barriers).
- Second Order Automatic Differentiation is enabled for any kind of option but the results are useless most of the time.
| FinancialMonteCarlo | https://github.com/rcalxrc08/FinancialMonteCarlo.jl.git |
|
[
"MIT"
] | 0.3.2 | 728c49a9de6ffe78fceb7bcba3b53db070fa5532 | docs | 1826 | # Create New Models and Payoffs
Whereas this package already provides a large collection of common models/payoffs out of box, there are still occasions where you want to create new models/payoffs (*e.g* your application requires a special kind of models/payoffs, or you want to contribute to this package).
Generally, you don't have to implement every API method listed in the documentation. This package provides a series of generic functions that turn a small number of internal methods into user-end API methods. What you need to do is to implement this small set of internal methods for your models/payoffs.
## Create a Model
To use your model inside the package, you must implement a struct, that is inheriting from one of the abstract classes defined in the Type section.
Such struct must contain the parameters of your model, then you have to implement a function called `simulate` or `simulate!` that is representing how your model simulates.
You can easily copy the signature of the function from one of the implementation in the models folder. Pay attention to the distinction between Engine and Model.
## Create a Payoff
To use your payoff inside the package, you must implement a struct, that is inheriting from one of the abstract classes defined in the Type section.
Such struct must contain the parameters (strike, time to maturity, barriers, etc) of your payoff, then you have to implement a function called `payoff` that is representing how your payoff acts.
You can easily copy the signature of the function from one of the implementation in the payoffs folder.
## Finalize the interaction
Once you have implemented your own payoff/model, you can directly use the functionalities provided already by the package, e.g. `pricer`,`var`,`ci` and all of the models/payoffs that have been already implemented. | FinancialMonteCarlo | https://github.com/rcalxrc08/FinancialMonteCarlo.jl.git |
|
[
"MIT"
] | 0.3.2 | 728c49a9de6ffe78fceb7bcba3b53db070fa5532 | docs | 1720 | ```@meta
EditURL = "../../examples/getting_started.jl"
```
# Getting Started
## Installation
The FinancialMonteCarlo package is available through the Julia package system
by running `]add FinancialMonteCarlo`.
Throughout, we assume that you have installed the package.
## Basic syntax
The basic syntax for FinancialMonteCarlo is simple. Here is an example of pricing a European Option with a Black Scholes model:
````@example getting_started
using FinancialMonteCarlo
S0 = 100.0;
K = 100.0;
r = 0.02;
T = 1.0;
d = 0.01;
D = 90.0;
nothing #hide
````
Define FinancialMonteCarlo Parameters:
````@example getting_started
Nsim = 10000;
Nstep = 30;
nothing #hide
````
Define Model Parameters.
````@example getting_started
σ = 0.2;
nothing #hide
````
Build the MonteCarlo configuration and the zero rate.
````@example getting_started
mcConfig = MonteCarloConfiguration(Nsim, Nstep);
rfCurve = ZeroRate(r);
nothing #hide
````
Define The Option
````@example getting_started
EuOption = EuropeanOption(T, K)
````
Define the Model of the Underlying
````@example getting_started
Model = BlackScholesProcess(σ, Underlying(S0, d));
nothing #hide
````
Call the pricer metric
````@example getting_started
@show EuPrice = pricer(Model, rfCurve, mcConfig, EuOption);
nothing #hide
````
## Using Other Models and Options
The package contains a large number of models of three main types:
* `Ito Process`
* `Jump-Diffusion Process`
* `Infinity Activity Process`
And the following types of options:
* `European Options`
* `Asian Options`
* `Barrier Options`
* `American Options`
The usage is analogous to the above example.
---
*This page was generated using [Literate.jl](https://github.com/fredrikekre/Literate.jl).*
| FinancialMonteCarlo | https://github.com/rcalxrc08/FinancialMonteCarlo.jl.git |
|
[
"MIT"
] | 0.3.2 | 728c49a9de6ffe78fceb7bcba3b53db070fa5532 | docs | 2062 | # FinancialMonteCarlo.jl
FinancialMonteCarlo.jl contains the following capabilities:
- Support for the following Single Name Models:
- Black Scholes
- Kou
- Merton
- Normal Inverse Gaussian
- Variance Gamma
- Heston
- LogNormal Mixture
- Support for Sobol and Vectorized RNG.
- Support for Multivariate processes through Gaussian Copula
- Support for non costant zero rates and dividends
- Support for the following Option families:
- European Options
- Barrier Options
- Asian Options
- Bermudan Options (Using Longstaff-Schwartz)
- American Options (Using Longstaff-Schwartz)
- Partial Support for the following Parallelization:
- CUDA using [CUDA.jl](https://github.com/JuliaGPU/CUDA.jl)
- Thread based (Native julia)
- Process based (Native julia)
It also supports the pricing directly from the definition of the Stochastic Differential Equation, using the package [DifferentiatialEquations.jl](https://github.com/JuliaDiffEq/DifferentialEquations.jl).
Currently supports [DualNumbers.jl](https://github.com/JuliaDiff/DualNumbers.jl), [HyperDualNumbers.jl](https://github.com/JuliaDiff/HyperDualNumbers.jl), [TaylorSeries.jl](https://github.com/JuliaDiff/TaylorSeries.jl), [ForwardDiff.jl](https://github.com/JuliaDiff/ForwardDiff.jl) and [ReverseDiff.jl](https://github.com/JuliaDiff/ReverseDiff.jl)
for Automatic Differentiation (where it makes sense).
## How to Install
To install the package simply type on the Julia REPL the following:
```julia
] add FinancialMonteCarlo
```
## How to Test
After the installation, to test the package type on the Julia REPL the following:
```julia
] test FinancialMonteCarlo
```
## Keep in mind
There are few things that you should keep in mind when using this library:
- First Order Automatic Differentiation is enabled for any kind of option, also for such that there is no sense (e.g. Binary, Barriers).
- Second Order Automatic Differentiation is enabled for any kind of option but the results are useless most of the time.
## Index
```@index
``` | FinancialMonteCarlo | https://github.com/rcalxrc08/FinancialMonteCarlo.jl.git |
|
[
"MIT"
] | 0.3.2 | 728c49a9de6ffe78fceb7bcba3b53db070fa5532 | docs | 1434 | # Interaction with [DifferentialEquations.jl](https://diffeq.sciml.ai/stable/)
The following example shows how to price different kind of options with underlying varying according to the Black Scholes Model, simulated using DifferentialEquations.jl.
```julia
#Import the Package
using FinancialMonteCarlo,DifferentialEquations;
#Define Spot Datas
S0=100.0;
K=100.0;
r=0.02;
T=1.0;
d=0.01;
D=90.0;
u0=S0;
#Define FinancialMonteCarlo Parameters
Nsim=10000;
Nstep=30;
#Define Model Parameters
σ=0.2;
#Build the Structs
mcConfig=MonteCarloConfiguration(Nsim,Nstep);
rfCurve=ZeroRate(S0,r,d);
#Define The Options
Fwd_payoff=Forward(T)
EU_payoff=EuropeanOption(T,K)
AM_payoff=AmericanOption(T,K)
Barrier_payoff=BarrierOptionDownOut(T,K,D)
AsianFloatingStrike_payoff=AsianFloatingStrikeOption(T)
AsianFixedStrike_payoff=AsianFixedStrikeOption(T,K)
##Define the Model
#Drift
f(u,p,t) = (r-d)*u
#Diffusion
g(u,p,t) = σ*u
#Time Window
tspan = (0.0,T)
#Definition of the SDE
prob = SDEProblem(f,g,u0,tspan)
Model = MonteCarloProblem(prob)
#Price
@show FwdPrice=pricer(Model,rfCurve,mcConfig,Fwd_payoff);
@show EuPrice=pricer(Model,rfCurve,mcConfig,EU_payoff);
@show AmPrice=pricer(Model,rfCurve,mcConfig,AM_payoff);
@show BarrierPrice=pricer(Model,rfCurve,mcConfig,Barrier_payoff);
@show AsianPrice1=pricer(Model,rfCurve,mcConfig,AsianFloatingStrike_payoff);
@show AsianPrice2=pricer(Model,rfCurve,mcConfig,AsianFixedStrike_payoff);
``` | FinancialMonteCarlo | https://github.com/rcalxrc08/FinancialMonteCarlo.jl.git |
|
[
"MIT"
] | 0.3.2 | 728c49a9de6ffe78fceb7bcba3b53db070fa5532 | docs | 1327 | # [Metrics](@id Metric)
The following type of *Metric* are supported from the package:
* `pricer`
* `delta`
* `rho`
* `variance`
* `confinter`
## Common Interface
Each Metric must implement its own *Metric* method; the general interface is the following:
```@docs
pricer(mcProcess::FinancialMonteCarlo.BaseProcess,spotData::ZeroRate,mcConfig::MonteCarloConfiguration,abstractPayoff::FinancialMonteCarlo.AbstractPayoff)
variance(mcProcess::FinancialMonteCarlo.BaseProcess,spotData::ZeroRate,mcConfig::MonteCarloConfiguration,abstractPayoff::FinancialMonteCarlo.AbstractPayoff)
confinter(mcProcess::FinancialMonteCarlo.BaseProcess,spotData::ZeroRate,mcConfig::MonteCarloConfiguration,abstractPayoff::FinancialMonteCarlo.AbstractPayoff,alpha::Real=0.99)
delta(mcProcess::FinancialMonteCarlo.BaseProcess,spotData::ZeroRate,mcConfig::MonteCarloConfiguration,abstractPayoff::FinancialMonteCarlo.AbstractPayoff,dS0::Real=1e-7)
rho(mcProcess::FinancialMonteCarlo.BaseProcess, rfCurve::FinancialMonteCarlo.AbstractZeroRateCurve, mcConfig::MonteCarloConfiguration, abstractPayoff::FinancialMonteCarlo.AbstractPayoff, dr::Real = 1e-7)
FinancialMonteCarlo.distribution(mcProcess::FinancialMonteCarlo.BaseProcess, rfCurve::FinancialMonteCarlo.AbstractZeroRateCurve, mcConfig::MonteCarloConfiguration, T::num_) where {num_ <: Number}
``` | FinancialMonteCarlo | https://github.com/rcalxrc08/FinancialMonteCarlo.jl.git |
|
[
"MIT"
] | 0.3.2 | 728c49a9de6ffe78fceb7bcba3b53db070fa5532 | docs | 372 | # [Multivariates](@id Multivariate)
The following types of *Multivariate* are supported from the package using package "DatagenCopulaBased.jl":
* `N dimensional Gaussian copula`
* `N dimensional Gaussian copula for log processes`
## Common Interface
The following option structs are provided:
```@docs
GaussianCopulaNVariateLogProcess
GaussianCopulaNVariateProcess
``` | FinancialMonteCarlo | https://github.com/rcalxrc08/FinancialMonteCarlo.jl.git |
|
[
"MIT"
] | 0.3.2 | 728c49a9de6ffe78fceb7bcba3b53db070fa5532 | docs | 1284 | # Variance Reduction, Parallel Mode and Random Number Generators
The package provides functionalities regarding variance reduction and parallel mode.
## Parallel Mode
The package provides the BaseMode type to represent the type of parallel processe that is going to simulate:
* `SerialMode`: classical serial mode with no parallelization
* `CudaMode`: support for CUDA using CUDA.jl
* `MultiThreading`: Threads parallelization with julia built in costructs
* `MultiProcess`: Processes parallelization with julia built in costructs
## Random Number Generator and seed control
You can provide your own rng (that must inherit from Base.AbstractRNG), or choose the built in one controlling the seed.
Seed is controlled from inside the package, each call to the constructor of MonteCarloConfiguration or pricer(...) automatically set the seed.
If you want to control the seed from outside, just provide already build rng to constructor of MonteCarloConfiguration and avoid calls to pricer(...).
## Variance Reduction
The variance reduction is achieved using antithetic variables approach and control variates.
## How to
In order to impose a particular parallel mode, rng or variance reduction tecnique you should provide additional parameters to MonteCarloConfiguration constructor. | FinancialMonteCarlo | https://github.com/rcalxrc08/FinancialMonteCarlo.jl.git |
|
[
"MIT"
] | 0.3.2 | 728c49a9de6ffe78fceb7bcba3b53db070fa5532 | docs | 980 | # [Payoffs](@id payoff)
The following type of *Payoff* are supported from the package:
* `European Options`
* `Asian Options`
* `Barrier Options`
* `American Options`
* `Bermudan Options`
## Common Interface
Each payoff must implement its own *payout* method; that will be called by the following general interface:
```@docs
payoff(S::AbstractMatrix, p::FinancialMonteCarlo.AbstractPayoff, r::FinancialMonteCarlo.AbstractZeroRateCurve, mc::FinancialMonteCarlo.AbstractMonteCarloConfiguration, T1::Number = p.T)
```
Depending on the type of AbstractPayoff, a different type of S must be specified. Look into the engines for more details.
The following option structs are provided:
```@docs
BinaryEuropeanOption
AsianFloatingStrikeOption
BarrierOptionDownOut
AsianFixedStrikeOption
DoubleBarrierOption
BarrierOptionUpOut
BarrierOptionUpIn
BinaryAmericanOption
EuropeanOption
Forward
BarrierOptionDownIn
AmericanOption
Spot
EuropeanOptionND
FinancialMonteCarlo.BermudanOption
``` | FinancialMonteCarlo | https://github.com/rcalxrc08/FinancialMonteCarlo.jl.git |
|
[
"MIT"
] | 0.3.2 | 728c49a9de6ffe78fceb7bcba3b53db070fa5532 | docs | 1352 | # [Stochastic Processes](@id stochproc)
The package support the following processes:
* `Black Scholes Process`
* `Heston Process`
* `Kou Process`
* `Merton Process`
* `Variance Gamma Process`
* `Normal Inverse Gaussian Process`
* `Lognormal Mixture Process`
* `Shifted Lognormal Mixture Process`
## Common Interface
A single method is implemented for each process, which provide the simulation output.
### Simulation
Each process behave in its own different way but returning the same kind of object after simulation,
the generic interfaces for simulating are the following:
```@docs
simulate(mcProcess::FinancialMonteCarlo.AbstractMonteCarloProcess,spotData::FinancialMonteCarlo.AbstractZeroRateCurve,mcBaseData::FinancialMonteCarlo.AbstractMonteCarloConfiguration, T::Number)
```
```@docs
simulate(mcProcess::FinancialMonteCarlo.AbstractMonteCarloEngine,mcBaseData::FinancialMonteCarlo.AbstractMonteCarloConfiguration, T::Number)
```
The following process are already implemented:
```@docs
BlackScholesProcess
BrownianMotion
FinancialMonteCarlo.BrownianMotionVec
GeometricBrownianMotion
FinancialMonteCarlo.GeometricBrownianMotionVec
HestonProcess
KouProcess
LogNormalMixture
MertonProcess
NormalInverseGaussianProcess
SubordinatedBrownianMotion
FinancialMonteCarlo.SubordinatedBrownianMotionVec
ShiftedLogNormalMixture
VarianceGammaProcess
``` | FinancialMonteCarlo | https://github.com/rcalxrc08/FinancialMonteCarlo.jl.git |
|
[
"MIT"
] | 0.3.2 | 728c49a9de6ffe78fceb7bcba3b53db070fa5532 | docs | 2359 | # Type Hierarchy
All models, payoffs and modes provided in this package are organized into a type hierarchy described as follows.
## Models
Remember that each model must have a `simulate` method implemented that specifies the way that the model behaves.
From that abstract class the followings are derived and decomposed as follows:
`AbstractMonteCarloProcess` is used to represent any model that is implemented completely inside this package:
```julia
abstract type AbstractMonteCarloProcess <: AbstractMonteCarloProblem end
```
`ItoProcess` is used to represent any Ito Process:
```julia
abstract type ItoProcess<:AbstractMonteCarloProcess end
```
`LevyProcess` is used to represent any Levy Process:
```julia
abstract type LevyProcess<:AbstractMonteCarloProcess end
```
`FiniteActivityProcess` is used to represent any Finite Activity Levy Process:
```julia
abstract type FiniteActivityProcess<:LevyProcess end
```
`InfiniteActivityProcess` is used to represent any Infinite Activity Levy Process:
```julia
abstract type InfiniteActivityProcess<:LevyProcess end
```
Each concrete model that is implemented inside this package inherits from one of these above models.
Remember that the model type is used to carry the parameters of the model and the dispatch when it's time to simulate, i.e.,
there is just one function `simulate` that is overloaded with respect to the model type.
## Payoffs
The type hierarchy has a root type called `AbstractPayoff`, that type is used whenever it is not necessary to know the model type, like in `pricer`,`var` and `ci`.
Each payoff must have a `payoff` method implemented that specifies the way that the payoff behaves.
From that abstract class the followings are derived and decomposed as follows:
```julia
abstract type AbstractPayoff end
```
```julia
abstract type EuropeanPayoff<:AbstractPayoff end
```
```julia
abstract type AmericanPayoff<:AbstractPayoff end
```
```julia
abstract type BarrierPayoff<:AbstractPayoff end
```
```julia
abstract type AsianPayoff<:AbstractPayoff end
```
Each concrete payoff that is implemented inside this package inherits from one of these above payoffs.
Remember that the payoff type is used to carry the parameters of the model and the dispatch when it's time to price, i.e.,
there is just one function `payoff` that is overloaded with respect to the payoff type. | FinancialMonteCarlo | https://github.com/rcalxrc08/FinancialMonteCarlo.jl.git |
|
[
"MIT"
] | 2.0.12 | 49f3d06de40de20ff0d8c7d855bd461d5061e96d | code | 1564 | using Documenter, Literate, NaiveNASflux
const nndir = joinpath(dirname(pathof(NaiveNASflux)), "..")
function literate_example(sourcefile; rootdir=nndir, sourcedir = "test/examples", destdir="docs/src/examples")
fullpath = Literate.markdown(joinpath(rootdir, sourcedir, sourcefile), joinpath(rootdir, destdir); flavor=Literate.DocumenterFlavor(), mdstrings=true, codefence="````julia" => "````")
dirs = splitpath(fullpath)
srcind = findfirst(==("src"), dirs)
joinpath(dirs[srcind+1:end]...)
end
quicktutorial = literate_example("quicktutorial.jl")
xorpruning = literate_example("xorpruning.jl")
makedocs( sitename="NaiveNASflux",
root = joinpath(nndir, "docs"),
format = Documenter.HTML(
prettyurls = get(ENV, "CI", nothing) == "true"
),
pages = [
"index.md",
quicktutorial,
xorpruning,
"API Reference" => [
"reference/createvertex.md",
"reference/layerwrappers.md",
"reference/misc.md"
]
],
modules = [NaiveNASflux],
)
function touchfile(filename, rootdir=nndir, destdir="test/examples")
filepath = joinpath(rootdir, destdir, filename)
isfile(filepath) && return
write(filepath, """
md\"\"\"
# Markdown header
\"\"\"
""")
end
if get(ENV, "CI", nothing) == "true"
deploydocs(
repo = "github.com/DrChainsaw/NaiveNASflux.jl.git",
push_preview=true
)
end | NaiveNASflux | https://github.com/DrChainsaw/NaiveNASflux.jl.git |
|
[
"MIT"
] | 2.0.12 | 49f3d06de40de20ff0d8c7d855bd461d5061e96d | code | 1112 | module NaiveNASflux
using Reexport
@reexport using NaiveNASlib
using NaiveNASlib.Extend, NaiveNASlib.Advanced
import Flux
using Flux: Dense, Conv, ConvTranspose, CrossCor, LayerNorm, BatchNorm, InstanceNorm, GroupNorm,
MaxPool, MeanPool, Dropout, AlphaDropout, GlobalMaxPool, GlobalMeanPool, cpu, @layer
import Optimisers
import Functors
using Statistics
using Setfield: @set, setproperties
using LinearAlgebra
import JuMP
import JuMP: @variable, @constraint, @expression, SOS1, MOI
import ChainRulesCore
import ChainRulesCore: rrule_via_ad, RuleConfig, HasReverseMode, Tangent, NoTangent
export denseinputvertex, rnninputvertex, fluxvertex, concat
export convinputvertex, conv1dinputvertex, conv2dinputvertex, conv3dinputvertex
export ActivationContribution, LazyMutable
export layer
export KernelSizeAligned
export NeuronUtilityEvery
include("types.jl")
include("util.jl")
include("constraints.jl")
include("select.jl")
include("mutable.jl")
include("vertex.jl")
include("neuronutility.jl")
# Stuff to integrate with Zygote
include("chainrules.jl")
include("precompile.jl")
end # module | NaiveNASflux | https://github.com/DrChainsaw/NaiveNASflux.jl.git |
|
[
"MIT"
] | 2.0.12 | 49f3d06de40de20ff0d8c7d855bd461d5061e96d | code | 1151 | # Stuff to make things play nice with AD (typically Zygote)
# Not exported, but I ended up using this in NaiveGAflux and don't want to update it now...
# Consider it deprecated
const nograd = ChainRulesCore.ignore_derivatives
ChainRulesCore.@non_differentiable mutate(args...)
# Temp workaround for https://github.com/FluxML/Zygote.jl/issues/1111
# Whole function can be deleted if/when issue is resolved
function ChainRulesCore.rrule(config::RuleConfig{>:HasReverseMode}, m::MutableLayer, args...)
res, back = rrule_via_ad(config, m.layer, args...)
function MutableLayer_back(Δ)
δs = back(Δ)
Tangent{MutableLayer}(layer=δs[1]), δs[2:end]...
end
return res, MutableLayer_back
end
# Not just a workaround!
# We do forcemutation so that we don't end up trying to differentiate through it
function ChainRulesCore.rrule(config::RuleConfig{>:HasReverseMode}, m::LazyMutable, args...)
forcemutation(m)
res, back = rrule_via_ad(config, m.mutable, args...)
function LazyMutable_back(Δ)
δs = back(Δ)
Tangent{LazyMutable}(mutable=δs[1]), δs[2:end]...
end
return res, LazyMutable_back
end
| NaiveNASflux | https://github.com/DrChainsaw/NaiveNASflux.jl.git |
|
[
"MIT"
] | 2.0.12 | 49f3d06de40de20ff0d8c7d855bd461d5061e96d | code | 19151 |
usesos1(model::JuMP.Model) = usesos1(JuMP.backend(model))
usesos1(m) = JuMP.MOI.supports_constraint(m, JuMP.MOI.VectorOfVariables, JuMP.MOI.SOS1)
"""
GroupedConvAllowNinChangeStrategy(newoutputsmax::Integer, multipliersmax::Integer, base, [fallback])
GroupedConvAllowNinChangeStrategy(allowed_new_outgroups::AbstractVector{<:Integer}, allowed_multipliers::AbstractVector{<:Integer}, base, [fallback])
`DecoratingJuMPΔSizeStrategy` which allows both nin and nout of grouped `Conv` layers (i.e `Conv` with `groups` != 1) to change independently.
Might cause optimization to take very long time so use with care! Use [`GroupedConvSimpleΔSizeStrategy`](@ref)
if `GroupedConvAllowNinChangeStrategy` takes too long.
The elements of `allowed_new_outgroups` determine how many extra elements in the output dimension of the weight
shall be tried for each existing output element. For example, for a `Conv((k1,k2), nin=>nout; groups=nin))` one
must insert integer multiples of `nout / nin` elements at the time. With `nin/nout = k` and `allowed_new_outgroups = 0:3` it is allowed to insert 0, `k`, `2k` or `3k` new elements in the output dimension between each already existing element.
The elements of `allowed_multipliers` determine the total number of allowed output elements, i.e the allowed
ratios of `nout / nin`.
If `fallback` is not provided, it will be derived from `base`.
"""
struct GroupedConvAllowNinChangeStrategy{S,F} <: DecoratingJuMPΔSizeStrategy
allowed_new_outgroups::Vector{Int}
allowed_multipliers::Vector{Int}
base::S
fallback::F
end
GroupedConvAllowNinChangeStrategy(newoutputsmax::Integer, multipliersmax::Integer,base,fb...) = GroupedConvAllowNinChangeStrategy(0:newoutputsmax, 1:multipliersmax, base, fb...)
function GroupedConvAllowNinChangeStrategy(
allowed_new_outgroups::AbstractVector{<:Integer},
allowed_multipliers::AbstractVector{<:Integer},
base, fb= recurse_fallback(s -> GroupedConvAllowNinChangeStrategy(allowed_new_outgroups, allowed_multipliers, s), base))
return GroupedConvAllowNinChangeStrategy(collect(Int, allowed_new_outgroups), collect(Int, allowed_multipliers), base, fb)
end
NaiveNASlib.base(s::GroupedConvAllowNinChangeStrategy) = s.base
NaiveNASlib.fallback(s::GroupedConvAllowNinChangeStrategy) = s.fallback
NaiveNASlib.add_participants!(s::GroupedConvAllowNinChangeStrategy, vs=AbstractVertex[]) = NaiveNASlib.add_participants!(base(s), vs)
"""
GroupedConvSimpleΔSizeStrategy(base, [fallback])
`DecoratingJuMPΔSizeStrategy` which only allows nout of grouped `Conv` layers (i.e `Conv` with `groups` != 1) to change.
Use if [`GroupedConvAllowNinChangeStrategy`](@ref) takes too long to solve.
The elements of `allowed_multipliers` determine the total number of allowed output elements, i.e the allowed
ratios of `nout / nin` (where `nin` is fixed).
If `fallback` is not provided, it will be derived from `base`.
"""
struct GroupedConvSimpleΔSizeStrategy{S, F} <: DecoratingJuMPΔSizeStrategy
allowed_multipliers::Vector{Int}
base::S
fallback::F
end
GroupedConvSimpleΔSizeStrategy(maxms::Integer, base, fb...) = GroupedConvSimpleΔSizeStrategy(1:maxms, base, fb...)
function GroupedConvSimpleΔSizeStrategy(ms::AbstractVector{<:Integer}, base, fb=recurse_fallback(s -> GroupedConvSimpleΔSizeStrategy(ms, s), base))
return GroupedConvSimpleΔSizeStrategy(collect(Int, ms), base, fb)
end
NaiveNASlib.base(s::GroupedConvSimpleΔSizeStrategy) = s.base
NaiveNASlib.fallback(s::GroupedConvSimpleΔSizeStrategy) = s.fallback
NaiveNASlib.add_participants!(s::GroupedConvSimpleΔSizeStrategy, vs=AbstractVertex[]) = NaiveNASlib.add_participants!(base(s), vs)
recurse_fallback(f, s::AbstractJuMPΔSizeStrategy) = wrap_fallback(f, NaiveNASlib.fallback(s))
recurse_fallback(f, s::NaiveNASlib.DefaultJuMPΔSizeStrategy) = s
recurse_fallback(f, s::NaiveNASlib.ThrowΔSizeFailError) = s
recurse_fallback(f, s::NaiveNASlib.ΔSizeFailNoOp) = s
recurse_fallback(f, s::NaiveNASlib.LogΔSizeExec) = NaiveNASlib.LogΔSizeExec(s.msgfun, s.level, f(s.andthen))
wrap_fallback(f, s) = f(s)
wrap_fallback(f, s::NaiveNASlib.LogΔSizeExec) = NaiveNASlib.LogΔSizeExec(s.msgfun, s.level, f(s.andthen))
function NaiveNASlib.compconstraint!(case, s, ::FluxLayer, data) end
function NaiveNASlib.compconstraint!(case, s::DecoratingJuMPΔSizeStrategy, lt::FluxLayer, data)
NaiveNASlib.compconstraint!(case, NaiveNASlib.base(s), lt, data)
end
# To avoid ambiguity
function NaiveNASlib.compconstraint!(case::NaiveNASlib.ScalarSize, s::DecoratingJuMPΔSizeStrategy, lt::FluxConvolutional, data)
NaiveNASlib.compconstraint!(case, NaiveNASlib.base(s), lt, data)
end
function NaiveNASlib.compconstraint!(::NaiveNASlib.ScalarSize, s::AbstractJuMPΔSizeStrategy, ::FluxConvolutional, data, ms=allowed_multipliers(s))
ngroups(data.vertex) == 1 && return
# Add constraint that nout(l) == n * nin(l) where n is integer
ins = filter(vin -> vin in keys(data.noutdict), inputs(data.vertex))
# "data.noutdict[data.vertex] == data.noutdict[ins[i]] * x" where x is an integer variable is not linear
# Instead we use the good old big-M strategy to set up a series of "or" constraints (exactly one of them must be true).
# This is combined with the abs value formulation to force equality.
# multiplier[j] is false if and only if data.noutdict[data.vertex] == ms[j]*data.noutdict[ins[i]]
# all but one of multiplier must be true
# Each constraint below is trivially true if multiplier[j] is true since 1e6 is way bigger than the difference between the two variables
multipliers = @variable(data.model, [1:length(ms)], Bin)
@constraint(data.model, sum(multipliers) == length(multipliers)-1)
@constraint(data.model, [i=1:length(ins),j=1:length(ms)], data.noutdict[data.vertex] - ms[j]*data.noutdict[ins[i]] + multipliers[j] * 1e6 >= 0)
@constraint(data.model, [i=1:length(ins),j=1:length(ms)], data.noutdict[data.vertex] - ms[j]*data.noutdict[ins[i]] - multipliers[j] * 1e6 <= 0)
# Inputs which does not have a variable, possibly because all_in_Δsize_graph did not consider it to be part of the set of vertices which may change
# We will constrain data.vertex to have integer multiple of its current size
fixedins = filter(vin -> vin ∉ ins, inputs(data.vertex))
if !isempty(fixedins)
fv_out = @variable(data.model, integer=true)
@constraint(data.model, [i=1:length(fixedins)], data.noutdict[data.vertex] == nout(fixedins[i]) * fv_out)
end
end
allowed_multipliers(s::GroupedConvAllowNinChangeStrategy) = s.allowed_multipliers
allowed_multipliers(s::GroupedConvSimpleΔSizeStrategy) = s.allowed_multipliers
allowed_multipliers(::AbstractJuMPΔSizeStrategy) = 1:10
function NaiveNASlib.compconstraint!(case::NaiveNASlib.NeuronIndices, s::DecoratingJuMPΔSizeStrategy, t::FluxConvolutional, data)
NaiveNASlib.compconstraint!(case, base(s), t, data)
end
function NaiveNASlib.compconstraint!(case::NaiveNASlib.NeuronIndices, s::AbstractJuMPΔSizeStrategy, t::FluxConvolutional, data)
ngroups(data.vertex) == 1 && return
# Fallbacks don't matter here since we won't call it from below here, just add default so we don't accidentally crash due to some
# strategy which hasn't defined a fallback
if 15 < sum(keys(data.outselectvars)) do v
ngroups(v) == 1 && return 0
return log2(nout(v)) # Very roughly determined...
end
return NaiveNASlib.compconstraint!(case, GroupedConvSimpleΔSizeStrategy(10, s, NaiveNASlib.DefaultJuMPΔSizeStrategy()), t, data)
end
# The number of allowed multipliers can probably be better tuned, perhaps based on current size.
return NaiveNASlib.compconstraint!(case, GroupedConvAllowNinChangeStrategy(10, 10, s, NaiveNASlib.DefaultJuMPΔSizeStrategy()), t, data)
#=
For benchmarking:
using NaiveNASflux, Flux, NaiveNASlib.Advanced
function timedwc(ds, ws)
for w in ws
for d in ds
iv = conv2dinputvertex("in", w)
dv = reduce((v, i) -> fluxvertex("dv$i", DepthwiseConv((1,1), nout(v) => fld1(i, 3) * nout(v)), v), 1:d; init=iv)
metric = sum(ancestors(dv)) do v
layer(v) isa Conv || return 0
return log2(nout(v))
end
res = @timed Δsize!(ΔNoutRelaxed(outputs(iv)[1] => w; fallback = ΔSizeFailNoOp()))
println((width=w, depth = d, metric=metric, time=res.time))
res.time < 5 || break
end
end
end
=#
end
function NaiveNASlib.compconstraint!(::NaiveNASlib.NeuronIndices, s::GroupedConvSimpleΔSizeStrategy, t::FluxConvolutional, data)
model = data.model
v = data.vertex
select = data.outselectvars[v]
insert = data.outinsertvars[v]
ngroups(v) == 1 && return
nin(v)[] == 1 && return # Special case, no restrictions as we only need to be an integer multple of 1
if size(weights(layer(v)), indim(v)) != 1
@warn "Handling of convolutional layers with groups != nin not implemented. Model might not be size aligned after mutation!"
end
# Neurons mapped to the same weight are interleaved, i.e layer.weight[:,:,1,:] maps to y[1:ngroups:end] where y = layer(x)
ngrps = div(nout(v), nin(v)[])
for group in 1:ngrps
neurons_in_group = select[group : ngrps : end]
@constraint(model, neurons_in_group[1] == neurons_in_group[end])
@constraint(model, [i=2:length(neurons_in_group)], neurons_in_group[i] == neurons_in_group[i-1])
insert_in_group = insert[group : ngrps : end]
@constraint(model, insert_in_group[1] == insert_in_group[end])
@constraint(model, [i=2:length(insert_in_group)], insert_in_group[i] == insert_in_group[i-1])
end
NaiveNASlib.compconstraint!(NaiveNASlib.ScalarSize(), s, t, data, allowed_multipliers(s))
end
function NaiveNASlib.compconstraint!(case::NaiveNASlib.NeuronIndices, s::GroupedConvAllowNinChangeStrategy, t::FluxConvolutional, data)
model = data.model
v = data.vertex
select = data.outselectvars[v]
insert = data.outinsertvars[v]
ngroups(v) == 1 && return
nin(v)[] == 1 && return # Special case, no restrictions as we only need to be an integer multple of 1?
# Step 0:
# Flux 0.13 changed the grouping of weigths so that size(layer.weight) = (..., nin / ngroups, nout)
# We can get back the shape expected here through weightgroups = reshape(layer.weight, ..., nout / groups, nin)
# Step 1:
# Neurons mapped to the same weight are interleaved, i.e layer.weight[:,:,1,:] maps to y[1:ngroups:end] where y = layer(x)
# where ngroups = nout / nin. For example, nout = 12 and nin = 4 mean size(layer.weight) == (..,3, 4)
# Thus we have ngroups = 3 and with groupsize of 4.
# Now, if we were to change nin to 3, we would still have ngroups = 3 but with groupsize 3 and thus nout = 9
#
ins = filter(vin -> vin in keys(data.noutdict), inputs(v))
# If inputs to v are not part of problem we have to keep nin(v) fixed!
isempty(ins) && return NaiveNASlib.compconstraint!(case, GroupedConvSimpleΔSizeStrategy(allowed_multipliers(s), base(s)), t, data)
# TODO: Check if input is immutable and do simple strat then too?
inselect = data.outselectvars[ins[]]
ininsert = data.outinsertvars[ins[]]
#ngroups = div(nout(v), nin(v)[])
if size(weights(layer(v)), indim(v)) != 1
@warn "Handling of convolutional layers with groups != nin not implemented. Model might not be size aligned after mutation!"
end
ningroups = nin(v)[]
add_depthwise_constraints(model, inselect, ininsert, select, insert, ningroups, s.allowed_new_outgroups, s.allowed_multipliers)
end
function add_depthwise_constraints(model, inselect, ininsert, select, insert, ningroups, allowed_new_outgroups, allowed_multipliers)
# ningroups is the number of "input elements" in the weight array, last dimension at the time of writing
# noutgroups is the number of "output elements" in the weight array, second to last dimension at time of writing
# nin is == ningroups while nout == ningroups * noutgroups
# When changing nin by Δ, we will get ningroups += Δ which just means that we insert/remove Δ input elements.
# Inserting one new input element at position i will get us noutgroups new consecutive outputputs at position i
# Thus nout change by Δ * noutgroups.
# Note: Flux 0.13 changed the grouping of weigths so that size(layer.weight) = (..., nin / ngroups, nout)
# We can get back the shape expected here through weightgroups = reshape(layer.weight, ..., nout / groups, nin)
# All examples below assume the pre-0.13 representation!
# Example:
# dc = DepthwiseConv((1,1), 3 => 9; bias=false);
# size(dc.weight)
# (1, 1, 3, 3)
# indata = randn(Float32, 1,1,3, 1);
# reshape(dc(indata),:)'
# 1×9 adjoint(::Vector{Float32}) with eltype Float32:
# 0.315234 0.267166 -0.227757 0.03523 0.0516438 -0.124007 -0.63409 0.0273361 -0.457146
# Inserting zeros instead of adding/removing just as it is less verbose to do so.
# dc.weight[:,:,:,2] .= 0;
# reshape(dc(indata),:)'
# 1×9 adjoint(::Vector{Float32}) with eltype Float32:
# 0.315234 0.267166 -0.227757 0.0 0.0 0.0 -0.63409 0.0273361 -0.457146
# When changing nout by Δ where Δ == k * ningroups where k is an integer we can simply just add/remove k output elements
# Output elements are interleaved in the output of the layer, so if we add/remove output element i, the elements i:ningroups:end
# will be added/dropped from the layer output.
# When Δ is not an integer multiple things get pretty hairy and I'm not sure the constraints below handle all causes
# We then basically need to change nin so that the new nout is an integer multiple of the new nin.
# Example
# dc = DepthwiseConv((1,1), 3 => 9; bias=false);
# reshape(dc(indata),:)'
# 1×9 adjoint(::Vector{Float32}) with eltype Float32:
# 0.109549 0.273408 -0.299883 0.0131096 0.00240822 -0.0461159 -0.138605 -0.557134 0.0246111
# julia> dc.weight[:,:,2,:] .= 0;
# reshape(dc(indata),:)'
# 1×9 adjoint(::Vector{Float32}) with eltype Float32:
# 0.109549 0.0 -0.299883 0.0131096 0.0 -0.0461159 -0.138605 0.0 0.0246111
# One thing which makes this a bit tricky is that while noutgruops and ningroups can change
# we are here stuck with the select and insert arrays that correspond to the original sizes
# As such, keep in mind that noutgroups and ningroups in this function always relate to the
# lengths of the arrays of JuMP variables that we have right now.
M = 1e6
noutgroups = div(length(select), ningroups)
# select_none_in_group[g] == 1 if we drop group g
# TODO: Replace by just sum(select_in_group[g,:]) below?
select_none_in_group = @variable(model, [1:noutgroups], Bin)
select_in_group = reshape(select, noutgroups, ningroups)
@constraint(model, sum(select_in_group, dims=2) .<= M .* (1 .- select_none_in_group))
# Tie selected input indices to selected output indices. If we are to drop any layer output indices, we need to drop the whole group
# as one whole group is tied to a single element in the output element dimension of the weight array.
@constraint(model, [g=1:noutgroups, i=1:ningroups], inselect[i] - select_in_group[g, i] + select_none_in_group[g] * M >= 0)
@constraint(model, [g=1:noutgroups, i=1:ningroups], inselect[i] - select_in_group[g, i] - select_none_in_group[g] * M <= 0)
# This variable handles the constraint that if we add a new input, we need to add noutgroups new outputs
# Note that for now, it is only connected to the insert variable through the sum constraint below.
insert_new_inoutgroups = @variable(model, [[1], 1:ningroups], Int, lower_bound=0, upper_bound=ningroups * maximum(allowed_multipliers))
insize = @expression(model, sum(inselect) + sum(ininsert))
outsize = @expression(model, sum(select) + sum(insert))
# inmultipliers[j] == 1 if nout(v) == allowed_multipliers[j] * nin(v)[]
inmultipliers = @variable(model, [1:length(allowed_multipliers)], Bin)
if usesos1(model)
#SOS1 == Only one can be non-zero. Not strictly needed, but it seems like it speeds up the solver
@constraint(model, inmultipliers in SOS1(1:length(inmultipliers)))
end
@constraint(model, sum(inmultipliers) == 1)
@constraint(model,[i=1:length(ininsert), j=1:length(inmultipliers)], allowed_multipliers[j] * ininsert[i] - insert_new_inoutgroups[1, i] + (1-inmultipliers[j]) * M >= 0)
@constraint(model,[i=1:length(ininsert), j=1:length(inmultipliers)], allowed_multipliers[j] * ininsert[i] - insert_new_inoutgroups[1, i] - (1-inmultipliers[j]) * M <= 0)
@constraint(model, [j=1:length(inmultipliers)], allowed_multipliers[j] * insize - outsize + (1-inmultipliers[j]) * M >= 0)
@constraint(model, [j=1:length(inmultipliers)], allowed_multipliers[j] * insize - outsize - (1-inmultipliers[j]) * M <= 0)
insert_new_inoutgroups_all_inds = vcat(zeros(noutgroups-1,ningroups), insert_new_inoutgroups)
# This variable handles the constraint that if we want to increase the output size without changing
# the input size, we need to insert whole outgroups since all noutgroup outputs are tied to a single
# output element in the weight array.
insert_new_outgroups = @variable(model, [1:noutgroups, 1:ningroups], Int, lower_bound = 0, upper_bound=noutgroups * maximum(allowed_new_outgroups))
# insert_no_outgroup[g] == 1 if we don't insert a new output group after group g
# TODO: Replace by just sum(insert_new_outgroups[g,:]) below?
insert_no_outgroup = @variable(model, [1:noutgroups], Bin)
@constraint(model, sum(insert_new_outgroups, dims=2) .<= M .* (1 .- insert_no_outgroup))
# When adding a new output group, all inserts must be identical
# If we don't add any, all inserts are just 0
@constraint(model, [g=1:noutgroups, i=2:ningroups], insert_new_outgroups[g,i] == insert_new_outgroups[g,i-1])
@constraint(model, [g=1:noutgroups], insert_new_outgroups[g,1] == insert_new_outgroups[g,end])
# new_outgroup[g,j] == 1 if we are inserting allowed_new_outgroups[j] new output groups after output group g
noutmults = 1:length(allowed_new_outgroups)
new_outgroup = @variable(model, [1:noutgroups, noutmults], Bin)
if usesos1(model)
#SOS1 == Only one can be non-zero. Not strictly needed, but it seems like it speeds up the solver
@constraint(model,[g=1:noutgroups], new_outgroup[g,:] in SOS1(1:length(allowed_new_outgroups)))
end
@constraint(model,[g=1:noutgroups], sum(new_outgroup[g,:]) == 1)
groupsum = @expression(model, [g=1:noutgroups], sum(insert_new_outgroups[g,:]) - sum(insert_new_inoutgroups_all_inds[g,:]))
@constraint(model, [g=1:noutgroups, j=noutmults], groupsum[g] - allowed_new_outgroups[j]*insize + (1-new_outgroup[g,j] + insert_no_outgroup[g]) * M >= 0)
@constraint(model, [g=1:noutgroups, j=noutmults], groupsum[g] - allowed_new_outgroups[j]*insize - (1-new_outgroup[g,j] + insert_no_outgroup[g]) * M <= 0)
# Finally, we say what the inserts shall be: the sum of inserts from new inputs and new outputs
# I think this allows for them to be somewhat independent, but there are still cases when they
# can't change simultaneously. TODO: Check those cases
@constraint(model, insert .== reshape(insert_new_outgroups, :) .+ reshape(insert_new_inoutgroups_all_inds,:))
end
| NaiveNASflux | https://github.com/DrChainsaw/NaiveNASflux.jl.git |
|
[
"MIT"
] | 2.0.12 | 49f3d06de40de20ff0d8c7d855bd461d5061e96d | code | 13931 |
"""
AbstractMutableComp
Abstract base type for computation units (read layers) which may mutate.
"""
abstract type AbstractMutableComp end
Base.Broadcast.broadcastable(m::AbstractMutableComp) = Ref(m)
# Generic forwarding methods. Just implement layer(t::Type) and wrapped(t::Type) to enable
# Not possible in julia <= 1.1. See #14919
# (m::AbstractMutableComp)(x...) = layer(m)(x...)
layer(m::AbstractMutableComp) = layer(wrapped(m))
layertype(m::AbstractMutableComp) = layertype(layer(m))
NaiveNASlib.op(m::AbstractMutableComp) = layer(m)
NaiveNASlib.nin(m::AbstractMutableComp) = nin(wrapped(m))
NaiveNASlib.nout(m::AbstractMutableComp) = nout(wrapped(m))
function NaiveNASlib.Δsize!(m::AbstractMutableComp, inputs::AbstractVector, outputs::AbstractVector;kwargs...)
NaiveNASlib.Δsize!(wrapped(m), inputs, outputs;kwargs...)
end
mutate_weights(m::AbstractMutableComp, w) = mutate_weights(wrapped(m), w)
function NaiveNASlib.compconstraint!(case, s::AbstractJuMPΔSizeStrategy, m::AbstractMutableComp, data)
NaiveNASlib.compconstraint!(case, s, layertype(m), data)
end
function NaiveNASlib.defaultutility(m::AbstractMutableComp)
util = neuronutility_safe(m)
return util === 1 ? NaiveNASlib.NoDefaultUtility() : util
end
"""
MutableLayer
Wraps a layer in order to allow for mutation as layer structures are typically immutable
"""
mutable struct MutableLayer <: AbstractMutableComp
layer # Can't specialize as this might mutate into something else, e.g. Dense{Float32} -> Dense{Float64} thanks to mutable functor. Try to make functor rebuild everything?
end
(m::MutableLayer)(x...) = layer(m)(x...)
wrapped(m::MutableLayer) = m.layer
layer(m::MutableLayer) = wrapped(m)
layertype(m::MutableLayer) = layertype(layer(m))
@layer :expand MutableLayer
function NaiveNASlib.Δsize!(m::MutableLayer, inputs::AbstractVector, outputs::AbstractVector; insert=neuroninsert, kwargs...)
@assert length(inputs) == 1 "Only one input per layer!"
mutate(m; inputs=inputs[1], outputs=outputs, insert=insert, kwargs...)
nothing
end
mutate_weights(m::MutableLayer, w) = mutate(layertype(m), m, other=w)
function mutate(m::MutableLayer; inputs, outputs, other = l -> (), insert=neuroninsert)
if inputs === missing
mutate(layertype(m), m; outputs, other, insert)
else
mutate(layertype(m), m; inputs, outputs, other, insert)
end
end
mutate(lt::FluxParLayer, m::MutableLayer; kwargs...) = _mutate(lt, m; kwargs...)
function _mutate(lt::FluxParLayer, m::MutableLayer; inputs=1:nin(m)[], outputs=1:nout(m), other= l -> (), insert=neuroninsert)
l = layer(m)
otherdims = other(l)
w = select(weights(l), indim(l) => inputs, outdim(l) => outputs, otherdims...; newfun=insert(lt, WeightParam()))
b = select(bias(l), 1 => outputs; newfun=insert(lt, BiasParam()))
newlayer(m, w, b, otherpars(other, l))
end
otherpars(o, l) = ()
function mutate(lt::FluxConvolutional{N}, m::MutableLayer; inputs=1:nin(m)[], outputs=1:nout(m), other= l -> (), insert=neuroninsert) where N
if ngroups(lt, layer(m)) == 1
return _mutate(lt, m; inputs, outputs, other, insert)
end
l = layer(m)
otherdims = other(l)
# TODO: Handle other cases than ngroups == nin
newingroups = 1
# inputs and outputs are coupled through the constraints (which hopefully were enforced) so we only need to consider outputs
currsize =size(weights(l))
wo = select(reshape(weights(l), currsize[1:N]...,:), N+1 => outputs, otherdims...; newfun=insert(lt, WeightParam()))
newks = size(wo)[1:N]
w = collect(reshape(wo, newks...,newingroups, :))
b = select(bias(l), 1 => outputs; newfun=insert(lt, BiasParam()))
newlayer(m, w, b, (;groups= length(inputs) ÷ newingroups, otherpars(other, l)...))
end
function mutate(lt::FluxRecurrent, m::MutableLayer; inputs=1:nin(m)[], outputs=1:nout(m), other=missing, insert=neuroninsert)
l = layer(m)
outputs_scaled = mapfoldl(vcat, 1:outscale(l)) do i
offs = (i-1) * nout(l)
return map(x -> x > 0 ? x + offs : x, outputs)
end
wi = select(weights(l), indim(l) => inputs, outdim(l) => outputs_scaled, newfun=insert(lt, WeightParam()))
wh = select(hiddenweights(l), 2 => outputs, 1 => outputs_scaled, newfun=insert(lt, RecurrentWeightParam()))
b = select(bias(l), 1 => outputs_scaled, newfun=insert(lt, BiasParam()))
mutate_recurrent_state(lt, m, outputs, wi, wh, b, insert)
end
function mutate_recurrent_state(lt::FluxRecurrent, m::MutableLayer, outputs, wi, wh, b, insert)
l = layer(m)
state0 = select(hiddenstate(l), 1 => outputs, newfun=insert(lt, RecurrentState()))
s = select(state(l), 1 => outputs; newfun=insert(lt, RecurrentState()))
cellnew = setproperties(layer(m).cell, (Wi=wi, Wh=wh, b = b, state0 = state0))
lnew = setproperties(layer(m), (cell=cellnew, state = s))
m.layer = lnew
end
function mutate_recurrent_state(lt::FluxLstm, m::MutableLayer, outputs, wi, wh, b, insert)
l = layer(m)
s0curr, scurr = hiddenstate(l), state(l)
s0 = select.(s0curr, repeat([1 => outputs], length(s0curr)); newfun=insert(lt, RecurrentState()))
s = select.(scurr, repeat([1 => outputs], length(scurr)); newfun=insert(lt, RecurrentState()))
cellnew = setproperties(layer(m).cell, (Wi=wi, Wh=wh, b = b, state0 = Tuple(s0)))
lnew = setproperties(layer(m), (cell=cellnew, state = Tuple(s)))
m.layer = lnew
return (;state0 = Tuple(s0)), Tuple(s)
end
function mutate(t::FluxParInvLayer, m::MutableLayer; inputs=missing, outputs=missing, other=missing, insert=neuroninsert)
@assert any(ismissing.((inputs, outputs))) || inputs == outputs "Try to mutate $inputs and $outputs for invariant layer $(m)!"
ismissing(inputs) || return mutate(t, m, inputs; insert=insert)
ismissing(outputs) || return mutate(t, m, outputs; insert=insert)
end
function mutate(lt::FluxScale, m::MutableLayer, inds; insert=neuroninsert)
l = layer(m)
w = select(weights(l), 1 => inds, newfun=insert(lt, WeightParam()))
b = select(bias(l), 1 => inds; newfun=insert(lt, BiasParam()))
newlayer(m, w, b)
end
function mutate(::FluxLayerNorm, m::MutableLayer, inds; insert=neuroninsert)
# LayerNorm is only a wrapped Scale. Just mutate the Scale and make a new LayerNorm of it
proxy = MutableLayer(layer(m).diag)
mutate(proxy; inputs=inds, outputs=inds, other=l->(), insert=insert)
updatelayer = layer(m)
m.layer = @set updatelayer.diag = layer(proxy)
end
function mutate(lt::FluxParNorm, m::MutableLayer, inds; insert=neuroninsert)
# Filter out the parameters which need to change and decide for each name (e.g. γ, β etc) what to do (typically insert 1 for scaling things and 0 for offset things)
parselect(p::Pair) = parselect(p...)
parselect(pname, x::AbstractArray) = select(x, 1 => inds; newfun = neuroninsert(lt, pname))
parselect(pname, x) = x
fs, re = Flux.functor(m.layer)
newlayer = re(map(parselect, pairs(fs) |> collect))
newlayer = @set newlayer.chs = length(inds)
m.layer = newlayer
end
function mutate(lt::FluxGroupNorm, m::MutableLayer, inds; insert=neuroninsert)
# TODO: This alg was from when Flux used a different way to represent the parameters of GroupNorm
# For some reason it still produces correct results in testcases, but it might very well do so for
# the wrong reasons...
l = m.layer
ngroups = l.G
nchannels = length(inds)
# Make a "best fit" to new group size, but don't allow 1 as group size
# Step 1: Possible group sizes are all integers which divde the new number of channels evenly
g_alts = filter(ga -> ga > 1, findall(r -> r == 0, nchannels .% (1:nchannels)))
# Step 2: Select the size which is closest to the original number of groups
ngroups = g_alts[argmin(abs.(g_alts .- ngroups))]
nchannels_per_group = div(nchannels, ngroups)
# Map indices to (new) groups
inds_groups = ceil.(Int, map(ind -> ind > 0 ? ind / nchannels_per_group : ind, inds))
# TODO: Select the most commonly occuring index in each column (except -1)
inds_groups = reshape(inds_groups, nchannels_per_group, ngroups)[1,:]
sizetoinds = Dict(nin(l)[] => inds, l.G => inds_groups)
parselect(p::Pair) = parselect(p...)
parselect(pname, x::AbstractArray) = select(x, 1 => sizetoinds[length(x)]; newfun = insert(lt, pname))
parselect(pname, x) = x
fs, re = Flux.functor(m.layer)
newlayer = re(map(parselect, pairs(fs) |> collect))
newlayer.G = ngroups
newlayer = @set newlayer.chs = length(inds)
m.layer = newlayer
m.layer.G = ngroups
end
newlayer(m::MutableLayer, w, b, other=nothing) = m.layer = newlayer(layertype(m), m, w, b, other)
newlayer(::FluxDense, m::MutableLayer, w, b, other) = Dense(w, b, deepcopy(layer(m).σ))
newlayer(::FluxConvolutional, m::MutableLayer, w, b, other) = setproperties(layer(m), (weight=w, bias=b, σ=deepcopy(layer(m).σ), other...))
newlayer(::FluxScale, m::MutableLayer, w, b, other) = Flux.Scale(w, b)
"""
LazyMutable
LazyMutable(m::AbstractMutableComp)
Lazy version of MutableLayer in the sense that it does not perform any mutations
until invoked to perform a computation.
This reduces the need to garbage collect when multiple mutations might be applied
to a vertex before evaluating the model.
Also useable for factory-like designs where the actual layers of a computation graph
are not instantiated until the graph is used.
# Examples
```jldoctest
julia> using NaiveNASflux, Flux
julia> struct DenseConfig end
julia> lazy = LazyMutable(DenseConfig(), 2, 3);
julia> layer(lazy)
DenseConfig()
julia> function NaiveNASflux.dispatch!(m::LazyMutable, ::DenseConfig, x)
m.mutable = Dense(nin(m)[1], nout(m), relu)
return m.mutable(x)
end;
julia> lazy(ones(Float32, 2, 5)) |> size
(3, 5)
julia> layer(lazy)
Dense(2 => 3, relu) # 9 parameters
```
"""
mutable struct LazyMutable <: AbstractMutableComp
mutable # May change at any time (see example)
inputs::Vector{Vector{Int}}
outputs::Vector{Int}
other # May change at any time
insert # May change at any time
end
LazyMutable(m::AbstractMutableComp) = LazyMutable(m, nin(m), nout(m))
LazyMutable(m, nin::Integer, nout::Integer) = LazyMutable(m, [nin], nout)
function LazyMutable(m, nins::AbstractVector{<:Integer}, nout::Integer)
inputs = map(nin -> collect(Int, 1:nin), nins)
outputs = collect(Int, 1:nout)
LazyMutable(m, inputs, outputs, m -> (), neuroninsert)
end
function Base.show(io::IO, lm::LazyMutable)
print(io, "LazyMutable(")
show(io, lm.mutable)
print(io, '[')
for inpt in lm.inputs
print(io, NaiveNASlib.compressed_string(inpt))
end
print(io, ']', NaiveNASlib.compressed_string(lm.outputs))
show(io, lm.other)
show(io, lm.insert)
end
wrapped(m::LazyMutable) = m.mutable
layer(m::LazyMutable) = layer(wrapped(m))
function Functors.functor(::Type{<:LazyMutable}, m)
forcemutation(m)
return (mutable=m.mutable,), y -> LazyMutable(y.mutable)
end
(m::LazyMutable)(x...) = dispatch!(m, m.mutable, x...)
dispatch!(::LazyMutable, m::AbstractMutableComp, x...) = m(x...)
NaiveNASlib.nin(m::LazyMutable) = length.(m.inputs)
NaiveNASlib.nout(m::LazyMutable) = length(m.outputs)
function NaiveNASlib.Δsize!(m::LazyMutable, inputs::AbstractVector, outputs::AbstractVector; insert=neuroninsert)
(all((i,k)::Tuple -> ismissing(i) || i == 1:k, zip(inputs, nin(m))) && outputs == 1:nout(m)) && return
m.insert = insert
m.mutable = ResetLazyMutable(trigger_mutation(m.mutable))
m.inputs = map(m.inputs, inputs) do currins, newins
ismissing(newins) && return currins
select(currins, 1 => newins, newfun = (args...) -> -1)
end
m.outputs = select(m.outputs, 1=>outputs, newfun = (args...) -> -1)
nothing
end
function mutate_weights(m::LazyMutable, w)
m.other == w && return
m.mutable = ResetLazyMutable(trigger_mutation(m.mutable))
m.other = w
end
function forcemutation(x) end
function forcemutation(::InputVertex) end
forcemutation(g::CompGraph) = forcemutation.(vertices(g::CompGraph))
forcemutation(v::AbstractVertex) = forcemutation(base(v))
forcemutation(v::CompVertex) = forcemutation(v.computation)
forcemutation(m::AbstractMutableComp) = forcemutation(NaiveNASflux.wrapped(m))
forcemutation(m::LazyMutable) = m(NoComp())
struct NoComp end
function (::MutableLayer)(::NoComp) end
"""
MutationTriggered
Dispatches mutation for LazyMutable.
"""
struct MutationTriggered{T}
wrapped::T
end
# Functionality is opt-in
trigger_mutation(m) = m
trigger_mutation(m::AbstractMutableComp) = MutationTriggered(m)
function dispatch!(lm::LazyMutable, m::MutationTriggered, x...)
NaiveNASlib.Δsize!(m.wrapped, lm.inputs, lm.outputs; other=lm.other, insert=lm.insert)
lm.mutable = m.wrapped
return lm(x...)
end
layer(m::MutationTriggered) = layer(m.wrapped)
layertype(m::MutationTriggered) = layertype(layer(m))
@layer :expand MutationTriggered
"""
ResetLazyMutable
Reset a `LazyMutable` when dispatching.
"""
struct ResetLazyMutable{T}
wrapped::T
end
ResetLazyMutable(r::ResetLazyMutable) = r
function dispatch!(lm::LazyMutable, m::ResetLazyMutable, x...)
lm.mutable = m.wrapped
output = lm(x...)
lm.inputs = map(i -> collect(1:i), nin(lm))
lm.outputs = 1:nout(lm)
lm.other = m -> ()
lm.insert = neuroninsert
return output
end
layer(m::ResetLazyMutable) = layer(m.wrapped)
layertype(m::ResetLazyMutable) = layertype(layer(m))
@layer :expand ResetLazyMutable
"""
NoParams
Ignores size mutation.
Useful for layers which don't have parameters.
"""
struct NoParams{T}
layer::T
end
(i::NoParams)(x...) = layer(i)(x...)
layer(i::NoParams) = i.layer
layertype(i::NoParams) = layertype(layer(i))
NaiveNASlib.op(i::NoParams) = layer(i)
LazyMutable(m::NoParams) = m
function mutate_weights(::NoParams, w) end | NaiveNASflux | https://github.com/DrChainsaw/NaiveNASflux.jl.git |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.