Wookeun Lee Wookeun Lee - 1 month ago 17
Python Question

Questions on pandas moving average

I am a beginner of python and pandas. I am having difficulty with making volatility adjusted moving average, so I need your help.

Volatility adjusted moving average is a kind of moving average, of which moving average period is not static, but dynamically adjusted according to volatility.

What I'd like to code is,


  1. Get stock data from yahoo finance (monthly close)

  2. Calculate monthly volatility X some constant --> use variables of dynamic moving average period

  3. Calculate dynamic moving average



I've tried this code, but only to fail. I don't know what the problem is. If you know the problem, or any better code suggestion, please let me know.

import pandas as pd
import matplotlib.pyplot as plt
import numpy as np
import pandas_datareader.data as web

def price(stock, start):
price = web.DataReader(name=stock, data_source='yahoo', start=start)['Adj Close']
price = price / price[0]
a = price.resample('M').last().to_frame()
a.columns = ['price']
return a


a = price('SPY','2000-01-01')
a['volperiod'] = round(a.rolling(12).std()*100)*2
for i in range(len(a.index)):
k = a['price'].rolling(int(a['volperiod'][i])).mean()
a['ma'][i] = k[i]

print(a)

Answer

first of all: you need to calculate pct_change on price to calculate volatility of returns

my solution

def price(stock, start):
    price = web.DataReader(name=stock, data_source='yahoo', start=start)['Adj Close']
    return price.div(price.iat[0]).resample('M').last().to_frame('price')

a = price('SPY','2000-01-01')

v = a.pct_change().rolling(12).std().dropna().mul(200).astype(int)

def dyna_mean(x):
    end = a.index.get_loc(x.name)
    start = end - x.price
    return a.price.iloc[start:end].mean()

pd.concat([a.price, v.price, v.apply(dyna_mean, axis=1)],
          axis=1, keys=['price', 'vol', 'mean'])