0

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
6
  • try for j in range(len(df['percent change'])): Commented Sep 26, 2018 at 22:02
  • no, it did not work.I think it is because of i, but I am not sure @Ruzihm Commented Sep 26, 2018 at 22:05
  • 1
    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 Commented Sep 26, 2018 at 22:07
  • In other words, do for i in range(len(profit_loss)): and for j in range(len(df['percent change'])): Commented Sep 26, 2018 at 22:10
  • it worked! @G.Anderson Commented Sep 26, 2018 at 22:11

1 Answer 1

1

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

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.