{"id":2140,"date":"2023-10-02T08:32:38","date_gmt":"2023-10-02T08:32:38","guid":{"rendered":"https:\/\/eodhd.com\/financial-academy\/?p=2140"},"modified":"2025-02-05T12:57:05","modified_gmt":"2025-02-05T12:57:05","slug":"a-step-by-step-guide-to-implementing-the-supertrend-indicator-in-python","status":"publish","type":"post","link":"https:\/\/eodhd.com\/financial-academy\/backtesting-strategies-examples\/a-step-by-step-guide-to-implementing-the-supertrend-indicator-in-python","title":{"rendered":"A Step-By-Step Guide to Implementing the SuperTrend Indicator in Python"},"content":{"rendered":"\n<p>I\u2019ve backtested numerous trading strategies using a wide variety of technical indicators. Among these, a few indicators have delivered exceptional results, and I consider them to be &#8220;premium&#8221; indicators. In today&#8217;s analysis, we\u2019ll focus on one such trend-following indicator that has earned its place in this exclusive group due to its accuracy and efficiency\u2014the&nbsp;SuperTrend indicator.<\/p>\n\n\n\n<p>We&#8217;ll begin by understanding what the SuperTrend indicator is and how its formula works, including its key&nbsp;parameters like volatility and&nbsp;settings for intraday&nbsp;trading. Afterward, we\u2019ll demonstrate how to build the indicator from scratch using Python, step-by-step, and integrate it into a simple trading strategy. Next, we\u2019ll backtest the strategy on Tesla&#8217;s stock and analyze its performance against the SPY ETF (an ETF designed to mimic the movements of the S&amp;P 500 market index).<\/p>\n\n\n\n<p>Finally, we\u2019ll discuss the&nbsp;best indicators to use with SuperTrend&nbsp;and how to optimize the indicator for maximum&nbsp;accuracy rate&nbsp;in various market conditions. Let&#8217;s dive into the article and explore how you can harness the power of the SuperTrend indicator in your trading strategies.<\/p>\n\n\n\n<p class=\"has-text-align-center\"><a class=\"maxbutton-1 maxbutton maxbutton-subscribe-to-api external-css btn\" href=\"https:\/\/eodhd.com\/register\"><span class='mb-text'>Register &amp; Get Data<\/span><\/a><\/p>\n\n\n\n\n\n\n<h1 class=\"wp-block-heading\" id=\"abdf\">Average True Range<\/h1>\n\n\n\n<p>Before moving on to discovering the&nbsp;SuperTrend indicator, it is essential to understand the&nbsp;parameters&nbsp;and role of the&nbsp;Average True Range (ATR), as it is crucial to the&nbsp;SuperTrend formula&nbsp;used in technical analysis and charting.<\/p>\n\n\n\n<p>The&nbsp;Average True Range&nbsp;is a technical indicator that measures how much an asset moves on average, often used in&nbsp;intraday&nbsp;trading strategies. It is a lagging indicator, meaning it relies on historical data to calculate the current value but does not predict future price movements. However, this is not considered a drawback, as ATR is widely regarded as one of the best indicators to track&nbsp;volatility. Its ability to assess market volatility is why it pairs well with the&nbsp;SuperTrend indicator&nbsp;for strategies focused on dynamic market conditions.<\/p>\n\n\n\n<p>Additionally, the ATR is a non-directional indicator, meaning its movement is not directly tied to the market&#8217;s trend. This makes it valuable for understanding overall volatility, regardless of whether the market is trending up or down. To calculate ATR, you must follow two key steps:<\/p>\n\n\n\n<ul class=\"wp-block-list\">\n<li>Calculate True Range (TR):&nbsp;A True Range of an asset is calculated by&nbsp;taking the greatest values of three price differences which are: market high minus marker low, market high minus previous market close, previous market close minus market low. It can be represented as follows:<\/li>\n<\/ul>\n\n\n\n<pre class=\"wp-block-preformatted has-background\" style=\"background-color:#abb7c217\"><strong>MAX <\/strong>[ {<strong>HIGH - LOW<\/strong>}, {<strong>HIGH - P.CLOSE<\/strong>}, {<strong>P.CLOSE - LOW<\/strong>} ]\n\nwhere,\nMAX = Maximum values\nHIGH = Market High\nLOW = Market Low\nP.CLOSE = Previous market close<\/pre>\n\n\n\n<ul class=\"wp-block-list\">\n<li>Calculate ATR:&nbsp;The calculation for the Average True Range is simple.&nbsp;We just have to take a&nbsp;smoothed average&nbsp;of the&nbsp;previously calculated True Range values&nbsp;for a specified number of periods.&nbsp;The smoothed average is not just any SMA or EMA but an own type of smoothed average created by Wilder Wiles himself but there aren\u2019t any restrictions in using other MAs too. In this article, we will be using the Exponential Moving Average&nbsp;(EMA) to calculate ATR&nbsp;rather than the custom moving average created by the founder of the indicator just to make things simple. The calculation of ATR with a traditional setting of 14 as the number of periods can be represented as follows:<\/li>\n<\/ul>\n\n\n\n<pre class=\"wp-block-preformatted has-background\" style=\"background-color:#abb7c217\"><strong>ATR 14<\/strong> = <strong>EMA 14<\/strong> [ <strong>TR <\/strong>]\n\nwhere,\nATR 14 = 14 Period Average True Range\nSMA 14 = 14 Period Simple Moving Average\nTR = True Range<\/pre>\n\n\n\n<p id=\"f67d\">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\u2019s now dive into the main concept of this article, the SuperTrend Indicator.<\/p>\n\n\n\n<h1 class=\"wp-block-heading\" id=\"889b\">SuperTrend Indicator<\/h1>\n\n\n\n<p>As the name suggests, the&nbsp;SuperTrend indicator&nbsp;tracks the direction of a trending market. This indicator is well-known for its precision in spotting efficient buy and sell signals for trades, making it a reliable tool for&nbsp;intraday&nbsp;trading as well. While the calculation of the SuperTrend might seem complex at first, I\u2019ll break it down into simpler steps to help you understand it better.<\/p>\n\n\n\n<p>There are two main&nbsp;parameters&nbsp;involved in the calculation of this indicator: the lookback period and the multiplier. The lookback period represents the number of data points considered, while the multiplier is used to adjust the&nbsp;volatilitycomponent, specifically by multiplying the&nbsp;ATR&nbsp;(Average True Range). The&nbsp;traditional setting&nbsp;for the SuperTrend indicator is a 10-period lookback and a multiplier of 3. Using these settings, let\u2019s proceed to the calculation of the&nbsp;SuperTrend formula.<\/p>\n\n\n\n<p>The first step is to determine the 10-day ATR, which we discussed earlier. Next, we calculate the basic upper and lower bands. To do this, we first find the High\/Low average (HLA), calculated by adding the high and low values of the stock and dividing by 2. Using the HLA, the upper band is determined by multiplying the 10-day ATR by the multiplier (3 in this case) and then adding it to the HLA value. For the lower band, the same method is applied, but instead of adding, we subtract the ATR product from the HLA. These two bands form the basis of the&nbsp;SuperTrend chart&nbsp;used in market&nbsp;analysis.<\/p>\n\n\n\n<p>The calculation of these two bands can be mathematically represented as follows:<\/p>\n\n\n\n<pre class=\"wp-block-preformatted has-background\" style=\"background-color:#abb7c217\"><strong>BASIC UPPER BAND<\/strong> = <strong>HLA <\/strong>+ [ <strong>MULTIPLIER <\/strong>* <strong>10-DAY ATR<\/strong> ]\n<strong>BASIC LOWER BAND<\/strong> = <strong>HLA <\/strong>-<strong> <\/strong>[ <strong>MULTIPLIER <\/strong>* <strong>10-DAY ATR <\/strong>]\n\nwhere,\nHLA = High Low Average\nMULTIPLIER = 3<\/pre>\n\n\n\n<p id=\"32e2\">Then comes the calculation of the final upper and lower bands, which are the core components involved in the calculation of the SuperTrend indicator. There is no formula for the calculation of the final bands, but instead, conditions are passed and the values will be appended to the bands concerning which condition gets satisfied. The condition for the&nbsp;current final upper band&nbsp;goes as follows:<\/p>\n\n\n\n<ul class=\"wp-block-list\">\n<li>If the current basic upper band is lesser than the previous final upper band, or the previous closing price of the stock is greater than the previous final upper band, then the current final upper band\u2019s value is the current basic upper band.<\/li>\n\n\n\n<li>If the condition fails to get satisfied, then the current final upper band\u2019s value is the previous final upper band. The condition of the final upper band can be represented as follows:<\/li>\n<\/ul>\n\n\n\n<pre class=\"wp-block-preformatted has-background\" style=\"background-color:#abb7c217\">IF <strong>C.BUB<\/strong> &lt; <strong>P.FUB<\/strong> OR <strong>P.CLOSE<\/strong> &gt; <strong>P.FUB<\/strong>: <strong>C.FUB<\/strong> = <strong>C.BUB\n<\/strong>IF <strong>THE CONDITION IS NOT SATISFIED: C.FUB <\/strong>= <strong>P.FUB<\/strong>\n\nwhere,\nC.BUB = Current Basic Upper Band\nP.FUB = Previous Final Upper Band\nP.CLOSE = Previous Closing Price of the Stock\nC.FUB = Current Final Upper Band<\/pre>\n\n\n\n<p id=\"454a\">The condition for the current lower band goes as follows:<\/p>\n\n\n\n<ul class=\"wp-block-list\">\n<li>If the current basic lower band is greater than the previous final lower band or the previous closing price of the stock is lesser than the previous final lower band, then the current final lower band\u2019s value is the current basic lower band.<\/li>\n\n\n\n<li>If this condition of the current final lower band fails to get satisfied, then the current final lower band is the previous final lower band. The condition can be represented as follows:<\/li>\n<\/ul>\n\n\n\n<pre class=\"wp-block-preformatted has-background\" style=\"background-color:#abb7c217\">IF <strong>C.BLB<\/strong> &gt; <strong>P.FLB<\/strong> OR <strong>P.CLOSE<\/strong> &lt; <strong>P.FLB<\/strong>: <strong>C.FLB<\/strong> = <strong>C.BLB<\/strong>\nIF <strong>THE CONDITION IS NOT SATISFIED: C.FLB <\/strong>= <strong>P.FLB<\/strong>\n\nwhere,\nC.BLB = Current Basic Lower Band\nP.FLB = Previous Final Lower Band\nP.CLOSE = Previous Closing Price of the Stock\nC.FLB = Current Final Lower Band<\/pre>\n\n\n\n<p id=\"0a74\">Now we have all the essential components to determine the values of the SuperTrend indicator. The same method that we used conditions to calculate the final bands\u2019 values applies to the calculation of the SuperTrend indicator too. While there is only one condition for determining the final bands\u2019 values, there are four different conditions for the SuperTrend indicator. The conditions for the current SuperTrend value goes as follows:<\/p>\n\n\n\n<ul class=\"wp-block-list\">\n<li>If the previous SuperTrend indicator value is equal to the previous final upper band and the current closing price of the stock is lesser than the current final upper band, then the current SuperTrend indicator value is the current final upper band.<\/li>\n\n\n\n<li>If the previous SuperTrend indicator value is equal to the previous final upper band and the current closing price of the stock is greater than the current final upper band, then the current SuperTrend indicator value is the current final lower band.<\/li>\n\n\n\n<li>If the previous SuperTrend indicator value is equal to the previous final lower band and the current closing price of the stock is greater than the current final lower band, then the current SuperTrend indicator value is the current final lower band.<\/li>\n\n\n\n<li>If the previous SuperTrend indicator value is equal to the previous final lower band and the current closing price of the stock is lesser than the current final lower band, then the current SuperTrend indicator value is the current final upper band.<\/li>\n<\/ul>\n\n\n\n<p id=\"c1ad\">When putting all these conditions together, the collective number of conditions can be represented as follows:<\/p>\n\n\n\n<pre class=\"wp-block-preformatted has-background\" style=\"background-color:#abb7c217\">IF P.ST == P.FUB AND C.CLOSE &lt; C.FUB: C.ST = C.FUB\nIF P.ST == P.FUB AND C.CLOSE &gt; C.FUB: C.ST = C.FLB\nIF P.ST == P.FLB AND C.CLOSE &gt; C.FLB: C.ST = C.FLB\nIF P.ST == P.FLB AND C.CLOSE &lt; C.FLB: C.ST = C.FUB\n\nwhere,\nP.ST = Previous SuperTrend indicator value\nP.FUB = Previous Final Upper Band\nP.FLB = Previous Final Lower Band\nC.CLOSE = Current Closing Price of the Stock\nC.ST = Current SuperTrend indicator value\nC.FUB = Current Final Upper Band\nC.FLB = Current Final Lower Band<\/pre>\n\n\n\n<p id=\"4815\">That\u2019s the whole process of calculating the SuperTrend indicator values. To build a stronger understanding of the indicator and how it works, let\u2019s explore a chart where the closing price of a stock is plotted along with the SuperTrend indicator\u2019s readings.<\/p>\n\n\n\n<figure class=\"wp-block-image size-full\"><img loading=\"lazy\" decoding=\"async\" width=\"1801\" height=\"853\" src=\"https:\/\/eodhd.com\/financial-academy\/wp-content\/uploads\/2023\/09\/image-19.png\" alt=\"\" class=\"wp-image-2142\"\/><\/figure>\n\n\n\n<p id=\"5309\">In the above chart, the blue line represents the closing price of the Tesla stock and the line with both red and green color represents the readings of the SuperTrend indicator. The line of the SuperTrend indicator turns green if the readings of the indicator are below the closing price and turns red if it\u2019s above the closing price. As I said before, the SuperTrend indicator is a trend-following indicator and this can be observed in the chart that the indicator directly reveals the current trend of the market more accurately.<\/p>\n\n\n\n<p id=\"673a\">Traders use the color changes or trend changes observed in the SuperTrend indicator line to mark buy and sell signals for their trades. To be more elaborate, traders go long (buy the stock) if the indicator\u2019s line crosses from above to below the closing price line, and similarly, they go short (sell the stock) if the indicator\u2019s line crosses from below to above the closing price line. This SuperTrend strategy is called the crossover strategy. This strategy can be represented as follows:<\/p>\n\n\n\n<pre class=\"wp-block-preformatted has-background\" style=\"background-color:#abb7c217\">IF <strong>PREV.ST<\/strong> &gt; <strong>PREV.CLOSE<\/strong> AND <strong>CUR.ST<\/strong> &lt; <strong>CUR.CLOSE<\/strong> ==&gt; <strong>BUY SIGNAL<\/strong><br>IF <strong>PREV.ST<\/strong> &lt; <strong>PREV.CLOSE<\/strong> AND <strong>CUR.ST<\/strong> &gt; <strong>CUR.CLOSE<\/strong> ==&gt; <strong>SELL SIGNAL<\/strong><\/pre>\n\n\n\n<p id=\"9f05\">This is the strategy we are going to implement in this article too. Many other strategies can also be implemented based on the SuperTrend indicator but just to make things simple to understand, we are going with the crossover strategy. This concludes our theory part on the SuperTrend indicator. Now, let\u2019s move on to the coding part where we are first going to build the indicator from scratch, build the crossover strategy which we just discussed, then, compare our strategy\u2019s performance with the SPY ETF\u2019s returns in Python. Let\u2019s do some coding!&nbsp;<strong>Before moving on, a note on disclaimer: This article\u2019s sole purpose is to educate people and must be considered as an information piece but not as investment advice.<\/strong><\/p>\n\n\n\n<h1 class=\"wp-block-heading\" id=\"562e\">Implementation in Python<\/h1>\n\n\n\n<p id=\"809c\">The coding part is classified into various steps as follows:<\/p>\n\n\n\n<pre class=\"wp-block-preformatted has-background\" style=\"background-color:#abb7c217\"><strong>1. Importing Packages<\/strong>\n<strong>2. API Key Activation\n3. Extracting Historical Stock Data\n4. SuperTrend Calculation\n5. Creating the Crossover Trading Strategy\n6. Plotting the Trading Lists\n7. Creating our Position\n8. Backtesting\n9. SPY ETF Comparison<\/strong><\/pre>\n\n\n\n<p id=\"b2f2\">We will be following the order mentioned in the above list and buckle up your seat belts to follow every upcoming coding part.<\/p>\n\n\n\n<h2 class=\"wp-block-heading\" id=\"5471\">Step-1: Importing Packages<\/h2>\n\n\n\n<p id=\"65f4\">Importing the required packages into the Python environment is a non-skippable step. The primary packages are going to be eodhd for extracting historical stock data, Pandas for data formatting and manipulations, NumPy to work with arrays and for complex functions, and Matplotlib for plotting purposes. The secondary packages are going to be Math for mathematical functions and Termcolor for font customization (optional).<\/p>\n\n\n\n<p id=\"b9a0\"><strong>Python Implementation:<\/strong><\/p>\n\n\n\n            <div class=\"code__wrapper\">\n                <div class=\"code__content\">\n                    \n<pre class=\"wp-block-code has-white-color has-black-background-color has-text-color has-background\"><code lang=\"python\" class=\"language-python\"># IMPORTING PACKAGES\n\nimport numpy as np\nimport matplotlib.pyplot as plt\nimport pandas as pd\nfrom termcolor import colored as cl\nfrom math import floor\nfrom eodhd import APIClient\n\nplt.rcParams['figure.figsize'] = (20,10)\nplt.style.use('fivethirtyeight')<\/code><\/pre>\n\n                <\/div>\n                <div class=\"code__btns\">\n                    <button class=\"code__copy\" class=\"copy\" title=\"Copy url\">\n                        <svg class=\"code__copy__icon\" width=\"20\" height=\"20\" viewBox=\"0 0 20 20\" xmlns=\"http:\/\/www.w3.org\/2000\/svg\">\n                            <use xlink:href=\"\/img\/icons\/copy.svg#copy\"><\/use>\n                        <\/svg>\n                        <img decoding=\"async\" class=\"code__copy__approve\" alt=\"\" src=\"\/img\/approve_ico.svg\" loading=\"eager\">\n                    <\/button>\n                <\/div>\n            <\/div>\n        \n\n\n<p id=\"6a56\">With the required packages imported into Python, we can proceed to fetch historical data for Tesla using EODHD&#8217;s <code>eodhd<\/code> Python library. Also, if you haven\u2019t installed any of the imported packages, make sure to do so using the&nbsp;<code>pip<\/code>&nbsp;command in your terminal.<\/p>\n\n\n\n<h2 class=\"wp-block-heading\" id=\"a9f4\">Step-2: API Key Activation<\/h2>\n\n\n\n<p id=\"c710\">It is essential to register the EODHD API key with the package in order to use its functions. If you don\u2019t have an EODHD API key, firstly, head over to their&nbsp;<a href=\"https:\/\/eodhistoricaldata.com\/?utm_source=medium&amp;utm_medium=post&amp;utm_campaign=a_python_package_to_retrieve_financial_data_part2\" rel=\"noreferrer noopener\" target=\"_blank\">website<\/a>, then, finish the&nbsp;<a href=\"https:\/\/eodhistoricaldata.com\/register?utm_source=medium&amp;utm_medium=post&amp;utm_campaign=a_python_package_to_retrieve_financial_data_part2\" rel=\"noreferrer noopener\" target=\"_blank\">registration<\/a>&nbsp;process to create an EODHD account, and finally, navigate to the \u2018<a href=\"https:\/\/eodhistoricaldata.com\/cp\/settings?utm_source=medium&amp;utm_medium=post&amp;utm_campaign=a_python_package_to_retrieve_financial_data_part2\" rel=\"noreferrer noopener\" target=\"_blank\">Settings<\/a>\u2019 page where you could find your secret EODHD API key. It is important to ensure that this secret API key is not revealed to anyone. You can activate the API key by following this code:<\/p>\n\n\n\n            <div class=\"code__wrapper\">\n                <div class=\"code__content\">\n                    \n<pre class=\"wp-block-code has-white-color has-black-background-color has-text-color has-background\"><code lang=\"python\" class=\"language-python\">api_key = '&lt;YOUR API KEY&gt;'\nclient = APIClient(api_key)<\/code><\/pre>\n\n                <\/div>\n                <div class=\"code__btns\">\n                    <button class=\"code__copy\" class=\"copy\" title=\"Copy url\">\n                        <svg class=\"code__copy__icon\" width=\"20\" height=\"20\" viewBox=\"0 0 20 20\" xmlns=\"http:\/\/www.w3.org\/2000\/svg\">\n                            <use xlink:href=\"\/img\/icons\/copy.svg#copy\"><\/use>\n                        <\/svg>\n                        <img decoding=\"async\" class=\"code__copy__approve\" alt=\"\" src=\"\/img\/approve_ico.svg\" loading=\"eager\">\n                    <\/button>\n                <\/div>\n            <\/div>\n        \n\n\n<p id=\"fd3d\">The code is pretty simple. In the first line, we are storing the secret EODHD API key into the&nbsp;<code>api_key<\/code>&nbsp;and then in the second line, we are using the&nbsp;<code>APIClient<\/code>&nbsp;class provided by the&nbsp;<code>eodhd<\/code>&nbsp;package to activate the API key and stored the response in the&nbsp;<code>client<\/code>&nbsp;variable.<\/p>\n\n\n\n<p id=\"4634\">Note that you need to replace&nbsp;<code>&lt;YOUR API KEY&gt;<\/code>&nbsp;with your secret EODHD API key. Apart from directly storing the API key with text, there are other ways for better security such as utilizing environmental variables, and so on.<\/p>\n\n\n\n<p class=\"has-text-align-center\"><a class=\"maxbutton-1 maxbutton maxbutton-subscribe-to-api external-css btn\" href=\"https:\/\/eodhd.com\/register\"><span class='mb-text'>Register &amp; Get Data<\/span><\/a><\/p>\n\n\n\n<h2 class=\"wp-block-heading\" id=\"8568\">Step-3: Extracting Historical Data<\/h2>\n\n\n\n<p id=\"ac40\">Before heading into the extraction part, it is first essential to have some background about historical or end-of-day data. In a nutshell, historical data consists of information accumulated over a period of time. It helps in identifying patterns and trends in the data. It also assists in studying market behavior. Now, you can easily extract the historical data of any tradeable assets using the&nbsp;<code>eod<\/code>&nbsp;package by following this code:<\/p>\n\n\n\n            <div class=\"code__wrapper\">\n                <div class=\"code__content\">\n                    \n<pre class=\"wp-block-code has-white-color has-black-background-color has-text-color has-background\"><code lang=\"python\" class=\"language-python\"># EXTRACTING HISTORICAL DATA\n\ndef extract_historical_data(ticker, start_date):\n    json_resp = client.get_eod_historical_stock_market_data(symbol = ticker, period = 'd', from_date = start_date, order = 'a')\n    df = pd.DataFrame(json_resp)\n    df = df.set_index('date')\n    df.index = pd.to_datetime(df.index)\n    return df\n\ntsla = extract_historical_data('TSLA', '2020-01-01')\ntsla.tail()<\/code><\/pre>\n\n                <\/div>\n                <div class=\"code__btns\">\n                    <button class=\"code__copy\" class=\"copy\" title=\"Copy url\">\n                        <svg class=\"code__copy__icon\" width=\"20\" height=\"20\" viewBox=\"0 0 20 20\" xmlns=\"http:\/\/www.w3.org\/2000\/svg\">\n                            <use xlink:href=\"\/img\/icons\/copy.svg#copy\"><\/use>\n                        <\/svg>\n                        <img decoding=\"async\" class=\"code__copy__approve\" alt=\"\" src=\"\/img\/approve_ico.svg\" loading=\"eager\">\n                    <\/button>\n                <\/div>\n            <\/div>\n        \n\n\n<p id=\"c103\">In the above code, we are using the&nbsp;<code>get_eod_historical_stock_market_data<\/code>&nbsp;function provided by the <code>eodhd<\/code> package to extract the split-adjusted historical stock data of Tesla. The function consists of the following parameters:<\/p>\n\n\n\n<ul class=\"wp-block-list\">\n<li>the&nbsp;<code>ticker<\/code>&nbsp;parameter where the symbol of the stock we are interested in extracting the data should be mentioned<\/li>\n\n\n\n<li>the&nbsp;<code>period<\/code>&nbsp;refers to the time interval between each data point (one-day interval in our case).<\/li>\n\n\n\n<li>the&nbsp;<code>from_date<\/code>&nbsp;and&nbsp;<code>to_date<\/code>&nbsp;parameters which indicate the starting and ending date of the data respectively. The format of the input should be \u201cYYYY-MM-DD\u201d<\/li>\n\n\n\n<li>the&nbsp;<code>order<\/code>&nbsp;parameter which is an optional parameter that can be used to order the dataframe either in ascending (<code>a<\/code>) or descending (<code>d<\/code>). It is ordered based on the dates.<\/li>\n<\/ul>\n\n\n\n<p id=\"a294\">After extracting the historical data, we are performing some data-wrangling processes to clean and format the data. The final dataframe looks like this:<\/p>\n\n\n\n<figure class=\"wp-block-image size-full\"><img loading=\"lazy\" decoding=\"async\" width=\"923\" height=\"459\" src=\"https:\/\/eodhd.com\/financial-academy\/wp-content\/uploads\/2023\/09\/image-20.png\" alt=\"\" class=\"wp-image-2144\"\/><\/figure>\n\n\n\n<h2 class=\"wp-block-heading\" id=\"c24a\">Step-4: SuperTrend Calculation<\/h2>\n\n\n\n<p id=\"1d19\">In this step, we are going to calculate the values of the SuperTrend indicator by following the methods we discussed before.<\/p>\n\n\n\n<p id=\"b3a5\"><strong>Python Implementation:<\/strong><\/p>\n\n\n\n            <div class=\"code__wrapper\">\n                <div class=\"code__content\">\n                    \n<pre class=\"wp-block-code has-white-color has-black-background-color has-text-color has-background\"><code lang=\"python\" class=\"language-python\">def get_supertrend(high, low, close, lookback, multiplier):\n    \n    # ATR\n    \n    tr1 = pd.DataFrame(high - low)\n    tr2 = pd.DataFrame(abs(high - close.shift(1)))\n    tr3 = pd.DataFrame(abs(low - close.shift(1)))\n    frames = [tr1, tr2, tr3]\n    tr = pd.concat(frames, axis = 1, join = 'inner').max(axis = 1)\n    atr = tr.ewm(lookback).mean()\n    \n    # H\/L AVG AND BASIC UPPER &amp; LOWER BAND\n    \n    hl_avg = (high + low) \/ 2\n    upper_band = (hl_avg + multiplier * atr).dropna()\n    lower_band = (hl_avg - multiplier * atr).dropna()\n    \n    # FINAL UPPER BAND    final_bands = pd.DataFrame(columns = ['upper', 'lower'])\n    final_bands.iloc[:,0] = [x for x in upper_band - upper_band]\n    final_bands.iloc[:,1] = final_bands.iloc[:,0]    for i in range(len(final_bands)):\n        if i == 0:\n            final_bands.iloc[i,0] = 0\n        else:\n            if (upper_band[i] &lt; final_bands.iloc[i-1,0]) | (close[i-1] &gt; final_bands.iloc[i-1,0]):\n                final_bands.iloc[i,0] = upper_band[i]\n            else:\n                final_bands.iloc[i,0] = final_bands.iloc[i-1,0]\n    \n    # FINAL LOWER BAND\n    \n    for i in range(len(final_bands)):\n        if i == 0:\n            final_bands.iloc[i, 1] = 0\n        else:\n            if (lower_band[i] &gt; final_bands.iloc[i-1,1]) | (close[i-1] &lt; final_bands.iloc[i-1,1]):\n                final_bands.iloc[i,1] = lower_band[i]\n            else:\n                final_bands.iloc[i,1] = final_bands.iloc[i-1,1]\n    \n    # SUPERTREND\n    \n    supertrend = pd.DataFrame(columns = [f'supertrend_{lookback}'])\n    supertrend.iloc[:,0] = [x for x in final_bands['upper'] - final_bands['upper']]\n    \n    for i in range(len(supertrend)):\n        if i == 0:\n            supertrend.iloc[i, 0] = 0\n        elif supertrend.iloc[i-1, 0] == final_bands.iloc[i-1, 0] and close[i] &lt; final_bands.iloc[i, 0]:\n            supertrend.iloc[i, 0] = final_bands.iloc[i, 0]\n        elif supertrend.iloc[i-1, 0] == final_bands.iloc[i-1, 0] and close[i] &gt; final_bands.iloc[i, 0]:\n            supertrend.iloc[i, 0] = final_bands.iloc[i, 1]\n        elif supertrend.iloc[i-1, 0] == final_bands.iloc[i-1, 1] and close[i] &gt; final_bands.iloc[i, 1]:\n            supertrend.iloc[i, 0] = final_bands.iloc[i, 1]\n        elif supertrend.iloc[i-1, 0] == final_bands.iloc[i-1, 1] and close[i] &lt; final_bands.iloc[i, 1]:\n            supertrend.iloc[i, 0] = final_bands.iloc[i, 0]\n    \n    supertrend = supertrend.set_index(upper_band.index)\n    \n    # ST UPTREND\/DOWNTREND\n    \n    upt = []\n    dt = []\n    close = close.iloc[len(close) - len(supertrend):]\n\n    for i in range(len(supertrend)):\n        if close[i] &gt; supertrend.iloc[i, 0]:\n            upt.append(supertrend.iloc[i, 0])\n            dt.append(np.nan)\n        elif close[i] &lt; supertrend.iloc[i, 0]:\n            upt.append(np.nan)\n            dt.append(supertrend.iloc[i, 0])\n        else:\n            upt.append(np.nan)\n            dt.append(np.nan)\n            \n    st, upt, dt = pd.Series(supertrend.iloc[:, 0]), pd.Series(upt), pd.Series(dt)\n    upt.index, dt.index = supertrend.index, supertrend.index\n    \n    return st, upt, dt\n\ntsla['st'], tsla['s_upt'], tsla['st_dt'] = get_supertrend(tsla['high'], tsla['low'], tsla['close'], 10, 3)\ntsla = tsla[1:]\ntsla.head()<\/code><\/pre>\n\n                <\/div>\n                <div class=\"code__btns\">\n                    <button class=\"code__copy\" class=\"copy\" title=\"Copy url\">\n                        <svg class=\"code__copy__icon\" width=\"20\" height=\"20\" viewBox=\"0 0 20 20\" xmlns=\"http:\/\/www.w3.org\/2000\/svg\">\n                            <use xlink:href=\"\/img\/icons\/copy.svg#copy\"><\/use>\n                        <\/svg>\n                        <img decoding=\"async\" class=\"code__copy__approve\" alt=\"\" src=\"\/img\/approve_ico.svg\" loading=\"eager\">\n                    <\/button>\n                <\/div>\n            <\/div>\n        \n\n\n<p id=\"92fe\"><strong>Output:<\/strong><\/p>\n\n\n\n<figure class=\"wp-block-image size-full\"><img loading=\"lazy\" decoding=\"async\" width=\"1122\" height=\"347\" src=\"https:\/\/eodhd.com\/financial-academy\/wp-content\/uploads\/2023\/09\/image-21.png\" alt=\"\" class=\"wp-image-2145\"\/><\/figure>\n\n\n\n<p id=\"4310\"><strong>Code Explanation:&nbsp;<\/strong>We are first defining a function named \u2018get_supertrend\u2019 which takes a stock\u2019s high (\u2018high\u2019), low (\u2018low\u2019), close (\u2018close\u2019), the lookback period (\u2018lookback), and the multiplier (\u2018multiplier\u2019) as parameters. The code inside the function can be divided into six parts: ATR calculation, HLA and basic bands calculation, final upper band calculation, final lower band calculation, SuperTrend indicator calculation, and determining the uptrend and downtrend of the indicator.<\/p>\n\n\n\n<p id=\"90de\">ATR calculation: To determine the readings of the Average True Range, we are first calculating the three differences and stored them into their respective variables. Then we are combining all three differences into one dataframe using the \u2018concat\u2019 function and took the maximum values out of the three collective differences to determine the True Range. Then, using the \u2018ewm\u2019 and \u2018mean\u2019 function, we are taking the Exponential Moving Average of True Range for a specified number of periods to get the ATR values. Many prefer using SMA for ATR calculation while determining the SuperTrend, but I used EMA for more accuracy.<\/p>\n\n\n\n<p id=\"c10f\">HLA and Basic Bands calculation: Before calculating the basic upper and lower bands, we need to first determine the High Low Average. To calculate the values of HLA, we are first finding the total of the high and low values of a stock, then dividing the total by 2. Using the HLA values which are stored into the \u2018hl_avg\u2019 variable, we are determining both the upper and lower bands by following the formula we discussed and stored the values into the \u2018upper_band\u2019 and \u2018lower_band\u2019 respectively.<\/p>\n\n\n\n<p id=\"e5c8\">Final Upper Band calculation: Before directly moving into calculating the final upper band values, we are first creating a dataframe named \u2018final_bands\u2019 to store both the final upper and lower bands. Then just for the sake to fill the dataframe with values, we are subtracting the upper band by itself to store zeros matching the length of the upper band series so that it can be used for iterations. This step of creating the dataframe is optional but highly recommended since it reduces future works of data processing and all similar stuff. After creating the dataframe, we are passing a for-loop to create the conditions we discussed before for determining the values of the final upper band.<\/p>\n\n\n\n<p id=\"b255\">Final Lower Band calculation: The code structure for determining the final lower band is most similar to the final upper band calculation but only the conditions change. But now, let\u2019s dive into exploring what\u2019s happening inside the for-loop we are passing to get the values of the final lower band. First, we are passing a for-loop that iterates over the length of the \u2018final_bands\u2019 dataframe we created before. Inside the for-loop, we are first defining an if-statement that appends the final lower band\u2019s value as 0 if the current iteration value is zero. This if-statement\u2019s purpose is to fill the first value of the final lower band as zero. After the if-statement, we are defining nested else-statement which appends the final lower band\u2019s value as the basic lower band value if the condition we discussed before gets satisfied, or else, it appends the previous final lower band value.<\/p>\n\n\n\n<p id=\"5897\">SuperTrend calculation: We are first creating a dataframe named \u2018supertrend\u2019 to store the values of the SuperTrend indicator. Like how we did before just to fill the dataframe with zeros to match the length of the basic bands series, we are doing the same here too to match the final bands series. Then comes the for-loop to determine the values of the SuperTrend indicator which appends the values concerning which condition gets satisfied out of the four. After the for-loop, we are doing some data processing to modify a bit and clean the dataframe.<\/p>\n\n\n\n<p id=\"3581\">Uptrend\/Downtrend determination: This step is optional as I did only to make the visualization of the indicator a bit easy but you can try doing this too. The main aim of this step is to classify the SuperTrend indicator\u2019s periods into two categories: the SuperTrend being below the closing price (uptrend), the SuperTrend being above the closing price (downtrend). With that being said, let\u2019s dive into the methods involved. We are first defining two empty lists named \u2018up\u2019 and \u2018down\u2019 in which the values of the uptrend and the downtrend will be appended respectively. We are also reducing the length of the closing price data to match that of the SuperTrend data, only then, the iteration would be possible. Next, we are passing a for-loop to iterate over the length of the SuperTrend data to determine and append both uptrend and downtrend values into their respective variables. The values will be appended concerning which condition gets satisfied that are defined inside the for-loop. If either condition gets satisfied, the values of both uptrend and downtrend will be appended as \u2018NaN\u2019 (not defined). Then, we are converting the lists we created to store the uptrend and downtrend into Pandas series as it will be more convenient to work with.<\/p>\n\n\n\n<p id=\"a468\">After calculating all these values, we are finally returning the SuperTrend indicator values, and both the uptrend and downtrend readings. Then, we are calling the created function to store the SuperTrend indicator values of Tesla along with the uptrend and downtrend readings with 10 as the lookback period and 3 as the multiplier. From the output being shown, it is observable that whenever the closing price is greater than the SuperTrend indicator, the downtrend readings (\u2018st_dt\u2019) represent \u2018NaN\u2019. Likewise, whenever the closing price is lesser than the SuperTrend indicator, the uptrend readings (\u2018st_upt\u2019) represent \u2018NaN\u2019.<\/p>\n\n\n\n<h2 class=\"wp-block-heading\" id=\"9506\">Step-5: Creating the trading strategy<\/h2>\n\n\n\n<p id=\"4666\">In this step, we are going to implement the discussed SuperTrend indicator crossover trading strategy in python.<\/p>\n\n\n\n<p id=\"a857\"><strong>Python Implementation:<\/strong><\/p>\n\n\n\n            <div class=\"code__wrapper\">\n                <div class=\"code__content\">\n                    \n<pre class=\"wp-block-code has-white-color has-black-background-color has-text-color has-background\"><code lang=\"python\" class=\"language-python\">def implement_st_strategy(prices, st):\n    buy_price = []\n    sell_price = []\n    st_signal = []\n    signal = 0\n    \n    for i in range(len(st)):\n        if st[i-1] &gt; prices[i-1] and st[i] &lt; prices[i]:\n            if signal != 1:\n                buy_price.append(prices[i])\n                sell_price.append(np.nan)\n                signal = 1\n                st_signal.append(signal)\n            else:\n                buy_price.append(np.nan)\n                sell_price.append(np.nan)\n                st_signal.append(0)\n        elif st[i-1] &lt; prices[i-1] and st[i] &gt; prices[i]:\n            if signal != -1:\n                buy_price.append(np.nan)\n                sell_price.append(prices[i])\n                signal = -1\n                st_signal.append(signal)\n            else:\n                buy_price.append(np.nan)\n                sell_price.append(np.nan)\n                st_signal.append(0)\n        else:\n            buy_price.append(np.nan)\n            sell_price.append(np.nan)\n            st_signal.append(0)\n            \n    return buy_price, sell_price, st_signal\n\nbuy_price, sell_price, st_signal = implement_st_strategy(tsla['close'], tsla['st'])<\/code><\/pre>\n\n                <\/div>\n                <div class=\"code__btns\">\n                    <button class=\"code__copy\" class=\"copy\" title=\"Copy url\">\n                        <svg class=\"code__copy__icon\" width=\"20\" height=\"20\" viewBox=\"0 0 20 20\" xmlns=\"http:\/\/www.w3.org\/2000\/svg\">\n                            <use xlink:href=\"\/img\/icons\/copy.svg#copy\"><\/use>\n                        <\/svg>\n                        <img decoding=\"async\" class=\"code__copy__approve\" alt=\"\" src=\"\/img\/approve_ico.svg\" loading=\"eager\">\n                    <\/button>\n                <\/div>\n            <\/div>\n        \n\n\n<p id=\"08d6\">Code Explanation:&nbsp;First, we&nbsp;are defining a function named \u2018implement_st_strategy\u2019 which takes the stock prices (\u2018prices\u2019), and the values of the SuperTrend indicator (\u2018st\u2019) as parameters.<\/p>\n\n\n\n<p id=\"c2bd\">Inside the function, we are creating three empty lists (buy_price, sell_price, and st_signal) in which the values will be appended while creating the trading strategy.<\/p>\n\n\n\n<p id=\"4a58\">After that, we are implementing the trading strategy through a for-loop. Inside the for-loop, we are passing certain conditions, and if the conditions are satisfied, the respective values will be appended to the empty lists. If the condition to buy the stock gets satisfied, the buying price will be appended to the \u2018buy_price\u2019 list, and the signal value will be appended as 1 representing to buy the stock. Similarly, if the condition to sell the stock gets satisfied, the selling price will be appended to the \u2018sell_price\u2019 list, and the signal value will be appended as -1 representing to sell the stock.<\/p>\n\n\n\n<p id=\"e647\">Finally, we are returning the lists appended with values. Then, we are calling the created function and stored the values into their respective variables. The list doesn\u2019t make any sense unless we plot the values. So, let\u2019s plot the values of the created trading lists.<\/p>\n\n\n\n<h2 class=\"wp-block-heading\" id=\"5b35\">Step-6: Plotting the trading signals<\/h2>\n\n\n\n<p id=\"b242\">In this step, we are going to plot the created trading lists to make sense out of them.<\/p>\n\n\n\n<p id=\"8fd2\"><strong>Python Implementation:<\/strong><\/p>\n\n\n\n            <div class=\"code__wrapper\">\n                <div class=\"code__content\">\n                    \n<pre class=\"wp-block-code has-white-color has-black-background-color has-text-color has-background\"><code lang=\"python\" class=\"language-python\">plt.plot(tsla['close'], linewidth = 2)<br>plt.plot(tsla['st'], color = 'green', linewidth = 2, label = 'ST UPTREND')<br>plt.plot(tsla['st_dt'], color = 'r', linewidth = 2, label = 'ST DOWNTREND')<br>plt.plot(tsla.index, buy_price, marker = '^', color = 'green', markersize = 12, linewidth = 0, label = 'BUY SIGNAL')<br>plt.plot(tsla.index, sell_price, marker = 'v', color = 'r', markersize = 12, linewidth = 0, label = 'SELL SIGNAL')<br>plt.title('TSLA ST TRADING SIGNALS')<br>plt.legend(loc = 'upper left')<br>plt.show()<\/code><\/pre>\n\n                <\/div>\n                <div class=\"code__btns\">\n                    <button class=\"code__copy\" class=\"copy\" title=\"Copy url\">\n                        <svg class=\"code__copy__icon\" width=\"20\" height=\"20\" viewBox=\"0 0 20 20\" xmlns=\"http:\/\/www.w3.org\/2000\/svg\">\n                            <use xlink:href=\"\/img\/icons\/copy.svg#copy\"><\/use>\n                        <\/svg>\n                        <img decoding=\"async\" class=\"code__copy__approve\" alt=\"\" src=\"\/img\/approve_ico.svg\" loading=\"eager\">\n                    <\/button>\n                <\/div>\n            <\/div>\n        \n\n\n<p id=\"cba3\"><strong>Output:<\/strong><\/p>\n\n\n\n<figure class=\"wp-block-image size-full\"><img loading=\"lazy\" decoding=\"async\" width=\"1801\" height=\"884\" src=\"https:\/\/eodhd.com\/financial-academy\/wp-content\/uploads\/2023\/09\/image-22.png\" alt=\"\" class=\"wp-image-2146\"\/><\/figure>\n\n\n\n<p id=\"8fa5\"><strong>Code Explanation:<\/strong>&nbsp;We are plotting the readings of the SuperTrend indicator along with the buy and sell signals generated by the trading strategy. We can observe that whenever the SuperTrend indicator line crosses from above to below the closing price line, a green-colored buy signal is plotted in the chart. Similarly, whenever the SuperTrend indicator line crosses from below to above the closing price line, a red-colored sell signal is plotted in the chart.<\/p>\n\n\n\n<h2 class=\"wp-block-heading\" id=\"bcf2\">Step-6: Creating our Position<\/h2>\n\n\n\n<p id=\"4c0d\">In this step, we are going to create a list that indicates 1 if we hold the stock or 0 if we don\u2019t own or hold the stock.<\/p>\n\n\n\n<p id=\"8a97\"><strong>Python Implementation:<\/strong><\/p>\n\n\n\n            <div class=\"code__wrapper\">\n                <div class=\"code__content\">\n                    \n<pre class=\"wp-block-code has-white-color has-black-background-color has-text-color has-background\"><code lang=\"python\" class=\"language-python\">position = []\nfor i in range(len(st_signal)):\n    if st_signal[i] &gt; 1:\n        position.append(0)\n    else:\n        position.append(1)\n        \nfor i in range(len(tsla['close'])):\n    if st_signal[i] == 1:\n        position[i] = 1\n    elif st_signal[i] == -1:\n        position[i] = 0\n    else:\n        position[i] = position[i-1]\n        \nclose_price = tsla['close']\nst = tsla['st']\nst_signal = pd.DataFrame(st_signal).rename(columns = {0:'st_signal'}).set_index(tsla.index)\nposition = pd.DataFrame(position).rename(columns = {0:'st_position'}).set_index(tsla.index)\n\nframes = [close_price, st, st_signal, position]\nstrategy = pd.concat(frames, join = 'inner', axis = 1)\n\nstrategy<\/code><\/pre>\n\n                <\/div>\n                <div class=\"code__btns\">\n                    <button class=\"code__copy\" class=\"copy\" title=\"Copy url\">\n                        <svg class=\"code__copy__icon\" width=\"20\" height=\"20\" viewBox=\"0 0 20 20\" xmlns=\"http:\/\/www.w3.org\/2000\/svg\">\n                            <use xlink:href=\"\/img\/icons\/copy.svg#copy\"><\/use>\n                        <\/svg>\n                        <img decoding=\"async\" class=\"code__copy__approve\" alt=\"\" src=\"\/img\/approve_ico.svg\" loading=\"eager\">\n                    <\/button>\n                <\/div>\n            <\/div>\n        \n\n\n<p id=\"3859\"><strong>Output:<\/strong><\/p>\n\n\n\n<figure class=\"wp-block-image size-full\"><img loading=\"lazy\" decoding=\"async\" width=\"854\" height=\"454\" src=\"https:\/\/eodhd.com\/financial-academy\/wp-content\/uploads\/2023\/09\/image-23.png\" alt=\"\" class=\"wp-image-2147\"\/><\/figure>\n\n\n\n<p id=\"1df9\"><strong>Code Explanation:<\/strong>&nbsp;First, we are creating an empty list named \u2018position\u2019. We are passing two for-loops, one is to generate values for the \u2018position\u2019 list to just match the length of the \u2018signal\u2019 list. The other for-loop is the one we are using to generate actual position values. Inside the second for-loop, we are iterating over the values of the \u2018signal\u2019 list, and the values of the \u2018position\u2019 list get appended concerning which condition gets satisfied. The value of the position remains 1 if we hold the stock or remains 0 if we sold or don\u2019t own the stock. Finally, we are doing some data manipulations to combine all the created lists into one dataframe.<\/p>\n\n\n\n<p id=\"88e5\">From the output being shown, we can see that in the first two rows our position in the stock has remained 1 (since there isn\u2019t any change in the SuperTrend indicator signal) but our position suddenly turned to -1 as we sold the stock when the SuperTrend indicator trading signal represents a sell signal (-1). Our position will remain 0 until some changes in the trading signal occur. Now it\u2019s time to implement some backtesting process!<\/p>\n\n\n\n<h2 class=\"wp-block-heading\" id=\"975d\">Step-7: Backtesting<\/h2>\n\n\n\n<p id=\"2359\">Before moving on, it is essential to know what backtesting is. Backtesting is the process of seeing how well our trading strategy has performed on the given stock data. In our case, we are going to implement a backtesting process for our SuperTrend indicator trading strategy over the Tesla stock data.<\/p>\n\n\n\n<p id=\"8d27\"><strong>Python Implementation:<\/strong><\/p>\n\n\n\n            <div class=\"code__wrapper\">\n                <div class=\"code__content\">\n                    \n<pre class=\"wp-block-code has-white-color has-black-background-color has-text-color has-background\"><code lang=\"python\" class=\"language-python\">tsla_ret = pd.DataFrame(np.diff(tsla['close'])).rename(columns = {0:'returns'})\nst_strategy_ret = []\n\nfor i in range(len(tsla_ret)):\n    returns = tsla_ret['returns'][i]*strategy['st_position'][i]\n    st_strategy_ret.append(returns)\n    \nst_strategy_ret_df = pd.DataFrame(st_strategy_ret).rename(columns = {0:'st_returns'})\ninvestment_value = 100000\nst_investment_ret = []\n\nfor i in range(len(st_strategy_ret_df['st_returns'])):\n    number_of_stocks = floor(investment_value\/tsla['close'][i])\n    returns = number_of_stocks*st_strategy_ret_df['st_returns'][i]\n    st_investment_ret.append(returns)\n\nst_investment_ret_df = pd.DataFrame(st_investment_ret).rename(columns = {0:'investment_returns'})\ntotal_investment_ret = round(sum(st_investment_ret_df['investment_returns']), 2)\nprofit_percentage = floor((total_investment_ret\/investment_value)*100)\nprint(cl('Profit gained from the ST strategy by investing $100k in TSLA : {}'.format(total_investment_ret), attrs = ['bold']))\nprint(cl('Profit percentage of the ST strategy : {}%'.format(profit_percentage), attrs = ['bold']))<\/code><\/pre>\n\n                <\/div>\n                <div class=\"code__btns\">\n                    <button class=\"code__copy\" class=\"copy\" title=\"Copy url\">\n                        <svg class=\"code__copy__icon\" width=\"20\" height=\"20\" viewBox=\"0 0 20 20\" xmlns=\"http:\/\/www.w3.org\/2000\/svg\">\n                            <use xlink:href=\"\/img\/icons\/copy.svg#copy\"><\/use>\n                        <\/svg>\n                        <img decoding=\"async\" class=\"code__copy__approve\" alt=\"\" src=\"\/img\/approve_ico.svg\" loading=\"eager\">\n                    <\/button>\n                <\/div>\n            <\/div>\n        \n\n\n<p id=\"dc20\"><strong>Output:<\/strong><\/p>\n\n\n\n<pre class=\"wp-block-preformatted has-background\" style=\"background-color:#abb7c217\"><strong>Profit gained from the ST strategy by investing $100k in TSLA : 232677.17\nProfit percentage of the ST strategy : 232%<\/strong><\/pre>\n\n\n\n<p id=\"f842\"><strong>Code Explanation:<\/strong>&nbsp;First, we are calculating the returns of the Tesla stock using the \u2018diff\u2019 function provided by the NumPy package and we have stored it as a dataframe into the \u2018tsla_ret\u2019 variable. Next, we are passing a for-loop to iterate over the values of the \u2018tsla_ret\u2019 variable to calculate the returns we gained from our SuperTrend indicator trading strategy, and these returns values are appended to the \u2018st_strategy_ret\u2019 list. Next, we are converting the \u2018st_strategy_ret\u2019 list into a dataframe and stored it into the \u2018st_strategy_ret_df\u2019 variable.<\/p>\n\n\n\n<p id=\"dc78\">Next comes the backtesting process. We are going to backtest our strategy by investing a hundred thousand USD into our trading strategy. So first, we are storing the amount of investment into the \u2018investment_value\u2019 variable. After that, we are calculating the number of Tesla stocks we can buy using the investment amount. You can notice that I\u2019ve used the \u2018floor\u2019 function provided by the Math package because, while dividing the investment amount by the closing price of Tesla stock, it spits out an output with decimal numbers. The number of stocks should be an integer but not a decimal number. Using the \u2018floor\u2019 function, we can cut out the decimals. Remember that the \u2018floor\u2019 function is way more complex than the \u2018round\u2019 function. Then, we are passing a for-loop to find the investment returns followed by some data manipulation tasks.<\/p>\n\n\n\n<p id=\"e6b9\">Finally, we are printing the total return we got by investing a hundred thousand into our trading strategy and it is revealed that we have made an approximate profit of two hundred and thirty-two thousand USD in one year. That\u2019s wonderful! Now, let\u2019s compare our returns with SPY ETF (an ETF designed to track the S&amp;P 500 stock market index) returns.<\/p>\n\n\n\n<h2 class=\"wp-block-heading\" id=\"0a7e\">Step-8: SPY ETF Comparison<\/h2>\n\n\n\n<p id=\"cb31\">This step is optional but it is highly recommended as we can get an idea of how well our trading strategy performs against a benchmark (SPY ETF). In this step, we are going to extract the data of the SPY ETF using the \u2018get_historical_data\u2019 function we created and compare the returns we get from the SPY ETF with our SuperTrend indicator trading strategy returns on Tesla.<\/p>\n\n\n\n<p id=\"6c8f\"><strong>Python Implementation:<\/strong><\/p>\n\n\n\n            <div class=\"code__wrapper\">\n                <div class=\"code__content\">\n                    \n<pre class=\"wp-block-code has-white-color has-black-background-color has-text-color has-background\"><code lang=\"python\" class=\"language-python\">def get_benchmark(start_date, investment_value):\n    spy = get_historical_data('SPY', start_date)['close']\n    benchmark = pd.DataFrame(np.diff(spy)).rename(columns = {0:'benchmark_returns'})\n    \n    investment_value = investment_value\n    benchmark_investment_ret = []\n    \n    for i in range(len(benchmark['benchmark_returns'])):\n        number_of_stocks = floor(investment_value\/spy[i]) \n        returns = number_of_stocks*benchmark['benchmark_returns'][i]\n        benchmark_investment_ret.append(returns)\n\n    benchmark_investment_ret_df = pd.DataFrame(benchmark_investment_ret).rename(columns = {0:'investment_returns'})\n    return benchmark_investment_ret_df\n\nbenchmark = get_benchmark('2020-01-01', 100000)\ninvestment_value = 100000\ntotal_benchmark_investment_ret = round(sum(benchmark['investment_returns']), 2)\nbenchmark_profit_percentage = floor((total_benchmark_investment_ret\/investment_value)*100)\nprint(cl('Benchmark profit by investing $100k : {}'.format(total_benchmark_investment_ret), attrs = ['bold']))\nprint(cl('Benchmark Profit percentage : {}%'.format(benchmark_profit_percentage), attrs = ['bold']))\nprint(cl('ST Strategy profit is {}% higher than the Benchmark Profit'.format(profit_percentage - benchmark_profit_percentage), attrs = ['bold']))<\/code><\/pre>\n\n                <\/div>\n                <div class=\"code__btns\">\n                    <button class=\"code__copy\" class=\"copy\" title=\"Copy url\">\n                        <svg class=\"code__copy__icon\" width=\"20\" height=\"20\" viewBox=\"0 0 20 20\" xmlns=\"http:\/\/www.w3.org\/2000\/svg\">\n                            <use xlink:href=\"\/img\/icons\/copy.svg#copy\"><\/use>\n                        <\/svg>\n                        <img decoding=\"async\" class=\"code__copy__approve\" alt=\"\" src=\"\/img\/approve_ico.svg\" loading=\"eager\">\n                    <\/button>\n                <\/div>\n            <\/div>\n        \n\n\n<p id=\"88a0\"><strong>Output:<\/strong><\/p>\n\n\n\n<pre class=\"wp-block-preformatted has-background\" style=\"background-color:#abb7c217\"><strong>Benchmark profit by investing $100k : 41144.52\nBenchmark Profit percentage : 41%\nST Strategy profit is 191% higher than the Benchmark Profit<\/strong><\/pre>\n\n\n\n<p id=\"0203\"><strong>Code Explanation:<\/strong>&nbsp;The code used in this step is almost similar to the one used in the previous backtesting step but, instead of investing in Tesla, we are investing in SPY ETF by not implementing any trading strategies. From the output, we can see that our SuperTrend indicator trading strategy has outperformed the SPY ETF by 191%. That\u2019s great!<\/p>\n\n\n\n<p class=\"has-text-align-center\"><a class=\"maxbutton-1 maxbutton maxbutton-subscribe-to-api external-css btn\" href=\"https:\/\/eodhd.com\/register\"><span class='mb-text'>Register &amp; Get Data<\/span><\/a><\/p>\n\n\n\n<h1 class=\"wp-block-heading\" id=\"b1c5\">Final Thoughts!<\/h1>\n\n\n\n<p id=\"3d46\">After a long process of crushing both theory and coding parts, we have successfully learned what the SuperTrend indicator is all about, its calculation, and how to build a simple crossover trading strategy based on it in python. One important thing we managed to accomplish in this article is understanding the complex math behind the indicator and this will help in increasing your understanding of the indicator significantly.<\/p>\n\n\n\n<p id=\"742c\">As the SuperTrend indicator has just started gaining momentum, there are a lot more spaces for improvement. One such important space is strategy optimization. I talk about this in almost every article of mine as it should be considered of paramount importance.<\/p>\n\n\n\n<p id=\"93f1\">For those who don\u2019t know what strategy optimization is, it is the process of tuning the trading algorithm to perform at its best. You can tune the SuperTrend indicator by experimenting with different settings. In this article, we built the indicator with the traditional setting of 14 as the lookback period and 3 as the multiplier but, you can try changing the values and run backtests for each and every change to acknowledge its performance. By doing this will help you reach the optimal setting for the indicator that can outperform the market itself.<\/p>\n\n\n\n<p id=\"fcb0\">We didn&#8217;t consider doing it in this article, as the sole purpose is not on building an optimistic trading strategy ,but on building a strong intuition on what the SuperTrend indicator is all about. But, it is highly recommended to get your hands dirty on experimenting with the indicator and introduce yourselves to a whole new level of possibilities. With that being said, you\u2019ve reached the end of the article. Hope you learned something useful from this article. Happy programming!<\/p>\n","protected":false},"excerpt":{"rendered":"<p>I\u2019ve backtested numerous trading strategies using a wide variety of technical indicators. Among these, a few indicators have delivered exceptional results, and I consider them to be &#8220;premium&#8221; indicators. In today&#8217;s analysis, we\u2019ll focus on one such trend-following indicator that has earned its place in this exclusive group due to its accuracy and efficiency\u2014the&nbsp;SuperTrend indicator. [&hellip;]<\/p>\n","protected":false},"author":18,"featured_media":2141,"comment_status":"closed","ping_status":"open","sticky":false,"template":"","format":"standard","meta":{"jetpack_post_was_ever_published":false,"_jetpack_newsletter_access":"","_jetpack_dont_email_post_to_subs":false,"_jetpack_newsletter_tier_id":0,"_jetpack_memberships_contains_paywalled_content":false,"_jetpack_memberships_contains_paid_content":false,"footnotes":""},"categories":[65,59,61],"tags":[],"coding-language":[30],"ready-to-go-solution":[56],"qualification":[31,32],"financial-apis-category":[36],"financial-apis-manuals":[39,38,40],"class_list":["post-2140","post","type-post","status-publish","format-standard","has-post-thumbnail","hentry","category-backtesting-strategies-examples","category-technical-analysis-examples","category-trading-indicators-implimentations","coding-language-python","ready-to-go-solution-eodhd-python-financial-library","qualification-experienced","qualification-guru","financial-apis-category-stock-market-prices","financial-apis-manuals-end-of-day","financial-apis-manuals-intraday","financial-apis-manuals-technical-indicators","has_thumb"],"yoast_head":"<!-- This site is optimized with the Yoast SEO Premium plugin v21.9 (Yoast SEO v26.7) - https:\/\/yoast.com\/wordpress\/plugins\/seo\/ -->\n<title>Building the SuperTrend Indicator from Scratch in Python | EODHD APIs Academy<\/title>\n<meta name=\"description\" content=\"Learn how to build the SuperTrend Indicator in Python and create a profitable trading strategy\" \/>\n<meta name=\"robots\" content=\"index, follow, max-snippet:-1, max-image-preview:large, max-video-preview:-1\" \/>\n<link rel=\"canonical\" href=\"https:\/\/eodhd.com\/financial-academy\/backtesting-strategies-examples\/a-step-by-step-guide-to-implementing-the-supertrend-indicator-in-python\" \/>\n<meta property=\"og:locale\" content=\"en_US\" \/>\n<meta property=\"og:type\" content=\"article\" \/>\n<meta property=\"og:title\" content=\"A Step-By-Step Guide to Implementing the SuperTrend Indicator in Python\" \/>\n<meta property=\"og:description\" content=\"Learn how to build the SuperTrend Indicator in Python and create a profitable trading strategy\" \/>\n<meta property=\"og:url\" content=\"https:\/\/eodhd.com\/financial-academy\/backtesting-strategies-examples\/a-step-by-step-guide-to-implementing-the-supertrend-indicator-in-python\" \/>\n<meta property=\"og:site_name\" content=\"Financial Academy\" \/>\n<meta property=\"article:publisher\" content=\"https:\/\/www.facebook.com\/eodhistoricaldata\" \/>\n<meta property=\"article:published_time\" content=\"2023-10-02T08:32:38+00:00\" \/>\n<meta property=\"article:modified_time\" content=\"2025-02-05T12:57:05+00:00\" \/>\n<meta property=\"og:image\" content=\"https:\/\/eodhd.com\/financial-academy\/wp-content\/uploads\/2023\/09\/image-18.png\" \/>\n\t<meta property=\"og:image:width\" content=\"828\" \/>\n\t<meta property=\"og:image:height\" content=\"828\" \/>\n\t<meta property=\"og:image:type\" content=\"image\/png\" \/>\n<meta name=\"author\" content=\"Nikhil Adithyan\" \/>\n<meta name=\"twitter:card\" content=\"summary_large_image\" \/>\n<meta name=\"twitter:creator\" content=\"@EOD_data\" \/>\n<meta name=\"twitter:site\" content=\"@EOD_data\" \/>\n<meta name=\"twitter:label1\" content=\"Written by\" \/>\n\t<meta name=\"twitter:data1\" content=\"Nikhil Adithyan\" \/>\n\t<meta name=\"twitter:label2\" content=\"Est. reading time\" \/>\n\t<meta name=\"twitter:data2\" content=\"21 minutes\" \/>\n<script type=\"application\/ld+json\" class=\"yoast-schema-graph\">{\"@context\":\"https:\/\/schema.org\",\"@graph\":[{\"@type\":\"Article\",\"@id\":\"https:\/\/eodhd.com\/financial-academy\/backtesting-strategies-examples\/a-step-by-step-guide-to-implementing-the-supertrend-indicator-in-python#article\",\"isPartOf\":{\"@id\":\"https:\/\/eodhd.com\/financial-academy\/backtesting-strategies-examples\/a-step-by-step-guide-to-implementing-the-supertrend-indicator-in-python\"},\"author\":{\"name\":\"Nikhil Adithyan\",\"@id\":\"https:\/\/eodhd.com\/financial-academy\/#\/schema\/person\/67681e71050cf7d8d0efb91fee5f0402\"},\"headline\":\"A Step-By-Step Guide to Implementing the SuperTrend Indicator in Python\",\"datePublished\":\"2023-10-02T08:32:38+00:00\",\"dateModified\":\"2025-02-05T12:57:05+00:00\",\"mainEntityOfPage\":{\"@id\":\"https:\/\/eodhd.com\/financial-academy\/backtesting-strategies-examples\/a-step-by-step-guide-to-implementing-the-supertrend-indicator-in-python\"},\"wordCount\":4589,\"publisher\":{\"@id\":\"https:\/\/eodhd.com\/financial-academy\/#organization\"},\"image\":{\"@id\":\"https:\/\/eodhd.com\/financial-academy\/backtesting-strategies-examples\/a-step-by-step-guide-to-implementing-the-supertrend-indicator-in-python#primaryimage\"},\"thumbnailUrl\":\"https:\/\/eodhd.com\/financial-academy\/wp-content\/uploads\/2023\/09\/image-18.png\",\"articleSection\":[\"Backtesting Strategies Examples\",\"Technical Analysis Examples\",\"Trading Indicators Implimentations\"],\"inLanguage\":\"en-US\"},{\"@type\":\"WebPage\",\"@id\":\"https:\/\/eodhd.com\/financial-academy\/backtesting-strategies-examples\/a-step-by-step-guide-to-implementing-the-supertrend-indicator-in-python\",\"url\":\"https:\/\/eodhd.com\/financial-academy\/backtesting-strategies-examples\/a-step-by-step-guide-to-implementing-the-supertrend-indicator-in-python\",\"name\":\"Building the SuperTrend Indicator from Scratch in Python | EODHD APIs Academy\",\"isPartOf\":{\"@id\":\"https:\/\/eodhd.com\/financial-academy\/#website\"},\"primaryImageOfPage\":{\"@id\":\"https:\/\/eodhd.com\/financial-academy\/backtesting-strategies-examples\/a-step-by-step-guide-to-implementing-the-supertrend-indicator-in-python#primaryimage\"},\"image\":{\"@id\":\"https:\/\/eodhd.com\/financial-academy\/backtesting-strategies-examples\/a-step-by-step-guide-to-implementing-the-supertrend-indicator-in-python#primaryimage\"},\"thumbnailUrl\":\"https:\/\/eodhd.com\/financial-academy\/wp-content\/uploads\/2023\/09\/image-18.png\",\"datePublished\":\"2023-10-02T08:32:38+00:00\",\"dateModified\":\"2025-02-05T12:57:05+00:00\",\"description\":\"Learn how to build the SuperTrend Indicator in Python and create a profitable trading strategy\",\"breadcrumb\":{\"@id\":\"https:\/\/eodhd.com\/financial-academy\/backtesting-strategies-examples\/a-step-by-step-guide-to-implementing-the-supertrend-indicator-in-python#breadcrumb\"},\"inLanguage\":\"en-US\",\"potentialAction\":[{\"@type\":\"ReadAction\",\"target\":[\"https:\/\/eodhd.com\/financial-academy\/backtesting-strategies-examples\/a-step-by-step-guide-to-implementing-the-supertrend-indicator-in-python\"]}]},{\"@type\":\"ImageObject\",\"inLanguage\":\"en-US\",\"@id\":\"https:\/\/eodhd.com\/financial-academy\/backtesting-strategies-examples\/a-step-by-step-guide-to-implementing-the-supertrend-indicator-in-python#primaryimage\",\"url\":\"https:\/\/eodhd.com\/financial-academy\/wp-content\/uploads\/2023\/09\/image-18.png\",\"contentUrl\":\"https:\/\/eodhd.com\/financial-academy\/wp-content\/uploads\/2023\/09\/image-18.png\",\"width\":828,\"height\":828,\"caption\":\"A Step-By-Step Guide to Implementing the SuperTrend Indicator in Python\"},{\"@type\":\"BreadcrumbList\",\"@id\":\"https:\/\/eodhd.com\/financial-academy\/backtesting-strategies-examples\/a-step-by-step-guide-to-implementing-the-supertrend-indicator-in-python#breadcrumb\",\"itemListElement\":[{\"@type\":\"ListItem\",\"position\":1,\"name\":\"Home\",\"item\":\"https:\/\/eodhd.com\/financial-academy\/\"},{\"@type\":\"ListItem\",\"position\":2,\"name\":\"A Step-By-Step Guide to Implementing the SuperTrend Indicator in Python\"}]},{\"@type\":\"WebSite\",\"@id\":\"https:\/\/eodhd.com\/financial-academy\/#website\",\"url\":\"https:\/\/eodhd.com\/financial-academy\/\",\"name\":\"Financial APIs Academy | EODHD\",\"description\":\"Financial Stock Market Academy\",\"publisher\":{\"@id\":\"https:\/\/eodhd.com\/financial-academy\/#organization\"},\"potentialAction\":[{\"@type\":\"SearchAction\",\"target\":{\"@type\":\"EntryPoint\",\"urlTemplate\":\"https:\/\/eodhd.com\/financial-academy\/?s={search_term_string}\"},\"query-input\":{\"@type\":\"PropertyValueSpecification\",\"valueRequired\":true,\"valueName\":\"search_term_string\"}}],\"inLanguage\":\"en-US\"},{\"@type\":\"Organization\",\"@id\":\"https:\/\/eodhd.com\/financial-academy\/#organization\",\"name\":\"EODHD (EOD Historical Data)\",\"url\":\"https:\/\/eodhd.com\/financial-academy\/\",\"logo\":{\"@type\":\"ImageObject\",\"inLanguage\":\"en-US\",\"@id\":\"https:\/\/eodhd.com\/financial-academy\/#\/schema\/logo\/image\/\",\"url\":\"https:\/\/eodhd.com\/financial-academy\/wp-content\/uploads\/2023\/12\/EODHD-Logo.png\",\"contentUrl\":\"https:\/\/eodhd.com\/financial-academy\/wp-content\/uploads\/2023\/12\/EODHD-Logo.png\",\"width\":159,\"height\":82,\"caption\":\"EODHD (EOD Historical Data)\"},\"image\":{\"@id\":\"https:\/\/eodhd.com\/financial-academy\/#\/schema\/logo\/image\/\"},\"sameAs\":[\"https:\/\/www.facebook.com\/eodhistoricaldata\",\"https:\/\/x.com\/EOD_data\",\"https:\/\/www.reddit.com\/r\/EODHistoricalData\/\",\"https:\/\/eod-historical-data.medium.com\/\"]},{\"@type\":\"Person\",\"@id\":\"https:\/\/eodhd.com\/financial-academy\/#\/schema\/person\/67681e71050cf7d8d0efb91fee5f0402\",\"name\":\"Nikhil Adithyan\",\"image\":{\"@type\":\"ImageObject\",\"inLanguage\":\"en-US\",\"@id\":\"https:\/\/eodhd.com\/financial-academy\/#\/schema\/person\/image\/\",\"url\":\"https:\/\/secure.gravatar.com\/avatar\/eb53ce41bde412555cee22b8b4c09c2ff51625fff05ba3696b20cac7a7c0d938?s=96&d=mm&r=g\",\"contentUrl\":\"https:\/\/secure.gravatar.com\/avatar\/eb53ce41bde412555cee22b8b4c09c2ff51625fff05ba3696b20cac7a7c0d938?s=96&d=mm&r=g\",\"caption\":\"Nikhil Adithyan\"},\"description\":\"Founder at BacktestZone | Streamlit Student Ambassador | FinTech &amp; Quantitative Finance enthusiast\",\"url\":\"https:\/\/eodhd.com\/financial-academy\/author\/nikhiladithyan\"}]}<\/script>\n<!-- \/ Yoast SEO Premium plugin. -->","yoast_head_json":{"title":"Building the SuperTrend Indicator from Scratch in Python | EODHD APIs Academy","description":"Learn how to build the SuperTrend Indicator in Python and create a profitable trading strategy","robots":{"index":"index","follow":"follow","max-snippet":"max-snippet:-1","max-image-preview":"max-image-preview:large","max-video-preview":"max-video-preview:-1"},"canonical":"https:\/\/eodhd.com\/financial-academy\/backtesting-strategies-examples\/a-step-by-step-guide-to-implementing-the-supertrend-indicator-in-python","og_locale":"en_US","og_type":"article","og_title":"A Step-By-Step Guide to Implementing the SuperTrend Indicator in Python","og_description":"Learn how to build the SuperTrend Indicator in Python and create a profitable trading strategy","og_url":"https:\/\/eodhd.com\/financial-academy\/backtesting-strategies-examples\/a-step-by-step-guide-to-implementing-the-supertrend-indicator-in-python","og_site_name":"Financial Academy","article_publisher":"https:\/\/www.facebook.com\/eodhistoricaldata","article_published_time":"2023-10-02T08:32:38+00:00","article_modified_time":"2025-02-05T12:57:05+00:00","og_image":[{"width":828,"height":828,"url":"https:\/\/eodhd.com\/financial-academy\/wp-content\/uploads\/2023\/09\/image-18.png","type":"image\/png"}],"author":"Nikhil Adithyan","twitter_card":"summary_large_image","twitter_creator":"@EOD_data","twitter_site":"@EOD_data","twitter_misc":{"Written by":"Nikhil Adithyan","Est. reading time":"21 minutes"},"schema":{"@context":"https:\/\/schema.org","@graph":[{"@type":"Article","@id":"https:\/\/eodhd.com\/financial-academy\/backtesting-strategies-examples\/a-step-by-step-guide-to-implementing-the-supertrend-indicator-in-python#article","isPartOf":{"@id":"https:\/\/eodhd.com\/financial-academy\/backtesting-strategies-examples\/a-step-by-step-guide-to-implementing-the-supertrend-indicator-in-python"},"author":{"name":"Nikhil Adithyan","@id":"https:\/\/eodhd.com\/financial-academy\/#\/schema\/person\/67681e71050cf7d8d0efb91fee5f0402"},"headline":"A Step-By-Step Guide to Implementing the SuperTrend Indicator in Python","datePublished":"2023-10-02T08:32:38+00:00","dateModified":"2025-02-05T12:57:05+00:00","mainEntityOfPage":{"@id":"https:\/\/eodhd.com\/financial-academy\/backtesting-strategies-examples\/a-step-by-step-guide-to-implementing-the-supertrend-indicator-in-python"},"wordCount":4589,"publisher":{"@id":"https:\/\/eodhd.com\/financial-academy\/#organization"},"image":{"@id":"https:\/\/eodhd.com\/financial-academy\/backtesting-strategies-examples\/a-step-by-step-guide-to-implementing-the-supertrend-indicator-in-python#primaryimage"},"thumbnailUrl":"https:\/\/eodhd.com\/financial-academy\/wp-content\/uploads\/2023\/09\/image-18.png","articleSection":["Backtesting Strategies Examples","Technical Analysis Examples","Trading Indicators Implimentations"],"inLanguage":"en-US"},{"@type":"WebPage","@id":"https:\/\/eodhd.com\/financial-academy\/backtesting-strategies-examples\/a-step-by-step-guide-to-implementing-the-supertrend-indicator-in-python","url":"https:\/\/eodhd.com\/financial-academy\/backtesting-strategies-examples\/a-step-by-step-guide-to-implementing-the-supertrend-indicator-in-python","name":"Building the SuperTrend Indicator from Scratch in Python | EODHD APIs Academy","isPartOf":{"@id":"https:\/\/eodhd.com\/financial-academy\/#website"},"primaryImageOfPage":{"@id":"https:\/\/eodhd.com\/financial-academy\/backtesting-strategies-examples\/a-step-by-step-guide-to-implementing-the-supertrend-indicator-in-python#primaryimage"},"image":{"@id":"https:\/\/eodhd.com\/financial-academy\/backtesting-strategies-examples\/a-step-by-step-guide-to-implementing-the-supertrend-indicator-in-python#primaryimage"},"thumbnailUrl":"https:\/\/eodhd.com\/financial-academy\/wp-content\/uploads\/2023\/09\/image-18.png","datePublished":"2023-10-02T08:32:38+00:00","dateModified":"2025-02-05T12:57:05+00:00","description":"Learn how to build the SuperTrend Indicator in Python and create a profitable trading strategy","breadcrumb":{"@id":"https:\/\/eodhd.com\/financial-academy\/backtesting-strategies-examples\/a-step-by-step-guide-to-implementing-the-supertrend-indicator-in-python#breadcrumb"},"inLanguage":"en-US","potentialAction":[{"@type":"ReadAction","target":["https:\/\/eodhd.com\/financial-academy\/backtesting-strategies-examples\/a-step-by-step-guide-to-implementing-the-supertrend-indicator-in-python"]}]},{"@type":"ImageObject","inLanguage":"en-US","@id":"https:\/\/eodhd.com\/financial-academy\/backtesting-strategies-examples\/a-step-by-step-guide-to-implementing-the-supertrend-indicator-in-python#primaryimage","url":"https:\/\/eodhd.com\/financial-academy\/wp-content\/uploads\/2023\/09\/image-18.png","contentUrl":"https:\/\/eodhd.com\/financial-academy\/wp-content\/uploads\/2023\/09\/image-18.png","width":828,"height":828,"caption":"A Step-By-Step Guide to Implementing the SuperTrend Indicator in Python"},{"@type":"BreadcrumbList","@id":"https:\/\/eodhd.com\/financial-academy\/backtesting-strategies-examples\/a-step-by-step-guide-to-implementing-the-supertrend-indicator-in-python#breadcrumb","itemListElement":[{"@type":"ListItem","position":1,"name":"Home","item":"https:\/\/eodhd.com\/financial-academy\/"},{"@type":"ListItem","position":2,"name":"A Step-By-Step Guide to Implementing the SuperTrend Indicator in Python"}]},{"@type":"WebSite","@id":"https:\/\/eodhd.com\/financial-academy\/#website","url":"https:\/\/eodhd.com\/financial-academy\/","name":"Financial APIs Academy | EODHD","description":"Financial Stock Market Academy","publisher":{"@id":"https:\/\/eodhd.com\/financial-academy\/#organization"},"potentialAction":[{"@type":"SearchAction","target":{"@type":"EntryPoint","urlTemplate":"https:\/\/eodhd.com\/financial-academy\/?s={search_term_string}"},"query-input":{"@type":"PropertyValueSpecification","valueRequired":true,"valueName":"search_term_string"}}],"inLanguage":"en-US"},{"@type":"Organization","@id":"https:\/\/eodhd.com\/financial-academy\/#organization","name":"EODHD (EOD Historical Data)","url":"https:\/\/eodhd.com\/financial-academy\/","logo":{"@type":"ImageObject","inLanguage":"en-US","@id":"https:\/\/eodhd.com\/financial-academy\/#\/schema\/logo\/image\/","url":"https:\/\/eodhd.com\/financial-academy\/wp-content\/uploads\/2023\/12\/EODHD-Logo.png","contentUrl":"https:\/\/eodhd.com\/financial-academy\/wp-content\/uploads\/2023\/12\/EODHD-Logo.png","width":159,"height":82,"caption":"EODHD (EOD Historical Data)"},"image":{"@id":"https:\/\/eodhd.com\/financial-academy\/#\/schema\/logo\/image\/"},"sameAs":["https:\/\/www.facebook.com\/eodhistoricaldata","https:\/\/x.com\/EOD_data","https:\/\/www.reddit.com\/r\/EODHistoricalData\/","https:\/\/eod-historical-data.medium.com\/"]},{"@type":"Person","@id":"https:\/\/eodhd.com\/financial-academy\/#\/schema\/person\/67681e71050cf7d8d0efb91fee5f0402","name":"Nikhil Adithyan","image":{"@type":"ImageObject","inLanguage":"en-US","@id":"https:\/\/eodhd.com\/financial-academy\/#\/schema\/person\/image\/","url":"https:\/\/secure.gravatar.com\/avatar\/eb53ce41bde412555cee22b8b4c09c2ff51625fff05ba3696b20cac7a7c0d938?s=96&d=mm&r=g","contentUrl":"https:\/\/secure.gravatar.com\/avatar\/eb53ce41bde412555cee22b8b4c09c2ff51625fff05ba3696b20cac7a7c0d938?s=96&d=mm&r=g","caption":"Nikhil Adithyan"},"description":"Founder at BacktestZone | Streamlit Student Ambassador | FinTech &amp; Quantitative Finance enthusiast","url":"https:\/\/eodhd.com\/financial-academy\/author\/nikhiladithyan"}]}},"jetpack_featured_media_url":"https:\/\/eodhd.com\/financial-academy\/wp-content\/uploads\/2023\/09\/image-18.png","jetpack_shortlink":"https:\/\/wp.me\/pdOdVT-yw","jetpack_sharing_enabled":true,"acf":[],"_links":{"self":[{"href":"https:\/\/eodhd.com\/financial-academy\/wp-json\/wp\/v2\/posts\/2140","targetHints":{"allow":["GET"]}}],"collection":[{"href":"https:\/\/eodhd.com\/financial-academy\/wp-json\/wp\/v2\/posts"}],"about":[{"href":"https:\/\/eodhd.com\/financial-academy\/wp-json\/wp\/v2\/types\/post"}],"author":[{"embeddable":true,"href":"https:\/\/eodhd.com\/financial-academy\/wp-json\/wp\/v2\/users\/18"}],"replies":[{"embeddable":true,"href":"https:\/\/eodhd.com\/financial-academy\/wp-json\/wp\/v2\/comments?post=2140"}],"version-history":[{"count":29,"href":"https:\/\/eodhd.com\/financial-academy\/wp-json\/wp\/v2\/posts\/2140\/revisions"}],"predecessor-version":[{"id":6273,"href":"https:\/\/eodhd.com\/financial-academy\/wp-json\/wp\/v2\/posts\/2140\/revisions\/6273"}],"wp:featuredmedia":[{"embeddable":true,"href":"https:\/\/eodhd.com\/financial-academy\/wp-json\/wp\/v2\/media\/2141"}],"wp:attachment":[{"href":"https:\/\/eodhd.com\/financial-academy\/wp-json\/wp\/v2\/media?parent=2140"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/eodhd.com\/financial-academy\/wp-json\/wp\/v2\/categories?post=2140"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/eodhd.com\/financial-academy\/wp-json\/wp\/v2\/tags?post=2140"},{"taxonomy":"coding-language","embeddable":true,"href":"https:\/\/eodhd.com\/financial-academy\/wp-json\/wp\/v2\/coding-language?post=2140"},{"taxonomy":"ready-to-go-solution","embeddable":true,"href":"https:\/\/eodhd.com\/financial-academy\/wp-json\/wp\/v2\/ready-to-go-solution?post=2140"},{"taxonomy":"qualification","embeddable":true,"href":"https:\/\/eodhd.com\/financial-academy\/wp-json\/wp\/v2\/qualification?post=2140"},{"taxonomy":"financial-apis-category","embeddable":true,"href":"https:\/\/eodhd.com\/financial-academy\/wp-json\/wp\/v2\/financial-apis-category?post=2140"},{"taxonomy":"financial-apis-manuals","embeddable":true,"href":"https:\/\/eodhd.com\/financial-academy\/wp-json\/wp\/v2\/financial-apis-manuals?post=2140"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}