我使用下面链接中提供的答案中的代码来汇总2天期间的每日价格(freq='2B');但是,日期戳显示的是聚合周期的开始日期。是否可以显示加盖期间最后日期的结果?
示例:如果在1月16日和17日聚合,日期戳将显示2023-01-17
https://stackoverflow.com/a/74775358/13415270
pd.Grouper()
支持convention
参数。您可以将此参数设置为"e"
或"end"
。convention
要求有一个周期索引。因此,您应该首先设置索引。把它们放在一起:
import yfinance as yf
import pandas as pd
df = yf.download("AAPL", period="2y", interval="1h")
# set period index
df.index = df.index.to_period(freq="2B")
# use convention
df_agg = df.groupby(pd.Grouper(freq="2B", convention="end")).agg(
{"Open": "first", "High": "max", "Low": "min", "Close": "last", "Adj Close": "last"}
)
df_agg.head()
输出:
Open High Low Close Adj Close
Datetime
2021-01-22 133.863998 139.850006 133.789993 138.969894 138.969894
2021-01-26 143.222702 145.080002 136.539993 143.184998 143.184998
2021-01-28 143.429993 144.300003 136.699997 137.089996 137.089996
2021-02-01 136.179993 136.729996 130.210007 134.110001 134.110001
2021-02-03 135.729996 136.309998 133.610001 133.904999 133.904999