**The case for Fuzzy Logic in Trading**

The more I backtest strategies the more I feel the need for robustness in a system. There is no point to optimize return. One should optimize** certainty of positive** return. Most strategies that do really well in the past are over complicated and over-fitted and tend to loose money.

One way to achieve robust results is to use approximate values.

You can say buy when RSI(3)<25

Or you can say Buy when RSI(3) is fairly Low

You can say Buy on Monday of Expiration Week

Or Buy around the middle of the month.

So here’s a system:

Buy when RSI(3) is Low and we are before Expiration week. Let’s test it.

How do we code this in

1. Matlab

2. Amibroker

1. Matlab –

First we construct a Fuzzy Model that will take 2 Inputs

a. RSI(3)

b.DayofMonth (i.e., 1…31)

Type “fuzzy” in the Terminal and voila…

We then add a second input and name both.

Set the ranges, 0-100 for rsi3 and 1-31 for day of month.

We then move around the MF’s (memebership functions) until we come up with this:

We then come up with the rules:

If rsi is low and month is around the middle then Buy

If rsi is high and month is early Sell

if rsi is High then Sell

Here’s what the rules look like visually:

The Lower the RSI the closer to 1 the output.

The More in the middle of the month the closer to 1 the output.

Keep in mind the Output ranges from 0 to 1. Towards 1 is Buy, towards 0 is Sell.

Here’s how the fuzzy model incorporates the “Common sense” non linearity (for a simple 2 input model)

This may look “scientific” but all it does is say “I like Mid-month and Low RSI”.

So now we have our model. We will save it as “RSI3_ExpWeek_Fis.fis”.

Now on to the script. We need daily prices of SPY to calculate RSI(3) and the day number. We ‘ll get it from Yahoo.

*%START CODE*

*%Download “SPY” from Yahoo*

ticker_fints=GetTickerV(‘SPY’,’15y’,’d’);

ticker_fints=GetTickerV(‘SPY’,’15y’,’d’);

DatesinCode=ticker_fints.dates;

close=fts2mat(ticker_fints.close);

open=fts2mat(ticker_fints.open);

dayofmonth=day(DatesinCode);

rsi3=rsi(close,3);

inputs=[rsi3 dayofmonth];

%open the fis model

b = readfis(‘RSI3_ExpWeek_Fis.fis’);

%Feed the inputs and get result (0…1)

result=evalfis(inputs,b);

%if result <0.5 Buy, else Sell

signal=iif(result>0.5,1,iif(result<0.5,-1,0));

*[pnl,pnlvector, sh]= backtestlongAmount(ticker_fints,signal,’open’,1,100000);*

*%END CODE*

**This code uses Custom Functions. Read the article and download them here.*So how did we do?

Anonymous says

Nice.

Thanks.

J.M.

Portugal

Jack says

Hi, Where is the rsi function for the matlab?

Sanz Prophet says

http://www.mathworks.com/matlabcentral/fileexchange/18675-rsi-calculator

http://www.mathworks.com/help/finance/rsindex.html

http://www.mathworks.com/matlabcentral/fileexchange/37932-automated-trading-with-matlab-2012/content/Models/rsi.m