Thursday, December 11, 2014

Will We Ever Kill The Bug?


There is something very attractive about vintage items that just won't die.

They just keep coming back. Same philosophy but better up-to-date technology.

It's not just cars. It's investment strategies, too.

Vintage strategies are often simple, easy to execute and provide amble 'out-of-sample' data. In other words one can see how they performed in real life years after they have been proposed. And like the VW bug, they are "safe" choices. Tried and true.

Can you imagine a 1965 VW running in the Autobahn? 
Although the essence counts for a lot, for the car to survive at today's highway speeds the tech needs to be up to date.

So let's take my favorite oldie and bring it up to speed: Harry Browne's Permanent Portfolio investment strategy.

From Investopedia:

… Browne believed that each of the aforementioned four asset classes would thrive in one of the four possible macroeconomic scenarios that exist.
  • Stocks would thrive during periods of economic prosperity.
  • Bonds would do well in deflation and acceptably well during periods of prosperity.
  • Gold during periods of high inflation would rapidly increase in value as the only true defence against a deteriorating currency.
  • Cash would act as a buffer against losses during a routine recession or tight-money episode, and would act well in deflationary times.
So let's see how it has performed.

The original rules:
25% in a stock market Index (SP500)
25% in Treasuries.
25% in Gold.
25% in Cash or similar.

Not bad. Annual return is 7.1% and maximum draw-down comes in at 17.84% since 1992.

For a far more detailed analysis of the so called "PP" you can see Gestaltu's excellent "PP Shakedown" series as well as Scott's Investments analysis. There are many other articles and analysis that serve as inspiration to this article.

Building a new strategy.

So let's update this strategy by using some recent tactics. All further rules assume monthly rebalance.

1. Volatility Targeting per Asset
If an asset exhibits historical volatility above a threshold, we cut it down in size as to reduce risk to the overall portfolio.


This decreases annual returns but also limits drawdown to under 9%. Overall, risk adjusted returns benefit. CarMDD is at 0.8.

2. Momentum
There's been a fair amount of talk about momentum. Let's try it. We will not limit our assets to just the few best. We are only trading four assets. Instead we will identify the worst performer. We will decrease funds invested in that asset and distribute those funds to the rest. So if gold underperforms all other assets, we will sell some gold, divide the proceeds in three and buy equal amounts of the SP550 index, Treasuries and Cash.

Let's try by pulling 15% of equity from the worst asset.


This seems to help. Annual return is up to 8.3% while draw-down comes in at a low and very respectable 7%.

3. Mean Reversion
What about mean reversion. Can we maybe try to sell shares of the best short-term performer and distribute the money to the others?


This marginally improves risk adjusted returns by further limiting draw-down to 6.78% while keeping annual returns almost the same. 

4. Timing
Let's use the good old simple average rule. If an asset's price is below its own 200-day simple moving average then we sell it. If it crosses up then we buy it. Trade only on the beginning of the month.


And to get things more interesting, let's use leverage up to 2x. That the portfolio can be invested from 0% all the way to 200%.

So now we are up to almost 12% annual returns with a drawdown of less than 13%.

What about over-fitting parameters. Let's run a permutation of all parameters (10,401). We will assume no leverage (1x).

The mean for the CarMaxDD is 0.772381 with a standard deviation of 0.216059.

Modifying the Asset base and using ETFs.

Finally let's include some 'newer' asset classes that were not easily accessible during the 80's.
  • Convertible bonds (CWB)
  • Foreign bonds (PCY)
  • Inflation protected Treasuries (TIP)
First of all, you may notice that all three assets are less volatile assets, at least compared to the equity/commodities class.

Convertible Bonds lie somewhere between Bonds and Equities. They do carry a lower interest rate risk than straight bonds but also carry some equity-like risk. Foreign Bonds is a diversifier out of U.S. debt. Inflation protection Treasuries also carry some inflation (albeit, limited) protection from interest rate hikes.

So let's go ahead and backtest using these 7 ETFs. We will use all layers mentioned before, as well as 2x leverage.


Since there is a good chance of over-optimizing parameters we will go through a number of parameters to get a sense of robustness:

First, let's look at Annual Return and Drawdowns. Each dot is one combination of parameters. What we are interested in is the range of results.

