{"id":1350,"date":"2023-08-07T10:16:42","date_gmt":"2023-08-07T10:16:42","guid":{"rendered":"https:\/\/eodhd.com\/financial-academy\/?p=1350"},"modified":"2025-02-05T13:20:03","modified_gmt":"2025-02-05T13:20:03","slug":"using-python-to-create-an-innovative-trading-strategy-and-achieve-better-results","status":"publish","type":"post","link":"https:\/\/eodhd.com\/financial-academy\/backtesting-strategies-examples\/using-python-to-create-an-innovative-trading-strategy-and-achieve-better-results","title":{"rendered":"Using Python to Create an Innovative Trading Strategy and Achieve Better Results"},"content":{"rendered":"\n<p>The trading arena is experiencing an influx of individuals striving to capitalize on the stock market. To stand out in this vast landscape and gain a competitive edge, innovation is key. Developing unconventional ideas that deviate from common practices is essential for success. For instance, although technical indicators like the&nbsp;Stochastic Oscillator&nbsp;have become widely adopted, achieving success demands creative utilization rather than adhering solely to traditional strategies. Today, we embark on a journey to do just that.<\/p>\n\n\n\n<p>In this article, we will utilize Python to create an innovative trading strategy by synergizing two potent indicators: the&nbsp;Stochastic Oscillator&nbsp;and the&nbsp;Moving Average Convergence\/Divergence (MACD) indicator. This strategy will explore how to use the&nbsp;Stochastic Oscillator for intraday&nbsp;trading, focusing on the&nbsp;raw stochastic value, the&nbsp;stochastic K and D line, and its role as a&nbsp;market edge oscillator. Our objective is to minimize false signals as much as possible, thereby enhancing overall performance. Without further delay, let&#8217;s dive into the content!<\/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=\"739f\">Stochastic Oscillator<\/h1>\n\n\n\n<p>The Stochastic Oscillator is a momentum-based leading indicator extensively employed to identify overbought and oversold conditions in the market. But what do these terms signify? Overbought refers to a stock in an extremely bullish market, likely to consolidate. Conversely, oversold indicates a stock in an extremely bearish market, with potential for a rebound.<\/p>\n\n\n\n<p>The Stochastic Oscillator values&nbsp;range&nbsp;between 0 and 100 due to normalization. Commonly, overbought and oversold levels are set at 70 and 30 respectively, although these thresholds can vary. The Stochastic Oscillator&nbsp;consists&nbsp;of two primary components: the&nbsp;stochastic K and D line, which together provide insight into market trends and potential reversals:<\/p>\n\n\n\n<ul class=\"wp-block-list\">\n<li><strong>%K Line:<\/strong>&nbsp;Also known as the Fast Stochastic indicator, this line is pivotal. It assesses the current market state (overbought or oversold). The %K line is calculated by subtracting the lowest price over a specific period from the closing price and dividing the result by the difference between the highest and lowest prices over the same period. The outcome is then multiplied by 100. With a popular setting of 14 periods, the %K line calculation is as follows:<\/li>\n<\/ul>\n\n\n\n<p class=\"has-background\" style=\"background-color:#abb7c217\"><strong><code>%K = 100 * ((14 DAY CLOSING PRICE - 14 DAY LOWEST PRICE) - (14 DAY HIGHEST PRICE - 14 DAY LOWEST PRICE))<\/code><\/strong><\/p>\n\n\n\n<ul class=\"wp-block-list\">\n<li><strong>%D Line:<\/strong> Referred to as the Slow Stochastic Indicator, this line is the moving average of the %K line over a designated period. It serves as the smoothed version of %K, appearing less erratic. A standard period for %D is 3.<\/li>\n<\/ul>\n\n\n\n<p>This summarizes the Stochastic Oscillator components. Now, let&#8217;s examine a chart featuring Apple&#8217;s closing price data along with the Stochastic Oscillator calculated using a 14-day period for %K and a 3-day period for %D. This will facilitate a better grasp of the indicator and its practical application.<\/p>\n\n\n\n<figure class=\"wp-block-image size-full\"><img loading=\"lazy\" decoding=\"async\" width=\"1801\" height=\"884\" src=\"https:\/\/eodhistoricaldata.com\/financial-academy\/wp-content\/uploads\/2023\/07\/image-12.png\" alt=\"\" class=\"wp-image-1352\"\/><\/figure>\n\n\n\n<p>The chart consists of two panels: the upper panel displays Apple&#8217;s closing price line plot, while the lower panel showcases the&nbsp;Stochastic Oscillator components. As a&nbsp;market edge oscillator&nbsp;and&nbsp;momentum&nbsp;indicator, the Stochastic Oscillator cannot be plotted alongside the closing price due to substantial value differences, so it&#8217;s plotted separately.<\/p>\n\n\n\n<p>The&nbsp;stochastic K and D lines&nbsp;are depicted in blue and orange respectively. Additionally, you&#8217;ll notice black dotted lines above and below these lines, representing the bands that highlight&nbsp;overbought and oversold regions.<\/p>\n\n\n\n<h1 class=\"wp-block-heading\" id=\"4638\">MACD<\/h1>\n\n\n\n<p>Before delving into MACD, let&#8217;s clarify Exponential Moving Average (EMA). EMA is a type of Moving Average that assigns greater weight to recent data points and lesser weight to distant ones. For instance, in a question paper consisting of 10% one-mark questions, 40% three-mark questions, and 50% long-answer questions, unique weights are assigned based on importance. Similarly, EMA assigns varying weights to data points based on their relevance.<\/p>\n\n\n\n<p>MACD, a trend-following leading indicator, is calculated by subtracting two EMAs (one with longer and one with shorter periods). Three key components constitute a MACD indicator:<\/p>\n\n\n\n<ul class=\"wp-block-list\">\n<li><strong>MACD Line:<\/strong>&nbsp;This line signifies the difference between two EMAs. It involves one EMA with a longer period (slow length) and another with a shorter period (fast length). Common settings are 12 and 26 for fast and slow lengths respectively. Calculation is simply the subtraction of slow length EMA from fast length EMA:<\/li>\n<\/ul>\n\n\n\n<pre class=\"wp-block-preformatted has-background\" style=\"background-color:#abb7c217\"><strong><code>MACD LINE = FAST LENGTH EMA - SLOW LENGTH EMA<\/code><\/strong><\/pre>\n\n\n\n<ul class=\"wp-block-list\">\n<li><strong>Signal Line:<\/strong>&nbsp;Also known as the Slow Stochastic Indicator, this is the EMA of the MACD line over a specified period, typically 9. As an average of the MACD line, the Signal line is smoother.<\/li>\n\n\n\n<li><strong>Histogram:<\/strong>&nbsp;Representing the difference between the MACD line and the Signal line, the Histogram aids in trend identification. Its calculation is straightforward:<\/li>\n<\/ul>\n\n\n\n<p class=\"has-background\" style=\"background-color:#abb7c217\"><strong><code>HISTOGRAM = MACD LINE - SIGNAL LINE<\/code><\/strong><\/p>\n\n\n\n<p>With a grasp of MACD&#8217;s essence, let&#8217;s analyze a MACD chart to foster intuition about the indicator.<\/p>\n\n\n\n<figure class=\"wp-block-image size-full\"><img loading=\"lazy\" decoding=\"async\" width=\"1801\" height=\"884\" src=\"https:\/\/eodhistoricaldata.com\/financial-academy\/wp-content\/uploads\/2023\/07\/image-13.png\" alt=\"\" class=\"wp-image-1353\"\/><\/figure>\n\n\n\n<p>The chart features two panels: the upper panel depicts Apple&#8217;s closing prices, while the lower panel presents a series of MACD components. Each component is worth inspecting.<\/p>\n\n\n\n<p>The most prominent aspect in the lower panel is the Histogram plot. This plot turns red during negative trends and green during positive ones, offering a visual trend indicator. The spread of the Histogram plot correlates with the difference between MACD and Signal lines. The plot enlarges when this difference is substantial, and contracts when it&#8217;s relatively smaller.<\/p>\n\n\n\n<p>The other components are the MACD line and the Signal line. The gray line denotes the MACD line, representing the disparity between slow-length and fast-length EMAs of Apple&#8217;s stock prices. The blue line, or Signal line, depicts the EMA of the MACD line. The Signal line is smoother due to averaging of MACD line values.<\/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=\"f7a8\">Trading Strategy<\/h1>\n\n\n\n<p>Now, having established foundational insights into both the Stochastic Oscillator and MACD, let&#8217;s address the trading strategy we&#8217;ll implement. The strategy is simple and aims to capitalize on overbought and oversold conditions while minimizing false signals.<\/p>\n\n\n\n<p>We buy (go long) if both %K and %D lines fall below 30, and if both MACD and Signal lines are less than -2. Similarly, we sell (go short) if %K and %D lines cross above 70, and if both MACD and Signal line values exceed 2. The strategy can be formalized as follows:<\/p>\n\n\n\n<p class=\"has-background\" style=\"background-color:#abb7c217\"><code>IF <strong>%K &lt; 30 <\/strong>AND <strong>%D &lt; 30 <\/strong>AND <strong>MACD.L &lt; -2 <\/strong>AND<strong> SIGNAL.L &lt; -2<\/strong> ==&gt; <strong>BUY<\/strong><br>IF <strong>%K &gt; 70 <\/strong>AND <strong>%D &gt; 70 <\/strong>AND <strong>MACD.L &gt; 2 <\/strong>AND<strong> SIGNAL.L &gt; 2<\/strong> ==&gt; <strong>SELL<\/strong><\/code><\/p>\n\n\n\n<p>This strategy concludes our theoretical segment. Let&#8217;s transition to the practical side \u2013 the programming. We&#8217;ll use Python to build the indicators from scratch, implement the discussed strategy, conduct backtesting on Apple stock data, and ultimately compare outcomes with the SPY ETF. Let&#8217;s embark on the coding journey!<\/p>\n\n\n\n<p><strong>Before we proceed, a disclaimer: The purpose of this article is educational, and the strategies presented should be<\/strong> <strong>considered as an information piece but not as investment advice<\/strong>.<\/p>\n\n\n\n<h1 class=\"wp-block-heading\" id=\"afff\">Implementation in Python<\/h1>\n\n\n\n<p id=\"8a3f\">The coding process is divided into several steps as outlined below:<\/p>\n\n\n\n<p class=\"has-background\" style=\"background-color:#abb7c217\"><strong>1. Importing Packages<br>2. Extracting Stock Data using EODHD API<br>3. Stochastic Oscillator Calculation<br>4. MACD Calculation<br>5. Creating the Trading Strategy<br>6. Creating our Position<br>7. Backtesting<br>8. SPY ETF Comparison<\/strong><\/p>\n\n\n\n<p id=\"aa1b\">We will follow the sequence mentioned above to guide you through each coding segment.<\/p>\n\n\n\n<h2 class=\"wp-block-heading\" id=\"394f\">Step-1: Importing Packages<\/h2>\n\n\n\n<p>Importing the necessary packages into the Python environment is a crucial initial step. The primary packages to be employed include Pandas for data manipulation, NumPy for array handling and complex operations, Matplotlib for plotting, and Requests for API calls. Additionally, Math is utilized for mathematical functions, and Termcolor offers optional font customization.<\/p>\n\n\n\n<p id=\"827b\"><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\"><strong># IMPORTING PACKAGES\n<\/strong>\nimport pandas as pd\nimport numpy as np\nimport requests\nimport matplotlib.pyplot as plt\nfrom math import floor\nfrom termcolor import colored as cl\n\nplt.style.use('fivethirtyeight')\nplt.rcParams['figure.figsize'] = (20,10)<\/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>Once we&#8217;ve imported all the required packages, we can proceed to retrieve 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=\"b063\">Step-2: Extracting Stock Data using EODHD<\/h2>\n\n\n\n<p id=\"9e41\">In this step, we&#8217;ll retrieve Apple&#8217;s historical stock data through <a href=\"https:\/\/eodhd.com\/financial-apis\/technical-indicators-api\/#Split_Adjusted_Data\">OHLC split-adjusted API endpoint<\/a> provided by&nbsp;<a href=\"https:\/\/eodhd.com\/\" target=\"_blank\" rel=\"noreferrer noopener\">EODHD<\/a>. Please note that&nbsp;<a href=\"https:\/\/eodhd.com\/\" target=\"_blank\" rel=\"noreferrer noopener\">EOD Historical Data<\/a> provides reliable financial APIs, encompassing diverse market data, from historical records to economic and financial news data. It&#8217;s essential to possess an <a href=\"https:\/\/eodhd.com\/register\">EODHD account<\/a> to access the secret API key, a crucial element for data extraction through the API.<\/p>\n\n\n\n<p id=\"f00a\"><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\"><strong># EXTRACTING STOCK DATA\n<\/strong>\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', '2010-01-01')\naapl.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=\"1067\"><strong>Output:<\/strong><\/p>\n\n\n\n<figure class=\"wp-block-image size-full\"><img loading=\"lazy\" decoding=\"async\" width=\"844\" height=\"456\" src=\"https:\/\/eodhistoricaldata.com\/financial-academy\/wp-content\/uploads\/2023\/07\/image-15.png\" alt=\"\" class=\"wp-image-1355\"\/><\/figure>\n\n\n\n<p><strong>Code Explanation:<\/strong>&nbsp;We begin by defining a function named &#8216;get_historical_data&#8217;. This function requires the stock symbol (&#8216;symbol&#8217;) and the starting date for historical data (&#8216;start_date&#8217;) as parameters. Within the function, we define the API key and URL, storing them in respective variables. Subsequently, we retrieve historical data in JSON format using the &#8216;get&#8217; function, storing it in the &#8216;raw_df&#8217; variable. After processing the raw JSON data to achieve a clean Pandas dataframe, we return it. Finally, we call this function to fetch Apple&#8217;s historical data from the start of 2010, storing it in the &#8216;aapl&#8217; variable.<\/p>\n\n\n\n<h2 class=\"wp-block-heading\" id=\"89b9\">Step-3: Stochastic Oscillator Calculation<\/h2>\n\n\n\n<p id=\"37c3\">In this phase, we calculate the components of the Stochastic Oscillator using the methods and formulas discussed earlier.<\/p>\n\n\n\n<p id=\"aaf8\"><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\"><strong># STOCHASTIC OSCILLATOR CALCULATION<br><\/strong><br>def get_stoch_osc(high, low, close, k_lookback, d_lookback):<br>    lowest_low = low.rolling(k_lookback).min()<br>    highest_high = high.rolling(k_lookback).max()<br>    k_line = ((close - lowest_low) \/ (highest_high - lowest_low)) * 100<br>    d_line = k_line.rolling(d_lookback).mean()<br>    return k_line, d_line<br><br>aapl['%k'], aapl['%d'] = get_stoch_osc(aapl['high'], aapl['low'], aapl['close'], 14, 3)<br>aapl.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=\"0f63\"><strong>Output:<\/strong><\/p>\n\n\n\n<figure class=\"wp-block-image size-full\"><img loading=\"lazy\" decoding=\"async\" width=\"1207\" height=\"465\" src=\"https:\/\/eodhistoricaldata.com\/financial-academy\/wp-content\/uploads\/2023\/07\/image-16.png\" alt=\"\" class=\"wp-image-1356\"\/><\/figure>\n\n\n\n<p id=\"e7ac\"><strong>Code Explanation:&nbsp;<\/strong>We define a function called &#8216;get_stoch_osc&#8217;. This function takes high (&#8216;high&#8217;), low (&#8216;low&#8217;), closing price (&#8216;close&#8217;), %K line lookback (&#8216;k_lookback&#8217;), and %D line lookback (&#8216;d_lookback&#8217;) as parameters. Inside the function, we compute the lowest low and highest high values over a specified period using Pandas&#8217; &#8216;rolling&#8217;, &#8216;min&#8217;, and &#8216;max&#8217; functions. These values are stored in &#8216;lowest_low&#8217; and &#8216;highest_high&#8217; variables, respectively.<\/p>\n\n\n\n<p>Next, we compute the %K line and %D line values according to their formulas, saving them in &#8216;k_line&#8217; and &#8216;d_line&#8217; variables. Finally, we return these values, applying the function to obtain Apple&#8217;s Stochastic Oscillator readings using lookback periods of 14 for %K and 3 for %D.<\/p>\n\n\n\n<h2 class=\"wp-block-heading\" id=\"f043\">Step-4: MACD Calculation<\/h2>\n\n\n\n<p>This step focuses on calculating the components of the MACD indicator using Apple&#8217;s extracted historical data.<\/p>\n\n\n\n<p id=\"6866\"><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\"><strong># MACD CALCULATION<br><\/strong><br>def get_macd(price, slow, fast, smooth):<br>    exp1 = price.ewm(span = fast, adjust = False).mean()<br>    exp2 = price.ewm(span = slow, adjust = False).mean()<br>    macd = pd.DataFrame(exp1 - exp2).rename(columns = {'close':'macd'})<br>    signal = pd.DataFrame(macd.ewm(span = smooth, adjust = False).mean()).rename(columns = {'macd':'signal'})<br>    hist = pd.DataFrame(macd['macd'] - signal['signal']).rename(columns = {0:'hist'})<br>    return macd, signal, hist<br><br>aapl['macd'] = get_macd(aapl['close'], 26, 12, 9)[0]<br>aapl['macd_signal'] = get_macd(aapl['close'], 26, 12, 9)[1]<br>aapl['macd_hist'] = get_macd(aapl['close'], 26, 12, 9)[2]<br>aapl = aapl.dropna()<br>aapl.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=\"7e5f\"><strong>Output:<\/strong><\/p>\n\n\n\n<figure class=\"wp-block-image size-full\"><img loading=\"lazy\" decoding=\"async\" width=\"1302\" height=\"354\" src=\"https:\/\/eodhistoricaldata.com\/financial-academy\/wp-content\/uploads\/2023\/07\/image-17.png\" alt=\"\" class=\"wp-image-1357\"\/><\/figure>\n\n\n\n<p id=\"ba30\"><strong>Code Explanation:<\/strong>&nbsp;We define a function named &#8216;get_macd&#8217;, which accepts stock prices (&#8216;prices&#8217;), slow EMA length (&#8216;slow&#8217;), fast EMA length (&#8216;fast&#8217;), and Signal line period (&#8216;smooth&#8217;) as inputs.<\/p>\n\n\n\n<p>Inside the function, we compute the slow and fast EMAs using Pandas&#8217; &#8216;ewm&#8217; function, storing them in &#8217;ema1&#8242; and &#8217;ema2&#8242; variables. We then calculate the MACD line by subtracting the slow EMA from the fast EMA and store it in the &#8216;macd&#8217; variable. The Signal line is computed by taking the EMA of the MACD line values for a specific period, stored in the &#8216;signal&#8217; variable. The Histogram values are derived from the difference between the MACD line and the Signal line, stored in the &#8216;hist&#8217; variable. Finally, all calculated values are returned, and the function is called to acquire Apple&#8217;s MACD components.<\/p>\n\n\n\n<h2 class=\"wp-block-heading\" id=\"1c87\">Step-5: Creating the Trading Strategy:<\/h2>\n\n\n\n<p>In this stage, we implement the combined trading strategy involving the Stochastic Oscillator and Moving Average Convergence\/Divergence (MACD) indicators using Python.<\/p>\n\n\n\n<p id=\"92a9\"><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\"><strong># TRADING STRATEGY<br><\/strong><br>def implement_stoch_macd_strategy(prices, k, d, macd, macd_signal):    <br>    buy_price = []<br>    sell_price = []<br>    stoch_macd_signal = []<br>    signal = 0<br><br>    for i in range(len(prices)):<br>        if k[i] &lt; 30 and d[i] &lt; 30 and macd[i] &lt; -2 and macd_signal[i] &lt; -2:<br>            if signal != 1:<br>                buy_price.append(prices[i])<br>                sell_price.append(np.nan)<br>                signal = 1<br>                stoch_macd_signal.append(signal)<br>            else:<br>                buy_price.append(np.nan)<br>                sell_price.append(np.nan)<br>                stoch_macd_signal.append(0)<br>                <br>        elif k[i] &gt; 70 and d[i] &gt; 70 and macd[i] &gt; 2 and macd_signal[i] &gt; 2:<br>            if signal != -1 and signal != 0:<br>                buy_price.append(np.nan)<br>                sell_price.append(prices[i])<br>                signal = -1<br>                stoch_macd_signal.append(signal)<br>            else:<br>                buy_price.append(np.nan)<br>                sell_price.append(np.nan)<br>                stoch_macd_signal.append(0)<br>        <br>        else:<br>            buy_price.append(np.nan)<br>            sell_price.append(np.nan)<br>            stoch_macd_signal.append(0)<br>            <br>    return buy_price, sell_price, stoch_macd_signal<br>            <br>buy_price, sell_price, stoch_macd_signal = implement_stoch_macd_strategy(aapl['close'], aapl['%k'], aapl['%d'], aapl['macd'], aapl['macd_signal'])<\/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=\"f931\"><strong>Code Explanation:<\/strong>&nbsp;We define a function named &#8216;bb_stoch_strategy&#8217;, which takes stock prices (&#8216;prices&#8217;), %K line values (&#8216;k&#8217;), %D line values (&#8216;d&#8217;), MACD line (&#8216;macd&#8217;), and Signal line (&#8216;macd_signal&#8217;) as inputs.<\/p>\n\n\n\n<p>Within the function, we create empty lists (&#8216;buy_price&#8217;, &#8216;sell_price&#8217;, and &#8216;stoch_macd_signal&#8217;) to which values will be appended while implementing the trading strategy.<\/p>\n\n\n\n<p id=\"07b5\">We then employ a for-loop to execute the trading strategy. Based on specified conditions, values are 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 buying 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.The function returns lists with appended values. We call this function to store the values in their respective variables.<\/p>\n\n\n\n<h2 class=\"wp-block-heading\" id=\"6190\">Step-6: Creating our Position<\/h2>\n\n\n\n<p>This step involves creating a list indicating whether we hold the stock (1) or not (0).<\/p>\n\n\n\n<p id=\"d20c\"><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\"><strong># POSITION<br><\/strong><br>position = []<br>for i in range(len(stoch_macd_signal)):<br>    if stoch_macd_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 stoch_macd_signal[i] == 1:<br>        position[i] = 1<br>    elif stoch_macd_signal[i] == -1:<br>        position[i] = 0<br>    else:<br>        position[i] = position[i-1]<br>        <br>close_price = aapl['close']<br>k_line = aapl['%k']<br>d_line = aapl['%d']<br>macd_line = aapl['macd']<br>signal_line = aapl['macd_signal']<br>stoch_macd_signal = pd.DataFrame(stoch_macd_signal).rename(columns = {0:'stoch_macd_signal'}).set_index(aapl.index)<br>position = pd.DataFrame(position).rename(columns = {0:'stoch_macd_position'}).set_index(aapl.index)<br><br>frames = [close_price, k_line, d_line, macd_line, signal_line, stoch_macd_signal, position]<br>strategy = pd.concat(frames, join = 'inner', axis = 1)<br><br>strategy<\/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=\"b004\"><strong>Output:<\/strong><\/p>\n\n\n\n<figure class=\"wp-block-image size-full\"><img loading=\"lazy\" decoding=\"async\" width=\"1275\" height=\"353\" src=\"https:\/\/eodhistoricaldata.com\/financial-academy\/wp-content\/uploads\/2023\/07\/image-18.png\" alt=\"\" class=\"wp-image-1358\"\/><\/figure>\n\n\n\n<p id=\"7e7d\"><strong>Code Explanation:<\/strong>&nbsp;We begin by creating an empty list called &#8216;position&#8217;. We employ two for-loops: the first to generate values for the &#8216;position&#8217; list to match the length of the &#8216;signal&#8217; list, and the second to generate actual position values.<\/p>\n\n\n\n<p>Inside the second for-loop, we iterate through the &#8216;signal&#8217; list values. Depending on conditions, we append values to the &#8216;position&#8217; list. The position remains 1 when holding the stock or 0 when not owning the stock. Finally, we manipulate data to combine the lists into a single dataframe.<\/p>\n\n\n\n<p>From the displayed output, it&#8217;s evident that our stock position remains 1 initially, indicating no change in the trading signal. However, the position shifts to 0 when we sell the stock due to a buy signal (-1). The position remains -1 until the trading signal changes. Now, let&#8217;s proceed to implement backtesting.<\/p>\n\n\n\n<h2 class=\"wp-block-heading\" id=\"6d6e\">Step-7: Backtesting<\/h2>\n\n\n\n<p>Before continuing, it&#8217;s crucial to understand backtesting. This process involves evaluating the performance of our trading strategy on the given stock data. In this case, we&#8217;ll backtest the combined Stochastic Oscillator and MACD trading strategy on Apple&#8217;s data.<\/p>\n\n\n\n<p id=\"0a2b\"><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\"><strong># BACKTESTING\n<\/strong>\naapl_ret = pd.DataFrame(np.diff(aapl['close'])).rename(columns = {0:'returns'})\nstoch_macd_strategy_ret = []\n\nfor i in range(len(aapl_ret)):\n    try:\n        returns = aapl_ret['returns'][i] * strategy['stoch_macd_position'][i]\n        stoch_macd_strategy_ret.append(returns)\n    except:\n        pass\n    \nstoch_macd_strategy_ret_df = pd.DataFrame(stoch_macd_strategy_ret).rename(columns = {0:'stoch_macd_returns'})\n\ninvestment_value = 100000\nstoch_macd_investment_ret = []\n\nfor i in range(len(stoch_macd_strategy_ret_df['stoch_macd_returns'])):\n    number_of_stocks = floor(investment_value\/aapl['close'][i])\n    returns = number_of_stocks * stoch_macd_strategy_ret_df['stoch_macd_returns'][i]\n    stoch_macd_investment_ret.append(returns)\n\nstoch_macd_investment_ret_df = pd.DataFrame(stoch_macd_investment_ret).rename(columns = {0:'investment_returns'})\ntotal_investment_ret = round(sum(stoch_macd_investment_ret_df['investment_returns']), 2)\nprofit_percentage = floor((total_investment_ret \/ investment_value) * 100)\nprint(cl('Profit gained from the STOCH MACD strategy by investing $100k in AAPL : {}'.format(total_investment_ret), attrs = ['bold']))\nprint(cl('Profit percentage of the STOCH MACD 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=\"9c46\"><strong>Output:<\/strong><\/p>\n\n\n\n<pre class=\"wp-block-preformatted has-background\" style=\"background-color:#abb7c217\"><strong>Profit gained from the STOCH MACD strategy by investing $100k in AAPL : 313585.35\nProfit percentage of the STOCH MACD strategy : 313%<\/strong><\/pre>\n\n\n\n<p id=\"7dc0\"><strong>Code Explanation:<\/strong>&nbsp;Firstly, we calculate returns for Apple stock using NumPy&#8217;s &#8216;diff&#8217; function, storing them as a dataframe in &#8216;aapl_ret&#8217;. We then use a for-loop to calculate returns obtained from our trading strategy, appending them to &#8216;stoch_macd_strategy_ret&#8217; list. This list is converted into a dataframe and stored in &#8216;stoch_macd_strategy_ret_df&#8217;.<\/p>\n\n\n\n<p>Next, we initiate backtesting by investing $100,000 in our strategy. Investment value is stored in &#8216;investment_value&#8217;. Using a for-loop, we calculate investment returns and perform data manipulations.<\/p>\n\n\n\n<p>Finally, we print the total return obtained by investing $100,000 in our trading strategy. The output shows that an approximate profit of $300,000 was generated in around thirteen and a half years, with a profit percentage of 313%. Impressive! Now, let&#8217;s compare these returns with the SPY ETF.<\/p>\n\n\n\n<h2 class=\"wp-block-heading\" id=\"6c5e\">Step-8: SPY ETF Comparison<\/h2>\n\n\n\n<p>This optional step involves comparing our trading strategy&#8217;s performance against a benchmark (SPY ETF). We&#8217;ll extract SPY ETF data using the &#8216;get_historical_data&#8217; function and compare its returns with those of our trading strategy on Apple.<\/p>\n\n\n\n<p id=\"c196\"><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\"><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[0])\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('2010-01-01', 100000)\n\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('STOCH MACD 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=\"d6bb\"><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 : 159095.09\nBenchmark Profit percentage : 159%\nSTOCH MACD Strategy profit is 154% higher than the Benchmark Profit<\/strong><\/pre>\n\n\n\n<p id=\"37d6\"><strong>Code Explanation:<\/strong>&nbsp;This code segment is similar to the previous backtesting step, except that we invest in the SPY ETF without implementing any trading strategy. The output indicates that our trading strategy has outperformed the SPY ETF by 154%. Excellent!<\/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=\"8ce1\">Final Thoughts!<\/h1>\n\n\n\n<p>After an extensive exploration of both theoretical concepts and coding, we&#8217;ve successfully comprehended the Stochastic Oscillator and Moving Average Convergence\/Divergence indicators. Using Python, we&#8217;ve combined these indicators to formulate a trading strategy that has outperformed the SPY ETF.<\/p>\n\n\n\n<p>This article offers a glimpse into how programming is applied in finance, particularly in the stock market. It underscores the importance of mastering programming and technical concepts to gain a competitive edge in the market.<\/p>\n\n\n\n<p><\/p>\n","protected":false},"excerpt":{"rendered":"<p>The trading arena is experiencing an influx of individuals striving to capitalize on the stock market. To stand out in this vast landscape and gain a competitive edge, innovation is key. Developing unconventional ideas that deviate from common practices is essential for success. For instance, although technical indicators like the&nbsp;Stochastic Oscillator&nbsp;have become widely adopted, achieving [&hellip;]<\/p>\n","protected":false},"author":18,"featured_media":1351,"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],"tags":[],"coding-language":[30],"ready-to-go-solution":[],"qualification":[31,32],"financial-apis-category":[36],"financial-apis-manuals":[39,40],"class_list":["post-1350","post","type-post","status-publish","format-standard","has-post-thumbnail","hentry","category-backtesting-strategies-examples","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>Python Trading Strategy: Synergizing Stochastic Oscillator and MACD Indicator | EODHD APIs Academy<\/title>\n<meta name=\"description\" content=\"Uncover the secrets to a powerful trading strategy with Python. Harness the potential of the Stochastic Oscillator and MACD indicator to optimize your trades\" \/>\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\/using-python-to-create-an-innovative-trading-strategy-and-achieve-better-results\" \/>\n<meta property=\"og:locale\" content=\"en_US\" \/>\n<meta property=\"og:type\" content=\"article\" \/>\n<meta property=\"og:title\" content=\"Using Python to Create an Innovative Trading Strategy and Achieve Better Results\" \/>\n<meta property=\"og:description\" content=\"Uncover the secrets to a powerful trading strategy with Python. Harness the potential of the Stochastic Oscillator and MACD indicator to optimize your trades\" \/>\n<meta property=\"og:url\" content=\"https:\/\/eodhd.com\/financial-academy\/backtesting-strategies-examples\/using-python-to-create-an-innovative-trading-strategy-and-achieve-better-results\" \/>\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-07T10:16:42+00:00\" \/>\n<meta property=\"article:modified_time\" content=\"2025-02-05T13:20:03+00:00\" \/>\n<meta property=\"og:image\" content=\"https:\/\/eodhd.com\/financial-academy\/wp-content\/uploads\/2023\/07\/image-11.png\" \/>\n\t<meta property=\"og:image:width\" content=\"828\" \/>\n\t<meta property=\"og:image:height\" content=\"522\" \/>\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=\"12 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\/using-python-to-create-an-innovative-trading-strategy-and-achieve-better-results#article\",\"isPartOf\":{\"@id\":\"https:\/\/eodhd.com\/financial-academy\/backtesting-strategies-examples\/using-python-to-create-an-innovative-trading-strategy-and-achieve-better-results\"},\"author\":{\"name\":\"Nikhil Adithyan\",\"@id\":\"https:\/\/eodhd.com\/financial-academy\/#\/schema\/person\/67681e71050cf7d8d0efb91fee5f0402\"},\"headline\":\"Using Python to Create an Innovative Trading Strategy and Achieve Better Results\",\"datePublished\":\"2023-08-07T10:16:42+00:00\",\"dateModified\":\"2025-02-05T13:20:03+00:00\",\"mainEntityOfPage\":{\"@id\":\"https:\/\/eodhd.com\/financial-academy\/backtesting-strategies-examples\/using-python-to-create-an-innovative-trading-strategy-and-achieve-better-results\"},\"wordCount\":2404,\"publisher\":{\"@id\":\"https:\/\/eodhd.com\/financial-academy\/#organization\"},\"image\":{\"@id\":\"https:\/\/eodhd.com\/financial-academy\/backtesting-strategies-examples\/using-python-to-create-an-innovative-trading-strategy-and-achieve-better-results#primaryimage\"},\"thumbnailUrl\":\"https:\/\/eodhd.com\/financial-academy\/wp-content\/uploads\/2023\/07\/image-11.png\",\"articleSection\":[\"Backtesting Strategies Examples\"],\"inLanguage\":\"en-US\"},{\"@type\":\"WebPage\",\"@id\":\"https:\/\/eodhd.com\/financial-academy\/backtesting-strategies-examples\/using-python-to-create-an-innovative-trading-strategy-and-achieve-better-results\",\"url\":\"https:\/\/eodhd.com\/financial-academy\/backtesting-strategies-examples\/using-python-to-create-an-innovative-trading-strategy-and-achieve-better-results\",\"name\":\"Python Trading Strategy: Synergizing Stochastic Oscillator and MACD Indicator | EODHD APIs Academy\",\"isPartOf\":{\"@id\":\"https:\/\/eodhd.com\/financial-academy\/#website\"},\"primaryImageOfPage\":{\"@id\":\"https:\/\/eodhd.com\/financial-academy\/backtesting-strategies-examples\/using-python-to-create-an-innovative-trading-strategy-and-achieve-better-results#primaryimage\"},\"image\":{\"@id\":\"https:\/\/eodhd.com\/financial-academy\/backtesting-strategies-examples\/using-python-to-create-an-innovative-trading-strategy-and-achieve-better-results#primaryimage\"},\"thumbnailUrl\":\"https:\/\/eodhd.com\/financial-academy\/wp-content\/uploads\/2023\/07\/image-11.png\",\"datePublished\":\"2023-08-07T10:16:42+00:00\",\"dateModified\":\"2025-02-05T13:20:03+00:00\",\"description\":\"Uncover the secrets to a powerful trading strategy with Python. Harness the potential of the Stochastic Oscillator and MACD indicator to optimize your trades\",\"breadcrumb\":{\"@id\":\"https:\/\/eodhd.com\/financial-academy\/backtesting-strategies-examples\/using-python-to-create-an-innovative-trading-strategy-and-achieve-better-results#breadcrumb\"},\"inLanguage\":\"en-US\",\"potentialAction\":[{\"@type\":\"ReadAction\",\"target\":[\"https:\/\/eodhd.com\/financial-academy\/backtesting-strategies-examples\/using-python-to-create-an-innovative-trading-strategy-and-achieve-better-results\"]}]},{\"@type\":\"ImageObject\",\"inLanguage\":\"en-US\",\"@id\":\"https:\/\/eodhd.com\/financial-academy\/backtesting-strategies-examples\/using-python-to-create-an-innovative-trading-strategy-and-achieve-better-results#primaryimage\",\"url\":\"https:\/\/eodhd.com\/financial-academy\/wp-content\/uploads\/2023\/07\/image-11.png\",\"contentUrl\":\"https:\/\/eodhd.com\/financial-academy\/wp-content\/uploads\/2023\/07\/image-11.png\",\"width\":828,\"height\":522,\"caption\":\"Using Python to Create an Innovative Trading Strategy and Achieve Better Results\"},{\"@type\":\"BreadcrumbList\",\"@id\":\"https:\/\/eodhd.com\/financial-academy\/backtesting-strategies-examples\/using-python-to-create-an-innovative-trading-strategy-and-achieve-better-results#breadcrumb\",\"itemListElement\":[{\"@type\":\"ListItem\",\"position\":1,\"name\":\"Home\",\"item\":\"https:\/\/eodhd.com\/financial-academy\/\"},{\"@type\":\"ListItem\",\"position\":2,\"name\":\"Using Python to Create an Innovative Trading Strategy and Achieve Better Results\"}]},{\"@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":"Python Trading Strategy: Synergizing Stochastic Oscillator and MACD Indicator | EODHD APIs Academy","description":"Uncover the secrets to a powerful trading strategy with Python. Harness the potential of the Stochastic Oscillator and MACD indicator to optimize your trades","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\/using-python-to-create-an-innovative-trading-strategy-and-achieve-better-results","og_locale":"en_US","og_type":"article","og_title":"Using Python to Create an Innovative Trading Strategy and Achieve Better Results","og_description":"Uncover the secrets to a powerful trading strategy with Python. Harness the potential of the Stochastic Oscillator and MACD indicator to optimize your trades","og_url":"https:\/\/eodhd.com\/financial-academy\/backtesting-strategies-examples\/using-python-to-create-an-innovative-trading-strategy-and-achieve-better-results","og_site_name":"Financial Academy","article_publisher":"https:\/\/www.facebook.com\/eodhistoricaldata","article_published_time":"2023-08-07T10:16:42+00:00","article_modified_time":"2025-02-05T13:20:03+00:00","og_image":[{"width":828,"height":522,"url":"https:\/\/eodhd.com\/financial-academy\/wp-content\/uploads\/2023\/07\/image-11.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":"12 minutes"},"schema":{"@context":"https:\/\/schema.org","@graph":[{"@type":"Article","@id":"https:\/\/eodhd.com\/financial-academy\/backtesting-strategies-examples\/using-python-to-create-an-innovative-trading-strategy-and-achieve-better-results#article","isPartOf":{"@id":"https:\/\/eodhd.com\/financial-academy\/backtesting-strategies-examples\/using-python-to-create-an-innovative-trading-strategy-and-achieve-better-results"},"author":{"name":"Nikhil Adithyan","@id":"https:\/\/eodhd.com\/financial-academy\/#\/schema\/person\/67681e71050cf7d8d0efb91fee5f0402"},"headline":"Using Python to Create an Innovative Trading Strategy and Achieve Better Results","datePublished":"2023-08-07T10:16:42+00:00","dateModified":"2025-02-05T13:20:03+00:00","mainEntityOfPage":{"@id":"https:\/\/eodhd.com\/financial-academy\/backtesting-strategies-examples\/using-python-to-create-an-innovative-trading-strategy-and-achieve-better-results"},"wordCount":2404,"publisher":{"@id":"https:\/\/eodhd.com\/financial-academy\/#organization"},"image":{"@id":"https:\/\/eodhd.com\/financial-academy\/backtesting-strategies-examples\/using-python-to-create-an-innovative-trading-strategy-and-achieve-better-results#primaryimage"},"thumbnailUrl":"https:\/\/eodhd.com\/financial-academy\/wp-content\/uploads\/2023\/07\/image-11.png","articleSection":["Backtesting Strategies Examples"],"inLanguage":"en-US"},{"@type":"WebPage","@id":"https:\/\/eodhd.com\/financial-academy\/backtesting-strategies-examples\/using-python-to-create-an-innovative-trading-strategy-and-achieve-better-results","url":"https:\/\/eodhd.com\/financial-academy\/backtesting-strategies-examples\/using-python-to-create-an-innovative-trading-strategy-and-achieve-better-results","name":"Python Trading Strategy: Synergizing Stochastic Oscillator and MACD Indicator | EODHD APIs Academy","isPartOf":{"@id":"https:\/\/eodhd.com\/financial-academy\/#website"},"primaryImageOfPage":{"@id":"https:\/\/eodhd.com\/financial-academy\/backtesting-strategies-examples\/using-python-to-create-an-innovative-trading-strategy-and-achieve-better-results#primaryimage"},"image":{"@id":"https:\/\/eodhd.com\/financial-academy\/backtesting-strategies-examples\/using-python-to-create-an-innovative-trading-strategy-and-achieve-better-results#primaryimage"},"thumbnailUrl":"https:\/\/eodhd.com\/financial-academy\/wp-content\/uploads\/2023\/07\/image-11.png","datePublished":"2023-08-07T10:16:42+00:00","dateModified":"2025-02-05T13:20:03+00:00","description":"Uncover the secrets to a powerful trading strategy with Python. Harness the potential of the Stochastic Oscillator and MACD indicator to optimize your trades","breadcrumb":{"@id":"https:\/\/eodhd.com\/financial-academy\/backtesting-strategies-examples\/using-python-to-create-an-innovative-trading-strategy-and-achieve-better-results#breadcrumb"},"inLanguage":"en-US","potentialAction":[{"@type":"ReadAction","target":["https:\/\/eodhd.com\/financial-academy\/backtesting-strategies-examples\/using-python-to-create-an-innovative-trading-strategy-and-achieve-better-results"]}]},{"@type":"ImageObject","inLanguage":"en-US","@id":"https:\/\/eodhd.com\/financial-academy\/backtesting-strategies-examples\/using-python-to-create-an-innovative-trading-strategy-and-achieve-better-results#primaryimage","url":"https:\/\/eodhd.com\/financial-academy\/wp-content\/uploads\/2023\/07\/image-11.png","contentUrl":"https:\/\/eodhd.com\/financial-academy\/wp-content\/uploads\/2023\/07\/image-11.png","width":828,"height":522,"caption":"Using Python to Create an Innovative Trading Strategy and Achieve Better Results"},{"@type":"BreadcrumbList","@id":"https:\/\/eodhd.com\/financial-academy\/backtesting-strategies-examples\/using-python-to-create-an-innovative-trading-strategy-and-achieve-better-results#breadcrumb","itemListElement":[{"@type":"ListItem","position":1,"name":"Home","item":"https:\/\/eodhd.com\/financial-academy\/"},{"@type":"ListItem","position":2,"name":"Using Python to Create an Innovative Trading Strategy and Achieve Better Results"}]},{"@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\/07\/image-11.png","jetpack_shortlink":"https:\/\/wp.me\/pdOdVT-lM","jetpack_sharing_enabled":true,"acf":[],"_links":{"self":[{"href":"https:\/\/eodhd.com\/financial-academy\/wp-json\/wp\/v2\/posts\/1350","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=1350"}],"version-history":[{"count":11,"href":"https:\/\/eodhd.com\/financial-academy\/wp-json\/wp\/v2\/posts\/1350\/revisions"}],"predecessor-version":[{"id":6282,"href":"https:\/\/eodhd.com\/financial-academy\/wp-json\/wp\/v2\/posts\/1350\/revisions\/6282"}],"wp:featuredmedia":[{"embeddable":true,"href":"https:\/\/eodhd.com\/financial-academy\/wp-json\/wp\/v2\/media\/1351"}],"wp:attachment":[{"href":"https:\/\/eodhd.com\/financial-academy\/wp-json\/wp\/v2\/media?parent=1350"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/eodhd.com\/financial-academy\/wp-json\/wp\/v2\/categories?post=1350"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/eodhd.com\/financial-academy\/wp-json\/wp\/v2\/tags?post=1350"},{"taxonomy":"coding-language","embeddable":true,"href":"https:\/\/eodhd.com\/financial-academy\/wp-json\/wp\/v2\/coding-language?post=1350"},{"taxonomy":"ready-to-go-solution","embeddable":true,"href":"https:\/\/eodhd.com\/financial-academy\/wp-json\/wp\/v2\/ready-to-go-solution?post=1350"},{"taxonomy":"qualification","embeddable":true,"href":"https:\/\/eodhd.com\/financial-academy\/wp-json\/wp\/v2\/qualification?post=1350"},{"taxonomy":"financial-apis-category","embeddable":true,"href":"https:\/\/eodhd.com\/financial-academy\/wp-json\/wp\/v2\/financial-apis-category?post=1350"},{"taxonomy":"financial-apis-manuals","embeddable":true,"href":"https:\/\/eodhd.com\/financial-academy\/wp-json\/wp\/v2\/financial-apis-manuals?post=1350"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}