0

For example I have a DF:

Adj Close   Close   High    Low Open    Volume
ABNB    GME ABNB    GME ABNB    GME ABNB    GME ABNB    GME ABNB    GME
Date                                                
2021-01-04  139.149994  17.250000   139.149994  17.250000   151.005005  19.100000   137.000000  17.15   150.990005  19.000000   6409900 10022500
2021-01-05  148.300003  17.370001   148.300003  17.370001   149.000000  18.080000   137.250000  17.23   138.279999  17.350000   5974200 4961500
2021-01-06  142.770004  18.360001   142.770004  18.360001   148.350006  18.980000   141.110001  17.33   145.750000  17.340000   4213900 6056200
2021-01-07  151.270004  18.080000   151.270004  18.080000   154.419998  19.450001   145.261002  18.02   146.369995  18.469999   4482800 6129300
2021-01-08  149.770004  17.690001   149.770004  17.690001   155.539993  18.299999   147.250000  17.08   153.449997  18.180000   4615600 6482000

and I am wanting to calculate the 52 week low for each day(row) in the DF. However for the rows that dont have 52 rows available, I would like to take the min() of whatever is available. Here is the code that I tried that isnt working:

for row in data.iterrows():
  if row[0] < (data.index[0] + timedelta(days = 365)):
    data['52wkLow'] = data['Low']['GME'].rolling((row[0]-data.index[0]).days).min())
  elif row[0] > (data.index[0] + timedelta(days = 365)):
    data['52wkLow'] = data['Low']['GME'].rolling(365).min()
PyNewb
  • 1
  • Why are iterating and using the rolling method? Also, could you provide the code for creating the data you posted here? Use this [guide](https://stackoverflow.com/questions/20109391/how-to-make-good-reproducible-pandas-examples) for reference on how to make good questions. – xicocaio Mar 31 '21 at 18:41
  • Can you explain in what way the code is not working? If you provide the output you're getting (or error message?) and how it differs from what you want, it would be easier to help you. – joanis Mar 31 '21 at 19:23

1 Answers1

0

The .rolling() method has an optional min_periods= argument (https://pandas.pydata.org/docs/reference/api/pandas.DataFrame.rolling.html)

min_periods int, default None Minimum number of observations in window required to have a value (otherwise result is NA). For a window that is specified by an offset, min_periods will default to 1. Otherwise, min_periods will default to the size of the window.

So you can set it to 1, and it will give you the min() of at least one value, e.g.,:

data['52wkLow'] = data['Low']['GME'].rolling(365, 1).min()

AlexK
  • 2,855
  • 9
  • 16
  • 27