Maximum drawdown is less than 12% while compound annual return comes in above 8%. Keep in mind that this system is designed for moderate growth with low volatility and risk. It is not meant to provide astonishing returns.

One more graph: Sortino Ratio and correlation to the S&P 500 index. Again we are looking for ballpark ranges.

Let me remind the reader that the Sortino Ratio is a risk adjusted metric similar to the sharpe ratio but only takes into account downside volatility. The correlation to the S&P 500 is important to many investors that already have active investments in equity. If the strategy is too correlated to the S&P 500 then it often does not fit into larger portfolios and could be replaced by the index.


The Sortino ration comes in above 1 while correlation to the S&P 500 index comes in between 0.005 and 0.25.


This strategy trades monthly. For the backtests the assumption is that one buys at the opening price of the second day of the month.

There'a plenty of ETFs to choose from. As a stock index proxy one can choose from a wide selection that includes SPY, IVV, VOO as well as VTI, SCHB. For treasuries one can use TLT. Gold can be traded through GLD or IAU. Finally, one of many options for cash is using SHY.


It's always interesting to look to the past for ideas on strategy development. In building a core, capital preservation strategy one can go back to such strategies as Harry Browne's Permanent and Bridgwater's All-Weather Portfolio. The main feature of these portfolios is a price-agnostic view of the markets and basic protection by using simple asset and weight selection.

In addition, in their most basic form, they have proven themselves in true, decade long, out-of-sample testing.

So once the essence of the strategies are incorporated, there is no reason not to include more recent rebalancing practices that have been introduced by academia as well as quantitative research: Momentum, mean reversion, volatility targeting and the more controversial timing rules.

Four Asset Base case System:

The base case system uses only the 4 core assets and variable leverage.
The system has a compound annual return of 12% with a 13% drawdown since 1992.
Most importantly it has behaved well in recent market corrections.

Moving Forward – Expanded Assets

On top of these 'layers' we introduce three more assets that provide a slightly larger opportunity for diversification and a slight bias towards increasing rates. The corresponding ETFs are CWB, TIP and PCY.

Since 2007 the expanded strategy gave an annual return of 12% with a maximum drawdown of 6.74%. An impressive number, especially the drawdown, for a conservative investor.

Too optimistic? Running through a parameter's test we still come up with Sortino ratios between 1 and 1.8 and drawdowns below 12%.


But is there a bias in the look-back of the Timing rule? Is the 200-day simple moving average chosen "after-the-fact"?

Well, because of the multiple 'layering', results seem robust in terms of picking look-back period. In other words, momentum and timing are, in some ways, similar in their effect. If an asset underperforms, it will go underweight using the momentum rule until it crosses its own average and then will be sold. So shifting through parameters in timing or momentum will have less effect than if they stood as single rules.

As for selection bias, keep in mind that the main 4 assets have been tested 'out-of-sample for some 20 years. The additional three assets, TIPS, Convertible Bonds and Foreign bonds are lower volatility assets that could provide an additional edge in the current environment and should not add excessive risk to the strategy.

Backtesting Bias

Backtesting a strategy does not mean that backtested returns guarantee future returns.
It does mean that one has thought about the strategy and detailed it enough as to create rules that keep an investor disciplined and protect him from his own emotions and the daily market noise.

PP B&H7%18%0.581992
Bug 412%13%0.711992
Bug 712%6.7%1.412007

Check out our free offer for this strategy.







Thursday, December 4, 2014

SanzP joins Logical-Invest

I joined the team at Logical-Invest.

Together with Frank, Alex and Scott (our info) we hope to create a place where we can develop strategies and actually offer them to the public for a low subscription.

This is something new. At least I think so.

If you have followed my blog you may have guessed that I support empowering the private investor to take investing into their own hands and use tools as good or better than the 'big guys' use. But I also understand that not everyone can become a full-time trader, learn programming or research the market for hours on end. Luckily there are quite a few management firms that are intelligent, publish their research, have good track records and are fairly priced.

We are taking a different route. We are providing strategies that someone can follow for a low fee.
What's new about that? Services like that have been around for quite some time.

This is what we are doing different:

1. We explain how the strategy works.

 In detail! Is there a danger that someone can replicate it and use it?
Sure, more power to them. We believe most people would rather pay a small fee and have us track, monitor and notify them when changes are due than having to create their own back-end from scratch. As Scott says, someone can go online and learn how to rewire his whole house. It doesn't mean they 'll want to do it themselves. Maybe they just want understand how it's done and then to pay someone to do it.

2. We put a face behind the strategy

A lot of strategies are 'face-less'. We are not sure who runs them. Is it a mature investor thinking about retirement? An aggressive young guru in his teens?
We have faces. We have e-mails. You know who we are and you can talk to us. We even have a forum!

3. Mix & Match

We are developing a portfolio tool where you can combine strategies and see how the resulting portfolio would perform.

4. We are experimenting. 

We don't know everything right from the start. We are already running some strategies but we all have our own opinions and preferences. And there are many paths to take.

So please visit us and let us know what you think. All suggestions are welcome.

Monday, July 21, 2014

Little "SanzP"


I have been absent from blogging for some time.
I have been giving most of my time to our little man. 
He 's now 10 months old and just had his first swim! 
So maybe Dad can go back to crunching those numbers...

Thursday, September 19, 2013

From Regime Switching to Fuzzy Logic -SP500


In the previous post I showed how one can implement "regime" switching to create a strategy that switches between a mean-reverting and a momentum sub-strategy.

Can we do something similar (or better) using Fuzzy Logic?

  Here's the setup: (here for some Fuzzy Logic backround)

We create a basic membership function for the RSI(2) indicator: "Low", Medium" and "High"
We create a basic membership functions for the Correlation* indicator: "Low","High".

We implement these rules:
1.//mean revert - LOW Autoccorelation
IF "rsi" is  "Low" AND "autocorrel" is "Low", "Action", 1 ; //Buy
IF "rsi" is "High" AND  "autocorrel" is "Low", "Action", -1 ; //Sell

//MOM - HIGH Autocorrelation
IF "rsi" is "Low" AND "autocorrel" is "High", "Action", -1 ; //Sell
IF "rsi" is "High" AND "autocorrel" is "High", "Action", 1 ;  //Buy

Here's the Equity:

As with Regime switching we can use Fuzzy Logic to solve the problem of using one strategy for trading pre- and post-2000 SP500. Furthermore, we have more robust and less specific rules to deal with (buy on "Low" RSI rather than Buy=RSI2<30).

*By "Correlation Indicator" I am referring to the  22-day Correlation (see previous post) between the current return and the previous day's return. In Amibroker Code: 

Thursday, September 12, 2013

Simple Regime Switching for SP500

image from
Let us consider two possible ways to trade the SP500.

1. If the index falls today, we buy tomorrow at the open. This is a "mean-reversion" strategy.
2. If the index rises today, we buy tomorrow at the open. A "follow-through" strategy.

From the graphs below, we can see that neither of these strategies worked well from 1960 to today.

Mean Reversion Trading On SP500

Follow-Thru (momentum) trading on SP500

Let's introduce a qualifier that will tell us which strategy to trade at what time.

We will try the most basic one: The correlation between today's return (close to yesterday's close) to the previous day's return. If it is negative we 'll use a contrarian logic. If the correlation is positive we 'll use a momentum logic.

The indicator of choice is the 2-period Relative Strength Index (RSI).

So if correlation between yesterday's and today's return is less than zero we buy on a correction. Otherwise we buy on strength. We trade at the next Open.

Here's the Amibroker Code:


Sunday, March 31, 2013

Strategies on The Cloud: TAA on Google Docs

Did you want to have a strategy on the cloud that monitors the market and updates you on new Buy/Sell signals (as well as number of shares, etc)  by email. Did you want to run it on best of breed "always ON" servers with free and accurate data?
How much would that set you back?

Well, Nada! Courtesy of Google.

This post will guide you through coding a simple Tactical Asset Allocation on Google's Docs.
You need:
1. A Google account.
2. Google Docs.

The system is similar to Faber's TAA model using 5 Etfs.: SPY,TLT,VNQ,EEM,DBC
We buy or sell at the beginning of the month ONLY.
If Close > 200-moving Average then we buy the ETF.
If Close < 200-moving Average then we sell the ETF.

Pseudo Code:
If TodayIsNewMonth AND CloseETF>MA(200) Then Buy
If TodayIsNewMonth AND CloseETF<MA(200) Then Sell

