Sei sulla pagina 1di 78

Build an Automated Stock Trading System in

Excel
By

Lawrence H. Klamecki, MBA, JD


Version 3.0

© 2014 Lawrence H. Klamecki


New York, NY

ISBN: 0-9760169-4-X

This e-book, including the text, trading model system logic, images, computer files, and other
accompanying material is protected by U.S. and international copyright laws. Your user license to the
e-book is for personal use only. A user license allows you to incorporate the information into your
own trading or analysis models, software, spreadsheets, or derivative works, however any
distribution or resale of these derivative works incorporating content from this e-book in original or
modified form outside of your own personal use requires a further written license. No reproduction
or distribution of any sort is permitted without the express written consent of Lawrence H. Klamecki.
All rights reserved.
Contents

Introduction
Basic Technical Requirements
The 5 Technical Indicators – A Primer
System Architecture
Setting Up the Excel Workbook
Writing the VBA Macro Code
Building the Signals Worksheet
Building the Data Source File
Loading Data from other Sources
Running the Model on a Daily Basis
Common VBA Macro Errors
Back Testing the Model
Frequently Asked Questions (FAQs)
Introduction
Automated trading models based on logical rules are very effective in isolating important information
about stock price, volume, and strength that can give you a distinct advantage in the markets.
Regardless of whether you are a short-term or long-term investor, custom trading models can be
highly effective tools. Such models are used widely within the institutional investment community,
ranging from complete "black box" systems to relatively simple tools used by traders and fund
managers to screen for pre-defined price or volume patterns.
This course introduces you to the basics of building an end-of-day automated stock trading system
using Microsoft Excel and daily data files. It covers technical requirements, data feeds, importing
data into Excel, spreadsheet management, data ranges, VBA macros, and formula-building. The
system incorporates 5 basic time-proven indicators—the Average Directional Movement Index
(ADX), moving average crossovers, stochastic oscillator, Bollinger bands, and Directional
Movement Indicator (DMI).
Included is a brief overview of the technical indicators used in the system and the functionality
available in Excel. It is assumed that you can already operate a computer, work on the Internet
comfortably, are familiar with Excel, and have read a thing or two about technical analysis.
Basic Technical Requirements
- Microsoft Excel for Windows
- 5 megabytes disk space (primarily for data storage)
- Daily Open-High-Low-Close-Volume stock price data
- (OPTIONAL) DDE or ActiveX data import link for Excel

About DDE/ActiveX importing programs

Many data providers offer a small piece of software designed to integrate Microsoft's ActiveX
(previously called DDE) linking technology into Excel. These programs are used to import data into
Excel automatically from a central database, either through an Internet connection or a local area
network.

This course shows you how to integrate a DDE/ActiveX link into the model to capture large amounts
of data automatically for hundreds of stocks.

DownloaderXL http://www.financial-edu.com/downloaderxl-pro.php is used as an example, but


similar applications are available from a number of data providers, including eSignal, Reuters,
Bloomberg, IDC, Money.net, etc.

If you intend to run the model on more than 5-10 stocks at once, you should use a DDE/ActiveX link.
The time savings is well worth the extra expense.
The 5 Technical Indicators – A Primer
Average Directional Movement Index (ADX)

J. Welles Wilder invented the ADX indicator to help determine whether a particular security is
moving in a trending mode or an oscillating mode (often called range-trading, or swing-trading). The
ADX is a tremendously useful indicator, not because it tells you when to buy or sell (which it
doesn’t), but because it tells you which type of other indicator to use in a particular situation.

As shown below, in trending mode prices climb or drop in a staircase pattern over time. The ADX
responds with an increasing "trend" value.

As you can see from the chart above, there is a clear trend in price movement from left to right. As the
trend continues, the ADX value increases, showing the build-up in momentum until the trend itself
begins to flatten.

Trending markets tend to continue heading in the same direction because the "herd" has momentum.
Since the world's financial markets are enormous (the major exchanges regularly trade hundreds of
billions of dollars per day) it takes a while for a trend to change direction, especially in a large cap
stock. The safest and most profitable thing to do is to go with the momentum of the crowd during a
trend and get out when the trend changes direction.

When a security is trending, the ADX shows a high directional value, telling us to use a trend-
following indicator such as moving average crossovers to make trading decisions.

In comparison, oscillating markets tend to go in one direction for a short time, then reverse direction,
and reverse again in the original direction, swinging back and forth with high frequency in a
somewhat-measurable range. During oscillating periods, the ADX shows a low value, telling us to
use an oscillator such as the stochastic indicator to make trading decisions.
The ADX indicator is a "primary filter" in the stock trading system you are building. By using the
ADX to first determine when a stock is "trending" versus "oscillating", we can then select either a
trend indicator or oscillating indicator to use for our entry and exit signals. This rule is encompassed
below:

RULE:

If ADX exceeds 10, use moving average crossovers to generate buy/sell signals. If the ADX value
is less than 10, use the stochastic indicator for buy/sell signals.
Trending or Oscillating?

Trending = Moving Average Crossovers

If the ADX indicates that a particular security is in trending mode, the most profitable and least risky
decision is to go with the flow, but keep watch for a change of direction and momentum. The most
popular and reliable indicator for profiting in trends is the moving average crossover.

Here, we will use simple moving averages. 10, 20, 50, 100, and 200-day moving averages are
commonly used, with more periods slowing down the indicator to make it less sensitive. There are
many different types of moving averages, linear regressions, channels, and other esoteric indicators
out there to handle trends.

The beauty of a moving average is that it smoothes out a string of random-looking prices into a more
coherent-looking trend line so you can see what is happening with more clarity. Another great thing
about a moving average is that it lags behind price somewhat (less lag for shorter periods such as 10
days, and more lag for long periods such as 200 days), so it is not too sensitive and helps eliminate
false trades during minor trend corrections. Some technical analysts call lag “smoothing” but don’t
get too worried about the terminology.

When price crosses a trend line, it gives a buy signal (if it crosses going up) or sell signal (if it
crosses going down). A moving average can also be used as a visual support and resistance line, and
may resist being penetrated completely for some time. This is especially true for the major trend lines
such as 200 days, 50 days, etc.

There are two ways to use moving average crossovers. First, you can use a single moving average
and buy or sell when the price line crosses it. This method reduces lag, but tends to cause a lot of
false signals in technical trading systems, since price will often cross back and forth over the trend
line for a short period before moving away from it. The second method is to use two moving averages
with the shorter moving average (such as 10 days) crossing over the longer moving average (such as
50 days) to give a signal. This method reduces false signals, but makes the indicator less sensitive to
rapid price changes, which can reduce profitability.

Our solution is to apply a very short moving average as a proxy for price with a longer moving
average in order to reduce lag and minimize false trades at the same time.

TRENDING RULE:

When ADX is greater than 10, buy when 5 day moving average crosses above 20 day moving
average, and sell when 5 day moving average crosses below 20 day moving average.

Oscillating = Stochastic Oscillator

If the ADX tells you that your security is in oscillating mode, you have three choices:

First, if you are a long-term tax efficient investor, you can hold through oscillating periods. This
decreases capital gains taxes and transaction costs. However, there is potential to incur losses over
time, since securities in oscillating mode can just as easily oscillate up or down as sideways.
Moreover, remaining invested in the market without trying to generate returns increases risk without
expectation of additional return.

Second, if you are a short-term investor less concerned with capital gains taxes, you can just liquidate
your positions, hold cash, and protect your capital (or reinvest it somewhere else). This approach
potentially increases taxes and adds some transaction costs. However, you minimize the risk of
potential losses, preserves your capital, and may profit from another investment.
The third choice is to try swing-trading. One piece of advice here: swing-trading successfully is much
more difficult than profiting during trends. It requires considerably more time and attention to the
markets, increases transaction costs, and can cause large losses if the security suddenly breaks out of
its trading range and you are on the wrong side. Swing-trading is inherently contrarian, because you
are betting that price will change direction rather than going with the herd. It also tends to be
dominated by sophisticated institutional investors and day traders who trade for a living with the
finest tools available. For those people who feel this is too risky or who do not have the time or
patience to swing-trade, there is a switch in the model to be able to withdraw from the market entirely
during oscillating periods.

If you decide to swing-trade, you can use the stochastic oscillator to help identify and profit from tops
and bottoms with alternating long and short positions.

The stochastic oscillator is an indicator developed by George C. Lane that does an excellent job of
signaling overbought and oversold conditions and detecting changes in momentum at price tops and
bottoms. The indicator can be applied to different time periods to increase sensitivity or decrease
false trade signals.

There are two main components to the stochastic indicator which appear as oscillating lines that
cross over one another. These are the %K line and the %D line.

The %K line is the faster-moving, more sensitive version (think of a short-term moving average),
while the %D line is just the moving average of the faster %K line. The %K line can vary from 5 to
10 periods, and the %D is generally a 3-period moving average of %K.

When both lines are above 80, this indicates an overbought situation, and you should be looking to
enter a short position or sell a long position. When both lines are below 20, this indicates an oversold
situation, and you should be looking to enter a long position or cover a short position. The actual
signal comes when the fast %K line crosses the slower %D line, just like a moving crossover signal
for trends. Experienced traders also look for positive and negative divergences between successive
stochastic peaks and price peaks.

OSCILLATING RULE:
When ADX is less than 10 then:

Sell if both %K and %D are above 80 and %K crosses below %D

OR

Buy if both %K and %D are below 20 and %K crosses above %D


Timing the Buy/Sell Signals with Bollinger Bands

A Golden Rule of technical analysis is “never rely on only one indicator and always look to another
non-correlated indicator of a different type to confirm your buy/sell signals.” Sometimes it is hard to
tell when a security is transitioning between oscillating mode and trending mode because price is not
moving up and down very far (i.e. there is low volatility), or the opposite is occurring and price
seems to be moving around randomly over a wide range (i.e. there is high volatility).

Therefore, we need another indicator to help us time our trades more accurately and avoid false trade
signals. This indicator should be self-adjusting to existing market conditions and different securities
and asset classes to produce a robust, flexible system that will work well over time.

John Bollinger developed his Bollinger bands to create price envelopes that encapsulate most of the
prices in a security’s trading range at any given time. Bollinger bands do this by combining a self-
adjusting volatility measure (standard deviation) with a moving average. The indicator uses a 10, 20,
or 50-day moving average as the center line, and upper and lower bands calculated by adding to and
subtracting standard deviations from the center line. Using two standard deviations, 95.5% of the
prices over a given period should be contained within the upper and lower bands. Using one standard
deviation, 66% of the prices are contained within the bands.

Since only a small percentage of prices move outside the Bollinger bands when there is a price
extreme, this indicator is very useful in timing trades to capture tops and bottoms during both trending
and oscillating periods. The use of Bollinger bands can increase profits over time and reduce risk and
trading costs by eliminating false trades.

Like the ADX, Bollinger bands do not actually give trading signals. Rather, they enhance and confirm
the moving average crossovers and stochastic oscillator we will use in the model. When prices touch
or penetrate the upper band, this signals an overbought condition and we should be looking to sell.
Likewise, when prices touch or penetrate the lower band, this signals an oversold condition and we
should be looking to buy. However, during a strong up or down trend, price will often penetrate the
bands repeatedly without reversing direction. This is why you should not rely solely on Bollinger
bands to make buy or sell decisions. We will use the statistical power of the Bollinger band indicator
to enhance trade timing during oscillating periods only, when the stock is highly overbought or
oversold.

OSCILLATING RULE:

If ADX is less than 10 then:

If price is greater than the upper Bollinger band, sell if stochastic indicators cross over each
other above 80.

If price is less than lower Bollinger band, buy if stochastic indicators cross over each other
below 20.
Enhancing Percentage Trade Success with the Directional Movement Index (DMI)

The Directional Movement Indicator (DMI) was also created by J. Welles Wilder. The DMI measures
“up” volatility versus “down” volatility. It is a very accurate indicator that closely tracks momentum
swings by focusing on the vertical location of the closing price in the price bars. It has very little lag,
but it also gives relatively few false signals, and therefore it is an excellent “confirming” indicator to
use with moving average crossovers.

The DMI is composed of the DMI+ (plus) and the DMI- (minus) lines. Wilder’s basic rule is to buy
when DMI+ is higher than DMI- and sell when DMI- is higher than DMI+. DMI is a component of the
ADX indicator (ADX is just a moving average of the DMI lines). This makes it easy for us to use it,
since we will already have the formulas.

RULE:

Buy when DMI+ crosses DMI- going up and sell when DMI- crosses DMI+ going down.
System Architecture
One of the key advantages of this trading model over other designs is the way the major components
are laid out in relation to one another. The model architecture has 3 parts as shown in the diagram
below:
Component 1: Data Provider

Component 1 is the external data source for ticker symbols, trade date, Open-High-Low-Close prices,
and volume. For our purposes, this can be either a subscription data provider such as eSignal,
Reuters, Bloomberg, etc., or it can be a free data provider such as Yahoo Finance.

The link between components 1 and 2 assumes your model interacts with your data source using the
Internet, but this could also be an internal network or data files. This course shows you how to use a
DDE/ActiveX link to make the connection between 1 and 2.
Component 2: Data Hub

Component 2 is the "data hub" Excel repository file to house bulk stock data locally on your machine.
If using a DDE/ActiveX link, the data will be imported automatically into this Excel workbook. If
not, you will have to import and format the data manually into the Excel repository. The model 3
automatically sources the data it needs from 2.
Component 3: Trading Model
Component 3 is the actual Excel trading model you will build. This is where all the signal logic,
calculations and VBA macro code are housed, and the point from which the user controls the whole
system. The Excel trading model code reaches out to Component 2 when it needs data.
This architecture is highly robust and flexible. If one or more of the Components break, it does not
take down the whole system. Each component is reduced in size, enabling faster operation and less
storage space.
A special feature of the "data hub" approach is that Component 2 can be used concurrently by other
trading models at the same time, for example if multiple users need data for different purposes. This
eliminates duplication, cost and complexity, and allows the data repository to be maintained
separately from the trading model formulas and code. It also allows the trading model to be
password-protected to maintain confidentiality while allowing multiple user access to the data.
Finally, it allows multiple users to "piggyback" on a single data license (NOTE: this may violate data
provider user license requirements -- check with your data provider).

Setting Up the Excel Workbook


NOTE: The file names and code are different between Excel and Windows versions so pay close
attention to the notes for different versions.
Building the Directory and File Structure

To establish the proper locations for your files and data, you need to add folders to your main hard
drive. This report assumes you use the C: drive as your main storage area. If your main hard drive is
designated with a different letter, just substitute the correct letter for C: in the directory structure and
macro code (see Building the VBA Macro Code section).

Windows Vista and Windows 7

In Windows Vista or Windows 7 follow these steps, starting from the Windows Desktop:

1) Go to the Start Menu and select Windows Explorer


2) Find the Computer icon and expand
3) Select the C: drive
4) Right click the C: drive icon and select New > Folder. Name it Stocks
5) Open the Stocks folder
6) Right click in main panel and select New > Folder. Name it Data
7) Right click in main panel again and select New > Folder. Name it Model

Windows XP

In Windows XP follow these steps, starting from the Windows Desktop:

