Monday, July 21, 2014



Here's the question: What can a small group of people do in 30 days?

So over @ QuantShare some of the users have created a newly founded group. Starting with Alex and Ivan, the group was created so QS users can privately exchange items like strategies, indicators, download plug-ins, money managment scripts, etc.

Yours truly joined in and had this idea:  Let's develop a few strategies and get them into "production"  in less than 30 days. In other words we would start paper-trading them 30 days later.

It's now 30 days later.
So what was achieved?

1. Code up and "customized" 10+ strategies from published or original ideas:

Grossman's rotation strategies
Permanent Portfolio with timing and custom performance-based re-balancing.
Minimum variance based AAA strategy with controllable margin.
Custom adaptive mean reversion strategy.
A couple of volatility based strategies.
Dr. W. Keller's FAA strategy.
amongst others...

These all include "attachable" money managment components that vary from a MinimumVariance Algo to risk parity, volatility targeting, margin control, equity curve feedback, etc. . Each strategy was assigned a lead developer and two "reviewers" to backtest and  stress test.

2. Approved a group of strategies and came up with an initial allocation of funds between them.
3. Setup an Amazon EC2 instance in the cloud and all installed all necessary components/software including IB TWS, QS, etc.
4. Created, from scratch, a QS portfolio --> IBGateway submission process for N-strategies using IbAPI in C# as well as a IBGateway  --> QS Portfolio submission process for reporting back into QuantShare.
5.Created a C# script to get daily N-strategy  signals, distribute to members, log all details of systems to a shared GDrive.

So. it's up and running on an IB paper trading account. Ten End-Of-Day strategies.

Group members include both pros and retail investors coming from the U.S., Mexico, Slovakia, Germany, Switzerland and Greece.

Our cost so far: $0

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."

Tuesday, March 12, 2013

Selling Puts on Breakouts

If someone asked you to sell Puts on the SP500 and hold to expiration, when would you sell them? On a correction or a bullish breakout?

This is a strategy that I came about by accident. I actually meant to do the exact opposite of what I ended up testing...  I can't say I would trade this as-is but there are some lessons to be learned here, at least for me.

The rules:

When SPY makes a new 15-day high, sell a next-month out-of-the-money PUT.
Pick the farthest strike whose corresponding option price is larger than $0.60.
So if SPY trades at 140, we would try selling the 125 strike. If it's priced at $0.10, we check a higher strike, i.e.,126, 127,128... until we get to a strike whose option price equals or is greater than $0.60.
If the option looses more than 30% of it's value at the close of the day (not intraday), we sell it on the next day at the close.
Otherwise hold to expiration.

Annual Return: 11.73%
DrawDown: -10.11%

Just to get some context:
You need to contrast the above chart to the typical Put-selling strategy. High win ratios (i.e., winners > 80% of the time) but when we have loosers, they are usually huge ones.

PnL of typical option selling strategy

Thoughts and Conclusion:
Having tried different versions of strategies that sell naked options, I can say that I would recommend against it. And if you must, please try to somehow backtest the strategy first.
My results have been mediocre at best. The risk of being short an option is just too massive. One loss may cripple months of winning. Stops may help but they tend to level the winning ratio and often cause multi-year flat equity curves.

Another conclusion is that complex option strategies can be thought of as  multi-strategy (MS) systems. In other words, a Buy-Write strategy, where one buys SPY and sells a call against it is nothing more than:
Strategy 1: A (very simple) long only  SPY stock strategy.
Strategy 2. A (very simple) short only call strategy.

Similarly, an Iron Condor is a simplified 4 strategy MS system.
All this is still work in progress as other factors like early exercise are being looked at.

What is interesting about the above strategy is that :
1. It's not intuitive (to me at least) that one would sell Puts on Bullish Breakouts*.
2. It limits draw-downs by not triggering unless we have a breakout on the long side. So if the market falls and keeps falling, this strategy stays flat.
3. A 30% stop on the option is a very tight stop. It means that  even a small move against us will immediately trigger an exit. On the other hand, by exiting on the next day close, we take advantage of mean-reversion. So if a 1% move down of SPY triggers the exit, chances are the next day will be an up day and we would sell (cover actually) at this up day's close.

*This is counter-intuitive since a bullish breakout would imply a collapse of implied volatility premium on the option to be sold. It's a proposition to sell on low premiums. Intuitively one would sell on bearish breakouts, where implied volatility surges causing the put to be more expensive (and us collecting a higher premium).

Sanz Prophet © 2010

PSD to Blogger Templates by OOruc & PSDTheme by PSDThemes