Home Commodities Forget Stocks, This Commodity Algo Trading Strategy Made +260% Returns | by...

Forget Stocks, This Commodity Algo Trading Strategy Made +260% Returns | by Nikhil Adithyan | Mar, 2024

22
0

And outperformed the market at the same time

Nikhil Adithyan

DataDrivenInvestor

Photo by Cedrik Wesche on Unsplash

People are going crazy about algo trading, thanks to the extremely ambitious stories on the internet. But one thing that stood out for me is that almost 90% of these stories are about creating algo trading strategies for stocks. In reality, stocks are not the only viable option in the market. In fact, there are better alternatives for a lot of scenarios.

Keeping that in mind, today, we’ll be focusing on creating an algo trading strategy to trade commodities. We’ll first gain some background about our trading strategy along with the technical indicator we’re going to use in our strategy. Then, we’ll move on to the coding part where we’ll be extracting FinancialModelingPrep’s (FMP) end-of-day commodities data and backtesting the trading strategy on the same.

It’s going to be an exciting journey and without further ado, let’s dive into the article!

As regards the choice of commodity, we are going to go with a highly-traded agricultural commodity. Why agri commodities? It’s because it’s less volatile which gives us a lot of room to capitalize on that characteristic. So, we’ll be going with Wheat as our choice of commodity.

Coming to the trading strategy, we are going to create one using a technical indicator that better handles the less volatile or choppy market of agri commodities. In that case, it’s best to go with any one of the Volatility indicators since they are highly capable of signaling entries and exits in a sideways market.

So, we are going to create a strategy using a popular indicator known as the Keltner Channel, and here are the strategy conditions for entry and exit:

  • We enter the market if: the close price crosses below the Keltner Channel lower band.
  • We exit the market if: the close price crosses above the Keltner Channel upper band.

This is honestly a very generic strategy but sometimes, it’s better to keep it simple instead of overcomplicating things.

I know you might wondering about what these lower and upper bands are, and what actually is Keltner Channel. Don’t worry, in the next section, we are going in-depth about this specific indicator to know its ins and outs. It will also make you feel comfortable working with this indicator and enable you to create your own strategies.

I know you might be thinking about where this indicator came from all of a sudden. The thing is, this indicator plays a very important role in the calculation of the Keltner Channel. So it is essential to know what the Average True Range (ATR) is.

Founded by Wilder Wiles (creator of the most popular indicator, the RSI), the Average True Range is a technical indicator that measures how much an asset moves on average. It is a lagging indicator meaning that it takes into account the historical data of an asset to measure the current value but it’s not capable of predicting the future data points. This is not considered a drawback while using ATR as it’s one of the indicators to track the volatility of a market more accurately. Along with being a lagging indicator, ATR is also a non-directional indicator meaning that the movement of ATR is inversely proportional to the actual movement of the market.

To calculate ATR, it is requisite to follow two steps:

  • Calculate True Range (TR): A True Range of an asset is calculated by taking the greatest values of three price differences which are: market high minus market low, market high minus previous market close, and previous market close minus market low. It can be represented as follows:
MAX [ {HIGH - LOW}, {HIGH - P.CLOSE}, {P.CLOSE - LOW} ]

where,
MAX = Maximum values
HIGH = Market High
LOW = Market Low
P.CLOSE = Previous market close

  • Calculate ATR: The calculation for the Average True Range is simple. We just have to take a smoothed average of the previously calculated True Range values for a specified number of periods. The smoothed average is not just any SMA or EMA but its own type of smoothed average created by Wilder Wiles himself which is nothing but subtracting one from the Exponential Moving Average of the True Range for a specified number of periods and multiplying the difference with two. The calculation of ATR for a specified number of periods can be represented as follows:
ATR N = EMA N [ TR ] - 1 * 2

where,
ATR N = Average True Range of 'N' period
SMA N = Simple Moving Average of 'N' period
TR = True Range

While using ATR as an indicator for trading purposes, traders must ensure that they are more cautious than ever as the indicator is very lagging. Now that we have an understanding of what the Average True Range is all about, let’s dive into the main concept of this article, the Keltner Channel.

Founded by Chester Keltner, the Keltner Channel is a technical indicator that is often used by traders to identify volatility and the direction of the market. The Keltner Channel is composed of three components: The upper band, the lower band, and the middle line. Now, let’s discuss how each of the components is calculated.

