Skip to content

Commit

Permalink
allow projections on AbstractArray of contracts
Browse files Browse the repository at this point in the history
  • Loading branch information
alecloudenback committed Nov 4, 2023
1 parent 1a8d195 commit 3b8aec0
Show file tree
Hide file tree
Showing 3 changed files with 33 additions and 0 deletions.
16 changes: 16 additions & 0 deletions docs/src/contracts.md
Original file line number Diff line number Diff line change
Expand Up @@ -88,6 +88,22 @@ Note that all contracts in FinanceModels.jl are currently *unit* contracts in th

#### More complex Contracts

##### Sets of contracts

Sets of contracts can be put in an `AbstractArray` contained (e.g. a `Vector`) and then handled together. For example, we combine two bonds as a portfolio to project together:

```julia-repl
julia> c1 = Bond.Fixed(0.05, Periodic(1), 2.0);
julia> c2 = Bond.Fixed(0.04, Periodic(1), 2.0);
julia> Projection([c1, c2]) |> collect
4-element Vector{Cashflow{Float64, Float64}}:
Cashflow{Float64, Float64}(0.05, 1.0)
Cashflow{Float64, Float64}(1.05, 2.0)
Cashflow{Float64, Float64}(0.04, 1.0)
Cashflow{Float64, Float64}(1.04, 2.0)
```

##### Transformations

Contracts (`<:AbstractContract`) and [`Projection`](@ref)s can be modified to be scaled or transformed using the transformations in [Transducers.jl](https://juliafolds2.github.io/Transducers.jl/stable/#List-of-transducers) after importing that package.
Expand Down
5 changes: 5 additions & 0 deletions src/Projection.jl
Original file line number Diff line number Diff line change
Expand Up @@ -88,6 +88,11 @@ Projection(c, m) = Projection(c, m, CashflowProjection())
function Transducers.asfoldable(c::C) where {C<:FinanceCore.AbstractContract}
Projection(c) |> Map(identity)
end
function Transducers.asfoldable(p::Projection{C,M,K}) where {C<:AbstractArray,M,K}
map(p.contract) do c
Projection(c, p.model, p.kind)
end |> Cat()
end

# A cashflow is the simplest, single item reducible collection
@inline function Transducers.__foldl__(rf, val, p::Projection{C,M,K}) where {C<:Cashflow,M,K}
Expand Down
12 changes: 12 additions & 0 deletions test/sp.jl
Original file line number Diff line number Diff line change
Expand Up @@ -23,6 +23,18 @@ end
@test pv(Yield.Constant(0.05), p) 1.0
end

@testset "AbstractArray of contracts" begin
c = Bond.Fixed(0.05, Periodic(1), 3.0)
p = Projection([c, c])
@test length(collect(p)) == 6
@test pv(Yield.Constant(0.00), p) 2.3
p = Projection([c, c |> Map(-)])
@test length(collect(p)) == 6
@test pv(Yield.Constant(0.00), p) 0.0



end
@testset "Floating Bonds" begin
p = Projection(
Bond.Floating(0.02, Periodic(1), 3.0, "SOFR"),
Expand Down

0 comments on commit 3b8aec0

Please sign in to comment.