1) Double click My Computer


2) Select C: drive
3) Click File > New > Folder. Name the new folder Stocks
4) Open the Stocks folder
5) Click File > New > Folder. Name the new folder Data
6) Return to the Stocks folder
7) Click File > New > Folder again. Name the new folder Model

Now you have your directory and file structure.

NOTE: It is a good idea to regularly save the original model file and a backup file in the
“Model” folder and on a USB drive. You will be grateful if your system ever crashes or you get a
bad virus!
Building the Spreadsheet Structure

Now open a new Excel workbook. This will be your trading model, which we will save as
C:/Stocks/Model/Modelv3.xlsm in Excel 2007 or Excel 2010.

IMPORTANT: In Excel 2007/2010 you must save the model as a “Macro-Enabled Workbook”
(.xlsm). Be careful to use the correct spelling and UPPER and lower case for the Modelv3.xlsm
file.

When you open a new Excel workbook, you get one or more blank default spreadsheets labeled Sheet
1, Sheet 2, etc.

Rename the first two worksheets by double-clicking on the worksheet tab you want to rename and
typing in the names Signals and Calculations. We will not use more than two worksheets, so simply
delete the extra sheets by right clicking on the sheet and selecting Delete.
Entering the Header Names in the Calculations Worksheet

The first seven columns A through F in the Calculations worksheet will be used to insert market
data. Type the following header names in the Calculations sheet cells A2 through F2 as shown
below:

In cells H2 through S2 in enter the header titles as shown below:

In cells U1 through AI2 enter the header titles as shown below:


Entering the Indicator Formulas in the Calculations Worksheet

Beginning in cell H3 copy the following ADX formulas directly into the Calculations worksheet. Be
careful, the ADX formulas are particularly complicated and sensitive to errors!

Cell Formula Notes


H3 =MAX(C3-D3,ABS(C3-E4),ABS(D3- Fill down to row 32
E4))
I3 =IF(C3-C4>D4-D3,MAX(C3-C4,0),0) Fill down to row 32
J3 =IF(D4-D3>C3-C4,MAX(D4-D3,0),0) Fill down to row 32
K3 =TRUNC((K4-(K4/14)+H3),3) Fill down to row 16
L3 =TRUNC((L4-(L4/14)+I3),3) Fill down to row 16
M3 =TRUNC((M4-(M4/14)+J3),3) Fill down to row 16
N3 =INT(100*L3/K3) Fill down to row 17
O3 =INT(100*M3/K3) Fill down to row 17
P3 =ABS(N3-O3) Fill down to row 17
Q3 =N3+O3 Fill down to row 17
R3 =INT(100*P3/Q3) Fill down to row 17
S3 =INT(((S4*13)+R3)/14) Fill down to row 4
K17 =SUM(H17:H32)
L17 =SUM(I17:I32)
M17 =SUM(J17:J32)
S5 =AVERAGE(R5:R17)

Skip column T to separate the indicators.

Next, copy the following the 5 day and 20 day moving average formulas directly into the
Calculations worksheet.

Cell Formula Notes


U3 =AVERAGE(E3:E7)
V3 =AVERAGE(E3:E22) Fill down to row 22

Skip column W to separate the indicators.

Repeat the process for the Stochastic formulas:

Cell Formula Notes


X3 =MIN(D3:D7) Fill down to row 5
Y3 =MAX(C3:C7) Fill down to row 5
Z3 =100*((E3-X3)/(Y3-X3)) Fill down to row 5
AA3 =AVERAGE(Z3:Z5)
Skip column AB to separate the indicators.

Repeat the process for the Bollinger Band formulas:

Cell Formula Notes


AC3 =(E3-V3)^2 Fill down to row 22
AD3 =SQRT((SUM(AC3:AC22)/20))
AE3 =V3+$AD$1*AD3
AF3 =V3-$AD$1*AD3

Skip column AG to separate the indicators.

Finally, copy and paste the following DMI formulas into the Calculations worksheet.

Cell Formula Notes


AH3 =L3 Copied from ADX formulas
AI3 =M3 Copied from ADX formulas

Now all the necessary technical indicator formulas are entered into the Calculations worksheet.

NOTE: Save the file immediately as C:/Stocks/Model/Modelv3.xlsm and back it up to prevent


losing your work!
Writing the VBA Macro Code
Microsoft's Visual Basic for Applications (VBA) language is the primary tool for automating Excel
workbooks. VBA or "macros" is a simple, structured, object-based language that is easy to read and
write.

Excel contains a complete VBA writing tool, with code library, automatic error checking and
handling, etc. The code is contained in "modules" hidden behind the normal Excel user interface.
These modules are easily accessible through the Visual Basic Editor.
The Visual Basic Editor Window

To begin, we need to open the Visual Basic Editor window. This is done using the View tab >
Macros icon or the Developer tab > Macros icon. You can also use the keyboard shortcut Alt + F8
to display the Macros screen.

NOTE: If you cannot see the Macros icon you need to enable macros. This is done slightly
differently in Excel 2007 and Excel 2010.

In Excel 2007 click the Office icon on the upper left and select Excel Options button > Popular
> Top options for working with Excel. Then check "Show developer tab in the Ribbon".

In Excel 2010 click File > Options > Customize Ribbon. One the right hand side in “Main
Tabs” select “Developer”.

Clicking the Macros icon opens the “Macro” launch screen. In the Macro name field enter
Run_Model and click Create.
The VBA Editor window should open with the first module ready for you to enter the Run_Model
code as shown below. Notice that Module1 is highlighted which is where the VBA code goes.
VBA Code

All the VBA code needed to automate the model is provided in a zip file you can download at
http://exceltradingmodels.com/backtest/

Follow the instructions to download the zip file. Save and unzip the zip file to your hard drive. Then
copy the VBA code from the VBACODE_StockModel.txt file.

This is what it should look like when you are done pasting the code into the VBA module:

If you want to build your own models or modify this one, you will need to develop the code yourself
and type it into a VBA Editor module.

If you have any issues with this VBA code please email help@financial-edu.com.

NOTE: Save the file immediately as C:\Stocks\Modelv3.xlsm and back it up to prevent losing
your work!
The VBA Code Explained

VBA is an object-oriented language. The code is written in small chunks called "subroutines"
designed for specific purposes, which may then call upon each other when they are needed. This is
both fast and flexible. Plus it is easy to understand and keep track of what the code is doing at any
given moment.

While a full discussion of VBA is beyond this course, some of the techniques used are discussed
below:

Sub...End Sub

Sub Run_Model ()

....

End Sub

Each section of the code is bracketed by "Sub" and "End Sub", which stands for "start subroutine" and
"end subroutine". After the first "Sub" is the name the programmer assigned to that subroutine. Within
the brackets, a programmer usually writes a chunk of code for a particular purpose, for example
saving a file or copying text from one point to another. "Sub" and "End Sub" are mandatory in VBA.

Code Comments

' inserts latest data in \Signals/ sheet cols B:G

