Search code examples
pythonpandasdataframeyfinance

How can I a weighted moving average using yfinance and pandas


I want to compare the 50 day moving average and 50 day weighted moving average of a company.

import yfinance as yf
import datetime as dt
start = '2021-05-01'                # format: YYYY-MM-DD
end = dt.datetime.now()             # today
stock='AMD'
df = yf.download(stock,start, end, interval='1h')

This is just to set up the data frame.

The code below adds a column to the data frame with the moving average, but I have been unsuccessful trying to do the same for a weighted moving average.

df['50MA']= df.iloc[:, 4].rolling(window=50).mean()

This is what I have which is incorrect

for i in range(len(df.index)):
    df['W50MA']=(df.iloc[i, 4]) * (df.iloc[i, 5]/sum(df.iloc[:, 5]))

Solution

  • You could try something like this:

    weights = np.array(list(range(1, 51))) / 100
    sum_weights = np.sum(weights)
    
    def weighted_ma(value):
        return np.sum(weights*value) / sum_weights
    
    df['50WMA'] = df.iloc[:, 4].rolling(window=50).apply(weighted_ma)