Advertisement
Guest User

Untitled

a guest
Jun 25th, 2019
74
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.11 KB | None | 0 0
  1. # Obtaining the number of observations
  2. n_obs=len(btc_data)
  3. loops=range(n_obs)
  4. results={}
  5.  
  6. # Looking at the period over which we want to calculate out the
  7. # volatility. 48*14 = 672
  8. n_period=672
  9. test_vol=[]
  10. error_capture=[]
  11. dates = []
  12.  
  13. for x in loops:
  14. # Obtaining the subset over which we will train our
  15. # GARCH model.
  16. train=btc_data[x+n_period:(n_period*2)+x]
  17.  
  18. # Generating the model. GARCH models don't work well
  19. # with small values close to 0. So the returns will be
  20. # multiplied by 1000 to change that. This will be accounted
  21. # for later.
  22. am_train = arch_model(train[['pct_change']]*1000,p=1,o=1,q=1,vol='GARCH')
  23.  
  24. try:
  25. # Attempting to fit the model.
  26. res_train = am_train.fit(0,disp='off',show_warning=0)
  27.  
  28. # Sometimes convergence errors occur. When this happens we flag
  29. # the observation where the error occured to be cleaned later.
  30. if res_train.convergence_flag != 0:
  31. error_capture.append(x)
  32. except:
  33. error_capture.append(x)
  34.  
  35. # Estimating the value of the volatility for the point
  36. # at the end of the 14 day time period.
  37. yhat = res_train.forecast(horizon=1)
  38.  
  39. # Annualizing the measure, and dividing by 1000 to account
  40. # for the previous scaling up.
  41. test_vol.append((yhat.variance.values[-1, :]**0.5)*((48*365)**0.5)/1000)
  42. dates.append(btc_data.iloc[x]['timestamp'])
  43.  
  44. results['vol14']=test_vol
  45. results['error14']=error_capture
  46. results['dates']=dates
  47.  
  48. def error_clean(volatility,error_points):
  49. cleaned_vol=volatility
  50. error=set(error_points)
  51. for x in error_points:
  52. if ((x+1) in error and (x-1) in error) == False:
  53. if (x-1) < 0:
  54. cleaned_vol[x]=volatility[x+1]
  55. elif (x+1) >=len(volatility):
  56. cleaned_vol[x]=volatility[x-1]
  57. else:
  58. cleaned_vol[x]=(volatility[x+1]+volatility[x-1])/2
  59. elif ((x+1) in error and (x+2) in error) == True:
  60. cleaned_vol[x]=volatility[x-1]
  61. return cleaned_vol
  62.  
  63. cleaner='vol14'
  64. error='error14'
  65. results[cleaner]=error_clean(results[cleaner],results[error])
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement