Lin*_*Jin 3 python math finance
from datetime import datetime
from pandas.io.data import DataReader
from numpy import cumsum, log, polyfit, sqrt, std, subtract
from numpy.random import randn
def hurst(ts):
"""Returns the Hurst Exponent of the time series vector ts"""
# Create the range of lag values
lags = range(2, 100)
# Calculate the array of the variances of the lagged differences
# Here it calculates the variances, but why it uses
# standard deviation and then make a root of it?
tau = [sqrt(std(subtract(ts[lag:], ts[:-lag]))) for lag in lags]
# Use a linear fit to estimate the Hurst Exponent
poly = polyfit(log(lags), log(tau), 1)
# Return the Hurst exponent from the polyfit output
return poly[0]*2.0
# Download the stock prices series from Yahoo
aapl = DataReader("AAPL", "yahoo", datetime(2012,1,1), datetime(2015,9,18))
# Call the function
hurst(aapl['Adj Close'])
Run Code Online (Sandbox Code Playgroud)
从这个用于估计Hurst指数的代码,当我们想要计算滞后差的方差时,为什么我们仍然使用标准偏差并取平方根?我困惑了很长时间,我不知道为什么其他人不会有同样的混淆.我误解了背后的数学吗?谢谢!
我也很困惑.我不明白std的sqrt来自哪里,并花了3天时间试图找出它.最后,我注意到QuantStart将Tom Starke博士归功于使用略有不同的代码.Tom Starke博士将Ernie Chan博士归功于他的博客:http://epchan.blogspot.fr/2016/04/mean-reversion-momentum-and-volatility.html我能够找到足够的信息放在一起我自己的原则代码.这不使用sqrt,使用variance而不是std,并在末尾使用2.0除数而不是2.0乘数.最后,它似乎给出了与你发布的quantstart代码相同的结果,但我能够从第一原理中理解它,我认为这很重要.我把一个更加清晰的Jupyter笔记本放在一起,但我不确定我是否可以在这里发布,所以我会尽力在这里解释一下.首先粘贴代码,然后解释.
lags = range(2,100)
def hurst_ernie_chan(p):
variancetau = []; tau = []
for lag in lags:
# Write the different lags into a vector to compute a set of tau or lags
tau.append(lag)
# Compute the log returns on all days, then compute the variance on the difference in log returns
# call this pp or the price difference
pp = subtract(p[lag:], p[:-lag])
variancetau.append(var(pp))
# we now have a set of tau or lags and a corresponding set of variances.
#print tau
#print variancetau
# plot the log of those variance against the log of tau and get the slope
m = polyfit(log10(tau),log10(variancetau),1)
hurst = m[0] / 2
return hurst
Run Code Online (Sandbox Code Playgroud)
陈博士没有在这个页面上给出任何代码(我相信他的工作在MATLAB而不是Python).因此,我需要将他自己的代码放在他在博客中给出的笔记中,并将答案提供给他在博客上提出的问题.
陈博士指出,如果z是对数价格,那么以τ间隔采样的波动率是波动率(τ)=√(Var(z(t)-z(t-τ))).对我来说另一种描述波动率的方法是标准差,所以std(τ)=√(Var(z(t)-z(t-τ)))
std只是方差的根,所以var(τ)=(Var(z(t)-z(t-τ)))
陈博士然后陈述:一般来说,我们可以写Var(τ)ατ^(2H)其中H是赫斯特指数
因此(Var(z(t)-z(t-τ)))ατ^(2H)
取每边的对数,我们得到log(Var(z(t)-z(t-τ)))α2Hlogτ
[log(Var(z(t)-z(t-τ)))/logτ] /2αH(给出赫斯特指数)我们知道最左边方括号中的项是对数的斜率tau的对数图和一组相应的方差.
如果您运行该功能并比较Quantstart功能的答案,它们应该是相同的.不确定这是否有帮助.
这里要做的只是数学符号的一种变化
我会定义
d = subtract(ts[lag:], ts[:-lag])
Run Code Online (Sandbox Code Playgroud)
那么很明显
np.log(np.std(d)**2) == np.log(np.var(d))
np.log(np.std(d)) == .5*np.log(np.var(d))
Run Code Online (Sandbox Code Playgroud)
那你就等价了
2*np.log(np.sqrt(np.std(d))) == .5*np.log(np.sqrt(np.var(d)))
Run Code Online (Sandbox Code Playgroud)
polyfit比例尺的功能输出与其输入成比例