Any line beginning with a single quote mark (') is simply a comment written by the programmer about
the code itself. This can be copyright or patent notices, code version, instructions or reminders to the
programmer, or any other information. If the single quote mark is left out, Excel will think that is an
actual line of code and try to process it -- leading to an immediate syntax error that stops the
subroutine. Don't forget those single quotes!

Dim and Variables

Dim rowcount, colcount, datacol, datarow As Integer

Dim DMIup, DMIdn, price, signal As Variant

The VBA code above contains programmer-created "variables" to which values may be assigned for
various purposes. The "Dim" line defines the variable names and the type of data that can be
contained in those variables. There can be multiple "Dim" lines and multiple variable data types, as
shown by "Integer" and "Variant" above.

The code we use relies heavily on variables which are assigned values, then are cleared of those
values and given new values as the code operates. Even when a variable is cleared of any value (i.e.
value=null) the variable still exists, and can be assigned another value of the data type indicated.

"Variant" is the broadest type of data that can be assigned to a variable, and includes text, numbers,
names, etc. "Integer" can only contain positive whole numbers, and is used in our code for numeric
sequences such as 1,2,3,...500. A subroutine usually has to have at least 1 variable, so the "Dim" line
is mandatory.

For...Next Loops

For rowcount = 1 To Range("Data").Rows.Count

...CODE HERE...

Exit For

Next rowcount

"For...Next" loops are used where an operation is repeated sequentially for each of a long list of
items. The stock model uses "For...Next" loops by going down a list of ticker symbols (located in the
Range called "Data"), selecting price data for that ticker symbol, doing calculations, and outputting
trading signals.

In the code above "rowcount" is a variable which is assigned an integer ranging from 1 to the number
of rows in the range called "Data". The code starts with the first ticker in row 1, goes through the
necessary operations to generate a trading signal for that ticeker, then "loops" back up to the top and
advances to the ticker in row 2, repeating over and over until trading signals for all the ticker symbols
are calculated.

In "For...Next" loops it is crucial to tell the computer when the loop should stop. This is provided by
the "Exit For" command, written in the form "If X occurs Then Exit For". In the model, if a blank row
is found, there are no more tickers left in the "Data" range, or the code has looped through all
available rows in the "Data" range, the "Exit For" command takes action and the loop is stopped. If an
"Exit For" command is not included, the "For...Next" loop will continue forever without stopping
(this is bad).

If...Then...Else...End If

If ADX > 10 And MA5 > MA20 And DMIup > DMIdn Then

signal = "Buy"

ElseIf ADX > 10 And MA5 < MA20 And DMIup < DMIdn Then

signal = "Sell"
Else: signal = "OUT"

End If

"If...Then" statements are the foundation of our stock trading model. Line 1-2 above is an "If" line: It
says "If ADX is greater than 10, and 5-Period Moving Average is greater than 20-Period Moving
Average, and DMI+ is greater than DMI-, then issue a Buy signal." Line 3-4 is an "Else" line: It says
"If any one of the conditions in Line 1 are NOT true, then follow an alternative logic that might lead to
a Sell signal." Line 5 is also an "Else" line: It says, "If none of the conditions in Line 1 or Line 3 are
true, then simply give an OUT signal". Line 6 is the "End" line which says "once all the logical rules
above are processed through, stop applying any more rules and move on to the next piece of code."

"If...Then" statements can be "nested". One set can fit inside another set. In addition, there can be an
infinite number of "ElseIf" statements. These two factors allow a programmer to write lots of logical
complexity into a trading model. Our trading model is not particularly complex, but it is effective and
easy to understand.
Checking for Code Errors

It is important to pinpoint syntax or other errors in the VBA macro code you write. This is done by
"debugging" the code -- by simply running it and seeing what happens, then fixing any errors as they
appear.

When a piece of code has an error, the VB Editor highlights it in yellow, and a popup box appears
with a message that might tell you what the real problem is. You will usually have to read the code
and identify the error yourself, then fix it and click "resume" on the toolbar -- if the code processes on
without fault, the fix is successful. If not, the VB Editor will highlight it again. The code provided
should not have any errors, as long as you copy it directly into the Excel code module from this
document or the VBACODE_StockModel.txt file.

Here's what a typical code error looks like when it occurs in the VB Editor window:

To prevent code errors before they occur, take the time to do the following steps:

1) Single quotes ( ‘ ) indicate comments in the code—did you forget any?

2) Double quotes ( “ “ ) indicate ranges—did you forget any?

3) Periods ( . ) separate objects and properties—did you forget any?

4) Colons ( : ) separate commands—did you forget any?

5) Check for missing variables and misspelled variables (things in the Dim statement lines are
variables).
6) Check for greater than ( > ) and less than ( < ) typos.

7) Check for misspellings, however minute.

8) Check for UPPERCASE-lowercase conflicts between the code and worksheet, workbook, and
range names. Names in the code and the Excel workbook must match perfectly.

9) Check for any other problems, however minute.

10) Recheck everything again.

See the Common Macro Errors section for further information.


Building the Signals Worksheet
In this section we will set up the Signals worksheet. This is the control center of our trading model.
We will create labels and formulas, build cell ranges, and name the ranges so the VBA code knows
where to look for data and insert the results of its calculations. After this is done, we will add a
control button to activate the model automatically with one click of the mouse.
Setting Up the Column Headers

First, go to the Signals worksheet and type the following header labels in cells A2 through K2 as
shown:
Creating the Ranges

Next, you will need to build three data ranges. A "range" in Excel is a pre-defined block of cells that
is given a name. So, instead of referring to "cells A2 through Z500" you can assign a short name to
that block of cells, such as "Trade_Block". You can then use the name itself in the VBA code.

We need to create three ranges called Data, Signal and Oscillating_Zone.

IMPORTANT!

Make sure you type in the range names EXACTLY as shown -- be careful to use the correct
combination of CAPS and lowercase (e.g. "Data" not "data"). Otherwise the model will not
work.

Building ranges is done differently in Excel 2007 and Excel 2010:

Excel 2010

To build the Data range:

1) Highlight cells A3 to G103.


2) Go to the Formulas tab and click the Name Manager icon. In the Name Manager popup
click New. Type in type Name: Data, Scope: Workbook and Refers to:
=Signals!$A$3:$G$103 then click OK. This gives the block of cells from A3 to G103 the
name “Data” so the VBA code can refer to it.
To build the Signal range:

1) Highlight cells H3 to H103.


2) Go to the Formulas tab and click the Name Manager icon. In the Name Manager popup
click New. Type in type Name: Signal, Scope: Workbook and Refers to:
=Signals!$H$3:$H$103 then click OK.
Finally, to build the Oscillating_Zone range:

1) Highlight cell K2.


2) Go to the Formulas tab and click the Name Manager icon. In the Name Manager popup
click New. Type in type Name: Oscillating_Zone, Scope: Workbook and Refers to:
=Signals!$K$2 then click OK. This is where you check the box so the model will give
signals during range-trading periods. If this cell is left empty the model will not give any
signals during range-trading periods. If you put an “X” or “Yes” or anything else in this cell,
the model will give you range-trading signals during oscillating periods.
Excel 2007
To build the Data range:

1) Highlight cells A3 to G103.


2) Go to the Formulas tab and click the Name Manager > Define Name or New… icon or
Ctrl+F3. Type in the word "Data" and click [OK]. This gives the block of cells from A3 to
G103 the name “Data” so the VBA code can refer to it.

To build the Signal range:

1) Highlight cells H3 to H103.


2) Go to the Formulas tab and click the Name Manager > Define Name icon or Ctrl+F3.
Type in the word "Signal" and click [OK].
Finally, to build the Oscillating_Zone range:

1) Highlight cell K2.


2) Go to the Formulas tab and click the Name Manager > Define Name icon or Ctrl+F3.
Type in the word "Oscillating_Zone" and click [OK]. This is where you check the box so
the model will give signals during range-trading periods. If this cell is left empty the model
will not give any signals during range-trading periods. If you put an “X” or “Yes” or anything
else in this cell the model will give you range-trading signals during oscillating periods.
Adding a Control Button

There are two ways to run a VBA macro -- either by selecting from a list of macros, or by setting up a
control button to run the macro automatically. The first method is a bit cumbersome so we will set up
a control button.

This is done the same in Excel 2007 and 2010. The icons just look slightly different.

