Getting the right discount rate with goal seek in Python

I have a present value calculation with a given discount rate. However, I also have a target value for this calculation. Here is a very simple code:

import pandas as pd
disc = 1.04
df = pd.DataFrame({'Income':[100*1.08**i for i in range(5)],
'Discount_vector':[disc**(-i) for i in range(5)]})
df['PV of CF'] = df['Income'] * df['Discount_vector']
x = df['PV of CF'].sum()
target = 545
    

What I would like is to minimize the difference between target and x by changing the value of the discount rate (i.e. disc). I would be grateful if you could help me. Thank you.

Answer

We can use min search function fmin from scipy.optimize after converting requirements to a function.

Code

import pandas as pd
from scipy.optimize import fmin

def f(disc):
    ' Create function that calculates error between x and target '
    df = pd.DataFrame({'Income':[100*1.08**i for i in range(5)], 
                       'Discount_vector':[disc**(-i) for i in range(5)]})

    df['PV of CF'] = df['Income'] * df['Discount_vector']
    x = df['PV of CF'].sum()
    
    target = 545
    error = x - target
    return error**2            # Returning squared error

Usage

# Starting discount rate
start = 1.04

# Find min of f starting at start
start = 1.04
discount = fmin(f, [start]) 

print(f'Discount = {discount}')

Output

Optimization terminated successfully.
         Current function value: 0.000035
         Iterations: 13
         Function evaluations: 26
Discount = [1.03537891]

Thus, Discount needed was 1.03537891