[英]Questions on pandas moving average
I am a beginner of python and pandas.我是python和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,我想编码的是,
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)
first of all: you need to calculate pct_change
on price
to calculate volatility
of returns
首先:您需要计算price
pct_change
以计算returns
volatility
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'])
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.