How to calculate pivot value from OHLC data

限于喜欢 提交于 2019-12-24 03:49:05

问题


I've a pandas dataset with open, high, low, close and key column. Now I want to group the dataset by key and calculate pivot with the formula - (high + low + close) / 3. Upto this I'm able to do. But the requirement is to shift the calculated data to next group which I'm unable to code.

I'm able to group the dataset by key column and able to calculate pivot data.

import pandas as pd
data = pd.DataFrame([[110, 115, 105, 111, 1],[11, 16, 6, 12, 1],[12, 17, 7, 13, 1],[12, 16, 6, 11, 2],[9, 13, 4, 13, 2],[13, 18, 9, 12, 3],[14, 16, 10, 13, 3]], columns=["open","high","low","close","key"])
data['p'] = (data.high.groupby(data.key).transform('max') + data.low.groupby(data.key).transform('min') + data.close.groupby(data.key).transform('last')) / 3
print(data)

Currently I'm getting below output.

   open  high  low  close  key      p
0   110   115  105    111    1  44.666667
1    11    16    6     12    1  44.666667
2    12    17    7     13    1  44.666667
3    12    16    6     11    2  11.000000
4     9    13    4     13    2  11.000000
5    13    18    9     12    3  13.333333
6    14    16   10     13    3  13.333333

But after shifting value to next group the expected output should be as mentioned below.

   open  high  low  close  key      p
0   110   115  105    111    1     NaN
1    11    16    6     12    1     NaN
2    12    17    7     13    1     NaN
3    12    16    6     11    2  44.666667
4     9    13    4     13    2  44.666667
5    13    18    9     12    3  11.000000
6    14    16   10     13    3  11.000000

回答1:


Instead 3 dimes groupby use GroupBy.agg with dictionary, then sum values per rows and divide 3. Last use Series.map with Series.shifted values for new column:

s = data.groupby('key').agg({'low':'min','high':'max','close':'last'}).sum(axis=1) / 3

data['s'] = data['key'].map(s.shift())
print(data)
   open  high  low  close  key          s
0   110   115  105    111    1        NaN
1    11    16    6     12    1        NaN
2    12    17    7     13    1        NaN
3    12    16    6     11    2  44.666667
4     9    13    4     13    2  44.666667
5    13    18    9     12    3  11.000000
6    14    16   10     13    3  11.000000


来源:https://stackoverflow.com/questions/56215790/how-to-calculate-pivot-value-from-ohlc-data

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!