Category Archives: Stocks & Commodities traders tips

System Development Using Artificial Intelligence

The AIQ code based on Domenico D’Errico and Giovanni Trombetta’s article in August 2017 Stock & Commodities issue, “System Development Using Artificial Intelligence,” is shown here. You can also download the EDS file from here

Are humans or computers better at trading? This question has been around on many fronts since the era of punch cards, and as technology advances, you question whether machines have limits. It’s the same with trading, and here’s an algorithm that may shed some light on which performs better…

!ARTIFICAL INTELLIGENCE FOR SYSTEM DEVELOPMENT
!Authors: Domenico D'Errico & Giovanni Trombetta, TASC August 2017
!Coded by: Richard Denning, 6/08/2017
!www.TradersEdgeSystems.com

!INPUTS:
O is [open].
C is [close].
H is [high].
L is [low].
exitBars is 8.
exitBarsP is 6.
enterGap is -0.08.

!CODE:
AvgP is (O+C+H+L)/4.
MedP is (H+L)/2.
MedB is (O+C)/2.

AvgP1 is valresult(AvgP,1).
AvgP2 is valresult(AvgP,2).
AvgP3 is valresult(AvgP,3).

MedP1 is valresult(MedP,1).
MedP2 is valresult(MedP,2).
MedP3 is valresult(MedP,3).
MedP4 is valresult(MedP,4).

MedB1 is valresult(MedB,1).
MedB2 is valresult(MedB,2).
MedB3 is valresult(MedB,3).
MedB4 is valresult(MedB,4).

!ENTRY & EXIT RULESl
Gandalf if 
  (AvgP1exitBars-1)
 or ({position days}>=exitBars-1)
 or ({position days}>=exitBarsP-1 and (C-{position entry price}>0)).

EntryPr is min(val([low],1) + enterGap,[open]).

Buy if Gandalf and [low] <= EntryPr.

See Figure 10 for how to set up the pricing in a backtest.
Sample Chart

FIGURE 10: AIQ. This shows the EDS backtest settings for entry pricing.
—Richard Denning
info@TradersEdgeSystems.com
for AIQ Systems

Detecting Swings

The AIQ code based on Domenico D’Errico’s article in the May 2017 issue of Stoks Commodities, “Detecting Swings,” is provided below.

I tested the author’s four systems using the NASDAQ 100 list of stocks on weekly bars, as did the author, from 3/16/2005 through 3/14/2017. Figure 7 shows the comparative metrics of the four systems using the four-week exit. The results were quite different than the author’s, probably due to a different test portfolio and also a 10-year test period rather than the author’s 20-year period. In addition, my test results show longs only, whereas the author’s results are the average of both the longs and shorts.

Sample Chart
 
FIGURE 7: AIQ. As coded in EDS, this shows the metrics for the author’s four systems run on NASDAQ 100 stocks (weekly bar data) over the period 3/16/2005 to 3/14/2007.

The Bollinger Band (Buy2) system showed the worst results, whereas the author’s results showed the Bollinger Band system as the best. The pivot system (Buy1) showed the best results, whereas the author’s results showed the pivot system as the worst. I am not showing here the comparative test results for the Sell1 thru Sell4 rules, as all showed an average loss over this test period.

!DECTECTING SWINGS
!Author: Domenico D'Errico, TASC May 2017
!Coded by: Richard Denning, 3/15/17
!www.TradersEdgeSystems.com

!Set to WEEKLY in properties

Low is  [low].
Low1  is valresult(Low,1).
Low2  is valresult(Low,2). 
High is [high].
High1  is valresult(High,1).
High2  is valresult(High,2). 
PivotLow if Low1 < Low2  and Low1 < Low.
PivotHigh if High1 > High2  and High1 > High.

Buy1 if  PivotLow.  
Sell1 if  PivotHigh.    

!Set parameter for bollinger bands to 12 with 2 sigma (weekly) in charts:
Buy2 if [close] > [Lower BB] and valrule([close] <= [Lower BB],1).
Sell2 if [close] < [Upper BB] and valrule([close] >= [Upper BB],1).

!Set parameter for Wilder RSI to 5 (weekly) in charts:
Buy3 if [RSI Wilder] > 40 and valrule([RSI Wilder] <= 40,1).
Sell3 if [RSI Wilder] < 60 and valrule([RSI Wilder] >= 60,1).

Buy4 if [RSI Wilder] < 40  And Low > Low1.
Sell4 if [RSI Wilder] > 60  And High < High1.    

Exit if {position days} >= 4.
—Richard Denning
info@TradersEdgeSystems.com
for AIQ Systems
Editor note: The code and EDS file can be downloaded from http://aiqsystems.com/Detecting_Swings_TASC_May_2017.EDS

Exponential Standard Deviation Bands

The AIQ code based on Vitali Apirine’s article in the 2017 issue of Stocks & Commodities magazine, “Exponential Standard Deviation Bands”

Editor note: “Author Vitali Apirine presented a method intended to help traders see volatility while a stock is trending. These bands, while similar to Bollinger Bands, are calculated using exponential moving averages rather than simple moving averages. Like Bollinger Bands, they widen when volatility increases and narrow as volatility decreases. He suggests that the indicator can be used as a confirming indication along with other indicators such as the ADX. Here’s an AIQ Chart with the Upper, Lower and Middle Exponential SD added as custom indicators.”

 

 

To compare the exponential bands to Bollinger Bands, I created a trend-following trading system that trades long only according to the following rules:
  1. Buy when there is an uptrend and the close crosses over the upper band. An uptrend is in place when the middle band is higher than it was one bar ago.
  2. Sell when the low is less than the lower band.
Figure 8 shows the summary test results for taking all signals from the Bollinger Band system run on NASDAQ 100 stocks over the period 12/9/2000 to 12/09/2016. Figure 9 shows the summary test results for taking all signals from the exponential band system on NASDAQ 100 stocks over the same period. The exponential band system improved the average profit per trade while reducing the total number of trades.

Sample Chart

FIGURE 8: AIQ. Here are summary test results for taking all signals from the Bollinger Band system run on NASDAQ 100 stocks over the period 12/9/2000 to 12/09/2016.

Sample Chart

FIGURE 9: AIQ. Here are summary test results for taking all signals from the exponential band system run on NASDAQ 100 stocks over the period 12/9/2000 to 12/09/2016.
The EDS file can be downloaded from http://aiqsystems.com/EDS/Exponential_Standard_Deviation_Bands.EDS 
and is also shown here:
!Exponential Standard Deviation Bands
!Author: Vitali Apirine, TASC February 2017
!Coded by: Richard Denning 12/11/2016
!www.TradersEdgeSystems.com!INPUT:
xlen is 20.
numSD is 2.

!INDICATOR CODE:
ExpAvg is expavg([close],xlen).
Dev is [close] – ExpAvg.
DevSqr is Dev*Dev.
SumSqr is sum(DevSqr,xlen).
AvgSumSqr is SumSqr / xlen.
ExpSD is sqrt(AvgSumSqr).

!UPPER EXPONENTIAL SD BAND:
UpExpSD is ExpAvg + numSD*ExpSD.  !PLOT ON CHART

!LOWER EXPONENTIAL SD BAND:
DnExpSD is ExpAvg – numSD*ExpSD.   !PLOT ON CHART

!MIDDLE EXPONENTIAL SD BAND:
MidExpSD is ExpAvg.

!BOLLINGER BANDS FOR COMPARISON:
DnBB is [Lower BB].  !Lower Bollinger Band
UpBB is [Upper BB].  !Upper Bollinger Band
MidBB is simpleavg([close],xlen). !Middle Bollinger Band
!REPORT RULE TO DISPLAY VALUES:
ShowValures if 1.

!TRADING SYSTEM USING EXPPONENTIAL SD BANDS:
UpTrend if MidExpSD > valresult(MidExpSD,1).
BreakUp if [close] > UpExpSD.
BuyExpSD if UpTrend and BreakUp and valrule(Breakup=0,1).
ExitExpSD if [Low] < DnExpSD.  ! or UpTrend=0.

!TRADING SYSTEM USING BOLLINGER BANDS:
UpTrendBB if MidBB > valresult(MidBB,1).
BreakUpBB if [close] > UpBB.
BuyBB if UpTrendBB and BreakUpBB and valrule(BreakupBB=0,1).
ExitBB if [Low] < DnBB.  ! or UpTrend=0.

—Richard Denning
info@TradersEdgeSystems.com
for AIQ Systems

Zero In On The MACD

