Quantopian's community platform is shutting down. Please read this post for more information and download your code.
Back to Community
Calculate daily returns for the past x days

It must be quite simple but i didn't manage to do it

How can I calculate the daily returns for the last X days?

I got

context.securities = symbols('AAPL', 'GOOG')

hist = history(80, '1d','close_price')

How can I get the average daily returns of the last 60 days in those securities?

And the average daily std?

Thanks!

4 responses

Hi,

The method I know is using ROCP and STDDEV function of TA-library but pandas offers such possibility as well.

Enter something like


def ROCP(symbols, periods):  
    return talib.ROCP(symbols, periods)*100  

and call it with


if ROCP(spy, 20)[-1] > etc  

Here is an example of getting the returns (both simple and log). It then get the average and standard deviation of the returns over the period. I multiplied them by 100 to record the results. I also used SPY instead of GOOG because Googles split means the GOOG ticker hasn't existed for very long. Hope this helps you out.

David

Thank you David, that was what I was looking for! :)

I see this is an older post, but just an fyi if anyone refers to it, note that I believe apple=avg_simple_return[symbol('AAPL')]*100 (including the preceding lines of code) is the same as apple = data[symbol('AAPL')].returns()*100 without all of those extra line of code. Maybe the return function was not available at that point when the above workaround code posted (adjust days as needed).