如何将现实世界中的5天每日股票数据转换为每周模式,以获得每周移动平均线



我有印度证券交易所的数据和一个代码,可以通过使用.rolling_mean给出简单的移动平均值,但我想对每周数据也这样做。我尝试了许多通过互联网和博客提供的方法,但似乎没有任何方法适用于我的用例。

我正在使用Python 3.7Pandas 1.3.0

以下是我尝试过的代码:

df1 = df.copy()
df1.set_index('DATE',drop=True,inplace=True)
logic = {'OPEN'  : 'first',
'HIGH'  : 'max',
'LOW'   : 'min',
'CLOSE' : 'last',}
offset = pd.offsets.timedelta(days=-6)
f = pd.read_clipboard(parse_dates=['DATE'], index_col=['DATE'])
f.resample('W', loffset=offset).apply(logic)

这个:

f = df.copy()
f['DATE'] = pd.to_datetime(f['DATE'])
f.set_index('DATE', inplace=True)
f.sort_index(inplace=True)
def take_first(array_like):
return array_like[0]
def take_last(array_like):
return array_like[-1]
output = f.resample('W',                                 # Weekly resample
how={'OPEN': take_first, 
'HIGH': 'max',
'LOW': 'min',
'CLOSE': take_last,}, 
loffset=pd.offsets.timedelta(days=-6))  # to put the labels to Monday
output = output[['OPEN', 'HIGH', 'LOW', 'CLOSE']]

两者都给出相同的错误:

AttributeError: module 'pandas.tseries.offsets' has no attribute 'timedelta'

可以使用Anchored offsets对固定到周一的每周进行重新采样,然后Resample.aggregate可以执行操作:

logic = {'Open': 'first',
'High': 'max',
'Low': 'min',
'Close': 'last'}
output = df.resample('W-MON').agg(logic)

一些样本数据:

import yfinance as yf
msft = yf.Ticker("MSFT")
df = msft.history(start='2021-06-20', end="2021-07-20")
Open        High  ...  Dividends  Stock Splits
Date                                ...                         
2021-06-21  259.820007  263.519989  ...          0             0
2021-06-22  262.720001  265.790009  ...          0             0
2021-06-23  265.989990  266.829987  ...          0             0
2021-06-24  266.160004  267.850006  ...          0             0
2021-06-25  266.230011  267.250000  ...          0             0
2021-06-28  266.190002  268.899994  ...          0             0
2021-06-29  268.869995  271.649994  ...          0             0
2021-06-30  270.690002  271.359985  ...          0             0
2021-07-01  269.609985  271.839996  ...          0             0

样本输出:

Open        High         Low       Close
Date                                                      
2021-06-21  259.820007  263.519989  257.920013  262.630005
2021-06-28  262.720001  268.899994  262.399994  268.720001
2021-07-05  268.869995  278.000000  267.980011  277.649994
2021-07-12  278.029999  280.690002  274.299988  277.320007
2021-07-19  277.519989  284.100006  275.000000  276.140015

最新更新