1) Make sure you are in the Signals sheet and select cell J4.
2) Go to the Developer tab and click the Insert Controls icon.

3) In the ActiveX controls section select Command Button (ActiveX Control). Your
cursor will turn into a small cross that allows you to draw a button on the worksheet
wherever you want it. Draw a button the size you want starting in cell J4. The button will be
labeled “CommandButton1”.

4) Right-click the button you have just drawn. A pull-down menu will appear. Select the
CommandButton Object > Edit option. This allows you to change the label on the button.
Change the label to Run Model and hit the [Esc] key on the keyboard to exit.
5) Right-click the button again. This time, select the View Code option.

This makes the Visual Basic Editor window open up with the following code already inserted:

Private Sub CommandButton1_Click()


End Sub

Add another line to the code so it reads as follows:

Private Sub CommandButton1_Click()


Call Run_Model
End Sub

6) Go back to the Developer tab controls and un-click the Design Mode icon. This takes
you out of Design Mode and activates the control button.
Adding Ticker Symbols to the Signals Worksheet

The trading model uses a list of stock ticker symbols as the primary point of reference. Each stock
ticker symbol in the list is used to tell Excel where to look for price data, how to run the trading
signal calculations, and where to put the trade signals for that stock. A large number of ticker symbols
can be used in the model at a time. If you want to expand the number of tickers, just increase the size
of the "Data" and "Signal" ranges described above. The number of stocks you can run in the model is
only limited by the number of tabs you can insert in the DATAv3.xlsm workbook (we will this build
later).

Once you have chosen a list of stocks to use in the model, type them into the model beginning with
cell A3, moving down cell-by-cell, as shown below.

IMPORTANT! Ticker symbols MUST be typed in ALLCAPS in cells A3 through A103. Do not
skip rows between ticker symbols.

DO NOT insert cells, move things around, or delete anything in the Signals worksheet. This will
definitely break the model.

Below is an example of a finished and formatted Signals worksheet. Feel free to reformat the
worksheet colors, fonts, cell borders, etc. These things have no effect on the functionality of the
model as long as you do not change any cell, row, or column locations.
You are now done with the Signals worksheet.

Save your Modelv3.xlsm file, plus one backup file called Modelv3BACKUP.xlsm in the “Model”
folder and a USB drive to protect your work.
Building the Data Source File
NOTE: This lesson uses DownloaderXL as a working example:

http://www.financial-edu.com/downloaderxl-pro.php

If you use another data provider with a DDE or ActiveX link to import data into Excel, consult
your data provider’s process manual to set it up properly.

We will now build a second "data hub" Excel workbook to act as the repository for stock price and
volume data. There are two benefits to using a second file, rather than storing the source data directly
in our trading model: 1) It makes the trading model file much smaller, simpler, and easier to manage,
and 2) The source file can hold many more stocks and can be used as a “data hub” for other models.

The focus in this section is on using a DDE/ActiveX add-in application for Excel to populate the
price data. These are available from a number of data providers and online brokers such as
Interactive Brokers, Reuters, Bloomberg, IDC, Money.net, eSignal, etc.

If you do not have access to a DDE/ActiveX link you will need to first build the DATAv3.xlsm file as
shown in steps 1) through 5) below, then populate it with .CSV or .TXT files. See the Data from
Other Sources section on how to import data from Yahoo Finance.

We will use DownloaderXL http://www.financial-edu.com/downloaderxl-pro.php with Yahoo


Finance data as our DDE/ActiveX example. DownloaderXL is great because you only pay once and
get free data for life, as opposed to subscription services which can cost a lot of money over time.

You can also manually populate the DATAv3.xlsm file after you build it (see the Data from Other
Sources section). This is very time-consuming and is not recommended with more than 5-10 stocks.
Steps to Build the DATA Source File

NOTE: If you plan to use .CSV or .TXT data instead of a DDE/ActiveX link, then build your
DATAv3.xlsm file and go directly to the Data from Other Sources section.

1) Open a new Excel workbook and save it exactly as C:/Stocks/Data/DATAv3.xlsm.


Remember to save it as a "Macro-Enabled Workbook". Be careful to use the correct
spelling and UPPER and lower case in the file name.

2) For each ticker symbol in the Signals sheet, you need a tab with the same ticker symbol in
the DATAv3.xlsm workbook. On the toolbar click Insert > Worksheet or click the “+” sign
at the bottom and add new sheets until you have one for each ticker symbol. Double-click the
sheet and rename it in ALLCAPS to match each of your ticker symbols similar to the
image below:

3) Go to the worksheet for your first ticker symbol. Enter the first ticker symbol in cell A1.

4) Continue adding your ticker symbols in cell A1 of the remaining worksheets until you are
done with your list of stock tickers.

5) Save and back up the DATAv3.xlsm file.

Importing Price Data with DownloaderXL


NOTE: If you plan to use .CSV or .TXT data instead of a DDE/ActiveX link then go directly to
the Data from Other Sources section.

1) Purchase DownloaderXL Pro for Excel 2010 and Excel 2013 here http://www.financial-
edu.com/downloaderxl-pro.php. Install it according to the instructions, using the default
values in the installation process.

2) In the DATAv3.xlsm workbook go to the first worksheet you want to update. Select cell
A2.
3) Go to the Add-Ins tab and click DownloaderXL Manager. This launches the
DownloaderXL Pro Add-In.

4) Configure the settings EXACTLY as shown below.


Tickers & Sources tab: set Data source = Yahoo! Finance, then add your tickers in the
Tickers list, select Date, Open, High, Low, Close, Volume, Adj. Close and uncheck the Draw
Chart box.

Parameters tab: set End date = today and Start date 5 months in the past. This
guarantees we import at least 100 days of price data for the model calculations. Check the
Floating radio button so updates always end at the current date. Set Periodicity = Daily and
Direction of data = From bottom to top.

IMPORTANT: The latest date MUST be at the top of the Data sheet!
Preferences tab: check Remember last settings, Destination sheet = Existing, Sheet
name prefix = blank, Beginning of data = A2 and Table style = None.

5) Click the Download data button. You should see a download progress bar as
DownloaderXL imports the price and volume data.
This is how each worksheet should look once DownloaderXL is done populating the data:

IMPORTANT:

The latest date must be at the top. If the earliest date is at the top, re-launch the DownloaderXL
add-in, go back to the Parameters tab and set Direction of data = From bottom to top.

Before running your Excel model, you will need to update the prices with DownloaderXL and
allow it to fully populate the price data. The model needs updated data to work properly.

Save the file immediately and back it up to prevent losing your work!
If you elect to use another DDE data source than DownloaderXL, you will have to build the new DDE
or ActiveX link formulas into the Data workbook.

If you are not using a DDE/ActiveX application, the worksheets in your DATAv3.xlsm file should
also look like this, but there will be no DDE formulas.

Now that you have the Data sheet set up, you are ready to run your model.
Loading Data from other Sources
If you do not have access to a DDE/ActiveX data link or an Internet data provider, you will need to
obtain and populate the DATAv3.xlsm file manually with .CSV or .TXT data files. This is not
recommended for more than 5 stocks, because it can be very time-consuming.

NOTE: In your data source make sure there are exactly 6 data fields in the correct order (i.e.
Day, Open, High, Low, Close, Volume).
Getting Free Historical .CSV or .TXT Files from Yahoo Finance

You can get free ASCII .TXT historical 20-minute delayed data files from the Yahoo Finance website
as follows (this may change without notice):

1) Go to http://finance.yahoo.com and enter a ticker symbol in the Enter Symbol(s) box at


the top.

2) Click historical prices

3) Check the Daily radio button. Enter a date range covering at least 100 days and click
Get Prices.