The AIQ code based on Barbara Star’s article in May issue of Stocks and Commodities “Zero In On The MACD,” is provided at www.TradersEdgeSystems.com/traderstips.htm, and is also shown below.
Sample Chart
FIGURE 7: AIQ. Here is a sample chart of VIAB with MACDhist, the color bars, and the 34- and 55-bar EMAs.
Figure 7 shows the MACD histogram on a chart of Viacom (VIAB) with the color bars and the 34- and 55-bar exponential moving averages (EMA). Note that I did not code the weighted moving average (WMA) but substituted the EMA for the WMA. I chose to view the chart of VIAB by running the EDS “Zero MACD.eds” on 3/14/2016 and examining the alert messages on the report “List.” VIAB is the only one on that date that showed a cross up on the MACDhist (see Figure 8 for a look at part of this report for 3/14/2016).
Sample Chart
FIGURE 8: AIQ. This shows part of the EDS custom report “List” that shows the MACDhist values on 3/14/2016, the color status, and any alerts that were generated for that day.
! ZERO IN ON THE MACD

! Author: Barbara Star, TASC May 2016

! Coded by: Richard Denning 3/14/16

! www.TradersEdgeSystems.com



! INPUTS:

macd1  is  12.

macd2  is  26.

macdSig is  1.



! INDICATORS:

emaST  is expavg([Close],macd1).

emaLT  is expavg([Close],macd2).

MACD  is emaST - emaLT.  ! MACD line

SigMACD is expavg(MACD,macdSig). ! MACD Signal line

MACDosc is MACD - SigMACD. ! MACD Oscillator



HD if hasdatafor(macd2) = macd2.

MACDhist is MACD.                                 ! plot as historigram

MACDblue if MACDhist > 0.  ! use these rules to color MACDhist

MACDred  if MACDhist < 0.  ! use these rules to color MACDhist

MACDcolor is iff(MACDblue and HD,"Blue",iff(MACDred and HD,"Red","White")). !for report list

List if 1.



!ALERTS:

EMA1 is expavg([close],34).

EMA2 is expavg([close],55).

xupEMA1 if [close] > EMA1 and valrule([close] < EMA1,1).

xdnEMA1 if [close] < EMA1 and valrule([close] > EMA1,1).

xupEMA2 if [close] > EMA2 and valrule([close] < EMA2,1).

xdnEMA2 if [close] < EMA2 and valrule([close] > EMA2,1).

xupMACD if MACDhist > 0 and valrule(MACDhist < 0,1).

xdnMACD if MACDhist < 0 and valrule(MACDhist > 0,1).

UpAlerts is iff(xupEMA1,"xupEMA1",iff(xupEMA2,"xupEMA2",iff(xupMACD,"xupMACD"," "))).

DnAlerts is iff(xdnEMA1,"xdnEMA1",iff(xdnEMA2,"xdnEMA2",iff(xdnMACD,"xdnMACD"," "))).

The code and EDS file can be downloaded from www.TradersEdgeSystems.com/traderstips.htm.

Trading Gap Reversals

The AIQ code based on Ken Calhoun’s article in April 2016 issue of Stock & Commodities Trading Gap Reversals”, is provided below. 
AIQ has also posted the EDS file at “ is provided for downloading at 
Save this file to your/wintes32/EDS Strategies folder.
Since I mainly work with daily bar strategies, I wanted to test the gap-down concept on a daily bar trading system rather than on one-minute bars. I set up a system that buys after a stock has gapped down at least 10% in the last two days and then trades above the high of the gap-down bar. The entry is then at the close of that bar. For exits, I used the built-in exit, the profit-protect exit set at 80% once profit reaches 3% or more combined with a stop-loss using the low of the gap-down bar and also a time exit set to five bars. 
I then ran this system on the NASDAQ 100 list of stocks in the EDS backtester over the period 12/31/1999 to 1/11/2016 (Figure 7). The system generated 303 trades with an average profit of 1.09% per trade with a reward-to-risk ratio of 1.35. Slippage and commissions have not been deducted from these results.
Sample Chart
FIGURE 7: AIQ. This shows the EDS test results for the example system.
Again, the code and EDS file can be downloaded from www.TradersEdgeSystems.com/traderstips.htm, and is also shown below.
!TRADING GAP REVERSALS
!Author: Ken Calhoun, TASC April 2016
!Coded by: Richard Denning 2/1/2016
!www.TradersEdgeSystems.com

!INPUTS:
GapSize is 10.
GapLookBack is 5.
MaxBars is 5.

!CODING ABBREVIATIONS:
H is [high].
C is [close].
C1 is val([close],1).
L is [low].
O is [open].

GapD is (O / C1 - 1) * 100.
GapOS is scanany(GapD < -GapSize,GapLookBack) <> nodate()
  then offsettodate(month(),day(),year()).
