# How to approximate the time to mean reversion for implied volatility in python

Its the same question as previous, except I am looking for code in python verses R. How to approximate the time to mean reversion for implied volatility

Given an option and its implied volatility, and also the mean value of the implied volatility over the last 30 days, if we find that the current IV is significantly (> 1 std dev.) away from the mean, then:

How to approximate the time for the IV to mean revert in vectorized python?

## 3 Answers

This is a python duplication with some modeled data

import pandas as pd
import numpy as np
from statsmodels.formula import api

n = 1000
x = pd.date_range('2010-12-31', periods=n)
y = np.random.randn(n)
s = pd.Series(y, x)
s = np.clip(abs(s.rolling(5).mean()) + .19, 0, 1.2) * 100

df = pd.concat([s.diff(), s.shift()], axis=1, keys=['diff', 'level']).dropna()

Y = df.iloc[:, [0]].values
X = df.iloc[:, [1]].values
X = np.concatenate([np.ones_like(X), X], axis=1)

beta = np.linalg.pinv(X.T.dot(X)).dot(X.T).dot(Y)
print(beta)

[[ 21.79316927]
[ -0.41239735]]


calculations

long_run_mean = -beta[0, 0] / beta[1, 0]
mean_reversion_speed = -beta[1, 0] * 100
halflife = -np.log(2) / beta[1, 0]

print(long_run_mean)
print(mean_reversion_speed)
print(halflife)

53.359813861
46.3557243425
1.49527850204


Use statsmodels

results = api.ols('diff ~ level', df).fit()
results.params

Intercept    24.735328
level        -0.463557
dtype: float64


Can't take credit for this but Stuart Reid over at Turing Finance (great resource) has a great post and notebook on this. Might give you a good starting point.

This post gives an overview of two methods to calibrate an OU process (least squares and max likelihood) and gives some code in Matlab. https://www.sitmo.com/?p=134