Questions on pandas moving average
<p>I am a beginner of python and pandas. I am having difficulty with making volatility adjusted moving average, so I need your help.</p>

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

<p>What I'd like to code is,</p>

<ol>
<li>Get stock data from yahoo finance (monthly close)</li>
<li>Calculate monthly volatility X some constant --> use variables of dynamic moving average period</li>
<li>Calculate dynamic moving average</li>
</ol>

<p>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.</p>

<pre><code>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)
</code></pre>

<p>first of all: you need to calculate <code>pct_change</code> on <code>price</code> to calculate <code>volatility</code> of <code>returns</code></p>

<p><strong><em>my solution</em></strong></p>

<pre><code>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'])
</code></pre>

python pandas