You have an unequal stream of payments occurring at variable intervals of time. And you know the formula for ROI. What you are trying to determine is what interest rate for the whole period best reflects the fund accumulated value, And you have correctly deduced the formula to calculate each...
Time Amount Effect
4 25000 25000((1+i)^4) #contribution due to first deposit
3 4000 4000((1+i)^3) #contribution due to second deposit
2 -300 -300((1+i)^2) #contribution due to third (withdrawal)
1 1500 1500((1+i)^1) #contribution due to fourth deposit
You need an iterative solution. You need start with a guess for your interest rate, i, and then iterate over your deposit vector, recalculating the fund with the guessed rate. You will need to adjust your guessed interest rate as you iterate, and the amount by which you adjust your guessed rate will affect how quickly you converge on a solution.
The amount you change your guessed rate will determine how quickly you converge on a solution (indeed, whether you converge on a solution). The general algorithm below will get you started. You need to tinker with the adjustment calculation in the guessrate function. The complication is that the ROI calculation is non-linear, so you will need something that adjusts non-linearly, and on an order similar to the calculation value. My sample guessrate function is linear, so you need to refine the function.
Try an iterative solution. Pick a value for i, and iterate
intialize_fund
{
value = 32318.63
//initialize your deposit/withdrawal vector/array
deposits[]
deposits[0] = +25000
deposits[1] = +4000
deposits[2] = -300
deposits[3] = +1500
duration = 5 //number of periods
}
calcval( deposits[], rate, duration )
{
accum = 0.0
for period=0; period<duration; ++period)
{
accum = accum * (1+rate)
if( exists deposits[period] ) accum += deposits[period]
}
return accum
}
#you will need to tinker with this until you get a function that
#converges
#converges quickly
guessrate( actual, calculated, rate )
{
adjustby = abs(actual - calculated) / actual
if(calculated > actual) rate = rate * (1.0 - adjustby)
else rate = rate * (1.0 + adjustby)
return rate
}
guessRoi
{
guess = 0.01 #initial guess
tryVal = calcval( guess, changes, duration )
while( abs(actual - tryVal) > .01 )
{
rate = guessrate( actual, tryVal, rate )
tryVal = calcval( deposits, rate, duration )
}
#guess has calculated rate, i
#tryRoi should have converged to actual accumulation
}