Thursday, September 19, 2013

From Regime Switching to Fuzzy Logic -SP500

2comments


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:



 Conclusion:
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: 
Dayreturn=ROC(C,1);
AutoCor=Correlation(Dayreturn,Ref(Dayreturn,-1),22);

Thursday, September 12, 2013

Simple Regime Switching for SP500

24comments
image from  http://brucekrasting.com/
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:

Dayreturn=ROC(C,1);
AutoCor=Correlation(Dayreturn,Ref(Dayreturn,-1),22);
BuyContr=RSI(2)<20;
SellContr=RSI(2)>70;
BuyMom=RSI(2)>60;
SellMoM=RSI(2)<50;
Buy=IIf(AutoCor<0,BuyContr,BuyMom);
Sell=IIf(AutoCor<0,sellContr,sellMom);
SetTradeDelays(1,1,1,1);
BuyPrice=SellPrice=O;
qty=1;
PositionSize=-100/qty;
SetOption("MaxOpenPositions",qty);

Sunday, March 31, 2013

Strategies on The Cloud: TAA on Google Docs

6comments
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)
 {
//tickerobj("SPY",154,1,20,150)
  this.symbol=symbol;
   this.close=close;
     this.action=action;
     this.posscore=posscore;
       this.sma=sma;
}

How do we retrieve data from Google?

function myGetHistoricalStockInfo(symbol,days)
{

 var start=new Date();
 var finish=new Date();
  start.setDate(finish.getDate()-days);
  finish.setDate(finish.getDate());

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

  if(data==undefined)
    return(0);
  else
    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;
   count++;
  }
  return (sum/period);
}

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

function NewMonth()
{
var now= new Date();
var  yesterday= new Date();
 yesterday.setDate(now.getDate()-1);

  if(now.getMonth()!=yesterday.getMonth())
    return (1);
  else
    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
      data=myGetHistoricalStockInfo(symbolarray[i],SMAperiod*2);
//get index of the last data point
      idx1=data.stockInfo.length-1;
//get the last closing price
     close[i]=data.stockInfo[idx1].close;
//get the moving average
     smat[i] = SMA(data, SMAperiod);
//not used in this example
     posscore[i]=0;
//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]);
   }
return(Instrument);
}


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
  sheet.getRange(3,1).setValue("Symbol");
    sheet.getRange(3,2).setValue("Close");
    sheet.getRange(3,3).setValue("SMA");
    sheet.getRange(3,4).setValue("Action");

  var idx=Instrument.length;

     for (var i=0;i<idx;i++)
   {
       sheet.getRange(5+i,1).setValue(Instrument[i].symbol);

       sheet.getRange(5+i,2).setValue(Instrument[i].close);
   
       sheet.getRange(5+i,3).setValue(Instrument[i].sma);
   
       sheet.getRange(5+i,4).setValue(Instrument[i].action);
   }
  sheet.getRange(1,1).setValue("Last Update");
  sheet.getRange(1,2).setValue(date);

}

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

0comments


bbc.co.uk:
"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

13comments
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).

Tuesday, February 26, 2013

VIX vs Italy: Rules vs Opinion

0comments
I am faced with the following dilemma:

1. I believe in rules and strategy-based trading. I believe one must not deviate from the "rules".
2. I can "see" risks that are not incorporated into my model(s).

Let me put this in context.
From a quant point of view (at least a simple, price-based quant model) a jump in VIX of 30%+ does signify an event. Some strategies will enter a mean reverting mode, some will sell-off to avoid a volatile environment, some will jump in and double down, some will sell options, etc.

Quantitatively speaking, one may start by looking at other instances where the VIX jumped more than X% and see what happened in the next few days (here, here , here and here).

From a fundamental (and common sense) point of view, the event that caused the VIX to jump was the outcome of the Italian elections. This is by no means a minor event. It is the first time the south European public votes against German imposed austerity, something that surprisingly  has not yet happened even in Greece (@34% unemployment... how long can that last?), Spain (@20%+ unemployment) or more recently, Cyprus.  This could cause fundamental long term changes to Europe and affect the U.S. market as well.

For illustrative purposes only, I created a simplistic diagram of outcomes following the Italian Elections:


No-matter what the final outcome, halfway through the diagram, there is a lose-lose situation. In other words, one can argue that until the Italian Elections are conclusive, it is not in the interest of the ECB or Germany to stabilize the markets, especially the Italian sovereign spreads.  So if we were to accept the logic of this diagram, even the market-positive outcome assumes a bearish transitory period.

So how does one incorporate this theoretical "belief" without diverging from the systems in place?

One solution is to do nothing and stick to your guns.
Another solution is to get out of the market and stay cash. 
But when do you come back in? How do you decide when the danger is over. When the market has already advanced another 15% while sitting in cash?

A third solution is to turn-on alternative strategies. These could be tail-protection* strategies.
There are many ways to protect from tail risk. Some are better than others. Most cost money in a bullish environment. An obvious example is buying puts. That could protect your positions but if the crash never materializes, the cost of the puts would eat into the returns.
Well, nowadays a retail investor has access to other protection than just buying puts. 

One way to find such a strategy is to split existing strategies into their short and their long components and trade just the short one as a hedge to existing positions.

Take MarketSci's proposed strategy as an example. As of yesterday the VIX futures are barely in contago, which means that the strategy is ready to go long the VXX.  
Here's another strategy that it's short side may work in a bearish environment.

Conclusion:
One way to solve the subjective opinion vs objective model dilemma is to create a strategy that is both agreeable to your subjective opinion and has done ok historically. Then instead of trading the subjective belief you trade the model that incorporates it.
If you cannot find a good model that incorporates it, chances are you shouldn't trade those beliefs in the first place.

*Tail protection is a fancy way of saying protection from abnormal events such as sudden market crashes. 
** This information is not to be construed as financial or investment advice. No information herein should be taken as a recommendation buy, hold or sell any investment or to use a specific investment strategy



Sunday, February 10, 2013

Raging Bull

0comments
It seems that most of the strategies that are in the public sphere, are consciously or unconsciously trying to prevent the large 2007-2009 draw-down. From simple to complex Tactical Allocation Systems, to mean-reverting strategies, to volatility based strategies, pairs strategies, etc. They all avoid (in hindsight) the biggest market crash that most of us have experienced.

But what happens in a Bull market? Most of these strategies will under-perform.








I will make an assumption, here:
Whatever strategy exists, if it is 'well performing' and is 'known' it will be imitated by more and more and eventually the 'market' will change in such a way as to make the strategy not work anymore. The market (or rather, the participants) will 'adapt' to the strategy.

Sample Tactical Allocation strategy: Immune to the 2008 drop but less so to the 2011 drop and 2012 bull run.

And let's just say I was to join ranks with those 'market paranoids' and look at ways on how the market is out to "outsmart' me. How could the market do that. What strategy would it employ?
Well, it would do what it has recently done:

Go up. Just up.

Most strategies I deal with have some kind of neutral outlook. I am fine with the market going no-where. I also like downside protection strategies that stand to benefit on a large downturn, either by shorting, hedging or playing the rise in volatility. What about raging Bull market? Where's the 2004-2007 index-beating straight-up bull strategy?

So here's one.



So yes, this has been a great bull market strategy. But during 2009-2012, when the SP500 did exceptionally well (and 'emerging' equity did less so) this remained fairly flat.


 I will not tell how it trades since I am sure you can build a better one. I will tell you that it trades country indices (data)*. You can get started by thinking of momentum vs value strategies.  I will also tell you what the current positions are:


See the catch?
How do you trade the Ukraine Index? Or the Lebanese?
So maybe Institutional investors are not 'smarter'. Maybe they just have more access to data and instruments.

If you know how to trade these indexes, or you live in these countries, drop me a line and tell me what you think, either here or via e-mail.





So far I only found etfs for Greece: GREK and GRE.PA

*Data used from MSCI Indexes.
 

Sanz Prophet © 2010

PSD to Blogger Templates by OOruc & PSDTheme by PSDThemes