【发布时间】:2020-12-09 06:12:55
【问题描述】:
我有以下 Pandas 数据框 df 包含分钟间隔股价数据:
High Low
Timestamp
2020-01-02 04:01:00 295.08 295.05
2020-01-02 04:07:00 295.59 295.35
2020-01-02 04:09:00 295.55 295.55
2020-01-02 04:10:00 295.75 295.74
2020-01-02 04:11:00 295.60 295.60
... ... ... ... ... ... ... ...
2020-08-18 19:56:00 462.98 462.98
2020-08-18 19:57:00 462.98 462.95
2020-08-18 19:58:00 462.88 462.88
2020-08-18 19:59:00 462.88 462.85
2020-08-18 20:00:00 462.85 462.80
Timestamp 是一个日期时间索引。我已经能够使用以下代码获得每个交易日上午 9 点 30 分到下午 4 点之间每个交易日的最高价和最低价和时间:
# Calculate the highest High and lowest low for each trading day
daily_high_low = df.between_time('09:30','16:00', include_start=False, include_end=True).resample('D').agg({'High':'max', 'Low':'min'}).dropna()
# Add 'Date' column to df for groupby
df['Date'] = df.index.date
# Get time of Reg. Trading Hours High and Low
high_time = df[['Date','High']].between_time('09:30','16:00', include_start=False, include_end=True).groupby('Date').idxmax()
high_time.index = pd.to_datetime(high_time.index)
high_time = high_time['High'].dt.time.rename('High_Time')
low_time = df[['Date','Low']].between_time('09:30','16:00', include_start=False, include_end=True).groupby('Date').idxmin()
low_time.index = pd.to_datetime(low_time.index)
low_time = low_time['Low'].dt.time.rename('Low_Time')
这使我能够生成以下数据框:
High Low High_Time Low_Time
Timestamp
2020-01-02 300.6000 295.1900 16:00:00 09:33:00
2020-01-03 300.5800 296.5000 12:52:00 09:31:00
2020-01-06 299.9600 292.7501 14:15:00 09:31:00
2020-01-07 300.9000 297.4800 09:35:00 10:29:00
2020-01-08 304.4399 297.1560 15:42:00 09:31:00
... ... ... ... ... ... ...
2020-08-12 453.1000 441.1900 12:46:00 09:45:00
2020-08-13 464.1700 455.7100 13:01:00 10:19:00
2020-08-14 460.0000 452.1800 15:56:00 11:05:00
2020-08-17 464.3600 455.8501 09:31:00 11:47:00
2020-08-18 464.0000 456.0300 14:24:00 10:31:00
我现在正在尝试生成和添加以下列,但完全卡住了:
-
L_after_H,当日高点之后的最低低点, -
H_after_L,当日低点之后的最高点, -
L_after_H_Time,在当天的高点之后出现的最低低点的时间, -
H_after_L_Time,即当天低点之后的最高高点时间。
我最好的尝试是这样的
df[['Date', 'High', 'Low']].groupby('Date') \
.between_time(high_time,'16:00', include_start=False, include_end=True)
但这失败了,因为'DataFrameGroupBy' object has no attribute 'between_time'。我真的很高兴能够过滤日期组以仅包含时间戳> high_time。
【问题讨论】:
-
我在我的问题中提到了它,但我最好的尝试是类似
df[['Date','High','Low']].groupby('Date').between_time(high_time,'16:00', include_start=False, include_end=True),但因为'DataFrameGroupBy' object has no attribute 'between_time'而失败了。我真的很高兴能够过滤日期组以仅包含时间戳> high_time。 -
基于这 10 个共享行,预期的输出是什么?
标签: python pandas pandas-groupby