Colin Hamm
Colin Hamm

Reputation: 11

Stock Price Returns

I have a list of stock returns and need to find the year over year return.

I have created an empty list for returns and tried iterating over the list to append for the year over year returns.

lst = [10.82, 18.89, 52.62, 44.29, 47.15, 39.46, 92.64, 51.28, 134.52, 180.0, 173.1, 250.87, 398.79, 310.35, 675.89, 749.87]

returns = []

for i in range(len(lst)): 
    returns.append((lst[i+1]//lst[i])-1)

Returns

IndexError                                
Traceback (most recent call last)
<ipython-input-37-526d26c5b374> in <module>
      2 
      3 for i in range(len(lst)):
----> 4     returns.append((lst[i+1]//lst[i])-1)
      5 
      6 print(returns)

IndexError: list index out of range

Upvotes: 0

Views: 68

Answers (2)

JBB
JBB

Reputation: 186

Colin,

Assuming you are somewhat new to python. For that reason, I might operate inside of a construct that has some nice architecture around it.

import pandas as pd
import numpy as np
price_series = pd.Series(lst)
return_series = np.log(price_series/price_series.shift(1))  # assuming daily returns
rolling_one_year = return_series.rolling(252).sum()

Start there. Strongly suggest you stay inside of pandas to start your work in financial series data for many reasons. Lots of help here on stack overflow for these libraries.

Best of luck!

Upvotes: 0

Chris Loonam
Chris Loonam

Reputation: 5745

This

for i in range(len(AMZN_stock_prices)):

will cause i to vary between 0 and len(AMZN_stock_prices)-1. When it's at its highest value, i+1 is outside the bounds of the list. Use

for i in range(len(AMZN_stock_prices)-1):

so that i+1 never goes outside the bounds.

Upvotes: 1

Related Questions