简体   繁体   中英

How to calculate percentage change in the Open price of a stock in pandas

I have the following data frame.

  Date       Open        Close  
2016-06-01  17670.85    17423.45
2016-06-02  17405.15    17567.80
2016-06-03  17657.20    17680.80
2016-06-06  17710.45    17671.40
2016-06-07  17796.55    17948.15
... ... ...
2020-05-11  19610.45    18950.50
2020-05-12  18751.40    18862.85
2020-05-13  20017.75    19634.95
2020-05-14  19197.70    19068.50
2020-05-15  19098.80    18833.95

I need to calculate the percentage change in open price from the previous close.

I tried using pct_change function of pandas but the percentage is not calculated correctly.

This is how I tried to calculate:

historical_data['change'] = historical_data[['Open','Close']].pct_change(axis=1)['Close'] and the output data is below wherein percentage change in not correct.

 Date        Open     Close    change                                
2016-06-01  17670.85  17423.45 -0.014000
2016-06-02  17405.15  17567.80  0.009345
2016-06-03  17657.20  17680.80  0.001337
2016-06-06  17710.45  17671.40 -0.002205
2016-06-07  17796.55  17948.15  0.008519
...              ...       ...       ...
2020-05-11  19610.45  18950.50 -0.033653
2020-05-12  18751.40  18862.85  0.005944
2020-05-13  20017.75  19634.95 -0.019123
2020-05-14  19197.70  19068.50 -0.006730
2020-05-15  19098.80  18833.95 -0.013867

Any idea what I am doing wrong here?

Yes. It is the PREVIOUS close you want, so

historicalData["prevClose"] = df.Close.shift(1)
historical_data['change'] = historical_data[['Open','prevClose']].pct_change(axis=1)['Close']

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM