更新时间:2023-11-07 13:34:16
IIUC,在 groupby
中,您可以通过"ticker"进行操作,也可以使用 pd.NamedAgg
,其中 first
用于打开, last
用于关闭, max
表示高, min
表示低.
IIUC, in the groupby
you can do it by 'ticker' but also using pd.Grouper
on 'time' with a frequence of 5 minutes. In the agg
method, you can use since pandas>0.25 pd.NamedAgg
with first
for open, last
for close, max
for high and min
for low.
# dummy variables
np.random.seed(0)
df = pd.DataFrame({'time':pd.date_range('2020-04-01 9:30:00', freq='20s', periods=50).tolist()*2,
'ticker': ['ticker1']*50 + ['ticker2']*50,
'price':np.random.randint(30, 50, 100)})
# groupby and agg, then reset_index
df_f = df.groupby(['ticker', pd.Grouper(key='time', freq='5T')])\
.agg(open=pd.NamedAgg(column='price', aggfunc='first'),
close=pd.NamedAgg(column='price', aggfunc='last'),
high=pd.NamedAgg(column='price', aggfunc='max'),
low=pd.NamedAgg(column='price', aggfunc='min'))\
.reset_index()
print (df_f)
ticker time open close high low
0 ticker1 2020-04-01 09:30:00 42 37 49 30
1 ticker1 2020-04-01 09:35:00 44 33 49 30
2 ticker1 2020-04-01 09:40:00 47 32 49 30
3 ticker1 2020-04-01 09:45:00 30 36 36 30
4 ticker2 2020-04-01 09:30:00 38 48 48 31
5 ticker2 2020-04-01 09:35:00 30 44 45 30
6 ticker2 2020-04-01 09:40:00 45 34 48 30
7 ticker2 2020-04-01 09:45:00 32 40 46 32
使用plotly绘制烛台,您可以执行以下操作:
for plotting candlestick with plotly, you can do:
import plotly.figure_factory
def plot_tick(data, ticker):
ts = data[data["ticker"]==ticker].reset_index(drop=True)
fig = plotly.figure_factory.create_candlestick(ts.open, ts.high, ts.low,
ts.close, dates=ts.time)
fig.show()
plot_tick(df_f, 'ticker1')