acturtle / cashflower

An open-source Python framework for actuarial cash flow models
https://cashflower.acturtle.com
MIT License
38 stars 9 forks source link

Goal-seeking function #334

Open zchmielewska opened 1 year ago

zchmielewska commented 1 year ago

The feature has been suggested by kyworkact.

I think if a goal seek function is available similar to what excel has, it would be very useful e.g. for generating premium rate in meeting certain profit target.

zchmielewska commented 1 year ago

Hi @kyworkact,

You previously mentioned a goal seek function similar to Excel's functionality, and I've prepared a simple example to show how it can be repliacted in Python.

Scenario: We have a 3-year term policy with a net premium of 100, and we want to find a profit margin that results in a present value of premiums equal to 3000, assuming a discount factor of 0.98.

Excel

In Excel's Solver, we would follow these steps:

  1. Setting up the problem:

solver_1

  1. Solution found:

solver_2

The profit margin that meets the criteria is 13.97%.

Python

In Python, we can achieve the same result using the scipy package. Here's the equivalent solution:

from scipy.optimize import root

DISCOUNT_FACTOR = 0.98

def premium(profit_margin):
    return 100 * (1 + profit_margin)

def pv_premium(t, profit_margin):
    if t == 36:
        return premium(profit_margin)
    return premium(profit_margin) + pv_premium(t+1, profit_margin) * DISCOUNT_FACTOR

def eqn(profit_margin):
    return pv_premium(0, profit_margin) - 3_000

myroot = root(eqn, 0)
print(myroot.x)  # Output: [0.13970692]

Does this solve your problem? If not then please feel free to share your specific problem. I'd be happy to help!

ghost commented 11 months ago

Thank you so much for sharing! I am still working on it, will let you know if I need further help. Thanks a lot again!

ghost commented 11 months ago

Hi, just want to let you know that I wasn't able to use root for what I wanted to do, but eventually did something similar to bisection to do the goal seeking. It's working alright now. Thanks a lot again for your help!