4) At the bottom of the HTML price-volume grid is a link Download to Spreadsheet.


Click the link and save the file, or right-click the link and "save target as" to the desired
folder.

NOTE: Make sure you split-adjust the Yahoo Finance historical data. If you see a huge drop in
past prices, it's usually a split. Adjust the data before the split by dividing by the number of
shares 1 share was split into. For example if XXX split 2-for-1, divide the Open, High, Low, and
Close prices by 2 prior to the split date. You will notice this if you have huge jumps or drops in
system equity in the BackTest model.
Using .CSV or .TXT Source Data Files

Follow these steps to use .CSV or .TXT data files from Yahoo Finance or another provider with the
DATAv3.xlsm "data hub" workbook.

IMPORTANT: If you are using data from another source other than Yahoo Finance, then make
sure the latest prices are pasted into row 4 of the appropriate DATAv3.xlsm worksheet. You do
not need the header row for the model to run properly, but you do need the latest day’s prices in
row 4, with the date in cell A4.

1) Open the .CSV or .TXT data file with Excel.

2) If necessary, arrange the data columns in the following order: Day, Open, High, Low,
Close, Volume, Adj. Close (optional).

3) Highlight and copy a block of at least 101 days of data. Start in cell A1 on the upper
left and end with the column F on the lower right.

4) Switch to the DATAv3.xlsm workbook, select the correct stock ticker sheet and click
Edit > Paste Special > Values in cell A3 (if your data has headers) or cell A4 (if your data
lacks headers).

IMPORTANT! Make sure the latest day’s prices are in row 4, with the date in cell A4.

5) Repeat steps 1) through 4) for every stock you intend to run in the model.

Here is what your worksheet should look like when you are finished pasting in the data:

Save your DATAv3.xlsm file, plus one backup file in the C:/Stocks/Data folder and a USB drive.
Now that you have the "data hub" Excel workbook set up, you are ready to run the model.
Running the Model on a Daily Basis
The trading model is designed to be run on a daily basis after the close of the trading day. Trades
should be entered so that they execute at or near the open of the following day.
Running the Model for the First Time

The first time you run the model all signals will be new. It is best to run the model for a week or two
without entering any trades so you can get a feel for when the trade signals occur. This will help you
understand when to rely or not on the model's signals.

Focus on the NEW signals. The system logic is designed to generate trade signals when the
probabilities of profit are highest and likelihood of losses are lowest. If you enter after a "Buy" or
"Sell" signal has been in play for a while, you risk entering at the tail end of a major move when the
likelihood of a reversal against you is greater. Try not to succumb to the "buy high, sell low"
temptation that plagues many inexperienced investors.
How to Run the Model

1) Open your Internet connection (or gather your .CSV or .TXT data files)

2) Open your DDE/ActiveX link (if applicable)

3) Open the DATAv3.xlsm file and populate it with stock price and volume data (or manually
copy data into it)

4) Open the Modelv3.xlsm file

5) Click the "Run Model" button on the Signals page

6) Save the file and back it up. The model does this automatically for you – just click “OK”
when it asks.

When the model is running, the screen will flash back and forth between the Signals worksheet in the
Modelv3.xlsm workbook and the data source worksheets in the DATAv3.xlsm workbook. This occurs
because "screen updating" is left on so it is easy to debug the model if the code stops due to a data
problem or some other reason. With "screen updating" off, the model operates faster but does not give
as much feedback.

If you do not want the screen to flash, simply add the following line of code after Sub Signals()

Application.Screenupdating="false"

Here is what your Signals worksheet should look like after it runs:
Trading Signals and What They Mean

The model generates three signals. Here is what they mean and what you should do:

Buy = enter a new long position

Sell = enter a new short position (or exit your existing long position for long-only traders)

OUT = exit any long position or short position so you have no position
Entry-Exit Techniques

Choosing which new trade entry method to use can be subjective. You can enter "at the market"
(market order), "on a stop" (stop order) or "at a limit price" (limit order). What entry technique you
use is up to you.

The benefit of market orders is you are almost guaranteed an entry somewhere near the opening price.
The downside is that significant morning volatility might lead to overpaying or underselling at a less-
than-profitable price.

The benefit of stop orders is that your entry occurs only when the stock is moving in the desired
direction (for example if you set a buy stop at or just above the prior day's closing price and it was
triggered as the stock moved up). The downside of stop orders is you may give up the opportunity to
buy at a lower price or sell short at a higher price.

Finally, the benefit of limit orders is the ability to target a specific entry price, but the downside is
that you often miss an entry and lose out on a profitable move.

Likewise, exit techniques are extremely important. You should use BOTH of the following
techniques: a) market order exits when the model says "OUT" and b) a trailing stop to prevent
large losses and protect profits. You can trail a stop below a long position or above a short position
using various techniques such as 10-, 15-, or 20-day previous low/high, average true range (ATR), or
a parabolic stop like Stop-and-Reverse (SAR). The simplest way is to trail a stop at the prior 15-day
high or low. Your experience and stock choices will lead you to the best stop for your purposes, but
always use a stop!
Risk Management and Limiting Losses

Remember, the model is a tool, not a holy grail. You must still use your understanding of the markets
to maximize returns and minimize risk. Although the model does much of the "heavy lifting" by
filtering out good entry and exit points, models have strengths and weaknesses. It is best combined
with some technical graph analysis and fundamental analysis to focus on the most profitable
opportunities. Not every signal the model generates will be profitable--many will be losses. It is up
to you to apply sound money management strategies to limit losses when they occur.

Risk management techniques you should use include:

1) Trailing stops (discussed above).

2) Diversification. Try to spread your available capital around 10 or more stocks in different
industry sectors and market capitalizations. Do not spread too thin, or you will lose too much
money on transaction costs per unit of profit you earn.

3) Long AND Short. Do not hold positions all in the same direction long or short. Keep at
least a few stocks that are lagging or outperforming the market and hold positions in them in
the opposite direction (let the model identify which ones). This cushions unforeseen price
shocks. Studies have proven that 70% long / 30% short portfolios generate greater returns and
less risk over time than 100% long or 100% short portfolios.

4) Go to cash when necessary. If there are no good signals, stay out of the market.

5) Minimize trading costs. Use a discount broker charging less than US$10 per trade. A
US$50 per trade account is not the place to use short term techniques. Also, make sure you
take positions greater than US$1,000 in dollar size, otherwise trading costs tend to eat into
your profits significantly.

6) Maintain equal position sizes. Don't "double down" on a particular stock unless you
hedge the risk somewhere else.
Common VBA Macro Errors
Many VBA code errors, how Excel handles them, and the likely solution are presented below.
Missing or Misspelled File Name

This occurs when you leave out or misspell a file name called out in the code. It is critical that you
spell file names correctly AND use the correct combination of lower case and UPPER case letters in
the code when referring to a file name. The DATAv3.xlsm workbook should NOT be spelled
"dataV3.xlsm" or "DATAV3.XLSM"or "Datav3.xlsm" or "dAtAV3.XLSM". If you misspell a file
name you will get a “subscript out of range” error like the one shown below.

Fix the issue by making sure the file name in the VBA code matches the actual file name.
Missing Single Quote in Comment Lines

