Big drops in stock price explained

This entry is part of 23 in the series Numpy Strategies

Numpy Strategies 0.0.3

It’s all about gravity. The same thing that happens, when Wilie E. Coyote runs too far off a cliff. On the menu for today is:

  • Try out a new screener and portfolio.
  • Gravity calculations.
  • Profit!

Big drops screener

The screener selects statistically big drops of the low price. These are then used to fit a trend line. The line becomes a bottom band and the top band is calculated by adding two standard deviations of the close.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
...
def select_indices( arr ):
   samesign = []
 
   for i in range( 0, len( arr ) ):
      if arr[i] < 0:
         samesign.append( arr[i] )
 
   sigma = std( samesign )
   mu = mean( samesign )
 
   selected = []
   factor = 2
 
   for i in range( 0, len( arr ) ):
      if arr[i] < 0 and arr[i] < mu - factor * sigma:
         selected.append( i )
 
   return selected
 
def within_bands_ratio(a,b,sigma,arr):
   count = 0
 
   for i in range(0, len(arr)):
      if(arr[i] > ( a * i + b ) and arr[i] < ( a * i + b + 2 * sigma) ):
         count += 1
 
   return float(count)/len(arr)
 
for file in files:
   if(not file.endswith('.csv') ):
      print file + 'skipped'
      continue
 
   l,c = loadtxt(fileDir + '/' +  file, delimiter=',', usecols=(5,6), unpack=True, converters={5: float_converter}) 
 
...
 
   beforeLastLow = len(l) - 2
 
   relchangeLow = diff(l[:beforeLastLow])/l[: beforeLastLow - 1]
 
   negative = select_indices( relchangeLow)
 
   bottoms = take(l[0:beforeLastLow], negative )
   A = vstack([ negative, ones( len( negative ) )]).T
   (p,residuals,rank,s) = linalg.lstsq(A, bottoms)
 
   if len( residuals ) == 0:
      continue
 
   aNeg,bNeg=p
 
   t = arange(0, len(l), 1)
   bottomBand = aNeg * t + bNeg
 
   beforeLastClose = len(c) - 2
   beforeLastVal = c[beforeLastClose]
   sigmaClose = std( c[ : beforeLastClose ] )
 
   if beforeLastVal <= ( aNeg * beforeLastClose + bNeg - float( argv[ 1 ] ) * sigmaClose ):
      wbr = within_bands_ratio( aNeg, bNeg, sigmaClose, c[ : beforeLastClose ] )
 
      if wbr < float ( argv[ 2 ] ):
         continue
...

Heavy, man!

As the famous philosopher Aristotle taught us, heavy objects fall faster. Isaac Newton, one of the best alchemists of all time (he was also head of treasury for a few years), wrote the book Principia Mathematica, that contains some very useful laws concerning gravity, mass and forces. In fact, he found an equation that pops up in different form in other places, for instance electrostatics. I am referring to the inverse square law. I attempt to investigate, whether Newton’s laws apply to financial mechanics as well. The code below gives an estimation for the gravitational constant G times the mass.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
...
def createDf( symbol ):
   dates,close = loadtxt(fileDir + '/' +  symbol + '.csv', delimiter=',', usecols=(1,6), unpack=True, converters={1: datestr2num}) 
 
   data = {
        symbol : close
   }
 
   dates = Index([datetime.fromordinal(int(d)) for d in dates])
   df = DataFrame(data, index=dates)
 
   return df
 
 
symbols = ['GXDX', 'MEMS', 'TESO', 'ULCM', 'WVFC', 'BNCL', 'BXS',  'CPLA',  'PMC',  'SHBI',  'VALU', 'RBNF', 'VPFG', 'WEST']
 
for argv1 in symbols:
   argvDf = createDf( argv1 )
   Gms = []
 
   for symbol in symbols:
      if symbol == argv1:
         continue
 
      df = createDf( symbol )
      joined = argvDf.join( df, how='inner' )
      prices = joined[ symbol ].values()
      argvPrices = joined[ argv1 ].values()
      r = prices[ : len( prices ) - 2 ] - argvPrices[ : len( argvPrices ) - 2 ]
      Gm = diff( prices, n = 2 ) * r * r
      Gms.append( mean( Gm ) )
...

I also plugged in the formulas we learned in high school about potential energy and kinetic energy in order to calculate g.

1
2
3
4
...
   v = diff(c)
   g = ( v * v ) / ( 2 * c[ : last ] )
...

I used the stocks from the Numpy 1 portfolio, Numpy 2 portfolio and Numpy 3 portfolio that I made today. The results can be found in this spreadsheet.

A Ferengi Portfolio (excerpt from the bestseller “Rules of Acquisition A modern Interpretation”)

Once you have their money … never give it back.

Many, many years into the future, in a far galaxy, in a parallel universe an alien civilization, called the Ferengi, dominated the inter Galactic markets. One young Ferengi by the name of Quark decided to invest some of the latinum, that he earned in the gambling house he owned, in a portfolio of Galactic stocks. He always followed the third rule of acquisition:

Never pay more for an acquisition than you have to.

So he decided to use a mean reverting strategy. This strategy looked for a breakout from the bottom band, defined by a fit through the statistical candidates for resistance points of the “low” prices. The Ferengi’s were pretty good statisticians, because of their gambling houses. Quark made sure that his stocks were not too strongly correlated. After all, the sixth rule of acquisition says:

A man is only worth the sum of his possessions.

Quark bought his stocks on a Friday at the open and after the first day, his portfolio was a bit down.

numpyStrategies003Portolio

Quark didn’t mind, because he knew that his portfolio would bounce back. He remembered the 62nd rule of acquisition:

The riskier the road, the greater the profit.

His exit strategy was to sell by Christmas. Not that the Ferengi’s celebrated Christmas, but that did not stop them from profitting from people who did.

Know your enemies … but do business with them always.

THE END

GPU Links of Interest

Random Links of Interest

Series NavigationSecret Transitions of a Markov Chain
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 programming and tagged , . Bookmark the permalink.