Let's get started. Go to Google Docs and create a new SpreadSheet. Call it TAA_5.
Once the spreadsheet is open in your browser, go up to the menu and select Tools-->Script Editor...
This should open a new script Editor. Select "SpreadSheet" as your project.

Lets start coding.
 Google Docs scripting uses a version of JavaScript which seems fairly easy for non programmers.

It would be nice to create an object that holds all the ETF information.
So here's the function to store each ETF's info:

function tickerobj(symbol,close,action,posscore,sma)

How do we retrieve data from Google?

function myGetHistoricalStockInfo(symbol,days)

 var start=new Date();
 var finish=new Date();

  var data = FinanceApp.getHistoricalStockInfo(symbol, start, finish, 1 );

    return data;

We need to calculate the Simple Moving Average from the Data to check if close>sma(200).

function SMA(data,period)
 //data is a FinanceApp.getHistoricalStockInfo object array
  var end=data.stockInfo.length-1;

  var close=[];
  var sum=0;var count=0;
  for (var i=end;i>end-period;i--)
  sum += data.stockInfo[i].close;
  return (sum/period);

How do we know it's the beginning of the month?

function NewMonth()
var now= new Date();
var  yesterday= new Date();

    return (1);
    return (0);
So let's start calculating and storing info for each ETF. Tickerlist would be "SPY,EEM,...etc".

function CreateInstr(tickerlist,SMAperiod)
  var symbolarray=[];
//split tickerlist by comma (",")
   symbolarray= tickerlist.split(",");
//how many symbols in the list
  var idx=symbolarray.length;
  var close=[];var smat=[];var posscore=[];var action=[];//var symbol=[];
  var Instrument=[]; var idx1; var data=[];
//Go through each symbol. I.e. SPY...then EEM...
   for (var i=0;i<idx;i++) 
//get hist data
//get index of the last data point
//get the last closing price
//get the moving average
     smat[i] = SMA(data, SMAperiod);
//not used in this example
//action - If close>mov. average, 1(buy) otherwise -1(sell)
     action[i]=(close[i]>smat[i])?1:-1 ; 
//Now store all the infor in the object
      Instrument[i]=new tickerobj(symbolarray[i],close[i],action[i],posscore[i],smat[i]);

So let's show all this info on the Spreadsheet.

function ShowTAAOnSpreadsheet()
  var sheet = SpreadsheetApp.getActiveSheet();
  var date=new Date();
  //You may use your own ticker list and period
   var Instrument=CreateInstr("TLT,SPY,EEM,VNQ,DBC",200);

//Set the Name headers for each column

  var idx=Instrument.length;

     for (var i=0;i<idx;i++)

  sheet.getRange(1,1).setValue("Last Update");


Now you can go on the top Menu and select a function to run. Select "ShowTAAOnSpreadsheet".
Press the "paly" button to run.

Go to the spreadsheet, see if it updated.

Last is a function to email ourselves the results. We should schedule this to run everyday (Menu-->Resources-->Current project's Triggers).
Please do not abuse Google's Servers by having it run too often. They are kind enough to provide this kind of functionality free of charge.

function EmailPositions()
 //if not new month do not calculate or email anything, just exit with 0. 
  if (NewMonth()==0)
    return (0);
    var email = Session.getActiveUser().getEmail();  
   var Instrument=CreateInstr("TLT,SPY,EEM,VNQ,DBC",200);
   var idx=Instrument.length;
  var txt="";
     for (var i=0;i<idx;i++) 
     txt=txt+Instrument[i].symbol+","+"  Action:  "+Instrument[i].action+"\n";
   MailApp.sendEmail(email, "TAA_5_FromGoogleDocs", txt);


You can easily customize the code to your needs. For example it should be fairly easy to calculate risk parity allocations weights and have them emailed to you.

Again, please do not abuse Google's servers. Let's keep this functionality free.

Here's the full code.

Sunday, March 17, 2013

Cyprus - Small gets pushed around

"Under the bailout's terms, people in Cyprus with less than 100,000 euros in their accounts would have to pay a one-time tax of 6.75%. Those with sums over that threshold would pay 9.9% in tax."

Sanz Prophet © 2010

PSD to Blogger Templates by OOruc & PSDTheme by PSDThemes