Before diving into the calculation of the Keltner Channel it is essential to know about the three important inputs involved in the calculation.

First is the ATR lookback period which is nothing but the number of periods that are taken into account for the calculation of ATR. Secondly, the Keltner Channel lookback period. This input is more or less similar to the first one but here, we are determining the number of periods that are taken into account for the calculation of the Keltner Channel itself. The final input is the multiplier which is a value determined to multiply with the ATR. The typical values that are taken as inputs are 10 as the ATR lookback period, 20 as the Keltner Channel lookback period, and 2 as the multiplier. Keeping these inputs in mind, let’s calculate the readings of the Keltner Channel’s components.

The first step in calculating the components of the Keltner Channel is determining the ATR values with 10 as the lookback period and it can be calculated by following the formula discussed before.

The next step is calculating the middle line of the Keltner Channel. This component is nothing but the 20-day Exponential Moving Average of the closing price of the security. The calculation can be represented as follows:

MIDDLE LINE 20 = EMA 20 [ C.SECURITY ]

where,
EMA 20 = 20-day Exponential Moving Average
C.SECURITY = Closing price of the security

The final step is calculating the upper and lower bands. Let’s start with the upper band. It is calculated by first adding the 20-day Exponential Moving Average of the closing price of the security by the multiplier (two) and then, multiplied by the 10-day ATR.

The lower band calculation is almost similar to that of the upper band but instead of adding, we will be subtracting the 20-day EMA by the multiplier. The calculation of both upper and lower bands can be represented as follows:

UPPER BAND 20 = EMA 20 [ C.SECURITY ] + MULTIPLIER * ATR 10
LOWER BAND 20 = EMA 20 [ C.SECURITY ] - MULTIPLIER * ATR 10

where,
EMA 20 = 20-day Exponential Moving Average
C.SECURITY = Closing price of the security
MULTIPLIER = 2
ATR 10 = 10-day Average True Range

That’s the whole process of calculating the components of the Keltner Channel. With this, we are going to put an end to the theoretical parts of the article as now we have a pretty good background about the technical indicator as well as the trading strategy. So, move on to the coding part and get our hands dirty.

Importing the required packages into the Python environment is a non-skippable step. The primary packages are going to be:

  • Pandas — for data formatting, clearing, manipulating, and other related purposes
  • Matplotlib — for creating charts and different kinds of visualizations
  • Requests — for making API calls in order to extract data

The secondary packages are going to be:

  • Termcolor — to customize the standard output shown in Jupyter notebook
  • Math — for various mathematical functions and operations

The following code imports all the necessary packages into our coding environment:

# IMPORTING PACKAGES

import requests
import pandas as pd
import matplotlib.pyplot as plt
from termcolor import colored as cl
import math

plt.rcParams['figure.figsize'] = (20,10)
plt.style.use('fivethirtyeight')

If you haven’t installed any of the imported packages, make sure to do so using the pip command in your terminal.

Historical data is of great importance in the backtesting process. To ensure data accuracy and reliability, we are going to extract the commodities data using FMP’s historical commodities data API endpoint. The following code extracts the historical data of Wheat:

# EXTRACTING HISTORICAL DATA

api_key = 'YOUR API KEY'

def extract_historical(api_key, start, symbol):
json = requests.get(f'https://financialmodelingprep.com/api/v3/historical-price-full/{symbol}?from={start}&apikey={api_key}').json()
df = pd.DataFrame(json['historical']).set_index('date')
df.index = pd.to_datetime(df.index)
df = df.iloc[::-1]
return df

wheat_hist = extract_historical(api_key, '2000-01-01', 'KEUSX')
wheat_hist

In the above code, we are first storing the API key in its respective variable. Make sure to replace YOUR API KEY with your actual secret API key which you can obtain by opening a developer account with FinancialModelingPrep (FMP).

Then, we define a function named extract_historical which extracts the historical data for the given commodity. The function takes the API key (api_key), the starting date of the dataframe (start), and the commodity symbol (symbol) as parameters.

Inside the function, we are making an API call to extract the historical data in JSON format. Then, we convert the JSON response into a Pandas dataframe followed by some data manipulations, and finally, we return the processed dataframe.

We are then calling the created function to extract the historical data of Wheat from the start of 2000 and this is the output:

Source link

LEAVE A REPLY

Please enter your comment!
Please enter your name here