-1

The title of this might be a bit confusing but i will try to explain what i am trying to do. I have an OHLC csv of stocks. I am trying to add a new column named L and H. Here what represents. I need to check for the smallest Open price in last n days (say 5). and i need to set it's Low price to L and High price as H.

Here is my Dataframe

            Date     Open     High      Low
5303  2018-06-11  1681.51  1694.24  1680.59
5304  2018-06-12  1693.00  1699.51  1691.52
5305  2018-06-13  1702.81  1713.75  1700.12
5306  2018-06-14  1713.48  1724.80  1708.87
5307  2018-06-15  1714.00  1720.87  1708.52
5308  2018-06-18  1706.26  1726.74  1702.56
5309  2018-06-19  1709.04  1736.11  1700.39
5310  2018-06-20  1742.50  1762.93  1741.36
5311  2018-06-21  1760.00  1763.10  1717.56
5312  2018-06-22  1742.62  1743.00  1711.90

I have tried the following way but it only returns the minimum value not the Series i can grab High and Low

df['Open'].rolling(5).min()

Here i am trying to get the index or whole Dataframe series of rolling() to grab Hig and Low values of this rolling. I hope I could explain.

EDIT: Added expected output

Let's say index 5308 is the smallest Open in last 5 rows. So L will be equal to 5308's Low column and H will be equal to 5308's High column in the rest of data

            Date     Open     High      Low        H        L
5309  2018-06-19  1709.04  1736.11  1700.39  1726.74  1702.56
5310  2018-06-20  1742.50  1762.93  1741.36  1726.74  1702.56
5311  2018-06-21  1760.00  1763.10  1717.56  1726.74  1702.56
5312  2018-06-22  1742.62  1743.00  1711.90  1726.74  1702.56
Don Coder
  • 526
  • 5
  • 24

1 Answers1

2

IIUC, use idxmin in apply with rolling:

df[['L','H']] = (df.reindex(df['Open'].rolling(5)
                                      .apply(lambda x: x.idxmin(), 
                                             raw=False))[['Low','High']].values)

Output:

            Date     Open     High      Low        L        H
5303  2018-06-11  1681.51  1694.24  1680.59      NaN      NaN
5304  2018-06-12  1693.00  1699.51  1691.52      NaN      NaN
5305  2018-06-13  1702.81  1713.75  1700.12      NaN      NaN
5306  2018-06-14  1713.48  1724.80  1708.87      NaN      NaN
5307  2018-06-15  1714.00  1720.87  1708.52  1680.59  1694.24
5308  2018-06-18  1706.26  1726.74  1702.56  1691.52  1699.51
5309  2018-06-19  1709.04  1736.11  1700.39  1700.12  1713.75
5310  2018-06-20  1742.50  1762.93  1741.36  1702.56  1726.74
5311  2018-06-21  1760.00  1763.10  1717.56  1702.56  1726.74
5312  2018-06-22  1742.62  1743.00  1711.90  1702.56  1726.74
Scott Boston
  • 147,308
  • 15
  • 139
  • 187