I have a DataFrame with daily OHLCV data.
I can calculate the range with:
s['Range'] = s['High'] - s['Low']
Simple. Now I would like to calculate a new column which I’ve called s['OIR'] (OIR = Open-In-Range)
The ['OIR'] column checks to see if we opened in range and it does this by testing if we opened above yesterdays low and below yesterday’s high. I need to reference the previous rows and I’m not quite sure how to do it. The return values would be True/False.
Thanks.
edit: I’m new to StackExchange and Python. Not sure where to drop sample data. Here’s an image of the dataframe.
http://i47.tinypic.com/142eb2a.png
Sample Data: Dictionary convert to DataFrame
{'High': {<Timestamp: 2007-03-02 00:00:00>: 1384.5,
<Timestamp: 2007-03-05 00:00:00>: 1373.0},
'Last': {<Timestamp: 2007-03-02 00:00:00>: 1365.0,
<Timestamp: 2007-03-05 00:00:00>: 1351.5},
'Low': {<Timestamp: 2007-03-02 00:00:00>: 1364.25,
<Timestamp: 2007-03-05 00:00:00>: 1350.5},
'OIR': {<Timestamp: 2007-03-02 00:00:00>: False,
<Timestamp: 2007-03-05 00:00:00>: False},
'Open': {<Timestamp: 2007-03-02 00:00:00>: 1378.5,
<Timestamp: 2007-03-05 00:00:00>: 1356.75},
'Range': {<Timestamp: 2007-03-02 00:00:00>: 20.25,
<Timestamp: 2007-03-05 00:00:00>: 22.5},
'Volume': {<Timestamp: 2007-03-02 00:00:00>: 1706906,
<Timestamp: 2007-03-05 00:00:00>: 1984041}}
Answer:
s['OIR'] = ((s['Open'] < s['High'].shift(1)) & (s['Open'] > s['Low'].shift(1)))
Referencing previous rows in the manner you suggest is best accomplished with the
Series.shift()function: