# First Steps with Quantiacs: Code a Trend-Following System in Python

*Note: this article points to the Legacy Version of Quantiacs. Please check more recent material on the new version of **Quantiacs**: **get started**, **simple bitcoin algorithm**, **machine learning example** and **optimizer**.*

*Trend-Following is a simple trading idea that determines an asset should be bought when the price trend moves up, and sold when the price trend moves down. This short article shows how to implement a trend-following strategy using the Quantiacs toolbox with Python.*

In the previous article, it shows how to install the Quantiacs toolbox.

Here, we describe the implementation of a trading strategy.

**The Trading System**

To begin, import numpy and define the function: “myTradingSystem”.

The function which will be used by the Quantiacs toolbox for evaluating the trading logic:

`import numpy`

def myTradingSystem(DATE, OPEN, HIGH, LOW, CLOSE, VOL, exposure, equity, settings):

'''This system uses trend following techniques to allocate capital into the desired equities.'''

nMarkets= CLOSE.shape[1]

Arguments in this case are:

- DATE: a date integer in the format YYYYMMDD;
- OPEN: the first price of the daily session;
- HIGH: the highest price of the daily session;
- LOW: the lowest price of the daily session;
- CLOSE: the last price of the daily session;
- VOL: the number of contracts traded on a daily basis;
- exposure: the trading positions;
- equity: the cumulative trading performance for each asset.

The trend-following strategy will evaluate two averages over time of the close price over a long/short time scale. The decision to enter, exit or short a market is then based on the comparison of the long/short term moving averages.

In this sense, the strategy ‘follows the trend’:

If a market has a significant upward trend, then we follow the trend and go long. If it lacks this trend, we short the asset.

The length of the two moving averages is defined using two variables fixing the number of days:

` perL= 200`

perS= 40

The two simple moving averages are then calculated for all assets at once by summing the values of the close within the time period, and dividing the results by the length of the time frame:

` smaLong = numpy.nansum(CLOSE[-perL:, :], axis=0)/perL`

smaRecent= numpy.nansum(CLOSE[-perS:, :], axis=0)/perS

If the recent moving average is above the long-term moving average, we go long. Otherwise, we short the asset:

` longEquity = smaRecent > smaLong`

shortEquity = ~longEquity

Finally, equal weights are placed on each market across the long/short positions and allocations are returned:

pos= numpy.zeros(nMarkets)

pos[longEquity] = 1

pos[shortEquity]= -1 weights= pos/numpy.nansum(abs(pos))

return weights, settings

**The Settings**

Within the function “mySettings”, we define the list of assets we want to trade. The time period to consider for the simulation, the lookback period for including data, the starting budget and the slippage:

`def mySettings():`

'''Define your trading system settings here.'''

settings= {}

# selected Futures contracts

settings['markets']= ['CASH','F_AD', 'F_BO', 'F_BP', 'F_C']

settings['beginInSample']= '20120506'

settings['endInSample'] = '20150506'

settings['lookback']= 504

settings['budget'] = 10**6

settings['slippage']= 0.05

return settings

**Strategy Evaluation**

After defining trading logic and evaluation settings, the system can be evaluated with this simple code snippet which imports the Quantiacs toolbox and runs the system:

`if __name__ = "__main__":`

import quantiacsToolbox

results = runts(__file__)

Running the file will produce a plot allowing you to check the values of the most important statistical indicators like the Sharpe Ratio:

If you submit your system by uploading the source file containing the trading logic before end of 2020, your code will take part in our algo trading competition where $2.25M USD will be allocated to the top performing algos.

**The Full Strategy**

`import numpy`

def myTradingSystem(DATE, OPEN, HIGH, LOW, CLOSE, VOL, exposure, equity, settings):

'''This system uses trend following techniques to allocate capital into the desired equities.'''

nMarkets= CLOSE.shape[1]

perL= 200

perS= 40

smaLong = numpy.nansum(CLOSE[-perL:, :], axis=0)/perL

smaRecent= numpy.nansum(CLOSE[-perS:, :], axis=0)/perS

longEquity= smaRecent > smaLong

shortEquity= ~longEquity

pos= numpy.zeros(nMarkets)

pos[longEquity]= 1

pos[shortEquity]= -1

weights = pos/numpy.nansum(abs(pos))

return weights, settings

def mySettings():

'''Define your trading system settings here.'''

settings= {}

# selected Futures contracts

settings['markets']= ['CASH', 'F_AD', 'F_BO', 'F_BP', 'F_C']

settings['beginInSample']= '20120506'

settings['endInSample'] = '20150506'

settings['lookback']= 504

settings['budget'] = 10**6

settings['slippage']= 0.05

return settings

if __name__ == "__main__":

import quantiacsToolbox

results = quantiacsToolbox.runts(__file__)