-2

I am really new to programming and trying to muddle my way through learning Python. I am writing some code to work with data from Yahoo Finance. It is mported to a Pandas dataframe

I want to perform a simple calculation that refers multiple rows of the dataframe. I Don't think I can do this with iterrows is covers one row at a time.

Below is my dataframe (index is date). The last row is my trigger to buy(1) or sell (-1) but the buy/sell price must come from the following row.

So in this example, Feb 22 is my signal day. I then need to use the open price on Feb 23 for my position calculations etc. What is the best way to access data in the df dependent on the values in the signal column (created using iterrows previously)? I cant do this during the iterrows iteration as it will only look at one row at a time (I think).

2016-02-19  117.580002  112.619343  108.836458  109.025525  2.025102            
2016-02-22  115.489998  112.892739  109.097382  109.089848  2.039591        1   
2016-02-23  117.220001  113.304859  109.415916  109.170745  2.028632        1   
2016-02-24  117.610001  113.714873  109.737252  109.254718  2.089769        1  

Any ideas would be much appreciated.

Cheers\MP

MaxU - stand with Ukraine
  • 205,989
  • 36
  • 386
  • 419
MGP
  • 1

1 Answers1

0

If your signal column is the las one and you want to select the rows where the value in that column is 1:

df.loc[df.iloc[:, -1] == 1]

I'd better use the column name if I knew it.

Stop harming Monica
  • 12,141
  • 1
  • 36
  • 56
  • The issue is working on the row below the first occurrence of 1 in the signal column. – MGP Mar 10 '16 at 05:27
  • Essentially searching down 'position' column in order of the index (time series) until there is a 1. Then returning the value located in the 'close' column of the following row. I only want to return this value the first time there is a 1 present. There may be a better way to create my DataFrame in the first place but this is based on an import from Yahoo Finance. – MGP Mar 10 '16 at 06:02