Category Archives: trading software

Mon AMMI

No, it’s not french and it’s not the movie.
It’s a fast-N-rough “Adaptive Multi strategy Multi Instrument” model.

Let’s assume we want to trade mean-reversion: If price moves down we buy, if it moves up we sell.

Possible Indicators from the blog-o-sphere:
RSI(2),RSI(3),RSI(4)
DV2 here and here
BSI here or here
BoilingerBands
CRSI here
TD9 here

Question 1: Which Indicator to use?

One way to choose an indicator is to run backtests for each one (and each one’s parameters) and pick the one that has performed the best in the recent past. “Performance” can be pure profit or it can be any other metric we choose:  CAR/MDD (annual return/MaxDrawdown), Profit Factor, Expectancy or your very own “Bliss function“.
So if DV2 has performed best in the past 6 months, maybe we should use that to trade for the next few weeks.

Question 2: What should we trade? 

Just one instrument?
Why not backtest all indicators on all instrument and let the data tell us which instrument behaves best with which indicator? We can then trade that one. Did someone say “overfit”?.
Why not a bunch of instruments? A portfolio! Yes and we ‘ll throw some weights in there, too:
30% SPY 10% AAPL 10% XLU 20% IBM 30% GLD  … wightN*InstrumentN

I guess now we have to backtest the different indicators with these different weights on our instruments, too. What are we doing here? Let’s step back.

Question 3: What are we doing here?

We start with a set of selected assets (StockA, StockB,… StockN).
We bring in a  set of selected indicators (ind1, Ind2, …IndN).
We then build an “ammi” that picks and chooses from these two universes.
We optimize that “ammi” using some type of non-exhaustive optimization technique.

In other words we are creating a portfolio and trading each instrument inside the portfolio with each own indicator/strategy. So what’s the catch? There’s nothing new here. We could just trade SPY with DV2 and AAPL with RSI(3). Allocate 30% of capital to strategy “SPY” and 10% to strategy “AAPL”. Is there an advantage in mixing it all up?

For the purposes of this post we will assume:
1. Our optimizing target  is % profit.
2. We are investing a fixed percentage of current equity on each trade (i.e., 10% of Equity). In other words we are compounding.

By optimizing one instrument and one strategy, the optimizer will look for the most consistent “timing” to enter and exit trades.

By optimizing the whole AMMI, the optimizer is handed one more tool. Since it wants to maximize compound profit it can do so by minimizing max drawdown which in turn gets accomplished by minimizing correlations between the “weighted and traded” equity curves. So, in theory, the optimizer should not necessarily choose the best timing of each instrument/indicator but rather the best combination of instruments/strategies that are somewhat profitable and least correlated*. We hope that this criterion is more robust criterion than just timing.

Almost forgot! We also want to be able to change both the “instrument” and the “strategy” as time passes. That means we re-optimize every x days and trade with the fresh settings. Hence, the “Adaptive Multi strategy Multi Instrument” , a.k.a, AMMI, nick-name.

For the sake of simplicity, we will consider indicators RSI(2), RSI(3) and RSI(4). Possible thresholds are 0–>50 for a Buy signal and 50–>100 for a Sell signal. We will use 10 instruments that can have weights ranging from 5% –> 100%. We assume the standard 2x leverage can be used.

Let’s run an Out Of Sample test. In_Sample (IS) Optimization period is 2 years, Out_Of_Sample trading period (OOS) is 3 months.**
Optimization is done using Amibroker’s non-exhaustive CMAE plug-in set to run very few “runs” so as not to overfit (and not wait too long…). Target for the optimization is pure % Profit (hence the huge draw-downs).

Here’s the  result trading a few instruments and using RSI(2), RSI(3) and RSI(4) as possible indicators with varied thresholds. This is an OOS (out of sample, i.e., realistic) equity. At 40%+ (in the “good” version) draw-downs, it’s not something I would trade***. It’s just for illustration purposes.

Again. this is a rough “model”. It is best used as a starting point to get ideas going. It might also help to get a sense of how different data groups react to different indicators.  Instead of mean reverting indicators you could have trend following , or pattern based indicators. And instead of optimizing precise values you could fuzzify them.

———————————————————————————
* Adding a losing strategy to a profitable strategy may increased the Sharpe Ratio of the system.

**The In-Sample optimization will gives us the weights on the instruments as well as the indicator and the thresholds that were used to produce the best performance. An example would be 5% InstrA, 0% InstrB, 0%InsrC,70% InstrD,100% InstrE, 25% InstrF, etc. Indicator would be RSI(4) and lower and upper thresholds would be 30 and 70. Those set of parameters whould then be used to trade “live” (Out-Of-Sample) for the next three months. After that we would re-optimize (inclusive of the 3 months that were traded) and change param for the next 3 months.

***Unless you know what you are doing, optimizing a system for Max Profit, is a fairly bad idea. It will tend to pick few winners and not diversify (i.e., in hindsight it will tend to pick 100% APPLE). 

———————————————————————————

The code in Amibroker:

 
//----Code by Sanz P.-----------------------------------------------------//
//----Place the instruments on a watchlist and select it under Parameters
//----Optimize/Walk Forward on that watchlist
//------------------------------------------------------------------------//
function Set2D( tablename, x, y, value )
{VarSet( tablename + StrFormat("%03.0f%03.0f", x, y ), value );}
function Get2D( tablename, x, y )
{return VarGet( tablename + StrFormat("%03.0f%03.0f", x, y ) );}
OptimizerSetEngine("cmae");
OptimizerSetOption("Runs", 3 );
OptimizerSetOption("MaxEval", 300 );
WatchlistNumber =Param("Choose Watchlist with Tickers",12,0,30,1);
TickerList= CategoryGetSymbols( categoryWatchlist , WatchlistNumber ) ;
tablename="a";
//init
for( n=0; (instrument=StrExtract( TickerList, n)) != ""; n++)
set2d( tablename, n, 0, n );
Buy=Sell=0;
for( n=0; (instrument=StrExtract( TickerList, n)) != ""; n++)
{
set2d( tablename, n, 1 , Optimize("Ticker"+n+ "Position",20,0,50,5) ); //pos
set2d( tablename, n, 2 , Optimize("Ind"+n,2,0,2,1) ); //ind
set2d( tablename, n, 3 , Optimize("Thrsh"+n,20,0,100,5) ); //thr
}
for( n=0; (instrument=StrExtract( TickerList, n)) != ""; n++)
{
if (Name()== instrument)
{
indicator=0;//init
indicatorcode=get2d( tablename, n, 2 );
switch(indicatorcode)
{
case 0:
indicator=RSI(2);
break;
case 1:
indicator=RSI(3);
break;
case 2:
indicator=RSI(4);
break;
}
PositionSize= - get2d( tablename, n, 1 );
thresh=get2d( tablename, n, 3 );
Buy=Cross(thresh,indicator);
Sell=Cross(indicator,thresh);
}
}
SetTradeDelays(1,1,1,1);
BuyPrice=SellPrice=ShortPrice=CoverPrice=O;
SetOption("MaxOpenPositions",10);

Connors RSI – Part 1

One of the readers of this blog, Mark, alerted me to a new indicator/system published from Connors/Alvarez : The ConnorsRSI.

What is the ConnorsRSI?

It consists of three components:
a. Short term Relative Strength, i.e., RSI(3).
b. Counting consecutive up and down days (streaks) and “normalizing” the data using RSI(streak,2). The result is a bounded, 0-100  indicator.
c. Magnitude of the move (percentage-wise) in relation to previous moves. This is measured using the percentRank() function.

The formula given is:
ConnorsRSI(3,2,100) = [ RSI(Close,3) + RSI(Streak,2) + PercentRank(percentMove,100) ] / 3

Bottom line: Connors/Alvarez have used similar indicators in the past. What is happening here is that they are creating a more robust indicator by averaging the three. They are “normalizing” the three indicators (rsi, consecutive moves and magnitude of move) to a 0-100 range and then averaging.

Connors/Alvarez propose a strategy that uses the Connors RSI coupled with other rules and filters on large section of U.S. Stocks.
In this post we’ll test the indicator on one security only, the SPY etf (as a proxy for the SP500).

Test A –
Instrument – SPY
1. Using ConnorsRSI(3,2,100) – We ‘ll call it Crsi.
2. Buy on Crsi<15
3. Sell on Crsi>70
4. Buy /Sell on the next bar Open price.
5. Commision of $0.005.

Test B –
The obvious question is whether the parameters are “fitted” to the data. What about using other parameters:
ConnorsRSI(a,b,c)
a–>2-4
b–>2-4
c–>80-140
BuyThreshold –>5-50
BuyThreshold –>50-95

Test C –
What about before 1994? We ‘ll use ^GSPC (the SP500 Index).
Same parameters as “Test A”

Detailed results Test A

All trades
Initial capital 100000
Ending capital 336322.84
Net Profit 236322.84
Net Profit % 236.32%
Exposure % 6.55%
Net Risk Adjusted Return % 3606.42%
Annual Return % 6.30%
Risk Adjusted Return % 96.17%

All trades 179
Avg. Profit/Loss 1320.24
Avg. Profit/Loss % 0.73%
Avg. Bars Held 4.77

Winners 136 (75.98 %)
Total Profit 439687.37
Avg. Profit 3233
Avg. Profit % 1.71%
Avg. Bars Held 3.93
Max. Consecutive 11
Largest win 15964.53
# bars in largest win 3

Losers 43 (24.02 %)
Total Loss -203364.52
Avg. Loss -4729.41
Avg. Loss % -2.37%
Avg. Bars Held 7.42
Max. Consecutive 3
Largest loss -35059.29
# bars in largest loss 10

Max. trade drawdown -58157.34
Max. trade % drawdown -23.75%
Max. system drawdown -58157.34
Max. system % drawdown -23.28%
Recovery Factor 4.06
CAR/MaxDD 0.27
RAR/MaxDD 4.13
Profit Factor 2.16
Payoff Ratio 0.68
Standard Error 20256.9
Risk-Reward Ratio 0.5
Ulcer Index 3.5
Ulcer Performance Index 0.26
Sharpe Ratio of trades 2.23
K-Ratio 0.0404

Quiz System

Here’s the  Equity curve:

And here’s the code:

Buy=Sell=Short=Cover=0;
if (StrFind(“WOODGDXEPUIDXPALLJJG”, Name()))
Buy=Sell=1;
qty=6;
SetOption(“MaxOpenPositions”,qty);;
PositionSize=-98/qty;
SetTradeDelays(0,1,1,1);
BuyPrice=C;
SellPrice=O;
ShortPrice=O;
CoverPrice=C;

What’s happening here?

This is a variation of Jay Kaeppel’s post at optionetics but using some extra ETFs that have exhibited the same kind of behavior. Original article: http://www.optionetics.com/market/articles/2012/11/28/kaeppels-corner-the-greatest-gold-stock-system-youll-probably-never-use

It buys equal amounts of each of these 6 etfs: WOOD,GDX,EPU,IDX,PALL,JJG.
It buys on the close of the U.S.session, holds overnight and sells on the open the next day.

That’s it.

Would you invest in this strategy
?

Backtest Multiple Strategies

If you are serious about trading and/or investing and are willing to commit a good amount of your net worth, you may choose not to follow just one strategy. You may be better off splitting your capital amongst not just different asset classes or stocks or etfs but also different strategies that trade those assets.

How can we simulate this?

One way is not to. You can develop good strategies independent of one another and invest in them as you see fit.
The other way is to simulate a multi-asset, multi-strategy portfolio as a whole.

You can think of a strategy as a time-series. SPY is a time-series. So is GLD, so is IBM. Just a sequence of numbers. So a strategy is it’s equity curve, an artificially made time series. You can invest in one or in multiple ones, just as if they were “assets” also.
20 years ago we should have diversified in different asset classes, now we may have to diversify in different strategies, as well.

So how can you do that? What tools to use?
There are many choices. I will briefly go through the ones I have tried. Others exists that might be better but I haven’t tried myself (NinjaTrader, TradingBlox, etc.)
_______________________________________________________________________________

  Amibroker

