How to calculate skewness and kurtosis from stock price return and/or from stock price time series?
How to calculate skewness and kurtosis from stock price return and/or from stock price time series?
def estimateAnnualVolatility(close_prices, open_prices=None, high_prices=None, low_prices=None, N=10, algo='YangZhang'):
"""
Volatility estimation
Possible algorithms: ['YangZhang', 'CC', 'Parkinson','Kurtosis','Skew']
"""
cc = np.log(close_prices/close_prices.shift(1))
if algo == 'YangZhang': # Yang-zhang volatility
ho = np.log(high_prices/open_prices)
lo = np.log(low_prices/open_prices)
co = np.log(close_prices/open_prices)
oc = np.log(open_prices/close_prices.shift(1))
oc_sq = oc**2
cc_sq = cc**2
rs = ho*(ho-co)+lo*(lo-co)
close_vol = pd.rolling_sum(cc_sq, window=N) * (1.0 / (N - 1.0))
open_vol = pd.rolling_sum(oc_sq, window=N) * (1.0 / (N - 1.0))
window_rs = pd.rolling_sum(rs, window=N) * (1.0 / (N - 1.0))
result = (open_vol + 0.164333 * close_vol + 0.835667 * window_rs).apply(np.sqrt) * np.sqrt(252)
elif algo == 'CC': # standard close-close estimator
result = np.sqrt(252)*np.sqrt(((pd.rolling_sum(cc**2,N))/N))
elif algo == 'Parkinson':
result = np.sqrt(252)*(1 / (4 * math.log(2))) * ((high_prices.tail(N) / low_prices.tail(N)).apply(np.log))**2
elif algo == 'Skew':
result = pd.rolling_skew(cc, window=N)
elif algo == 'Kurtosis':
result = pd.rolling_kurt(cc, window=N)-3.0
else:
raise ValueError('Unknown algo type.')
result[:N-1] = np.nan
return result