Coder Social home page Coder Social logo

juliaactuary / actuaryutilities.jl Goto Github PK

View Code? Open in Web Editor NEW
37.0 3.0 8.0 998 KB

Common functions in actuarial and financial routines

Home Page: https://juliaactuary.github.io/ActuaryUtilities.jl/dev/

License: MIT License

Julia 100.00%
cashflows life-insurance finance actuarial-science hacktoberfest julia

actuaryutilities.jl's Introduction

ActuaryUtilities

Stable Dev CI Codecov

Quickstart

cfs = [5, 5, 105]
times    = [1, 2, 3]

discount_rate = 0.03

present_value(discount_rate, cfs, times)           # 105.65
duration(Macaulay(), discount_rate, cfs, times)    #   2.86
duration(discount_rate, cfs, times)                #   2.78
convexity(discount_rate, cfs, times)               #  10.62

Features

A collection of common functions/manipulations used in Actuarial Calculations.

Financial Maths

  • duration:
    • Calculate the Macaulay, Modified, or DV01 durations for a set of cashflows
    • Calculate the KeyRate(time) (a.k.a. KeyRateZero)duration or KeyRatePar(time) duration
  • convexity for price sensitivity
  • Flexible interest rate models via the FinanceModels.jl package.
  • internal_rate_of_return or irr to calculate the IRR given cashflows (including at timepoints like Excel's XIRR)
  • breakeven to calculate the breakeven time for a set of cashflows
  • accum_offset to calculate accumulations like survivorship from a mortality vector
  • spread will calculate the spread needed between two yield curves to equate a set of cashflows

Risk Measures

  • Calculate risk measures for a given vector of risks:
    • CTE for the Conditional Tail Expectation
    • VaR for the percentile/Value at Risk
    • WangTransform for the Wang Transformation
    • ProportionalHazard for proportional hazards
    • DualPower for dual power measure

Insurance mechanics

  • duration:
    • Calculate the duration given an issue date and date (a.k.a. policy duration)

Typed Rates

  • functions which return a rate/yield will return a FinanceCore.Rate object. E.g. irr(cashflows) will return a Rate(0.05,Periodic(1)) instead of just a 0.05 (float64) to convey the compounding frequency. This is compatible across the JuliaActuary ecosystem and can be used anywhere you would otherwise use a simple floating point rate.

A couple of other notes:

  • rate(...) will return the scalar rate value from a Rate struct:
julia> r = Rate(0.05,Periodic(1));

julia> rate(r) 
0.05
  • You can still pass a simple floating point rate to various methods. E.g. these two are the same (the default compounding convention is periodic once per period):
discount(0.05,cashflows)

r = Rate(0.05,Periodic(1));
discount(r,cashflows)
  • convert between rates with:
r = Rate(0.05,Periodic(1));

convert(Periodic(2),  r)   # convert to compounded twice per timestep
convert(Continuous(2),r)   # convert to compounded twice per timestep

For more on Rates, see FinanceCore.jl. FinanceModels.jl also provides a rich and flexible set of yield models to use.

Documentation

Full documentation is available here.

Examples

Interactive, basic cashflow analysis

See JuliaActuary.org for instructions on running this example.

Simple cashflow analysis with ActuaryUtilities.jl

Useful tips

Functions often use a mix of interest_rates, cashflows, and timepoints. When calling functions, the general order of the arguments is 1) interest rates, 2) cashflows, and 3) timepoints.

actuaryutilities.jl's People

Contributors

alecloudenback avatar github-actions[bot] avatar kuldeepborkar avatar timholy avatar xlxs4 avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar

actuaryutilities.jl's Issues

API of Derivative values

See #53, #59

For further consideration:

Dispatching (or the lack thereof)

Current functions use keyword args and is purely functional with no types/dispatch involved. Alternate design could be to design, e.g., option types which could be dispatched upon for better performance and more data/domain oriented design. However, this is a bit awkward where you might design a struct that has the strike price and dividend yield... but then user still has to provide all the other market data. Wikipedia nicely separates the sources for the variables:

General and market related:

 t, a time in years; we generally use  t=0 as now;
 r, the annualized risk-free interest rate, continuously compounded Also known as the force of interest;

Asset related:

 S(t), the price of the underlying asset at time t, also denoted as  S_{t};
 \mu , the drift rate of  S, annualized;
\sigma , the standard deviation or Std of the stock's returns; this is the square root of the quadratic variation of the stock's log price process, a measure of its volatility;

Option related:

V(S,t), the price of the option as a function of the underlying asset S, at time t; in particular
C(S,t) is the price of a European call option and
P(S,t) the price of a European put option;
T, time of option expiration;
\tau , time until maturity, which is equal to  \tau =T-t;
K, the strike price of the option, also known as the exercise price.

IRR solve failure

