Reputation: 73
Hello I am writing this python code by using pandas to analyze some stock data. I am using two too loops for getting cumulative profit.But it gave me list index out of range error. Anyone could help? df is dataframe I am using and it has about 10 columns included 'invest' and 'percent change'. df['invest'] column is all binary numbers 1 or 0 and df['percent change'] is stock price changed compared with last day. windows here mean if I see windows consecutive 0 such as 2 consecutive 0, I am going to buy this stock and sell it the next day.
This one is my assignment. It is not really stock analysis. So please do not take the analytics method too seriously. These just for demonstrating python for data science
count=0
countseq=0
principal=100
windows=[1,2,3,4,5]
profit_loss=[0,0,0,0,0]
for i in windows:
for j in range(len(df)-1):
if df['invest'][j]==0:
count+=1
if count==i:
profit_loss[i]+=principal*df['percent change'][j+1]
count=0
countseq+=1
IndexError Traceback (most recent call last)
<ipython-input-119-53972da7243a> in <module>()
10 count+=1
11 if count==i:
---> 12 profit_loss[i]+=principal*df['percent change'][j+1]
13 count=0
14 countseq+=1
IndexError: list index out of range
Upvotes: 0
Views: 1935
Reputation: 5955
You're using the values of windows
, with max 5
, to index into profit_loss
, whose max index is 4
. Remember that python is zero-indexed
Upvotes: 1