Fastest way to calculate and append rolling mean as columns for grouped dataframe

Viewed 22

Have the following dataset. This is a small sample while the actual dataset is much larger.

What is the fastest way to:

  • iterate through days = (1,2,3,4,5,6)
  • calculate [...rolling(day, min_periods=day).mean()]
  • add it as column name df[f'sma_{day}']

Method I have is casting it to dict of {ticker:price_df} and looping through shown below..

Have thought of methods like groupby, stack/unstack got stuck and need help with appending the columns because they are multi-index.

Am favouring the method with the fastest %%timeit.

import yfinance as yf
df = yf.download(['MSFT','AAPL','AMZN'], start="2022-09-13").loc[:,['Close']].stack().swaplevel().sort_index()
df.index.set_names(['Ticker','Date'], inplace=True)
df

enter image description here

Here is a sample dictionary method I have..

df = df.reset_index()
df = dict(tuple(df.groupby(['Ticker'])))

## Iterate through days and keys
days = (1, 2, 3, 4, 5, 6)
for key in df.keys():
    for day in days:
        df[key][f'sma_{day}'] = df[key].Close.sort_index(ascending=True).rolling(day, min_periods=day).mean()

## Flatten dictionary
pd.concat(df.values()).set_index(['Ticker','Date']).sort_index()

enter image description here

enter image description here

0 Answers
Related