As you know I am a big fan of Amibroker. It is not an obvious choice for backtesting a multi-asset, multi-strategy portfolio. But as usual there’s many ways to do things in AB. The obvious choice is to backtest each strategy and export the individual equities. Then trade those equity curves as buy & hold. The downside is that it takes two steps to do this. The upside is that you can write a new script and develop rules or allocation schemes on when and how much to trade in each strategy. Another choice is to program multiple strategies in one afl script, so that both available funds as well as compound profits are taken into consideration.
This  can be done, with some limitations. If someone is interested, I can do a post with the afl code and logic.
________________________________________________________________________________

The more I work with this software, the more I like it.
In QuantShare, you first develop individual strategies. Each can trade it’s own specific basket of assets.  You can then combine strategies by using the combine-trading-systems plug-in.
 It asks you to choose which strategies to test, then combines them and returns stats and equity curves. By listing the stats of all the possible combinations, you can quickly see which combinations of strategies are better without going through a correlation analysis.
Another way to backtest multiple strategies is to write a MoneyManagment script. Using such a script (in C# or JScript) you can control multiple “categories” that have their own rules.
In the next post I will go briefly through an adaptive multi-strategy script.

_______________________________________________________________________________

I downloaded a 30-day trial and so far I am very impressed, especially with the ease it communicates with Interactive Brokers (as well as many other brokers and feeds) and the potential to run ATS (automated trading strategies) with many different brokers. I was able to set up a simple ATS system in less than 10 minutes and run it. This is definitively a contender when it comes to intra-day ATS systems.
That said, MultiChart can also backtest multi-strategy,multi-assets portfolios.

________________________________________________________________________________

Now, this is a very interesting piece of software.
a. You can perform multi-asset, multi-strategy backtesting by using “Accounts”. Each Portfolio has one or more accounts. Each account has each own instrument list, strategy, money managment script, as well as commissions and broker connection (for autotrading).
b. You can have a Master money managment script that “sees” all accounts under the portfolio and reallocates funds according to set rules.
c. You can have a Master risk-controlling script that “sees” all accounts and ,for example, rejects positions if different strategies tend to buy the same one stock. You can automate all this, not just backtest. As an exampe: Let’s say you have two brokers: Interactive Brokers and MB Trading. Under Portfolio I can create two Accounts: InteractiveBrokers_1 and MBTrading_1. Both can be auto-traded from IQ.  So even if you are a bit paranoid and don’t trust your broker,  you can execute through them only half your strategy! 🙂
e.IQBroker uses C# and allows you to import dll references.
f. It’s currently free for individuals.
So, what’s the downside?
A bit of a steep learning curve and no support (unless you pay).

Quantshare Trading Software on Amazon’s EC2

I wrote an article on how to automate the process of updating quotes, updating multiple trading strategies and e-mailing next day signals form the cloud to our own e-mail boxes. This time I am using QuantShare as the trading software and an Amazon EC2 micro instance as the host cloud.

You can read the article at the QuantShare Blog.
More…

QuantShare is a fairly new piece of software that can be used to develop and backtest trading strategies. It has many features (I will get into them in another article/review). I will just go through a few that interest me. Keep in mind that most of my system backtesting and development has been done in Amibroker.

1. It has a similar “language” and array based logic as Amibroker. That means one can develop quickly in Amibroker and then “detail” the strategy in QuantShare. More…

2. You can write a Money Management script in C# to extend the rules of the main strategy.
 More…

3. You can write your own indicators in C# and then call them from the array based language as functions.

4. It has a genetic optimizer that works with a “Rules” list. You can combine rules and “auto-generate” systems in minutes. Or better, take your existing system and “look” for filters or additional rules that might improve it.
 More

5. QS uses custom databases. They can hold quotes, fundamentals  Yahoo news, tweets, COT data, whatever. It has a downloaded tool that can be customized to handle all kinds of downloads and update the database. Ready made downloaders exists for different markets. These historical databases can then be called from the backtester. More…

6. There is a community and ready made “scripts” that can be downloaded through the “Sharing Server“.

7. You can “combine” systems. So you can see the equity curve of trading MySystem1 with MySystem2 and… MySystemN.  More…

8. Reasonably priced.

So what’s the downside?
The real-time version is still in Beta as of this writing ( 28/10/2012).  So you cannot connect to a broker or auto-trade, yet.