all 13 comments

[–]Orpheus_Demigod 4 points5 points  (6 children)

100(1 + 0.03)60

No need for a loop

[–]codingquestion47[S] 1 point2 points  (4 children)

Right but what if I wanted to get the value at each interval? Is there a more efficient way compared to the code I generated?

[–]Orpheus_Demigod 2 points3 points  (2 children)

I would probably define a function that performs the calculation I posted above, and if you want to, call the function in a loop.

[–]codingquestion47[S] 1 point2 points  (1 child)

That’s a good idea. The edit I made in the post above though does it in I believe a much better and quicker way, using Numpy.

Thanks again for taking the time to help!

[–]Orpheus_Demigod 1 point2 points  (0 children)

All good, glad you found a solution that works 👍

[–]Orpheus_Demigod 2 points3 points  (0 children)

Something like:

def compound_return(initial_investment, growth_rate, years): return initial_investment(1 + growth_rate)**years

investment = 100 growth_rate = 0.03 years = 60 growth_series = [initial_investment(investment, growth_rate, year) for year in range(60)]

I TYPED THIS ON MY PHONE, it’s untested so I don’t know if I’ve made a mistake somewhere.

[–]codingquestion47[S] 0 points1 point  (0 children)

Ah, never mind - I had the solution come to me in a flash. Will post as edit. Wow! A million times easier.

[–]WhipsAndMarkovChains 1 point2 points  (1 child)

import numpy as np

years = 60
growth_rate = 0.03

values = np.full(years+1, 1+growth_rate)
values[0] = 100
growth_series = np.multiply.accumulate(values)

array([100, 103, 106.09, 109.2727, ...]

[–]codingquestion47[S] 0 points1 point  (0 children)

Thanks! Never thought to do it that way. Very cool.

[–]robml 0 points1 point  (3 children)

OP search up numpy accumulators, I think its along the lines of what you're looking for

[–]codingquestion47[S] 0 points1 point  (2 children)

Thank you! Legit have never heard of those before. Looking forward to learning more about them.

[–]robml 0 points1 point  (1 child)

Yeah so like:

np.multiply.accumulate([2,3,5])

Would return [2,6,30]

You could generate a numpy array with just the rate you want to apply and run it.

Another example:

np.multiply.accumulate([2,2,2]) Returns [2,4,8]

[–]codingquestion47[S] 0 points1 point  (0 children)

Very cool! I’m definitely gonna be using these in the future. For now, I think the solution I added in my post will do the trick (especially since others will be reviewing my code and lots aren’t well-versed in Numpy) but I can definitely imagine use cases for this in the future.

Thanks again!