Search code examples
pythondataframerowsquantitative-finance

How do I check a previous row's value, (OHLC Stock Data)?


I'm trying to do data-mine a stock data frame where the signal generated is in this format:

Signal = (stratdf['High'].shift() > (stratdf['Open'].shift()))

How do I code to check the previous row's value and compare it to the corresponding rows value (example: 1 bar ago > 10 bars ago) with the Signal being executed the next day (or row) after the logic is true?


Solution

  • >>> import pandas as pd
    >>> df = pd.DataFrame([[4, 5, 9, 7, 10], [5, 4, 11, 8, 9]]).T
    >>> df.columns = ['High', 'Open']
    >>> df
       High  Open
    0     4     5
    1     5     4
    2     9    11
    3     7     8
    4    10     9
    >>> df['pre_high'] = df['High'].shift(1)
    >>> df
       High  Open  pre_high
    0     4     5       NaN
    1     5     4       4.0
    2     9    11       5.0
    3     7     8       9.0
    4    10     9       7.0
    

    Now if you want to check where the pre_high is greater than the current open, then you can do the following:

    >>> df['Signal'] = df['High'].shift(1) > df['Open']
    >>> df
       High  Open  pre_high  Signal
    0     4     5       NaN   False
    1     5     4       4.0   False
    2     9    11       5.0   False
    3     7     8       9.0    True
    4    10     9       7.0   False