cfs = [-8.728037307132952e7, 3.043754023830998e7, 2.963004184784189e7, 2.8803030748755097e7, 2.7956912111811966e7, 2.7092182051244527e7, 2.6209069543806538e7, 2.5307964329840004e7, 2.438961041057478e7, 2.3455084653011695e7, 2.2505925520018265e7, 2.154395414765592e7, 2.0571076113065004e7, 1.958930608135183e7, 1.8600627464895025e7, 1.7606980923262402e7, 1.661046149512893e7, 1.561312825963898e7, 1.461760481586352e7, 1.3626801207410209e7, 1.2644733969499402e7, 1.1675393687299855e7, 1.0722720151658386e7, 9.79075673433771e6, 8.883278741880089e6, 8.004445298876338e6, 7.1588010859461725e6, 6.351121678665243e6, 5.585860320479795e6, 4.8673895159943625e6, 4.19908059495347e6, 3.583538247530099e6, 3.022766488834396e6, 2.5181072324190177e6, 2.0701053881076649e6, 1.6782921224664208e6, 1.3410605489291362e6, 1.0556643097527474e6, 818348.5357315112, 624147.9373214925, 467849.788997191, 344241.752520618, 248285.65630649775, 175235.5475426321, 120677.87174498942, 80759.09804678289, 52186.83400936739, 32211.057718402008, 18589.51907385164, 9540.782278174447, 3688.4015341755294]

irr(cfs,0:50) Should return something in the neighborhood of 30%, but returns nothing instead.

Add more profit measures

There's already breakeven, irr, embedded_value (via pv) Add

  • moic: multiple on invested capital
  • mirr: modified irr (ref #27)

durations and negative PVs

duration and it's various methods will error when given a stream of cashflows that results in a negative present value. E.g.:

cfs = [-1, -1, -5]
times = [0, 1, 2]
duration(0.05,cfs,times)

results in:

DomainError with -6.487528344671202:

log will only return a complex result if called with a complex argument. Try log(Complex(x)).

I think this is because the standard definition is price sensitivity not value sensitivity. Should duration change the range of inputs and take the absolute value before calculating? Alternative might be to make the default δvalue/ δyield, more akin to DV01?

I'm currently leaning towards the former...

Interest Rates

Pull the interest rate logic out of this package into another and consider API. Consider using InterestRates.jl as basis

Alternative clipboard feature package

Hello!

I really like the functions xlcopy() and xlcopy(data). I think it's really awesome to have such easy interoperability with excel.

They seem so important that they probably shouldn't live in a domain-specific package like ActuaryUtilities. Everyone, even non-actuaries, should use this feature.

So I've created ClipboardCSV which takes some of the core features from xlcopy and puts them in a standalone package. Here are some examples of how it works

julia> using DataFrames, ClipboardCSV

julia> df = DataFrame(a = [1, 2], b = [3, 4], c = [5, 6], d = [7, 8])
2×4 DataFrame
 Row │ a      b      c      d     
     │ Int64  Int64  Int64  Int64 
─────┼────────────────────────────
   11      3      5      7
   22      4      6      8

julia> tabletoclip(df)
a,b,c,d
1,3,5,7
2,4,6,8


julia> cliptotable()
2-element CSV.File{false}:
 CSV.Row: (a = 1, b = 3, c = 5, d = 7)
 CSV.Row: (a = 2, b = 4, c = 6, d = 8)

julia> @tabletomwe df
df = """
a,b,c,d
1,3,5,7
2,4,6,8
""" |> IOBuffer |> CSV.File |> DataFrame



julia> eval(first(Meta.parse(clipboard(), 1)))
2×4 DataFrame
 Row │ a      b      c      d     
     │ Int64  Int64  Int64  Int64 
─────┼────────────────────────────
   11      3      5      7
   22      4      6      8

This package is not yet mature. It needs tests, a few more features, and documentation. However when all that is done and the package is released, would you consider deprecating xlcopy and taking ClipboardCSV.jl as a dependency?

`duration` with Yields

duration(Yields.Constant(0.04), cfs, times) doesn't work (though duration(0.04, cfs, times) does.

Make `irr` more robust

Currently a lot of magic numbers and forgiveness on the solve result to get the Optim result to pass .

TagBot trigger issue

This issue is used to trigger TagBot; feel free to unsubscribe.

If you haven't already, you should update your TagBot.yml to include issue comment triggers.
Please see this post on Discourse for instructions and more details.

If you'd like for me to do this for you, comment TagBot fix on this issue.
I'll open a PR within a few hours, please be patient!

Feature Parity with numpy-financial?

Numpy-financial functions:

  • fv(rate, nper, pmt, pv[, when]) | Compute the future value.
  • ipmt(rate, per, nper, pv[, fv, when]) | Compute the interest portion of a payment.
  • irr(values) | Return the Internal Rate of Return (IRR).
  • mirr(values, finance_rate, reinvest_rate) | Modified internal rate of return.
  • nper(rate, pmt, pv[, fv, when]) | Compute the number of periodic payments.
  • npv(rate, values) | Returns the NPV (Net Present Value) of a cash flow series.
  • pmt(rate, nper, pv[, fv, when]) | Compute the payment against loan principal plus interest.
  • ppmt(rate, per, nper, pv[, fv, when]) | Compute the payment against loan principal.
  • pv(rate, nper, pmt[, fv, when]) | Compute the present value.
  • rate(nper, pmt, pv, fv[, when, guess, tol, …]) | Compute the rate of interest per period.

Not sure that we actually want to have all of these. ActuaryUtilities provides a more flexible interface, I think?

E.g. for present value, the above definition restricts you:

  • npv you can have a vector of rates, but not specify the timepoints. And the rate needs to be constant
  • pv is the old calculator bond formula. Great for doing a super simple bond calc, but for everything else...?

In contrast, with ActuaryUtilities present_value(rate,cfs,times) or pv:

  • rate can be a constant or a curve
  • cfs can vary
  • times lets you specify when cashflows occur and they can be of varying magnitude and at uneven times

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.