This occurs when you leave out a single quote ( ' ) before your code comments. Excel thinks the
comment is actual code and tries to run it.

Fix this issue by adding a single quote to the highlighted line.


Bad Single Quote in Comment Lines

This occurs when the single quotes (') before your code comments are there but Excel does not
recognize them. When some users copy the code from the course materials and past it into the VBA
Editor, the single quotes are not properly transferred.

Fix this issue by retyping all the single quotes at the beginning of all the comment lines, or removing
the comment lines completely.
Missing or Misspelled Range Name

This occurs when you forget or misspell a range name defined in one of the Excel worksheets. Excel
looks for the range name, but cannot find it and generates a global object "range" error.

Fix this issue by retyping the correct range name with the right spelling and capitalization into the
VBA code.
Missing "End If" in If-Then Statement

All If-Then statements, whether they are nested or not, require an "End If" at the end. This is one of
the most difficult errors to detect if you also use For-Next loops in the code, because the VB Editor
thinks the error is in the For-Next loop instead of the If-Then statement.

Fix this issue by checking for missing “End If” lines in every If-Then sequence, and adding them if
missing.

There are a virtually unlimited number of VBA macro errors you might come across. The best tools to
identify and fix them are the VB Editor's debugging tools under "Debug" in the VB Editor tool bar.
Combining the debug functions with your own visual scan of the VBA code will allow you to identify
and fix most problems.
Back Testing the Model
CFTC RULE 4.41 - HYPOTHETICAL OR SIMULATED PERFORMANCE RESULTS HAVE
CERTAIN LIMITATIONS. UNLIKE AN ACTUAL PERFORMANCE RECORD, SIMULATED
RESULTS DO NOT REPRESENT ACTUAL TRADING. ALSO, SINCE THE TRADES HAVE NOT
BEEN EXECUTED, THE RESULTS MAY HAVE UNDER-OR-OVER COMPENSATED FOR THE
IMPACT, IF ANY, OF CERTAIN MARKET FACTORS, SUCH AS LACK OF LIQUIDITY.
SIMULATED TRADING PROGRAMS IN GENERAL ARE ALSO SUBJECT TO THE FACT THAT
THEY ARE DESIGNED WITH THE BENEFIT OF HINDSIGHT. NO REPRESENTATION IS
BEING MADE THAT ANY ACCOUNT WILL OR IS LIKELY TO ACHIEVE PROFIT OR LOSSES
SIMILAR TO THOSE SHOWN.
How to Get Your Free Back Testing Model

This course includes a free back testing model. It is very useful for researching how the model may
have performed in the past using historical stock price data.

To get your back testing model visit http://exceltradingmodels.com/backtest/ and enter your email and
order number in the “Stock Backtest Model” form.

You will automatically be emailed the back testing model and instructions.

NOTE: Don’t forget to save the model on your hard drive and back it up to a USB drive for safe
keeping.
Instructions for using the Back Test Model

If the back test model shows consistent positive performance over time for a particular stock, this an
indicator that the model may generate positive performance in the future. If back testing shows a
stock performed poorly over time in the past, you may choose to leave that stock out of your list of
stocks for your trading.

Here is how you set up and use the back test model:

1) Unzip the file with WinZip (www.winzip.com) or other free unzip utility. Save it to your
hard drive and back it up.

2) Open the file in Excel.

3) Obtain .CSV, .TXT, or Excel files with 2-10 years of daily data in the form of Date-
Open-High-Low-Close-Volume for every stock you want to back test.

NOTE: Make sure you use split-adjusted historical price data. If you see a huge drop in past
prices, it's usually a split. Adjust the data before the split by dividing by the number of shares 1
share was split into. For example if XXX split 2-for-1, divide the Open, High, Low, and Close
prices by 2 prior to the split date. You will notice this if you have huge jumps or drops in system
equity in the Back Test model.

4) Open the data file for your first stock

5) Highlight all the price and volume data below the header row. Click the Data tab and
Sort by: Date, Sort on: Values, Order: Newest to Oldest as shown below. This sorts the
data so the latest date is at the top. This is mandatory for the back test model to work.

6) Copy the highlighted data, and switch to the back test model Data worksheet.
NOTE: You may need to clear out the existing data in cells A3 through F10000 first. CAUTION!
Use the "clear" function NOT "delete" or you may break the back test formulas!

7) Edit > Paste Special > Values all the copied data into cell A3. The trading signals will
automatically calculate.

8) Switch to the Performance & Statistics worksheet to see the statistical and graphical
back test performance of your chosen stock. The charts show Combined results and
drawdowns, Stochastic-only results, and Trend-only results.

9) Repeat the steps above for each stock you wish to back test.
Adjusting the Back Test Model

You can adjust the inputs to the back test model in the Controls sheet. However, you must ensure
both the trading and back test model use the same settings for the test results to be valid. Otherwise
you will not be trading the same model you’re testing!

The variables you can change are:

Stochastic ON or OFF (preset to ON)

Commission per Trade (preset at $10, can be adjusted to your broker's commission rate)

Slippage per Trade (preset at $50, can be adjusted up or down depending on account size and
liquidity of stock)

Leverage (preset at 1.5, meaning the model assumes you buy or sell short 1.5 your available equity
per trade. We have found moderate leverage can help the model perform better on a risk-adjusted
basis.)

ADX trend threshold (preset at 10, can be changed between 5 and 30)

Bollinger Band standard deviations (preset at 1.5, can be changed between 1 and 2)

Model Starting Equity (preset at $10,000, can be adjusted to your account size)
Frequently Asked Questions (FAQs)
This section includes answers to a number of the most frequently asked questions. For more answers
on the intricacies of VBA and using the model please visit this page:

http://exceltradingmodels.com/category/faqs/

The VBA macro code isn't working. What do I do?

First, see the previous section and try the various solutions to the problems there. Then go through the
FAQs below.

The macro stopped in the middle and there are many #DIV/0! errors in the Calculations sheet.

This is caused by data with gaps in it. When there are zeros in the price data or missing rows of data,
the technical indicators cannot calculate properly, potentially causing #DIV/0! (divided by zero)
errors.

The problem shown above is caused by the zeros in the High, Low, and Close price columns C, D,
and E of the Calculations sheet. The zeros are causing the ADX/DMI formulas to generate #DIV/0!
Errors when used in the denominator of a calculation.

The first place to look is the DATA.xlsm workbook -- occasionally the DDE links do not populate
properly and need to be restarted, or the data provider's system is generating zeros. Another reason
might be that the stock was delisted, changed ticker symbols, or was acquired. The solution is to
either 1) remove the problem stock from the model, or 2) clean the data manually by copying good
data from another source over the zeros or missing data in the Calculations sheet. After you have done
one of these two, simply resume the macro by clicking the "resume macro" toolbar button in the VB
Editor window. You should invest in a good data provider that guarantees data accuracy and
completeness.

I am having difficulty getting one section of the code to work. Some of the code is highlighted in
dark blue, and some is highlighted in yellow.

Most problems are typically caused by a missing or misnamed .csv data file, ticker symbol, or data
range. If any components of the model are not complete, the code will not work properly -- this is
common during a model building project. The VBA code is not smart, so things like ALLCAPS and
syntax must match between the code and file names, etc.

When a section of code is highlighted in the debugger window, it helps to move the cursor over
different code elements in the area above the location of the highlighted code. Look for a variable
name you set in the "Dim" statement, such as a range name, worksheet name, or file name -- when the
cursor hovers over a variable, the value it contains will appear. This gives you a clue about where to
look for a missing name or mismatch.

Can the formulas be modified to use different length moving averages, etc.?

Yes, you can modify the formulas. Of course, the model is likely to behave differently – back testing
will show the potential differences. Make sure you don't "over-optimize" and end up curve fitting
your results. Also, make sure that your trading model and the back test model use exactly the same
logic and input values -- do not make the mistake of back testing a different model than you are
trading!

With Yahoo Finance price data, do I use the 'Close' or 'Adjusted Price'?

Use the Close price instead of Adjusted Price with Yahoo Finance data. However, you must make
sure the prices are split-adjusted.

