Estimating with mean and standard deviation

This entry is part 17 of 23 in the series Numpy Strategies

Gravity waves. Aren’t they something! Today another distasteful finance post in which I try finding support and resistance. Actually I will just focus on resistance, since the procedure for support is similar. A new day, a new idea. This time the idea is that we can forecast a variable, by forecasting its mean, standard deviation and a correction factor. The mean and standard deviation will be calculated with a sliding exponential weights window. To determine the size of the window I will use the max lag given by a formula I found in the documentation of statsmodels ad_fuller. I don’t know where this formula comes from, but it looks reasonable. I hope that someone like Morgan Freeman can explain it (in a televisual way). Everything becomes clear when Morgan Freeman explains it. The following is quick and dirty code. Use with care I haven’t tested it properly yet. Since we are looking for resistance, I cheated by demanding a positive value for the correcting factor. For support I would require a negative value of course. Also there is some code to check after the fact how often the resistance holds for the prediction and if we cheat even more by adding a little bit to the resistance. I am not bothering with cross-validation here in the hope that statsmodels does something smart.

def std_error(p):
   return np.sqrt(p - p**2)
 
def predict(a, lag):
   ar = AR(a)
   params = ar.fit(maxlag=lag).params
 
   return ar.predict(params)
 
def print_stats(h, limit):
   hits = len(h[h <= limit])
   n = len(h)
 
   ratio = hits*1.0/n   
   print "Hits", hits, "Hit ratio", round(ratio, 2), "Std error", round(std_error(ratio),2)
 
   lag = int(12 * (len(h)/100)**.25)
   ema = ewma(h, span=lag)
   pred_ema = predict(ema, lag)
 
   devs = ewmstd(h, span=lag)
   pred_devs = predict(devs, lag)
 
   fctr = (h - ema)/devs
   pred_fctr = predict(fctr, lag)
   pred_h = pred_ema[-1] + np.abs(pred_fctr[-1]) * pred_devs[-1]
   print pred_h
 
   fit = pred_ema + np.abs(pred_fctr) * pred_devs
   y = h[lag:]
 
   print_stats(h[lag:], fit)
   means = []
   rest = np.abs(fit - y)
 
   for i in xrange(len(rest)):
      slise = rest[:i]
      means.append(slise.mean() + slise.std())
 
   print_stats(y, fit + means)
Series Navigation
By the author of NumPy Beginner's Guide, NumPy Cookbook and Instant Pygame. If you enjoyed this post, please consider leaving a comment or subscribing to the RSS feed to have future articles delivered to your feed reader.
Share
This entry was posted in Uncategorized. Bookmark the permalink.