Weekly Sample Moving Average

673 Views Asked by At

I am trying to get the data from yahoo finance (yfinance) and calculate the simple moving average(SMA) but it only works for daily data instead of weekly data. Daily data of SMA returned calculated SMA20 but weekly data only returned NaN. Anything wrong in my code below? Grateful if you could help.

import yfinance as yf
#Weekly
stock = yf.download(tickers= 'MSFT',interval='1wk')
stock['SMA_20'] = stock['Close'].rolling(window=20).mean()
print(stock)

#Daily
stock = yf.download(tickers= 'MSFT',interval='1d')
stock['SMA_20'] = stock['Close'].rolling(window=20).mean()
print(stock)
1

There are 1 best solutions below

2
Richard K Yu On

Specify the min_periods parameter in the rolling() method to show results earlier than the first 20 intervals. Please check the documentation on the method for additional details:

Also note that your SMA_20 is over weeks rather than days when you specify the interval to be 1wk.

import yfinance as yf
#Weekly
stock = yf.download(tickers= 'MSFT', interval='1wk')
stock['SMA_20'] = stock['Close'].rolling(window=20, min_periods = 1).mean()
print(stock)

#Daily
stock = yf.download(tickers= 'MSFT', interval='1d')
stock['SMA_20'] = stock['Close'].rolling(window=20,min_periods = 1).mean()
print(stock)

Output: enter image description here enter image description here