If you see a huge drop in past prices, it's usually a split. Adjust the data before the split by dividing by
the number of shares 1 share was split into. For example if XXX split 2-for-1, divide the Open, High,
Low, and Close prices by 2 prior to the split date. You will notice this if you have huge jumps or
drops in system equity in the back test model.

Can the back testing model be adjusted? Can I use different lengths for the indicators? Can I
adjust for commissions, slippage and available equity?

Yes, you can change several of the variables in the back test model. However, it is important to
understand that you will also have to change the trading model formulas and VBA code to match the
back testing model if you choose to trade with the new parameters. It is generally not a good idea to
optimize the back testing model too much. Over-optimizing the back testing inputs can produce a
false sense of accuracy and performance that may not be translated into future market conditions.
Rather, it is always better to use the same general variables across a variety of securities and
historical time periods to determine if the model may behave profitably in the future.

The variables you can change are below. These are highlighted in yellow with blue text in the back
testing model.

Bollinger Band standard deviations (preset at 1.5, can be reduced to 1 or increased to 2)

ADX trend cutoff length (can be changed between 10 and 30)

Starting Equity (preset at $10,000, can be adjusted to your account size)

Commission per Trade (preset at $10, can be adjusted to your broker's commission rate)

Price Slippage per Trade (preset at $50, can be adjusted depending on account size)

What are the back testing model assumptions?

The back testing model makes several assumptions. It is important to understand that these
assumptions may not be true in real life trading. Trading profits and losses are dependent on a wide
variety of factors which may or may not be in the trader's control, such as amount of capital, what
time during the day a trade is executed, how liquid the stock is, what stocks you are trading, how you
enter and exit (stops, targets, market, limit), commissions, speed of execution, price slippage, etc.

That being said, the back testing model assumes the following:

1) The model generates BUY/SELL/OUT signals today, and you enter or exit at tomorrow's
Open price.
2) A commission is charged on each trade.
3) There is some price slippage in each trade (you enter and exit on a worse price than
shown in the price data).
4) Leverage may be used. This is defined in the Leverage variable cell.
5) All available capital is used for each trade.
6) Trades are executed solely based on the model's signals. No stops or targets are used to
enter or exit positions.
7) The entire position is entered in one trade and exited in one trade. There is no scaling in
or out of positions.

Can the model be built so that trades actually get executed through my broker using Excel?

In order to execute trades directly from Excel you will need an Excel add-in from your broker that
allows orders to be sent directly to the broker's system. Interactive Brokers is the most popular one,
but they are available from other brokers.

How the add-in executes trades directly from Excel is unique to each broker. Your broker's Excel API
is designed to interact with its unique order management system. The API must incorporate some
security and encryption features to prevent unauthorized access to the order system.

This type of project can involve a fair amount of programming. Contact your broker to determine if
it's something you can do on your own.

How does the model handle stock splits?

Splits are tricky with any trading system. It really depends on how your data provider handles them.
Normally data providers automatically split-adjust their historical data. Splits are not surprise events
-- companies must notify the exchange several weeks at a minimum before actually splitting, so a
competent data provider has plenty of time to make the adjustment. In fact, most of them buy and
resell data from the exchanges, so it's already done for them. Can you imagine how much money
would be gained and lost on a split day at the NYSE otherwise?

If you see a huge drop in past prices, it's usually a split. Adjust the data before the split by dividing by
the number of shares 1 share was split into. For example if XXX split 2-for-1, divide the Open, High,
Low, and Close prices by 2 prior to the split date. You will notice this if you have huge jumps or
drops in system equity in the back test model.

Splits are a data issue, not a system issue. Use split-adjusted data wherever you can.

The day a stock splits there is often a huge spike in volume and upward price movement. This is
normally preceded by a big volume spike when the split announcement is made -- in anticipation of
subsequent upward move. The model can often give a short signal on these spikes. These types of
signals are rare, but they usually occur when the stock is "tied up" -- when the moving averages are
unwinding and there's a sudden move outside the normal volatility range. The model will fade those
rare moves. In the case of a split, the spike is backed up by fundamental information that makes it a
bad trade. Your stops should take you out, or you should not obey the trade signal in the first place if
you know about the split.

I copied the VBA macro code from the site but it doesn't work correctly. The Visual Basic model
then pops-up showing the "Sub Run_Model()" (with those words highlighted in yellow). A
message states "Compile error:", "Syntax error".

There are multiple comment lines in the code like this:

’open data .csv file and copy column B data to Data sheet

The problem is the single quote mark at the beginning of the line. This quote mark may have copied
incorrectly from the course materials to your code module. The fix is to highlight all the code in the
VBA module and use the find > replace function to replace all the single quotes ( ' ) [leave the
parentheses out].

I want to make this model work on real time data. If I write a program to poll data at 5 minute
intervals from Yahoo or other sites, and populate the excel data sheet, will the model work?

You can import real time data into the stock data workbook then do either of two things:

a) Create a macro that runs the model on set periods, depending on the data period you use (5 min, 15
min, 60 min, etc.). This is easier.

b) Run the model manually on set periods by clicking the Run Model button.

Regarding whether the model will work with intra-day data: there are too many variables (stocks
chosen, liquidity, spreads, commissions, market conditions, etc.) to predict performance. This is the
case with any model. We have had good success with the model using daily data for a number of
years. You may need to adjust the parameters to make it work intra-day.

I was not able to figure out what approximate price do I enter the market (buy/sell a stock) and
at which price I exit (Out)?

The model is designed to enter/exit at the next bar open. It does not assume target or limit prices.

Regarding probable entry/exit prices, most low frequency trading systems will operate on a particular
bar interval (1 min, 5 min, 60 min, daily, etc.) then enter/exit at a point in the next bar once the
indicators are set. Most automated systems assume entry/exit at the open of the next bar -- in other
words, at the market. This is the case with TradeStation and other popular software packages. You
can also set limit entry and exit prices, but the important thing to remember is there is no guarantee
that those prices will be hit. Assuming limit orders will be executed at your desired price (or
executed at all) introduces a false assumption into your system and back test results. Remember,
probabilities are not actualities and there are hundreds of variables that can make a system look good
on paper but lose money in real trading.

High-frequency systems deal in tick-level data, which assumes a much higher level of
computing/network infrastructure. It also assumes a much lower (or zero) commission rate -- in other
words you are a broker-dealer. Otherwise you will lose money. Excel is not the environment for
high-frequency trading.

Can you recommend other tools to download and/or import price data into Excel automatically?

NOTE: This customer asked the more detailed question below.


Question:

I’m trying to download data from the Internet and I can get the data into EXCEL doing a web query,
but when I try to set up the spreadsheet, 2 undesirable things happen;

1-EXCEL captures needless info surrounding the true number I want. I delete this unwanted info so
that the true number is left in the appropriate row and column, but

2- Then EXCEL downloads the next true number into the SAME cell deleting the prior true number so
that I am unable to graph anything.

Answer:

Everybody who tries to do a web query directly from Excel runs into the same barriers you have. The
painless solution for getting price quote data into Excel efficiently is to buy a proper quote download
tool like DownloaderXL http://financial-edu.com/downloaderxl-pro.php

DownloaderXL is an outstanding tool to have. The delayed data is from Yahoo Finance (stocks,
indices, funds, ETFs), Google Finance (stocks, ETFs), PiFin (FX, futures, indices) and CBOE
(options). It does an excellent job of pulling in data from free web servers and comes with a bunch of
other features like one-click updates. We guarantee you will use it regularly. Trust us the value of your
time and headaches saved is way more than the cost of the software!

Don't see an answer to your question?

First, visit http://exceltradingmodels.com/category/faqs/ If you still cannot find an answer, send an


email to help@financial-edu.com and we will do our best to help.

Potrebbero piacerti anche