I just started studying pandas and have questions. Firstly, I'd like to ask this.
I have dataframe and it's like below.
Date Open High Low Close
2015-11-02 711.059998 721.619995 705.849976 721.109985
2015-11-03 718.859985 724.650024 714.719971 722.159973
2015-11-04 722.000000 733.099976 721.900024 728.109985
2015-11-05 729.469971 739.479980 729.469971 731.250000
2015-11-06 731.500000 735.409973 727.010010 733.760010
I know
df["Close"].pct_change()
make the percent change from Close to Close.
But, I want to add a new column, "CloseToOpen" which is a percent change of "yesterday Close to today Open".
So, it is "Open(Day 0) / Close(Day -1) -1". Of course, the first row should be "NaN" or Zero because there's no "previous day's Close".
How can I make this with python pandas code??
Thanks guys!
This is what I want.
Date Open High Low Close CloseToOpen
2015-11-02 711.059998 721.619995 705.849976 721.109985 0.000000
2015-11-03 718.859985 724.650024 714.719971 722.159973 -0.003120
2015-11-04 722.000000 733.099976 721.900024 728.109985 -0.000222
2015-11-05 729.469971 739.479980 729.469971 731.250000 0.001868
2015-11-06 731.500000 735.409973 727.010010 733.760010 0.000342
Also you can use standard operands to achieve what you wanted:
df['CloseToOpen'] = (df['Open'] / df['Close'].shift(1) - 1).fillna(0)
Use:
df['CloseToOpen'] = df['Open'].sub(df['Close'].shift()).div(df['Close'] - 1).fillna(0)
print (df)
Open High Low Close CloseToOpen
Date
2015-11-02 711.059998 721.619995 705.849976 721.109985 0.000000
2015-11-03 718.859985 724.650024 714.719971 722.159973 -0.003120
2015-11-04 722.000000 733.099976 721.900024 728.109985 -0.000220
2015-11-05 729.469971 739.479980 729.469971 731.250000 0.001862
2015-11-06 731.500000 735.409973 727.010010 733.760010 0.000341