Implementing SMA in QuantScript
Let's create our own QuantScript implementation of a Simple Moving Average.
QuantScript includes a built-in implementation of SMA, and many other indicators. However, for the purposes of this guide, we are going to write one ourselves.
A Simple Moving Average represents the average of some value, e.g., for the last x bars (usually 14).
Let's use everything we have learned so far. We begin by creating two variables -and . We will refer to these variables, instead of writing and directly - this way, we could easily change our value/period later, should we decide to do so.
Next, we need to calculate the sum of the last 14prices. We'll use a for loop:
Two things need explaining here:
- What happens when the distance is 0?
We're accessing , which is equivalent to . We are instructing the time-travel operator to go back bars, so it stays in place - this is equivalent to just .
- The distance ends at
We don't want to add to the sum, because that would make the sum of the last 15 open prices, instead of the last 14. Remember, we start from 0. . Why?
All that's left is to divide our sum by the period. Here's what our SMA looks like:
Done! Now, let's write some entry/exit rules that use our SMA.
Creating a strategy based on SMA
Let's enter a long position whenever our SMA has increased and exit that position whenever it has decreased, compared to the previous bar.
We can use thetime travel operator even on a complex variable such as our :
Here,is equal to
and is equal to .
Let's make our strategy more robust by adding a second SMA. This time we'll calculate it over theprice and with a period of 26 bars.
Creating a strategy based on two SMAs
Creating a close-based 26-period SMA is easy - we just change thevariable to and the variable to 26.
However, we want to have the two SMAs simultaneously. To do that, we need to first compute our 14-period SMA, which we'll save in a variable called. Then, we need to change and , and copy-paste our , for loop and division:
This works, but once again we have a problem with code duplication.
Next, we'll look at how functions can help us solve this problem.