采样 30 天增量并从现有的每日框架创建新的数据框架

问题描述 投票:0回答:1

我将每日数据存储到一个数据框中,并希望创建一个新的数据框,其中仅包含该月最后一天(或过去 30 天或 60 天)的数据,并在条形图中绘制给定时间范围内的这些周期回报。我尝试使用重新采样函数,但是,它会跳过最后一个工作日并在某些月份的最后一天返回 NA。

有没有办法计算从开始到结束的30天滚动回报,并以末期结束(< 30 days) shown in the plot using a few lines of code?

s1 = yf.download("^GSPC", start="2005-02-01", end="2007-12-31")

s1.resample('M', convention='end').asfreq()
python pandas datetime finance pandas-resample
1个回答
0
投票

您可以尝试以下操作:使用 aggregation 重置索引并按年和月对数据框进行 group

import yfinance as yf
import pandas as pd

s1 = yf.download("^GSPC", start="2005-02-01", end="2007-12-31")

s1 = s1.reset_index()

df = (s1.groupby([s1['Date'].dt.year, s1['Date'].dt.month], as_index=False)
      .agg({'Date' : 'first', 'Open': 'first', 'High': 'max',
       'Low': 'min', 'Close': 'last', 'Volume': 'sum'})).set_index('Date')

print(df)
© www.soinside.com 2019 - 2024. All rights reserved.