Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- # Obtaining the number of observations
- n_obs=len(btc_data)
- loops=range(n_obs)
- results={}
- # Looking at the period over which we want to calculate out the
- # volatility. 48*14 = 672
- n_period=672
- test_vol=[]
- error_capture=[]
- dates = []
- for x in loops:
- # Obtaining the subset over which we will train our
- # GARCH model.
- train=btc_data[x+n_period:(n_period*2)+x]
- # Generating the model. GARCH models don't work well
- # with small values close to 0. So the returns will be
- # multiplied by 1000 to change that. This will be accounted
- # for later.
- am_train = arch_model(train[['pct_change']]*1000,p=1,o=1,q=1,vol='GARCH')
- try:
- # Attempting to fit the model.
- res_train = am_train.fit(0,disp='off',show_warning=0)
- # Sometimes convergence errors occur. When this happens we flag
- # the observation where the error occured to be cleaned later.
- if res_train.convergence_flag != 0:
- error_capture.append(x)
- except:
- error_capture.append(x)
- # Estimating the value of the volatility for the point
- # at the end of the 14 day time period.
- yhat = res_train.forecast(horizon=1)
- # Annualizing the measure, and dividing by 1000 to account
- # for the previous scaling up.
- test_vol.append((yhat.variance.values[-1, :]**0.5)*((48*365)**0.5)/1000)
- dates.append(btc_data.iloc[x]['timestamp'])
- results['vol14']=test_vol
- results['error14']=error_capture
- results['dates']=dates
- def error_clean(volatility,error_points):
- cleaned_vol=volatility
- error=set(error_points)
- for x in error_points:
- if ((x+1) in error and (x-1) in error) == False:
- if (x-1) < 0:
- cleaned_vol[x]=volatility[x+1]
- elif (x+1) >=len(volatility):
- cleaned_vol[x]=volatility[x-1]
- else:
- cleaned_vol[x]=(volatility[x+1]+volatility[x-1])/2
- elif ((x+1) in error and (x+2) in error) == True:
- cleaned_vol[x]=volatility[x-1]
- return cleaned_vol
- cleaner='vol14'
- error='error14'
- results[cleaner]=error_clean(results[cleaner],results[error])
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement