Dick Thompson
Dick Thompson

Reputation: 609

Pandas looping through rows and skipping over rows?

I have a pandas dataframe with prices in one column and datetime in another. All I'm looking to do is create a backtesting loop that says if price hits a certain point, skip through 30 rows and calculate the difference in prices between that row and 30th row after it. Then, continue the loop to the last row of the dataframe.

Is there a more pythonic way to do this instead of just entering continue 30 times?

Appreciate the help

Sample df:

index                  vol1     vol2          vol3           price  
0            0.0    0.984928    0.842774    0.403604        0.24676   
1            0.0    0.984928    0.842774    0.403604        0.24676   
2            0.0    0.984928    0.842774    0.403604        0.24676   
3            0.0    0.984928    0.842774    0.403604        0.24676   
4            0.0    0.984928    0.842774    0.403604        0.24683   
5            0.0    0.958933    0.843822    0.407730        0.24724   
6            0.0    0.950355    0.842774    0.412017        0.24724   
7            0.0    0.946536    0.843822    0.419604        0.24725   
8            0.0    0.941535    0.843822    0.421247        0.24683   
9            0.0    0.935383    0.842775    0.415184        0.24708   
10           0.0    0.934629    0.842774    0.402836        0.24691 

Upvotes: 0

Views: 2548

Answers (1)

bluenex
bluenex

Reputation: 349

I 'm not sure you want to completely skip the row between those 30 rows or want to continue. I try to give an idea of what you want in continuing row by row version. Sample data and your prototype code are needed, as suggested by Peter, so that more people can help you.

Here is my sample code:

# load dataframe to df
df = pd.Dataframe()

# set threshold for the price
limit_price = x

# collect difference of prices as a list
diff_prices = []

# loop through dataframe df
for index, row in df.iterrows():
  # row is pd.Series now, check if it pass certain point here
  if row.prices > limit_price:
    # if pass find the diff of this row and 30 row ahead of it
    # and then add to a list
    diff_prices.append(row.prices - df.iloc[index+30].prices)
  else:
    # if not pass add 0 to a list instead
    diff_prices.append(0)

Upvotes: 1

Related Questions