How to optimize maximum drawdowns of stock returns

This entry is part of 23 in the series Numpy Strategies

Numpy Strategies 0.0.9

Merry Xmas everybody. If you don’t celebrate Xmas, don’t worry, you are not missing that much. Maximum drawdown is defined as the maximum decline from a historical peak. Obviously, this is a measure of risk as well. So some optimization is needed. Also I try to shoot below the open price with a new method.

Predictions for 2011

So this is the heathen tradition of trying to forecast the future. It’s for one year, so it’s 300 times less reliable than the weather forecast. I looked deep into my cup of tea and saw this:

  • The gold bubble will rise for a short while in 2011, but will burst unexpectedly leading to an uncontrollable fall of the gold price.
  • The U.S. will invade a country starting with L. The name of the country that is.
  • A largish meteorite will strike the moon. Nobody would be hurt or injured in any way, but it will lead to outrage and the creation of the Preservation of the Moon Society (PMS).

Resolutions for 2011

So this is the more modern tradition of promising to do things and then forgetting about them after a week.

  • Blog more often.
  • Try to keep stock picks private, except of course if in conflict with number 1 resolution.
  • Improve money management.
  • Learn a new programming language.
  • Tell everybody about this programming language and how amazing it is and that everybody should use it. Then tell them again. Repeat until 2012.
  • What I said in previous bullet points, but substitute “programming language” with technology, tool or whatever.

Numpy 3 closed

The Numpy 3 portfolio was by far the most succesful one. 99% of it created by me and 1% contribution from a grumpy wizard from the Land of Ice. Yes, I could have done the 1 % on my own, but hey that’s how it went. We are talking about 17% overall return. It could have been more with tighter stops etc.

perfNumpy3chartNumpy3

Stops update

It was a good week for the Numpy 4 portfolio. No positions had to be closed.

The Numpy 5 portfolio had some startup issues, but this week was pretty OK.

Maximum drawdown optimization

I attempt to optimize the maximum drawdown CAPM style in relation to the Volume Weighted Average Return, skewness of the returns and liquidity.

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
...
def maxDrawdown(arr):
   top = arr[0]
   maxDD = 0
 
   for i in range(1, len(arr)):
      if arr[i] > top:
         top = arr[i]
 
      drawdown = (top - arr[i]) / arr[i]
 
      if drawdown > maxDD:
         maxDD = drawdown
 
   return maxDD
...
   ev = average(returns, weights=v[:len(returns) ])
   maxDD = maxDrawdown( c )
   evs.append( ev )
 
   maxDDs.append( maxDD )
 
   S = stats.skew( returns  ) 
   skews.append( S )
 
   vol = log( geomean( v ) )
   vols.append( vol )
 
   if returns[-2] > -1 * float(argv[1]):
      continue
 
   t = file.replace('.csv', ''), ev, maxDD, S, vol
   records.append( t )
 
( a,b,residuals ) = fitline( maxDDs, evs )
( aSkew, bSkew, residuals ) = fitline( maxDDs, skews )
( aVol, bVol, residuals ) = fitline( maxDDs, vols )
 
for t in records:
   symbol, evC, maxDD, S, vol = t
 
   if evC > a * maxDD + b:
      if S > 0 and S > aSkew * maxDD + bSkew:
         if vol > aVol * maxDD + bVol:
...

Blind shooting

I try to shoot below the open price with a new method. Starting with the close price of a day, I try extrapolating a low price for the next day. The steps of the extrapolation are:

  1. Calculate relative daily spreads of the close and next day low price.
  2. Estimate the per percentile probability that the projected value will fall within the open – low range.
  3. Use the optimal probability for the actual projection.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
...
   tomorL = roll(l,1)
   r = (c[:-3] - tomorL[1 :-2])/tomorL[1:-2]
 
   N += 1
 
   for i in range(1,100):
      score = stats.scoreatpercentile(r, float(i) )
      p = c[-3]/(1 + score)
 
      if not isnan(score):
         means[i] += score
 
      if p >= l[-2] and p < o[-2]:
         ratios[i] += 1
 
ratios = ratios / N
...
maxr = max(ratios)
indices =  where( ratios >= maxr )
...

Here are some plots based on the data in my historical prices database.

clpercentileStats

Entries for the Numpy 9 portfolio.

A Xmas portfolio

Bah, humbug!

‘Twas the night before Xmas, when all through the house, not a creature was stirring, not even a mouse. Except maybe for old Ibanizar Scruch and he wasn’t in a house, but an abandoned office. He had a sweet deal, that allowed him to live in the building, in return he was supposed to keep squatters out. He did that of course unless people paid him enough to let them stay.

Ibanizar wasn’t poor. In fact he was quite rich. He had a small business which was a cross between a bank and a hedge fund. A very small one. He jokingly told people that it was a reverse risk neutral Ponzi scheme.

Scruch was a very thrifty fellow. He liked simple living. Ibanizar found the whole idea of spending money on goods and services, that were unnecessary really strange. It seemed to him like the whole world had gone mad. Spending beyond one’s means had become the norm. People would only save their money if the interest on a savings account was ridiculously high such as was the case for certain Interweb banks from the Land of Iceland.

The Interweb, that was yet another thing that Scruch despised. Actually he hated technology and in particular information technology. Ibanizar felt that technology only enforced the trend of pursuing the latest and greatest. All the technologists did was repackage old ideas, increase the version of their product and then sell at an ever increasing price. This led to absurdities like companies being worth billions without ever producing anything.

Scruch was fast asleep in an improvised bedlike structure. He made it himself from second hand materials that he purchased from a nearby thrift store. A loud popping noise awoke Ibanizar. He saw a humanlike figure in a white robe standing over him. The creature appeared to be made out of some kind of metal. A blazing light was coming from its head.

“Who are you?” asked Scruch.

“I am the Ghost of Xmas Past,” answered the android.

“I don’t believe in ghosts,” said Ibanizar.

“Do you believe in aliens?”

“Not really. However I don’t believe that they don’t exist either.”

“I am an alien life form. My civillization has evolved in the course of billions of your Earth years, so that we don’t need bodies anymore. So we are like ghosts. What you see before you, is just an illusion.”

The Ghost of Xmas Past took Scruch back in time. The alien showed the old man how people used to be more frugal and happy in the past. Ibanizar and his childhood friends had almost no toys or possesions. Most of them did not have any allowance. They had lots of fun though, playing and exploring outside. Sometimes their mothers had to drag them back inside. The Ghost transported Ibanizar to the scene of the last Xmas dinner he had with his fiancee Mary. They never ended their relationship, but it just fell apart. She wanted to dance every night, go out, buy a big house, travel all over the world. All those things never interested Scruch. They retained a sort of business relation, that is, he lend her money whenever one of her many business schemes failed.

The Ghost proceeded to show Scruch the four weddings of his former fiancee with increasingly older and richer men. Mary had many kids, lived in many beautiful homes and travelled around the world. She seemed outwardly happy, but was in reality constantly worried and nervous. She constantly worried about money and about the people in her life. Mary smoked a pack of cigarettes a day and her skin had become hard and wrinkled. Scruch led a mindboggingly dull life, but at least he looked like he was still about 30 years old. His emotional barometer pointed to “content”, from the moment he woke up in the morning till he went back to bed. Nothing could disturb his peace.

The light on the head of the Ghost of Xmas Past slowly died and Scruch found himself back in his bedroom. Before leaving the Ghost told Ibanizar that he will be visited by two more ghosts. The next ghost took the shape of a giant. He was called the Ghost of Xmas Present.

The giant gave Scruch a tour round the city, showing him all the have and have nots united in their desire to spend, spend, spend. They see a vision of an elderly couple, who borrowed a lot of money during their life. The Andersons spent a large portion of that capital already and the rest was invested in stocks of a large bank. Unfortunately, the bank declared bankruptcy, resulting in an enormous debt. The Ghost of Xmas Present and Scruch also met a guy who slept on a park bench. Ed used to have a good job, but because of his love of alcohol and gambling, he was forced to borrow a lot. At a certain point he had more than a dozen of credit cards. Eventually Ed lost it all and had to sleep on the streets.

The Ghost finally introduces Ibanizar to the Interweb and a blog article about investing. The miser finds the article so interesting that he makes the following virtual Numpy 9 portfolio.


numpy9

On the stroke of midnight the spirit disappeared and left Scruch to face the Ghost of Xmas Yet to Come. The last Ghost was completely covered by a black robe and appeared to hover. He didn’t speak but only pointed with his bony hand. The Ghost takes him to a stockholder meeting in a futuristic setting. Ibanizar had never seen the kind of clothes people are wearing. Nor was he familiar with the tech that surrounded him. Apparently Scruch’s company went public after adopting some new trading idea and business was good. So good in fact that Ibanizar has 300 banks as customer. Although that’s not much of an achievement since many banks are nationalised, reduced in size or both. Next, Scruch is shown his private island, mansion, jet and yacht. He also has a small submarine, but that is more for showing off, for he hates submarines.

Scruch wakes up very happy and spends the rest of Xmas and the beginning of the next year preparing to execute his new investment plan.

THE END

Random links of general interest

If you liked this post and are interested in NumPy check out NumPy Beginner’s Guide by yours truly.

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.