Hgap  is valresult(H,^GapOS).
Lgap  is valresult(L,^GapOS).
SU if  scanany(GapD < -GapSize,GapLookBack).
SU1 if  scanany(GapD < -GapSize,GapLookBack,1).
SU2 if  scanany(GapD < -GapSize,GapLookBack,2).
LE if ((SU1 then resetdate()) or (SU2 then resetdate())) 
 and H > Hgap.
ExitLong if {position days} > maxBars
 or C < Lgap.
EntryPr is max(O,Hgap).
List  if C > 0.
—Richard Denning

Back to Basics with MACD (Part 2)

In this article I detailed one relatively “simple” approach to using the MACD indicator to identify potentially bullish opportunities.  In this piece we will look at one to actually put those signals to use.
The Limited Risk Call Option
One possibility upon generating a bullish signal as described in the last article is to buy shares of the stock/ETF/index/etc in question.  Not a thing wrong with that.  But there is a less expensive alternative.
Figure 1 reproduces Figure 1 from the last piece showing ticker XLF.  Let’s look at the signal generated on 2/12/16.
1Figure 1 – Ticker XLF (Courtesy AIQ TradingExpert)
One alternative that I like is to use the “Percent to Double” routine at www.OptionsAnalysis.com to find an inexpensive call option that has lot of upside potential.  The input screen with a few key input selections highlighted appears in Figure 1a (if it looks intimidating please note that a reusable set of criteria can be captured in a “Saved Wizard”, which appear towards the lower right of of Figure 1a.  Once a set of criteria is saved it can be reused by simply clicking on the Wizard name and clicking “Load”.)
NOTE: My own personal preference is to consider options that have at least 45 days left until expiration (as time decay can become a very negative factor as option expiration draws closer).

1a

Figure 1a – Percent to Double Inputs (Courtesy www.OptionsAnalysis.com)

Figure 1b displays the output screen.
NOTE: For my own purposes I like to see a Delta of at least 40 for the option I might consider buying (nothing “scientific” here.  It is just that the lower the Delta the further out-of-the-money the option strike price is. I prefer to buy a strike price that is not too far from the current price of the stock; hence I look for a Delta of 40 or higher).  With XLF trading at $20.49, in Figure 1b I have highlighted the 2nd choice on the list – the April 21 call – which has a delta of 43.1bFigure 1b – Percent to Double Output (Courtesy www.OptionsAnalysis.com)
So a trader now has two alternatives:
*Buy 2 Apr 21 strike price XLF calls for $70 apiece ($140 total cost; 86 total deltas)
*Buy 86 shares of XLF at $20.49 apiece ($1,760 total cost, 86 total deltas)
Figure 1c displays the particulars for buying a 2-lot of the April 21 call for a total cost of $140.1cFigure 1c – XLF Apr 21 call (Courtesy www.OptionsAnalysis.com)
By 3/18 the shares had gained 11% and the Apr 21 call had gained 143%.  See Figure 1d.1dFigure 1d – XLF Apr 21 call (Courtesy www.OptionsAnalysis.com)
Summary
Obviously not every trade works out as well as this one.  Still, the key things to remember are:
*The option trade cost $140 instead of $1760
*The worst case scenario was a loss of $140.
Something to think about.
Chief Market Analyst at JayOnTheMarkets.com and TradingExpert Pro client

Back to Basics with MACD

