{"id":1717,"date":"2023-08-31T15:28:24","date_gmt":"2023-08-31T15:28:24","guid":{"rendered":"https:\/\/eodhd.com\/financial-academy\/?p=1717"},"modified":"2024-03-12T09:26:39","modified_gmt":"2024-03-12T09:26:39","slug":"coding-the-true-strength-index-and-backtesting-a-trading-strategy-in-python","status":"publish","type":"post","link":"https:\/\/eodhd.com\/financial-academy\/backtesting-strategies-examples\/coding-the-true-strength-index-and-backtesting-a-trading-strategy-in-python","title":{"rendered":"Coding the True Strength Index and Backtesting a Trading Strategy in Python"},"content":{"rendered":"\n<p id=\"90f1\">In a realm of exotic technical indicators, such as the Relative Strength Index, Stochastic Oscillator, MACD, etc., the indicator we are going to discuss today would fit nicely, given its performance that exceeds those of the above-mentioned ones. It\u2019s none other than the True Strength Index, shortly known as TSI.<\/p>\n\n\n\n<p>In this article, we will first build some basic intuitions about the indicator and how it is calculated or the mathematics behind it. Then, we will move on to the programming part where we will use Python to build the indicator from scratch, construct a trading strategy, backtest the strategy and compare the results with those of the SPY ETF (an ETF particularly designed to track the movement of the S&amp;P 500 market index). Without further ado, let\u2019s jump into the article!<\/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=\"201d\">True Strength Index (TSI)<\/h1>\n\n\n\n<p id=\"db0b\">The True Strength Index (TSI) is a momentum oscillator that is primarily used by traders to determine whether a market is an upward or a downward momentum and trade along with it. It is also used to identify the current state of the market, overbought or oversold, but this is not the indicator\u2019s main strength. The True Strength Index is composed of two components:<\/p>\n\n\n\n<ul class=\"wp-block-list\">\n<li>TSI Line: The first component is the TSI line itself which is calculated by first determining the actual price change (current closing price minus the previous closing price) and the absolute price change (absolute values of the actual price change). Then an EMA with 25 as the number of periods (long) is taken for both the actual price change and the absolute price change. These two EMAs are then again smoothed by a 13-day period (short) Exponential Moving Average. This process of smoothing a data series with two EMAs is known as double smoothing and the goal of doing this is to eliminate noise from the data. Now, the double-smoothed actual price change is divided by the double-smoothed absolute price change and then multiplied by 100 to obtain the readings of the TSI line. Note that the parameters (25, 13) we took into consideration are the typical setting but can be tuned accordingly. The calculation might be fuzzy but can be easily understood if we interpret it in the form of a formula or representation:<\/li>\n<\/ul>\n\n\n\n<pre class=\"wp-block-preformatted has-background\" style=\"background-color:#abb7c217\"><strong>TSI LINE<\/strong> = [ <strong>DS. ACTUAL PC<\/strong> \/ <strong>DS. ABSOLUTE PC<\/strong> ] * <strong>100<\/strong>\n\nwhere,\n<strong>DS. ACTUAL PC<\/strong> = Double smoothed actual price change with the length of 25 and 13\n<strong>DS. ABSOLUTE PC<\/strong> = Double smoothed absolute price change with the length of 25 and 13<\/pre>\n\n\n\n<ul class=\"wp-block-list\">\n<li>Signal line: The next component is the Signal line component which is the Exponential Moving Average of the TSI for a specified number of periods (falls within 7 to 12 periods). Most traders prefer periods near to 7 for day trading purposes and close to 12 for long-term investing. In this article, we are going with 12 as the number of periods since we will be dealing with a daily timeframe stock data rather than a minute timeframe. The calculation can be represented as follows:<\/li>\n<\/ul>\n\n\n\n<pre class=\"wp-block-preformatted has-background\" style=\"background-color:#abb7c217\"><strong>SIGNAL LINE<\/strong> = <strong>EXP.MA 13<\/strong> [ <strong>TSI LINE <\/strong>]<\/pre>\n\n\n\n<p id=\"50d8\">That\u2019s what the indicator is all about and the mathematics behind it. Now, let\u2019s analyze a chart where the readings of the True Strength Index are plotted along with the closing price data of Apple to build more understanding about the indicator and its workings.<\/p>\n\n\n\n<figure class=\"wp-block-image size-full\"><img loading=\"lazy\" decoding=\"async\" width=\"1805\" height=\"884\" src=\"https:\/\/eodhd.com\/financial-academy\/wp-content\/uploads\/2023\/08\/image-17.png\" alt=\"\" class=\"wp-image-1719\"\/><\/figure>\n\n\n\n<p id=\"e5a2\">The above chart is divided into two panels: the upper panel with the plot of the closing price data of Apple and the lower panel with the readings of TSI\u2019s components. As I said before, the TSI is primarily used to spot the momentum of the market and this can be seen clearly in the chart where the readings of the TSI above the positive territory (greater than zero) directly reveals that the market is in upward momentum and below the negative territory reveals a downward momentum in the market.<\/p>\n\n\n\n<p id=\"1d0e\">Now, let\u2019s see how TSI can be used to determine whether the market is in the state of overbought or oversold. Usually, indicators like RSI have a standard threshold of overbought and oversold levels which is 70 and 30 respectively, and these thresholds are applicable to any tradable asset. Whereas, the levels of overbought and oversold vary from one asset to another while using the True Strength Index, and in our case, we could consider -10 as the oversold level and 10 as the overbought level. But still, it won\u2019t be as effective as the other popular momentum oscillators.<\/p>\n\n\n\n<p id=\"d1ec\">Speaking about trading strategies, to my knowledge, we could apply three types of strategies based on the True Strength Index. The first one is the overbought and oversold levels. This one is the most common strategy among the momentum oscillators which reveals a buy signal whenever the components of the TSI go below the oversold level and a sell signal is generated whenever the readings of both the components rise above the overbought level. I personally don\u2019t use this strategy since I believe the True Strength Index doesn&#8217;t have a good history with the concept of overbought and oversold levels.<\/p>\n\n\n\n<p id=\"4980\">The second trading strategy is the zero-line crossover which reveals a buy signal whenever the TSI\u2019s components cross from below to above zero, likewise, a sell signal is revealed whenever the components of the TSI go from above the below zero. This strategy is effective but not as much as the next trading strategy we are going to discuss.<\/p>\n\n\n\n<p id=\"60df\">The final trading strategy and the one we are going to implement in this article is the signal line crossover which reveals a buy signal whenever the TSI line crosses from below to above the Signal line, and similarly, a sell signal is revealed whenever the TSI line goes from above to below the Signal line. This strategy is one of the most-used trading strategies among the others while using the True Strength Index due to its efficiency in the market. This trading 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.TLINE<\/strong> &lt; <strong>PREV.SLINE<\/strong> AND <strong>CUR.TLINE <\/strong>&gt; <strong>CUR.SLINE<\/strong> ==&gt; <strong>BUY SIGNAL<\/strong><br>IF <strong>PREV.TLINE<\/strong> &gt; <strong>PREV.SLINE<\/strong> AND <strong>CUR.TLINE <\/strong>&lt;<strong> CUR.SLINE<\/strong> ==&gt; <strong>SELL SIGNAL<\/strong><\/pre>\n\n\n\n<p id=\"e8a8\">That\u2019s it! This concludes our theory part on the True Strength Index. Let\u2019s now move on to the programming where we will use Python to first build the indicator from scratch, construct the signal line crossover trading strategy, backtest the strategy on Apple stock data and compare the results with those of SPY ETF. 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<p><\/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=\"fe6c\">Implementation in Python<\/h1>\n\n\n\n<p id=\"76b9\">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\n2. Extracting Stock Data from EODHD\n3. True Strength Index Calculation\n4. Creating the Signal line crossover Trading Strategy\n5. Plotting the Trading Lists\n6. Creating our Position\n7. Backtesting\n8. SPY ETF Comparison<\/strong><\/pre>\n\n\n\n<p id=\"7d55\">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<h1 class=\"wp-block-heading\" id=\"e5bb\">Step-1: Importing Packages<\/h1>\n\n\n\n<p id=\"fabc\">Importing the required packages into the Python environment is a non-skippable step. The primary packages are going to be Pandas to work with data, NumPy to work with arrays and for complex functions, Matplotlib for plotting purposes, and Requests to make API calls. The secondary packages are going to be Math for mathematical functions and Termcolor for font customization (optional).<\/p>\n\n\n\n<p id=\"3156\"><strong>Python Implementation:<\/strong><\/p>\n\n\n\n<pre class=\"wp-block-preformatted has-white-color has-black-background-color has-text-color has-background\"><strong># IMPORTING PACKAGES<br><\/strong><br>import pandas as pd<br>import requests<br>import matplotlib.pyplot as plt<br>import numpy as np<br>from math import floor<br>from termcolor import colored as cl<br><br>plt.style.use('fivethirtyeight')<br>plt.rcParams['figure.figsize'] = (20,10)<\/pre>\n\n\n\n<p id=\"d9d8\">With the required packages imported into Python, we can proceed to fetch historical data for Apple using EODHD&#8217;s OHLC split-adjusted data API endpoint.<\/p>\n\n\n\n<h2 class=\"wp-block-heading\" id=\"c515\">Step-2: Extracting data from EODHD<\/h2>\n\n\n\n<p id=\"b704\">In this phase, we&#8217;re set to retrieve the historical stock data for Apple using the <a href=\"https:\/\/eodhd.com\/financial-apis\/technical-indicators-api\/#Split_Adjusted_Data\" target=\"_blank\" rel=\"noreferrer noopener\">OHLC split-adjusted API endpoint<\/a> provided by&nbsp;<a href=\"https:\/\/eodhd.com\/\" target=\"_blank\" rel=\"noreferrer noopener\">EODHD<\/a>. It&#8217;s important to note that&nbsp;<a href=\"https:\/\/eodhd.com\/\" target=\"_blank\" rel=\"noreferrer noopener\">EOD Historical Data<\/a> (EODHD)is a reliable provider of financial APIs, encompassing an extensive array of market data, including historical data and economic news. Be sure to possess an <a href=\"https:\/\/eodhd.com\/register\">EODHD account<\/a> and access your secret API key, a crucial element for data extraction via the API.<\/p>\n\n\n\n<p id=\"a8d8\"><strong>Python Implementation:<\/strong><\/p>\n\n\n\n<pre class=\"wp-block-preformatted has-white-color has-black-background-color has-text-color has-background\"># EXTRACTING STOCK DATA\n\ndef get_historical_data(symbol, start_date):\n    api_key = 'YOUR API KEY'\n    api_url = f'https:\/\/eodhistoricaldata.com\/api\/technical\/{symbol}?order=a&amp;fmt=json&amp;from={start_date}&amp;function=splitadjusted&amp;api_token={api_key}'\n    raw_df = requests.get(api_url).json()\n    df = pd.DataFrame(raw_df)\n    df.date = pd.to_datetime(df.date)\n    df = df.set_index('date')\n    return df\n\naapl = get_historical_data('AAPL', '2019-01-01')\naapl.tail()<\/pre>\n\n\n\n<p id=\"aad5\"><strong>Output:<\/strong><\/p>\n\n\n\n<figure class=\"wp-block-image size-full\"><img loading=\"lazy\" decoding=\"async\" width=\"870\" height=\"452\" src=\"https:\/\/eodhd.com\/financial-academy\/wp-content\/uploads\/2023\/08\/image-18.png\" alt=\"\" class=\"wp-image-1720\"\/><\/figure>\n\n\n\n<p id=\"1e31\"><strong>Code Explanation:<\/strong>&nbsp;We begin by defining a function named &#8216;get_historical_data,&#8217; which takes the stock symbol (&#8216;symbol&#8217;) and the start date for historical data (&#8216;start_date&#8217;) as parameters. Inside the function, we define the API key and URL, then retrieve the historical data in JSON format using the &#8216;get&#8217; function and store it in the &#8216;raw_df&#8217; variable. After cleaning and formatting the raw JSON data, we return it as a Pandas dataframe. Finally, we call this function to fetch Apple&#8217;s historical data from the start of 2019 and store it in the &#8216;aapl&#8217; variable.<\/p>\n\n\n\n<h2 class=\"wp-block-heading\" id=\"d36e\">Step-3: True Strength Index Calculation<\/h2>\n\n\n\n<p id=\"00de\">In this step, we are going to calculate the components of the True Strength Index by following the methods and formulas we discussed before.<\/p>\n\n\n\n<p id=\"0e69\"><strong>Python Implementation:<\/strong><\/p>\n\n\n\n<pre class=\"wp-block-preformatted has-white-color has-black-background-color has-text-color has-background\"><strong># TRUE STRENGTH INDEX CALCULATION <br><\/strong><br>def get_tsi(close, long, short, signal):<br>    diff = close - close.shift(1)<br>    abs_diff = abs(diff)<br>    <br>    diff_smoothed = diff.ewm(span = long, adjust = False).mean()<br>    diff_double_smoothed = diff_smoothed.ewm(span = short, adjust = False).mean()<br>    abs_diff_smoothed = abs_diff.ewm(span = long, adjust = False).mean()<br>    abs_diff_double_smoothed = abs_diff_smoothed.ewm(span = short, adjust = False).mean()<br>    <br>    tsi = (diff_double_smoothed \/ abs_diff_double_smoothed) * 100<br>    signal = tsi.ewm(span = signal, adjust = False).mean()<br>    tsi = tsi[tsi.index &gt;= '2020-01-01'].dropna()<br>    signal = signal[signal.index &gt;= '2020-01-01'].dropna()<br>    <br>    return tsi, signal<br><br>aapl['tsi'], aapl['signal_line'] = get_tsi(aapl['close'], 25, 13, 12)<br>aapl = aapl[aapl.index &gt;= '2020-01-01']<br>aapl.tail()<\/pre>\n\n\n\n<p id=\"d5ee\"><strong>Output:<\/strong><\/p>\n\n\n\n<figure class=\"wp-block-image size-full\"><img loading=\"lazy\" decoding=\"async\" width=\"1232\" height=\"468\" src=\"https:\/\/eodhd.com\/financial-academy\/wp-content\/uploads\/2023\/08\/image-19.png\" alt=\"\" class=\"wp-image-1721\"\/><\/figure>\n\n\n\n<p id=\"4406\"><strong>Code Explanation:<\/strong>&nbsp;Firstly, we are defining a function named \u2018get_tsi\u2019 that takes a stock\u2019s closing price data (\u2018close\u2019), the lookback period for the long EMA (\u2018long\u2019), the lookback period for the short EMA (\u2018short\u2019), and the lookback period for the signal line (\u2018signal\u2019) as parameters. Inside the function, we are first calculating and storing the actual price change (\u2018diff\u2019) and the absolute price change (\u2018abs_diff\u2019) into their respective variable.<\/p>\n\n\n\n<p id=\"e902\">Then, using the \u2018ewm\u2019 function provided by the Pandas package for determining the Exponential Moving Average, we are double smoothing the previously calculated price changes to obtain the double smoothed actual price change (\u2018diff_double_smoothed\u2019) and the double smoothed absolute price change (\u2018abs_diff_double_smoothed\u2019).<\/p>\n\n\n\n<p id=\"ae1b\">We are then substituting the double smoothed values into the formula of the TSI line to determine its readings. To calculate the signal line\u2019s values, we are taking an EMA of the determined TSI line\u2019s readings for a specified number of periods. Finally, we are returning the calculated components and calling the created function to store Apple\u2019s TSI components\u2019 values.<\/p>\n\n\n\n<h2 class=\"wp-block-heading\" id=\"2ba9\">Step-4: Creating the trading strategy<\/h2>\n\n\n\n<p id=\"026b\">In this step, we are going to implement the discussed True Strength Index signal line crossover trading strategy in Python.<\/p>\n\n\n\n<p id=\"928d\"><strong>Python Implementation:<\/strong><\/p>\n\n\n\n<pre class=\"wp-block-preformatted has-white-color has-black-background-color has-text-color has-background\"><strong># TRUE STRENGTH INDEX STRATEGY<br><\/strong><br>def implement_tsi_strategy(prices, tsi, signal_line):<br>    buy_price = []<br>    sell_price = []<br>    tsi_signal = []<br>    signal = 0<br>    <br>    for i in range(len(prices)):<br>        if tsi[i-1] &lt; signal_line[i-1] and tsi[i] &gt; signal_line[i]:<br>            if signal != 1:<br>                buy_price.append(prices[i])<br>                sell_price.append(np.nan)<br>                signal = 1<br>                tsi_signal.append(signal)<br>            else:<br>                buy_price.append(np.nan)<br>                sell_price.append(np.nan)<br>                tsi_signal.append(0)<br>        elif tsi[i-1] &gt; signal_line[i-1] and tsi[i] &lt; signal_line[i]:<br>            if signal != -1:<br>                buy_price.append(np.nan)<br>                sell_price.append(prices[i])<br>                signal = -1<br>                tsi_signal.append(signal)<br>            else:<br>                buy_price.append(np.nan)<br>                sell_price.append(np.nan)<br>                tsi_signal.append(0)<br>        else:<br>            buy_price.append(np.nan)<br>            sell_price.append(np.nan)<br>            tsi_signal.append(0)<br>            <br>    return buy_price, sell_price, tsi_signal<br><br>buy_price, sell_price, tsi_signal = implement_tsi_strategy(aapl['close'], aapl['tsi'], aapl['signal_line'])<\/pre>\n\n\n\n<p id=\"ef1e\"><strong>Code Explanation:<\/strong>&nbsp;First, we are defining a function named \u2018implement_tsi_strategy\u2019 which takes the stock prices (\u2018prices\u2019), and the components of the True Strength Index (\u2018tsi\u2019, \u2018signal_line\u2019) as parameters.<\/p>\n\n\n\n<p id=\"df2a\">Inside the function, we are creating three empty lists (buy_price, sell_price, and tsi_signal) in which the values will be appended while creating the trading strategy.<\/p>\n\n\n\n<p id=\"ceb8\">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=\"3e4a\">Finally, we are returning the lists appended with values. Then, we are calling the created function and stored the values in 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=\"30d0\">Step-5: Plotting the trading signals<\/h2>\n\n\n\n<p id=\"b934\">In this step, we are going to plot the created trading lists to make sense of them.<\/p>\n\n\n\n<p id=\"01e5\"><strong>Python Implementation:<\/strong><\/p>\n\n\n\n<pre class=\"wp-block-preformatted has-white-color has-black-background-color has-text-color has-background\"><strong># TRUE STRENGTH INDEX TRADING SIGNALS PLOT<br><\/strong><br>ax1 = plt.subplot2grid((11,1), (0,0), rowspan = 5, colspan = 1)<br>ax2 = plt.subplot2grid((11,1), (6,0), rowspan = 5, colspan = 1)<br>ax1.plot(aapl['close'], linewidth = 2)<br>ax1.plot(aapl.index, buy_price, marker = '^', markersize = 12, color = 'green', linewidth = 0, label = 'BUY SIGNAL')<br>ax1.plot(aapl.index, sell_price, marker = 'v', markersize = 12, color = 'r', linewidth = 0, label = 'SELL SIGNAL')<br>ax1.legend()<br>ax1.set_title('AAPL TSI TRADING SIGNALS')<br>ax2.plot(aapl['tsi'], linewidth = 2, color = 'orange', label = 'TSI LINE')<br>ax2.plot(aapl['signal_line'], linewidth = 2, color = '#FF006E', label = 'SIGNAL LINE')<br>ax2.set_title('AAPL TSI 25,13,12')<br>ax2.legend()<br>plt.show()<\/pre>\n\n\n\n<p id=\"b947\"><strong>Output:<\/strong><\/p>\n\n\n\n<figure class=\"wp-block-image size-full\"><img loading=\"lazy\" decoding=\"async\" width=\"1805\" height=\"884\" src=\"https:\/\/eodhd.com\/financial-academy\/wp-content\/uploads\/2023\/08\/image-20.png\" alt=\"\" class=\"wp-image-1722\"\/><\/figure>\n\n\n\n<p id=\"7b13\"><strong>Code Explanation:<\/strong>&nbsp;We are plotting the components of the True Strength Index along with the buy and sell signals generated by the signal line crossover trading strategy. We can observe that whenever the previous reading of the TSI line is below the previous reading of the Signal Line and the current reading of the TSI line is above the current reading of the Signal line, a green-colored buy signal is plotted in the chart. Similarly, whenever the previous reading of the TSI line is above the previous reading of the Signal Line and the current reading of the TSI line is below the current reading of the Signal line, a red-colored sell signal is plotted in the chart.<\/p>\n\n\n\n<h2 class=\"wp-block-heading\" id=\"3e84\">Step-6: Creating our Position<\/h2>\n\n\n\n<p id=\"100f\">In this step, we are going to create a&nbsp;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=\"fedb\"><strong>Python Implementation:<\/strong><\/p>\n\n\n\n<pre class=\"wp-block-preformatted has-white-color has-black-background-color has-text-color has-background\"><strong># STOCK POSITION<br><\/strong><br>position = []<br>for i in range(len(tsi_signal)):<br>    if tsi_signal[i] &gt; 1:<br>        position.append(0)<br>    else:<br>        position.append(1)<br>        <br>for i in range(len(aapl['close'])):<br>    if tsi_signal[i] == 1:<br>        position[i] = 1<br>    elif tsi_signal[i] == -1:<br>        position[i] = 0<br>    else:<br>        position[i] = position[i-1]<br>        <br>close_price = aapl['close']<br>tsi = aapl['tsi']<br>signal_line = aapl['signal_line']<br>tsi_signal = pd.DataFrame(tsi_signal).rename(columns = {0:'tsi_signal'}).set_index(aapl.index)<br>position = pd.DataFrame(position).rename(columns = {0:'tsi_position'}).set_index(aapl.index)<br><br>frames = [close_price, tsi, signal_line, tsi_signal, position]<br>strategy = pd.concat(frames, join = 'inner', axis = 1)<br><br>strategy<\/pre>\n\n\n\n<p id=\"0209\"><strong>Output:<\/strong><\/p>\n\n\n\n<figure class=\"wp-block-image size-full\"><img loading=\"lazy\" decoding=\"async\" width=\"1064\" height=\"461\" src=\"https:\/\/eodhd.com\/financial-academy\/wp-content\/uploads\/2023\/08\/image-21.png\" alt=\"\" class=\"wp-image-1723\"\/><\/figure>\n\n\n\n<p id=\"c5b1\"><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=\"bfa8\">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 True Strength Index signal) but our position suddenly turned to -1 as we sold the stock when the True Strength Index 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 do implement some backtesting process!<\/p>\n\n\n\n<h2 class=\"wp-block-heading\" id=\"948a\">Step-7: Backtesting<\/h2>\n\n\n\n<p id=\"f110\">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 True Strength Index trading strategy over the Apple stock data.<\/p>\n\n\n\n<p id=\"9628\"><strong>Python Implementation:<\/strong><\/p>\n\n\n\n<pre class=\"wp-block-preformatted has-white-color has-black-background-color has-text-color has-background\"><strong># BACKTESTING\n<\/strong>\naapl_ret = pd.DataFrame(np.diff(aapl['close'])).rename(columns = {0:'returns'})\ntsi_strategy_ret = []\n\nfor i in range(len(aapl_ret)):\n    returns = aapl_ret['returns'][i]*strategy['tsi_position'][i]\n    tsi_strategy_ret.append(returns)\n    \ntsi_strategy_ret_df = pd.DataFrame(tsi_strategy_ret).rename(columns = {0:'tsi_returns'})\ninvestment_value = 100000\ntsi_investment_ret = []\n\nfor i in range(len(tsi_strategy_ret_df['tsi_returns'])):\n    number_of_stocks = floor(investment_value\/aapl['close'][i])\n    returns = number_of_stocks*tsi_strategy_ret_df['tsi_returns'][i]\n    tsi_investment_ret.append(returns)\n\ntsi_investment_ret_df = pd.DataFrame(tsi_investment_ret).rename(columns = {0:'investment_returns'})\ntotal_investment_ret = round(sum(tsi_investment_ret_df['investment_returns']), 2)\nprofit_percentage = floor((total_investment_ret\/investment_value)*100)\nprint(cl('Profit gained from the tsi strategy by investing $100k in AAPL : {}'.format(total_investment_ret), attrs = ['bold']))\nprint(cl('Profit percentage of the tsi strategy : {}%'.format(profit_percentage), attrs = ['bold']))<\/pre>\n\n\n\n<p id=\"9f98\"><strong>Output:<\/strong><\/p>\n\n\n\n<pre class=\"wp-block-preformatted has-background\" style=\"background-color:#abb7c217\"><strong>Profit gained from the tsi strategy by investing $100k in AAPL : 95230.25\nProfit percentage of the tsi strategy : 95%<\/strong><\/pre>\n\n\n\n<p id=\"c1cf\"><strong>Code Explanation:<\/strong> First, we are calculating the returns of the Apple stock using the \u2018diff\u2019 function provided by the NumPy package and we have stored it as a dataframe in the \u2018aapl_ret\u2019 variable. Next, we are passing a for-loop to iterate over the values of the \u2018aapl_ret\u2019 variable to calculate the returns we gained from our TSI trading strategy, and these returns values are appended to the \u2018tsi_strategy_ret\u2019 list. Next, we are converting the \u2018tsi_strategy_ret\u2019 list into a dataframe and storing it in the \u2018tsi_strategy_ret_df\u2019 variable.<\/p>\n\n\n\n<p id=\"0d1e\">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 Apple 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 Apple 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=\"826b\">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 ninety-five thousand USD in one year. That\u2019s not bad! 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=\"24d2\">Step-8: SPY ETF Comparison<\/h2>\n\n\n\n<p>While this step is optional, it is highly recommended as it enables us to assess the performance of our trading strategy against a benchmark (SPY ETF). Here, we&#8217;ll extract SPY ETF data using the &#8216;get_historical_data&#8217; function and compare the returns from the SPY ETF with the returns generated by our trading strategy applied to Apple stock.<\/p>\n\n\n\n<p id=\"6e8a\"><strong>Python Implementation:<\/strong><\/p>\n\n\n\n<pre class=\"wp-block-preformatted has-white-color has-black-background-color has-text-color has-background\"><strong># SPY ETF COMPARISON\n<\/strong>\ndef 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('TSI Strategy profit is {}% higher than the Benchmark Profit'.format(profit_percentage - benchmark_profit_percentage), attrs = ['bold']))<\/pre>\n\n\n\n<p id=\"e408\"><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 : 40181.36\nBenchmark Profit percentage : 40%\nTSI Strategy profit is 55% higher than the Benchmark Profit<\/strong><\/pre>\n\n\n\n<p id=\"9273\"><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 Apple, we are investing in SPY ETF by not implementing any trading strategies. From the output, we can see that our True Strength Index signal line crossover trading strategy has outperformed the SPY ETF by 55%. That\u2019s great!<\/p>\n\n\n\n<p><\/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=\"ebfd\">Final Thoughts!<\/h1>\n\n\n\n<p id=\"7df2\">After an overwhelming process of crushing both theory and programming parts, we have successfully learned what the True Strength Index is all about, the mathematics behind the indicator, and the implementation of a profitable trading strategy based on it. Even though we managed to surpass the results of the SPY ETF, we are still lagging in one specific space.<\/p>\n\n\n\n<p id=\"05e7\">In this article, our algorithm buys and sells the same amount of stocks for all trades but that would not be an optimal decision to make while trading in the real world since it\u2019s arbitrary, and here is where the concept of position sizing comes into play. For those who don\u2019t have an idea about this concept, position sizing is the process of allocating a share of our portfolio to a specific stock we would like to trade. What we could do is, we can deploy a position-sizing system that assesses the risk involved in each trade and allocate the number of shares accordingly. This will not only boost the performance substantially but also prevents us from facing unexpected losses. So, I highly recommend you follow up with this concept and try implementing it into a trading strategy.<\/p>\n\n\n\n<p id=\"af18\">With that being said, you have reached the end of the article. Hope you learned something new and useful from this article.<\/p>\n","protected":false},"excerpt":{"rendered":"<p>A complete process in implementing a powerful indicator and a trading strategy in python to make better trades in the market<\/p>\n","protected":false},"author":18,"featured_media":1718,"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,42,59,61],"tags":[],"coding-language":[30],"ready-to-go-solution":[],"qualification":[31,32],"financial-apis-category":[36],"financial-apis-manuals":[39,40],"class_list":["post-1717","post","type-post","status-publish","format-standard","has-post-thumbnail","hentry","category-backtesting-strategies-examples","category-stocks-data-analysis-examples","category-technical-analysis-examples","category-trading-indicators-implimentations","coding-language-python","qualification-experienced","qualification-guru","financial-apis-category-stock-market-prices","financial-apis-manuals-end-of-day","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>Backtesting Index Trading Strategy Python: A Step-by-Step Guide | EODHD APIs Academy<\/title>\n<meta name=\"description\" content=\"Learn how to use Python to build and backtest a trading strategy based on the True Strength Index (TSI)\" \/>\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\/coding-the-true-strength-index-and-backtesting-a-trading-strategy-in-python\" \/>\n<meta property=\"og:locale\" content=\"en_US\" \/>\n<meta property=\"og:type\" content=\"article\" \/>\n<meta property=\"og:title\" content=\"Coding the True Strength Index and Backtesting a Trading Strategy in Python\" \/>\n<meta property=\"og:description\" content=\"Learn how to use Python to build and backtest a trading strategy based on the True Strength Index (TSI)\" \/>\n<meta property=\"og:url\" content=\"https:\/\/eodhd.com\/financial-academy\/backtesting-strategies-examples\/coding-the-true-strength-index-and-backtesting-a-trading-strategy-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-08-31T15:28:24+00:00\" \/>\n<meta property=\"article:modified_time\" content=\"2024-03-12T09:26:39+00:00\" \/>\n<meta property=\"og:image\" content=\"https:\/\/eodhd.com\/financial-academy\/wp-content\/uploads\/2023\/08\/image-16.png\" \/>\n\t<meta property=\"og:image:width\" content=\"828\" \/>\n\t<meta property=\"og:image:height\" content=\"621\" \/>\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=\"14 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\/coding-the-true-strength-index-and-backtesting-a-trading-strategy-in-python#article\",\"isPartOf\":{\"@id\":\"https:\/\/eodhd.com\/financial-academy\/backtesting-strategies-examples\/coding-the-true-strength-index-and-backtesting-a-trading-strategy-in-python\"},\"author\":{\"name\":\"Nikhil Adithyan\",\"@id\":\"https:\/\/eodhd.com\/financial-academy\/#\/schema\/person\/67681e71050cf7d8d0efb91fee5f0402\"},\"headline\":\"Coding the True Strength Index and Backtesting a Trading Strategy in Python\",\"datePublished\":\"2023-08-31T15:28:24+00:00\",\"dateModified\":\"2024-03-12T09:26:39+00:00\",\"mainEntityOfPage\":{\"@id\":\"https:\/\/eodhd.com\/financial-academy\/backtesting-strategies-examples\/coding-the-true-strength-index-and-backtesting-a-trading-strategy-in-python\"},\"wordCount\":2893,\"publisher\":{\"@id\":\"https:\/\/eodhd.com\/financial-academy\/#organization\"},\"image\":{\"@id\":\"https:\/\/eodhd.com\/financial-academy\/backtesting-strategies-examples\/coding-the-true-strength-index-and-backtesting-a-trading-strategy-in-python#primaryimage\"},\"thumbnailUrl\":\"https:\/\/eodhd.com\/financial-academy\/wp-content\/uploads\/2023\/08\/image-16.png\",\"articleSection\":[\"Backtesting Strategies Examples\",\"Stocks Data Analysis Examples\",\"Technical Analysis Examples\",\"Trading Indicators Implimentations\"],\"inLanguage\":\"en-US\"},{\"@type\":\"WebPage\",\"@id\":\"https:\/\/eodhd.com\/financial-academy\/backtesting-strategies-examples\/coding-the-true-strength-index-and-backtesting-a-trading-strategy-in-python\",\"url\":\"https:\/\/eodhd.com\/financial-academy\/backtesting-strategies-examples\/coding-the-true-strength-index-and-backtesting-a-trading-strategy-in-python\",\"name\":\"Backtesting Index Trading Strategy Python: A Step-by-Step Guide | EODHD APIs Academy\",\"isPartOf\":{\"@id\":\"https:\/\/eodhd.com\/financial-academy\/#website\"},\"primaryImageOfPage\":{\"@id\":\"https:\/\/eodhd.com\/financial-academy\/backtesting-strategies-examples\/coding-the-true-strength-index-and-backtesting-a-trading-strategy-in-python#primaryimage\"},\"image\":{\"@id\":\"https:\/\/eodhd.com\/financial-academy\/backtesting-strategies-examples\/coding-the-true-strength-index-and-backtesting-a-trading-strategy-in-python#primaryimage\"},\"thumbnailUrl\":\"https:\/\/eodhd.com\/financial-academy\/wp-content\/uploads\/2023\/08\/image-16.png\",\"datePublished\":\"2023-08-31T15:28:24+00:00\",\"dateModified\":\"2024-03-12T09:26:39+00:00\",\"description\":\"Learn how to use Python to build and backtest a trading strategy based on the True Strength Index (TSI)\",\"breadcrumb\":{\"@id\":\"https:\/\/eodhd.com\/financial-academy\/backtesting-strategies-examples\/coding-the-true-strength-index-and-backtesting-a-trading-strategy-in-python#breadcrumb\"},\"inLanguage\":\"en-US\",\"potentialAction\":[{\"@type\":\"ReadAction\",\"target\":[\"https:\/\/eodhd.com\/financial-academy\/backtesting-strategies-examples\/coding-the-true-strength-index-and-backtesting-a-trading-strategy-in-python\"]}]},{\"@type\":\"ImageObject\",\"inLanguage\":\"en-US\",\"@id\":\"https:\/\/eodhd.com\/financial-academy\/backtesting-strategies-examples\/coding-the-true-strength-index-and-backtesting-a-trading-strategy-in-python#primaryimage\",\"url\":\"https:\/\/eodhd.com\/financial-academy\/wp-content\/uploads\/2023\/08\/image-16.png\",\"contentUrl\":\"https:\/\/eodhd.com\/financial-academy\/wp-content\/uploads\/2023\/08\/image-16.png\",\"width\":828,\"height\":621,\"caption\":\"Coding the True Strength Index and Backtesting a Trading Strategy in Python\"},{\"@type\":\"BreadcrumbList\",\"@id\":\"https:\/\/eodhd.com\/financial-academy\/backtesting-strategies-examples\/coding-the-true-strength-index-and-backtesting-a-trading-strategy-in-python#breadcrumb\",\"itemListElement\":[{\"@type\":\"ListItem\",\"position\":1,\"name\":\"Home\",\"item\":\"https:\/\/eodhd.com\/financial-academy\/\"},{\"@type\":\"ListItem\",\"position\":2,\"name\":\"Coding the True Strength Index and Backtesting a Trading Strategy 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":"Backtesting Index Trading Strategy Python: A Step-by-Step Guide | EODHD APIs Academy","description":"Learn how to use Python to build and backtest a trading strategy based on the True Strength Index (TSI)","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\/coding-the-true-strength-index-and-backtesting-a-trading-strategy-in-python","og_locale":"en_US","og_type":"article","og_title":"Coding the True Strength Index and Backtesting a Trading Strategy in Python","og_description":"Learn how to use Python to build and backtest a trading strategy based on the True Strength Index (TSI)","og_url":"https:\/\/eodhd.com\/financial-academy\/backtesting-strategies-examples\/coding-the-true-strength-index-and-backtesting-a-trading-strategy-in-python","og_site_name":"Financial Academy","article_publisher":"https:\/\/www.facebook.com\/eodhistoricaldata","article_published_time":"2023-08-31T15:28:24+00:00","article_modified_time":"2024-03-12T09:26:39+00:00","og_image":[{"width":828,"height":621,"url":"https:\/\/eodhd.com\/financial-academy\/wp-content\/uploads\/2023\/08\/image-16.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":"14 minutes"},"schema":{"@context":"https:\/\/schema.org","@graph":[{"@type":"Article","@id":"https:\/\/eodhd.com\/financial-academy\/backtesting-strategies-examples\/coding-the-true-strength-index-and-backtesting-a-trading-strategy-in-python#article","isPartOf":{"@id":"https:\/\/eodhd.com\/financial-academy\/backtesting-strategies-examples\/coding-the-true-strength-index-and-backtesting-a-trading-strategy-in-python"},"author":{"name":"Nikhil Adithyan","@id":"https:\/\/eodhd.com\/financial-academy\/#\/schema\/person\/67681e71050cf7d8d0efb91fee5f0402"},"headline":"Coding the True Strength Index and Backtesting a Trading Strategy in Python","datePublished":"2023-08-31T15:28:24+00:00","dateModified":"2024-03-12T09:26:39+00:00","mainEntityOfPage":{"@id":"https:\/\/eodhd.com\/financial-academy\/backtesting-strategies-examples\/coding-the-true-strength-index-and-backtesting-a-trading-strategy-in-python"},"wordCount":2893,"publisher":{"@id":"https:\/\/eodhd.com\/financial-academy\/#organization"},"image":{"@id":"https:\/\/eodhd.com\/financial-academy\/backtesting-strategies-examples\/coding-the-true-strength-index-and-backtesting-a-trading-strategy-in-python#primaryimage"},"thumbnailUrl":"https:\/\/eodhd.com\/financial-academy\/wp-content\/uploads\/2023\/08\/image-16.png","articleSection":["Backtesting Strategies Examples","Stocks Data Analysis Examples","Technical Analysis Examples","Trading Indicators Implimentations"],"inLanguage":"en-US"},{"@type":"WebPage","@id":"https:\/\/eodhd.com\/financial-academy\/backtesting-strategies-examples\/coding-the-true-strength-index-and-backtesting-a-trading-strategy-in-python","url":"https:\/\/eodhd.com\/financial-academy\/backtesting-strategies-examples\/coding-the-true-strength-index-and-backtesting-a-trading-strategy-in-python","name":"Backtesting Index Trading Strategy Python: A Step-by-Step Guide | EODHD APIs Academy","isPartOf":{"@id":"https:\/\/eodhd.com\/financial-academy\/#website"},"primaryImageOfPage":{"@id":"https:\/\/eodhd.com\/financial-academy\/backtesting-strategies-examples\/coding-the-true-strength-index-and-backtesting-a-trading-strategy-in-python#primaryimage"},"image":{"@id":"https:\/\/eodhd.com\/financial-academy\/backtesting-strategies-examples\/coding-the-true-strength-index-and-backtesting-a-trading-strategy-in-python#primaryimage"},"thumbnailUrl":"https:\/\/eodhd.com\/financial-academy\/wp-content\/uploads\/2023\/08\/image-16.png","datePublished":"2023-08-31T15:28:24+00:00","dateModified":"2024-03-12T09:26:39+00:00","description":"Learn how to use Python to build and backtest a trading strategy based on the True Strength Index (TSI)","breadcrumb":{"@id":"https:\/\/eodhd.com\/financial-academy\/backtesting-strategies-examples\/coding-the-true-strength-index-and-backtesting-a-trading-strategy-in-python#breadcrumb"},"inLanguage":"en-US","potentialAction":[{"@type":"ReadAction","target":["https:\/\/eodhd.com\/financial-academy\/backtesting-strategies-examples\/coding-the-true-strength-index-and-backtesting-a-trading-strategy-in-python"]}]},{"@type":"ImageObject","inLanguage":"en-US","@id":"https:\/\/eodhd.com\/financial-academy\/backtesting-strategies-examples\/coding-the-true-strength-index-and-backtesting-a-trading-strategy-in-python#primaryimage","url":"https:\/\/eodhd.com\/financial-academy\/wp-content\/uploads\/2023\/08\/image-16.png","contentUrl":"https:\/\/eodhd.com\/financial-academy\/wp-content\/uploads\/2023\/08\/image-16.png","width":828,"height":621,"caption":"Coding the True Strength Index and Backtesting a Trading Strategy in Python"},{"@type":"BreadcrumbList","@id":"https:\/\/eodhd.com\/financial-academy\/backtesting-strategies-examples\/coding-the-true-strength-index-and-backtesting-a-trading-strategy-in-python#breadcrumb","itemListElement":[{"@type":"ListItem","position":1,"name":"Home","item":"https:\/\/eodhd.com\/financial-academy\/"},{"@type":"ListItem","position":2,"name":"Coding the True Strength Index and Backtesting a Trading Strategy 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\/08\/image-16.png","jetpack_shortlink":"https:\/\/wp.me\/pdOdVT-rH","jetpack_sharing_enabled":true,"acf":[],"_links":{"self":[{"href":"https:\/\/eodhd.com\/financial-academy\/wp-json\/wp\/v2\/posts\/1717","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=1717"}],"version-history":[{"count":11,"href":"https:\/\/eodhd.com\/financial-academy\/wp-json\/wp\/v2\/posts\/1717\/revisions"}],"predecessor-version":[{"id":3056,"href":"https:\/\/eodhd.com\/financial-academy\/wp-json\/wp\/v2\/posts\/1717\/revisions\/3056"}],"wp:featuredmedia":[{"embeddable":true,"href":"https:\/\/eodhd.com\/financial-academy\/wp-json\/wp\/v2\/media\/1718"}],"wp:attachment":[{"href":"https:\/\/eodhd.com\/financial-academy\/wp-json\/wp\/v2\/media?parent=1717"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/eodhd.com\/financial-academy\/wp-json\/wp\/v2\/categories?post=1717"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/eodhd.com\/financial-academy\/wp-json\/wp\/v2\/tags?post=1717"},{"taxonomy":"coding-language","embeddable":true,"href":"https:\/\/eodhd.com\/financial-academy\/wp-json\/wp\/v2\/coding-language?post=1717"},{"taxonomy":"ready-to-go-solution","embeddable":true,"href":"https:\/\/eodhd.com\/financial-academy\/wp-json\/wp\/v2\/ready-to-go-solution?post=1717"},{"taxonomy":"qualification","embeddable":true,"href":"https:\/\/eodhd.com\/financial-academy\/wp-json\/wp\/v2\/qualification?post=1717"},{"taxonomy":"financial-apis-category","embeddable":true,"href":"https:\/\/eodhd.com\/financial-academy\/wp-json\/wp\/v2\/financial-apis-category?post=1717"},{"taxonomy":"financial-apis-manuals","embeddable":true,"href":"https:\/\/eodhd.com\/financial-academy\/wp-json\/wp\/v2\/financial-apis-manuals?post=1717"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}