Hi,
I am trying to code the a strategy that involves trading at market close based on the realised volatility of the security over the past X days (say 20).
Security_Exposure(t) = 20% / Realised_Volatility(t-1)
The intention is to have a strategy that tracks the security but targets a realised volatility of 20%.
I saw the code below for a daily interval algorithm but I do not know how to use that when I need to trade at market close.
Thanks,
Brian
vol = compute_volatility(price_history)
# Get historical price data
@batch_transform(refresh_period=1, window_length=20)
def get_past_prices(data):
prices = data['price']
return prices
# Compute historical volatility
def compute_volatility(price_history):
# Compute daily returns
daily_returns = price_history.pct_change().dropna().values.T
# Compute daily volatility
historical_vol_daily = std(daily_returns)
# Convert daily volatility to annual volatility, assuming 252 trading days
historical_vol_annually = historical_vol_daily*sqrt(252)
# Return estimate of annual volatility
return 100*historical_vol_annually