One danger of getting “way to into” the financial markets is that you can find yourself progressing into some needlessly complicated stuff (“Hi, my name is Jay”).  I mean it is only natural to wonder “hey, what if I divided this indicator value by that indicator value” and such.  But once you start finding yourself taking an exponential moving average of a regression line with a variable lag time, well, you can find yourself “a tad far afield.”  (Trust me on this one).  Which leads us directly to:
Jay’sTradingMaxim #44: Every once in awhile it pays to remember that the end goal is simply to make money.  The more easily the better.
So today let’s go back to a simple “basic approach.”
The Bullish MACD Divergence
We will define an “asset” as any stock, ETF, commodity, index, etc. that can be traded on an exchange (and for my purposes, there should be a liquid market for options on that asset).
Step 1. An asset price falls to a new 20-day low and the MACD value is less than 0.  Note the MACD value on this date.
Step 2. Not less than one week but not more than 2 months later:
*Price closes below its closing level in Step 1
*The MACD indicator is above its level at the time of Step 1
Step 3. The next time the daily MACD indicator “ticks higher” a buy alert is triggered
Can it really be that simple?  The Good News is “Yes, it can.”  The Bad News is that “It isn’t always.”  To put it another way, like a lot of trading methods it can generate a surprising abundance of useful trading signals.  However, there is no guarantee that any given signal will turn out to be timely.  In other words:
This method gives you a good guideline for when to get in, but:
*It may be early at times (i.e., price will move lower still before advancing)
*It will at times be flat out wrong
*You still have to decide when to exit the bullish position.
*Call options are useful with this approach as it allows you to risk a limited amount of capital.
Examples
Figures 1 through 4 highlight some recent examples using this method.  Note that the charts show only entry points.  Exit points are “a separate topic”.
1
Figure 1 – Ticker XLF (Courtesy TradingExpert Pro)
2
Figure 2 – Ticker WMT (Courtesy TradingExpert)
3
Figure 3 – Ticker AAPL (Courtesy TradingExpert)
4
Figure 4 – Ticker GDX (Courtesy TradingExpert)
As you can see, some signals were quite timely while others were quite early.  For the record, I started getting bullish on gold and gold stocks early in 2016 based in part on the multiple alerts that appear in Figure 4.
Chief Market Analyst at JayOnTheMarkets.com and TradingExpert Pro client

ADX Breakouts

The AIQ code based on Ken Calhoun’s article in the March 2016 issue of Stocks and Commodities, “ADX Breakouts,” is provided at www.TradersEdgeSystems.com/traderstips.htm.
Since I mainly work with daily bar strategies, I wanted to test the ADX concept from the article on a daily bar trading system. So I set up a system that buys after a stock has based around the 200-day simple moving average (Basing200). Basing200 is coded in the system as:
  • The stock closing above the 200-SMA only 19 bars or less out of the last 100 bars, and
  • The stock closing greater than two bars above the 200-SMA in the last 10 bars.
For exits, I used the following built-in exits: a capital-protect exit set at 80% and a profit-protect exit set at 80% once profit reaches 5% or more.
I ran this system on the NASDAQ 100 list of stocks in the EDS backtester over the period 12/31/1999 to 1/11/2016. I then ran a second test on the system using the ADX filter (ADX must be greater than 40 at the time of the signal to buy). I used the same list of stocks, exits, and test period.
Figure 8 shows the first test without the filter: 883 trades, 1.84% average profit per trade, 1.51 reward/risk. Figure 9 shows the second test with the filter: 151 trades, 2.12% average profit per trade, 1.66 reward/risk.
Sample Chart
FIGURE 8: AIQ, WITHOUT FILTER. Here are the EDS test results for the example system without the ADX filter.
Sample Chart
FIGURE 9: AIQ, WITH FILTER. Here are the EDS test results for the example system with the ADX filter.
Although all of the key metrics are better with the filter, there is a significant reduction in the number of trades. In fact, 151 trades would not be sufficient for a trading system over this long test period. If one wanted to use the filter, then the list of stocks would need to be increased to about 2,000 stocks.
!ADX BREAKOUTS
!Author: Ken Calhoun, TASC March 2016
!Coded by: Richard Denning, 1/11/2016
!www.TradersEdgeSystems.com

!NOTE; THIS SAMPLE SYSTEM IS FOR 
           !DAILY BAR TESTING OF ADX FILTER ONLY

SMA200 is simpleavg([close],200).
HD is hasdatafor(250).
Above200 if ( [close] > SMA200 ) .
Basing200 if CountOf(Above200,10) >2
 and CountOf(Above200,100) 200. 
ADXhi if [ADX] >= 40.
BuyADX if Buy and ADXhi.
This code and EDS file can be downloaded from www.TradersEdgeSystems.com/traderstips.htm.
—Richard Denning
info@TradersEdgeSystems.com
for AIQ Systems

Higher Highs and Lower Lows

The AIQ code based on Vitali Apirine’s article in February  issue of Stocks and Commodities, “Higher Highs and Lower Lows,” is shown here.
The code provided computes the indicator values for the HHS and LLS indicators as well as allowing us to plot the indicator on a chart.
Figure 8 shows the indicator on a chart of Align Technology (ALGN).

Sample Chart

FIGURE 8: AIQ. Here, the HHS and LLS indicators are shown on a chart of ALGN.
EDS code is shown below.

!HIGHER HIGHS AND LOWER LOWS

!Author: Vitali Aprine, TASC Feb 2016

!Coded by: Richard Denning, 12/09/2015

!TradersEdgeSystems.com