31.07.2021 Views

Ultimate Algorithmic Trading System

Using automated systems for trading in stock markets

Using automated systems for trading in stock markets

SHOW MORE
SHOW LESS

Create successful ePaper yourself

Turn your PDF publications into a flip-book with our unique Google optimized e-Paper software.

function modules and some are a little more sophisticated and are programmed as

a class structure. I said you would be exposed to procedural (functions) and objectoriented

(classes) programming. Let’s start slowly with a simple indicator function.

sAverage

def sAverage(prices,lookBack,curBar,offset):

result = 0.0

for index in range((curBar - offset) - (lookBack-1),

curBar - offset +1):

result = result + prices[index]

result = result/float(lookBack)

return result

172

USING PYTHON TO BACKTEST YOUR ALGORITHM

This looks pretty palatable! All functions or, if you like, subprograms, use the

key word def to let the interpreter know a function is about to be defined. The

function has to have a name, and in this case it is sAverage (simple moving average).

Remember how we called functions in AFL and VBA? You do it exactly the same way

in Python. The list of arguments or parameters that are included in the parentheses

after the function name are known as the formal argument list. These parameters are

called formal because they’re included in the function definition. Since we are using

Python you don’t need to employ function prototyping or forward declaration.

In other words, you don’t need to tell the interpreter the types of the arguments

before-hand. The sAverage function requires four parameters:

prices. This is a list of price data (open, high, low, close, volume, or open

interest). In this application of Python, we will be using the word list instead of

array, but know they mean basically the same thing. The Python list structure is

very powerful as you will find out.

lookback. The number of days in the calculation of the indicator. This would

equate to 20 in a 20-day moving average.

curBar. Simply the historic bar being evaluated.

offset. Just like the ESB, this number will usually be set to one. The indicator

value from the prior day. You can go offset with a more positive number. If you

use two, then it will return the indicator value form two days prior.

Notice the colon (:) at the end of the function definition. The colon tells the

interpreter that the indented code (four spaces) below is controlled by the current

line. So everything that is indented below the function definition header is included

in the function. Indentation is very important in Python. Don’t use tabs to indent;

simply hit the spacebar four times. Don’t forget this—spacebar four times. Things

will become much clearer very quickly.

www.rasabourse.com

Hooray! Your file is uploaded and ready to be published.

Saved successfully!

Ooh no, something went wrong!