<?xml version="1.0" encoding="UTF-8"?><rss xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:content="http://purl.org/rss/1.0/modules/content/" xmlns:atom="http://www.w3.org/2005/Atom" version="2.0" xmlns:cc="http://cyber.law.harvard.edu/rss/creativeCommonsRssModule.html">
    <channel>
        <title><![CDATA[Stories by BDPO.io on Medium]]></title>
        <description><![CDATA[Stories by BDPO.io on Medium]]></description>
        <link>https://medium.com/@BDPO?source=rss-5b69c5e67df1------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*A3R47QAoW2FlDpEdxuig-Q.jpeg</url>
            <title>Stories by BDPO.io on Medium</title>
            <link>https://medium.com/@BDPO?source=rss-5b69c5e67df1------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Sun, 06 Dec 2026 00:01:15 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@BDPO/feed" rel="self" type="application/rss+xml"/>
        <webMaster><![CDATA[yourfriends@medium.com]]></webMaster>
        <atom:link href="http://medium.superfeedr.com/" rel="hub"/>
        <item>
            <title><![CDATA[Creating a profitable trading strategy using RSI and Bollinger bands]]></title>
            <link>https://medium.com/@BDPO/creating-a-profitable-trading-strategy-using-rsi-and-bollinger-bands-aacaa89a571b?source=rss-5b69c5e67df1------2</link>
            <guid isPermaLink="false">https://medium.com/p/aacaa89a571b</guid>
            <category><![CDATA[technology]]></category>
            <category><![CDATA[trading]]></category>
            <category><![CDATA[passive-income]]></category>
            <category><![CDATA[cryptocurrency]]></category>
            <category><![CDATA[stock-market]]></category>
            <dc:creator><![CDATA[BDPO.io]]></dc:creator>
            <pubDate>Wed, 08 Mar 2023 11:10:50 GMT</pubDate>
            <atom:updated>2023-03-08T11:10:50.677Z</atom:updated>
            <content:encoded><![CDATA[<p>Learn how to create a simple yet effective trading strategy using RSI and Bollinger Bands, and backtest it using Backtrader to maximize your profits.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*7NgqUktjtg-xJ_jdR3uGHw.png" /><figcaption>The strategy in this article backtested on TLSA</figcaption></figure><p><em>Disclaimer: The material in this article is for purely educational purposes and should not be taken as professional investment advice. Invest at your discretion.</em></p><h3>Introduction</h3><p>Backtrader is a popular open-source framework for building and backtesting trading strategies. In this article, we’ll explore how to implement a strategy using the Relative Strength Index (RSI) and Bollinger Bands to trade the stock of Apple (AAPL). The strategy will use technical indicators to determine when to buy and sell AAPL based on market trends.</p><h3>Overview of the Strategy</h3><p>The strategy we’ll implement is based on two popular technical indicators: the Relative Strength Index (RSI) and Bollinger Bands. The RSI is a momentum oscillator that measures the strength of a security’s price action, while Bollinger Bands are a measure of volatility based on moving averages.</p><p>Our strategy will generate buy and sell signals based on the following rules:</p><ul><li>Buy when the RSI is below 30 and the price is below the lower Bollinger Band.</li><li>Sell when the RSI is above 70 or the price is above the upper Bollinger Band.</li></ul><p>We’ll use Backtrader to backtest this strategy on historical data for AAPL and evaluate its performance.</p><h3>Installing the requirements</h3><pre>from backtrader.indicators import RSI, BollingerBands<br>import backtrader as bt<br>import matplotlib.pyplot as plt<br>import backtrader as bt<br>import datetime<br>import yfinance as yf</pre><h3>Loading Historical Data</h3><p>Now, we’ll load historical price data for AAPL using the pandas data feed from Yahoo Finance. We&#39;ll define the start and end dates for the data and use the yf.download function to download the data for AAPL.</p><pre># Define the start and end dates<br>start_date = datetime.datetime(2010, 1, 1)<br>end_date = datetime.datetime(2021, 12, 31)<br><br># Load historical price data using the pandas data feed<br>data = bt.feeds.PandasData(<br>    dataname=yf.download(&#39;AAPL&#39;, start=start_date, end=end_date, interval=&quot;1d&quot;)<br>)</pre><p>This code loads daily price data for AAPL from January 1st, 2010 to December 31st, 2021 using the yf.download function from the yfinance module. We then create a PandasData object with this data and assign it to the data variable.</p><h3>Defining the Strategy</h3><p>Next, we’ll define the strategy by subclassing the bt.Strategy class in Backtrader. We&#39;ll define the __init__ method to initialize the strategy, and the next method to generate buy and sell signals based on the RSI and Bollinger Bands.</p><pre>class RsiBollingerBands(bt.Strategy):<br>    params = (<br>        (&#39;rsi_period&#39;, 14),<br>        (&#39;bb_period&#39;, 20),<br>        (&#39;bb_dev&#39;, 2),<br>        (&#39;oversold&#39;, 30),<br>        (&#39;overbought&#39;, 70)<br>    )<br><br>    def __init__(self):<br>        self.rsi = RSI(period=self.params.rsi_period)<br>        self.bbands = BollingerBands(period=self.params.bb_period, devfactor=self.params.bb_dev)<br><br>    <br>    def next(self):<br>        if not self.position:<br>            if self.rsi &lt; self.params.oversold and self.data.close[0] &lt;= self.bbands.lines.bot[0]:<br>                self.buy()<br>        else:<br>            if self.rsi &gt; self.params.overbought or self.data.close[0] &gt;= self.bbands.lines.top[0]:<br>                self.close()</pre><p>In this code, we define the RSIBBStrategy class to inherit from the bt.Strategy class. In the __init__ method, we define the rsi indicator using the RSI_SMA function with a period of 14 days. We also define the `bollinger_topandbollinger_bottomindicators using theBollingerBands` function with a period of 20 days and a standard deviation of 2.</p><p>In the next method, we check if the RSI is below 30 and the price is below the lower Bollinger Band, and generate a buy signal using the buy method. Similarly, if the RSI is above 70 or the price is above the upper Bollinger Band, we generate a sell signal using the sell method.</p><h3>Running the Backtest</h3><p>Now that we’ve defined the strategy, we can run a backtest using Backtrader to evaluate its performance. We’ll create a Cerebro object, which is the main class for managing the backtest, and adding our strategy and data to it.</p><pre>if __name__ == &quot;__main__&quot;:<br>    cerebro = bt.Cerebro()<br><br>    cerebro.addstrategy(RsiBollingerBands)<br><br><br>    cerebro.adddata(data)<br><br>    cerebro.broker.setcash(1000)<br><br>    cerebro.broker.setcommission(commission=0.001)<br>    cerebro.broker.set_slippage_fixed(0.01)<br>    cerebro.run()<br>  <br>  # Print the final portfolio value<br>    print(f&quot;Final portfolio value: {cerebro.broker.getvalue():,.2f} USD&quot;) </pre><p>In the above, we have also defined commission to be 0.1% of both the opening and closing of trades alongside a slippage of 0.01. This code runs the backtest and prints out the final portfolio value using the getvalue method of the broker object.</p><h3>Plotting the strategy</h3><pre>  cerebro.plot()<br>    plt.show()</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/640/1*ngCcpkDr8bSpeLOumzMoQA.png" /></figure><h3>Results</h3><p>As you can see from the graph above running this strategy does indeed beat commission and makes 1.1% over the time period. Noting while this seems like a profitable strategy and beats commission. If we were just to buy and hold the underlying we would have made significantly more, so while this strategy beats commission it does not beat the market!</p><h3>Conclusion</h3><p>In this article, we’ve demonstrated how to use Backtrader to implement a very simple trading strategy using the Relative Strength Index (RSI) and Bollinger Bands to trade the stock of Apple (AAPL). We’ve shown how to load historical data, define the strategy, run the backtest, and evaluate the results using Backtrader’s Analyzer module.</p><p>It’s worth noting that this strategy is a simple example and should not be used for actual trading without further analysis and testing. Backtesting is an important tool for evaluating trading strategies, but it’s important to keep in mind that past performance is not necessarily indicative of future results.</p><p>In conclusion, we hope this article has given you a basic understanding of how to use Backtrader to implement a trading strategy using the Relative Strength Index (RSI) and Bollinger Bands. With further study and experimentation, you can use Backtrader to develop and backtest your own trading strategies, and potentially improve your trading performance.</p><h3>Future ideas</h3><p>In future articles, we will be adding to this strategy and improving it to a system that will take into account the underlying trend of the market and trade in both directions. This was simply meant to be an initial article demonstrating how to use Backtrader.</p><h3>Full code</h3><pre>from backtrader.indicators import RSI, BollingerBands<br>import backtrader as bt<br>import matplotlib.pyplot as plt<br>import backtrader as bt<br>import datetime<br>import yfinance as yf<br><br># Define the start and end dates<br>start_date = datetime.datetime(2010, 1, 1)<br>end_date = datetime.datetime(2021, 12, 31)<br><br>data = bt.feeds.PandasData(<br>    dataname=yf.download(&#39;AAPL&#39;, start=start_date, end=end_date, interval=&quot;1d&quot;)<br>)<br><br><br><br>class RsiBollingerBands(bt.Strategy):<br>    params = (<br>        (&#39;rsi_period&#39;, 14),<br>        (&#39;bb_period&#39;, 20),<br>        (&#39;bb_dev&#39;, 2),<br>        (&#39;oversold&#39;, 30),<br>        (&#39;overbought&#39;, 70)<br>    )<br><br>    def __init__(self):<br>        self.rsi = RSI(period=self.params.rsi_period)<br>        self.bbands = BollingerBands(period=self.params.bb_period, devfactor=self.params.bb_dev)<br><br>    <br>    def next(self):<br>        if not self.position:<br>            if self.rsi &lt; self.params.oversold and self.data.close[0] &lt;= self.bbands.lines.bot[0]:<br>                self.buy()<br>        else:<br>            if self.rsi &gt; self.params.overbought or self.data.close[0] &gt;= self.bbands.lines.top[0]:<br>                self.close()<br><br><br><br>if __name__ == &quot;__main__&quot;:<br>    cerebro = bt.Cerebro()<br><br>    cerebro.addstrategy(RsiBollingerBands)<br><br><br>    cerebro.adddata(data)<br><br>    cerebro.broker.setcash(1000)<br><br>    cerebro.broker.setcommission(commission=0.001)<br>    cerebro.broker.set_slippage_fixed(0.01)<br>    cerebro.run()<br><br>    cerebro.plot()<br>    plt.show()</pre><p>At BDPO we have developed a number of strategies that have been back-tested, optimised and most importantly forward-tested on unseen data, to explore our backtests and market signal service along with Forex news alerts, earnings briefings, Golden Cross and RSI oversold/overbought alerts please visit:</p><p><a href="http://www.bdpo.co.uk/">www.BDPO.co.uk</a></p><p>If you have a custom strategy but don’t know how to code, please get visit BDPO and we can create a custom backtest report for your own strategy.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*xAuu2UtMl_bXnDJMnHvTfw.png" /><figcaption>TSLA Backtest</figcaption></figure><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=aacaa89a571b" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Unlock the Power of Technical Analysis with RSI and Plotly: A Comprehensive Guide for Traders]]></title>
            <link>https://medium.com/@BDPO/unlock-the-power-of-technical-analysis-with-rsi-and-plotly-a-comprehensive-guide-for-traders-2f209faf5cbf?source=rss-5b69c5e67df1------2</link>
            <guid isPermaLink="false">https://medium.com/p/2f209faf5cbf</guid>
            <dc:creator><![CDATA[BDPO.io]]></dc:creator>
            <pubDate>Sat, 04 Mar 2023 17:13:27 GMT</pubDate>
            <atom:updated>2023-03-04T17:13:27.804Z</atom:updated>
            <content:encoded><![CDATA[<p><em>Discover How to Visualize RSI and Close Price Data for Better Trading Decisions with Plotly and Python</em></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*p4hFn3YKkGGw9zjquS2csQ.png" /><figcaption>Visualising the RSI</figcaption></figure><p><em>Disclaimer: The material in this article is for purely educational purposes and should not be taken as professional investment advice. Invest at your discretion</em></p><p>The world of trading can be complex and overwhelming, especially for those new to the game. However, with the right tools and knowledge, anyone can succeed in the stock market. One of the key tools in a trader’s arsenal is the Relative Strength Index (RSI), a popular technical indicator used to determine if a stock is overbought or oversold. In this blog post, we’ll explore the RSI, how to visualize it using Plotly and Pandas_ta, and how it can be used in trading.</p><p>The RSI is a simple yet powerful indicator that compares the magnitude of a stock’s recent gains to the magnitude of its recent losses. It’s calculated using a simple formula and ranges from 0 to 100, with readings above 70 indicating overbought conditions and readings below 30 indicating oversold conditions. By visualizing the close price and RSI chart on the same page, traders can quickly determine if a stock is overbought or oversold, allowing them to make informed decisions on when to buy or sell. In this post, we’ll take a step-by-step approach to creating this visualization using Plotly and Pandas_ta.</p><p>In this blog post, we will show you how to visualize the close price and RSI chart on the same page using Python. We will use the yfinance library to download the stock data, pandas_ta library to calculate the RSI, and Plotly’s make_subplots function to create a subplot with two separate plots.</p><p>First, we’ll import the required libraries and download the stock data:</p><pre>import yfinance as yf<br>import pandas as pd<br>import pandas_ta as ta<br>import plotly.graph_objects as go<br>from plotly.subplots import make_subplots<br><br># get stock data<br>ticker = &quot;AAPL&quot;<br>df = yf.download(ticker, start=&quot;2020-01-01&quot;, end=&quot;2022-12-31&quot;)</pre><p>Next, we’ll use the pandas_ta library to calculate the RSI and drop any missing values:</p><pre># calculate RSI<br>df[&quot;RSI&quot;] = ta.rsi(df[&quot;Close&quot;], length=14, show=False)<br>df = df.dropna()<br>print(df)</pre><p>Now, we’ll create a subplot using the make_subplots function:</p><pre># create subplot<br>fig = make_subplots(rows=2, cols=1, row_heights=[0.7, 0.3])<br><br>fig.add_trace(go.Scatter(x=df.index, y=df[&#39;Close&#39;], name=&#39;Close&#39;),<br>            row=1, col=1)<br><br>fig.add_trace(go.Scatter(x=df.index, y=df[&#39;RSI&#39;], name=&#39;RSI&#39;),<br>                row=2, col=1)<br><br># update layout<br>fig.update_layout(title=f&quot;{ticker} Close Price and RSI&quot;, showlegend=False)<br><br># show plot<br>fig.show()</pre><p>To add the red dots on the close price plot, we’ll use the Scatter trace in Plotly and filter the data points where the RSI is above 70. The x and y parameters of the Scatter trace will be the index and close price of these filtered data points respectively. We&#39;ll use the mode parameter to set the marker style to &quot;markers&quot; and the marker parameter to set the marker color to red.</p><pre>fig.add_trace(go.Scatter(x=df[df[&#39;RSI&#39;] &gt; 70].index, y=df[df[&#39;RSI&#39;] &gt; 70][&#39;Close&#39;], name=&#39;Above 70&#39;, mode=&#39;markers&#39;, marker=dict(color=&#39;red&#39;)))</pre><p>Similarly, we’ll add green dots on the close price plot where the RSI is below 30.</p><pre>fig.add_trace(go.Scatter(x=df[df[&#39;RSI&#39;] &lt; 30].index, y=df[df[&#39;RSI&#39;] &lt; 30][&#39;Close&#39;], name=&#39;Below 30&#39;, mode=&#39;markers&#39;, marker=dict(color=&#39;green&#39;)))</pre><p>Finally, we’ll update the layout to show the legend and add a title to the plot.</p><pre>fig.update_layout(title=f&quot;{ticker} Close Price and RSI with Overbought and Oversold Indicators&quot;, showlegend=True)<br>fig.show()</pre><p>Overall, by visualizing the close price and RSI chart on the same page, traders can quickly determine if a stock is overbought or oversold. The red dots indicate when the RSI is above 70, indicating that the stock is overbought and a potential correction or pullback could occur. The green dots indicate when the RSI is below 30, indicating that the stock is oversold and a potential rebound could occur.</p><p>Traders can use this information to make informed decisions on when to buy or sell a stock. For example, if a stock is overbought, a trader may choose to sell the stock or take profits. If a stock is oversold, a trader may choose to buy the stock, as it could be due for a rebound.</p><p>It is important to note that the RSI should not be used in isolation to make trading decisions. Traders should also consider other technical and fundamental factors, such as trend analysis, moving averages, support and resistance levels, and earnings reports.</p><p>In conclusion, visualizing the close price and RSI chart using Plotly and Pandas_ta is a powerful tool for traders. It provides a quick and easy way to determine if a stock is overbought or oversold, allowing traders to make informed decisions on when to buy or sell.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*QZWvR00YvrqagxEvZSvzfA.png" /><figcaption>GOOG RSI Plot</figcaption></figure><p>The complete code for this plot is as follows:</p><pre>import yfinance as yf<br>import pandas as pd<br>import pandas_ta as ta<br>import plotly.graph_objects as go<br>from plotly.subplots import make_subplots<br><br># get stock data<br>ticker = &quot;AAPL&quot;<br>df = yf.download(ticker, start=&quot;2020-01-01&quot;, end=&quot;2022-12-31&quot;)<br><br># calculate RSI<br>df[&quot;RSI&quot;] = ta.rsi(df[&quot;Close&quot;], length=14, show=False)<br>df = df.dropna()<br><br># create subplot<br>fig = make_subplots(rows=2, cols=1, row_heights=[0.7, 0.3])<br><br># add close price plot<br>fig.add_trace(go.Scatter(x=df.index, y=df[&#39;Close&#39;], name=&#39;Close&#39;),<br>            row=1, col=1)<br><br># add RSI plot<br>fig.add_trace(go.Scatter(x=df.index, y=df[&#39;RSI&#39;], name=&#39;RSI&#39;),<br>                row=2, col=1)<br><br># add red dots for RSI above 70<br>fig.add_trace(go.Scatter(x=df[df[&#39;RSI&#39;] &gt; 70].index,<br>                         y=df[df[&#39;RSI&#39;] &gt; 70][&#39;Close&#39;],<br>                         mode=&#39;markers&#39;,<br>                         marker=dict(size=8, color=&#39;red&#39;),<br>                         name=&#39;RSI above 70&#39;,<br>                         showlegend=False),<br>              row=1, col=1)<br><br># add green dots for RSI below 30<br>fig.add_trace(go.Scatter(x=df[df[&#39;RSI&#39;] &lt; 30].index,<br>                         y=df[df[&#39;RSI&#39;] &lt; 30][&#39;Close&#39;],<br>                         mode=&#39;markers&#39;,<br>                         marker=dict(size=8, color=&#39;green&#39;),<br>                         name=&#39;RSI below 30&#39;,<br>                         showlegend=False),<br>              row=1, col=1)<br><br># update layout<br>fig.update_layout(title=f&quot;{ticker} Close Price and RSI&quot;, showlegend=False)<br><br># show plot<br>fig.show()</pre><p>This code will download the historical close price data for Apple Inc. (AAPL) from 2020 to 2022, calculate the RSI using Pandas_ta, and create a visualization with two subplots: one for the close price and another for the RSI. Additionally, it will add red dots on the close price plot where the RSI is above 70 and green dots where the RSI is below 30. This allows traders to easily see the relationship between the RSI and close price, and make informed trading decisions.</p><p>At BDPO we have developed a number of strategies that have been back-tested, optimised and most importantly forward-tested on unseen data, to explore our backtests and market signal service along with Forex news alerts, earnings briefings, Golden Cross and RSI oversold / overbought alerts please visit:</p><p><a href="http://www.bdpo.co.uk/">www.BDPO.co.uk</a></p><p>If you have a custom strategy but don’t know how to code, please get visit BDPO and we can create a custom backtest report for your own strategy.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=2f209faf5cbf" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Maximize Your Trading Success: The Ultimate Guide to Developing a Winning Strategy]]></title>
            <link>https://medium.com/@BDPO/maximize-your-trading-success-the-ultimate-guide-to-developing-a-winning-strategy-dc419113a2a8?source=rss-5b69c5e67df1------2</link>
            <guid isPermaLink="false">https://medium.com/p/dc419113a2a8</guid>
            <category><![CDATA[python]]></category>
            <category><![CDATA[trading]]></category>
            <category><![CDATA[planning]]></category>
            <category><![CDATA[life-lessons]]></category>
            <category><![CDATA[life]]></category>
            <dc:creator><![CDATA[BDPO.io]]></dc:creator>
            <pubDate>Sat, 11 Feb 2023 16:14:46 GMT</pubDate>
            <atom:updated>2023-02-11T17:20:18.917Z</atom:updated>
            <content:encoded><![CDATA[<p>Discover the Key Elements of a Profitable Trading Plan and How to Implement It</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*cgc4GnM43myxeemejn9lbQ.jpeg" /><figcaption>Setting up a trading plan</figcaption></figure><p><em>Disclaimer: The material in this article is for purely educational purposes and should not be taken as professional investment advice. Invest at your discretion</em></p><p>The world of trading can be a challenging and exciting one, with the potential for significant financial rewards. However, success in trading is not guaranteed and requires a well-defined strategy, careful planning, and ongoing education. Whether you are a seasoned trader or just starting out, it’s important to understand the key elements of a successful trading plan and how to implement it. In this blog post, we will discuss the steps you can take to develop a successful trading strategy, including defining your goals, identifying your risk tolerance, choosing a market and trading style, developing a trading plan, practising risk management, and staying informed and educated. By following these guidelines, you can increase your chances of success in the markets and achieve your trading goals.</p><p>Here are ten steps you can use in starting your trading plan:</p><ol><li>Define your goals: Defining your goals is an important first step in developing a successful trading strategy. Ask yourself what you hope to achieve through trading, whether it’s generating income, growing your wealth, or both. Your goals will influence the type of strategy you choose and the markets you trade in. For example, if your goal is to generate income, you may want to focus on day trading or swing trading in markets with high liquidity. If your goal is to grow your wealth, you may want to focus on long-term investments in stocks or other assets.</li><li>Identify your risk tolerance: Understanding your risk tolerance is key to developing a successful trading strategy. Ask yourself how much risk you are willing to take on to achieve your goals. This will help you determine the types of investments that are suitable for you and the amount of risk you are willing to take on. It’s important to be realistic about your risk tolerance and to avoid taking on too much risk, as this can lead to significant losses.</li><li>Choose a market: There are many markets to choose from, including stocks, bonds, commodities, and currencies. Consider your goals and risk tolerance when choosing a market. For example, if you have a low risk tolerance, you may want to consider investing in bonds, while if you have a high risk tolerance, you may want to consider trading in the stock market.</li><li>Choose a trading style: Different trading styles suit different types of traders. Day trading involves buying and selling securities within the same day, swing trading involves holding positions for several days or weeks, and position trading involves holding positions for several months or longer. Consider your goals, risk tolerance, and market when choosing a trading style. For example, if you have a low risk tolerance and are seeking long-term growth, you may want to consider position trading.</li><li>Develop a trading plan: A trading plan is a detailed roadmap that outlines your goals, risk tolerance, market, and trading style. It should also include a strategy for risk management and a plan for monitoring your trades. Your trading plan should be flexible and adaptable, allowing you to make changes as market conditions change.</li><li>Implement your strategy: Once you have developed a trading plan, it’s time to implement your strategy. This involves executing trades, monitoring your positions, and making adjustments as needed. It’s important to stick to your trading plan and avoid making impulsive decisions based on short-term market fluctuations.</li><li>Review and refine your strategy: Regularly reviewing and refining your strategy is an important part of successful trading. Use the information gathered from your trades to make informed decisions about your strategy and adjust it as needed. This will help you stay up-to-date on market conditions and improve your chances of success in the markets.</li><li>Stay informed and educated: The markets are constantly changing, and it’s essential to stay informed and up-to-date on current market conditions and trends. This can be achieved through reading financial news, following market analysis, and participating in trading forums and webinars. Education is also crucial in developing a successful trading strategy. Consider taking courses or reading books to expand your knowledge and skills.</li><li>Have patience: Successful trading requires patience. Don’t make impulsive decisions based on short-term market fluctuations. Stick to your trading plan and be patient as you wait for opportunities to arise.</li><li>Practice risk management: Risk management is a crucial component of a successful trading strategy. Develop a plan for managing risk, including setting stop-loss orders and diversifying your portfolio. It’s also important to understand the concept of position sizing, which is the process of determining the appropriate size of your trades based on your overall trading capital. This will help you control your risk and limit your potential losses. Additionally, regularly monitoring your positions and adjusting your stop-loss orders can help you minimize risk and protect your profits.</li></ol><p>In conclusion, developing a successful trading strategy is a process that requires careful planning, discipline, and ongoing education. By defining your goals, identifying your risk tolerance, choosing a market and trading style, developing a trading plan, and practising risk management, you can increase your chances of success in the markets. Remember, the key to success in trading is to have a well-defined strategy, stick to your plan, and continually refine your approach based on market conditions and your own experiences. With patience and discipline, you can achieve your trading goals and succeed in the financial markets.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*uTP3qP5WORU38auzDM_BRg.jpeg" /><figcaption>Creating the plan</figcaption></figure><p>Disclaimer: This blog post is for educational purposes only and should not be considered as investment advice. The information provided is not a recommendation to buy or sell any securities and should not be relied upon in making investment decisions. Trading can be risky and result in substantial losses. Before making any trades, it is important to thoroughly research the market and seek the advice of a licensed financial advisor. The views expressed in this post are the author’s own and do not necessarily reflect the views of the organization they represent.</p><p>At BDPO we have developed a number of strategies that have been back-tested, optimised and most importantly forward-tested on unseen data, to explore our backtests and market signal service along with Forex news alerts, earnings briefings, Golden Cross and RSI oversold / overbought alerts please visit:</p><p><a href="http://www.bdpo.co.uk/">www.BDPO.co.uk</a></p><p>If you have a custom strategy but don’t know how to code, please get visit BDPO and we can create a custom backtest report for your own strategy.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=dc419113a2a8" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Master Stock Trading with the MACD Indicator: A Step-by-Step Guide Using Plotly, pandas-ta, and…]]></title>
            <link>https://medium.com/@BDPO/master-stock-trading-with-the-macd-indicator-a-step-by-step-guide-using-plotly-pandas-ta-and-9f9caf7e302f?source=rss-5b69c5e67df1------2</link>
            <guid isPermaLink="false">https://medium.com/p/9f9caf7e302f</guid>
            <category><![CDATA[cryptocurrency]]></category>
            <category><![CDATA[crypto]]></category>
            <category><![CDATA[python]]></category>
            <category><![CDATA[technology]]></category>
            <category><![CDATA[trading]]></category>
            <dc:creator><![CDATA[BDPO.io]]></dc:creator>
            <pubDate>Mon, 23 Jan 2023 20:50:08 GMT</pubDate>
            <atom:updated>2023-01-23T20:50:08.925Z</atom:updated>
            <content:encoded><![CDATA[<h3>Master Stock Trading with the MACD Indicator: A Step-by-Step Guide Using Plotly, pandas-ta, and yfinance</h3><p><em>Unleash the Power of Data Analysis: Learn to Use the MACD Indicator and Remove the Time Slider for a Clear Picture of Your Stock’s Performance.</em></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*pVRo4fGDeOVlKNhNP_HMoA.png" /><figcaption>Chart of MSFT showing the MACD as a seperate subplot.</figcaption></figure><p><em>Disclaimer: The material in this article is for purely educational purposes and should not be taken as professional investment advice. Invest at your discretion</em></p><p>When it comes to trading stocks, having the right tools and indicators at your disposal can make all the difference. One such tool is the Moving Average Convergence Divergence (MACD) indicator, which is widely used among traders to identify trends and make informed decisions about when to buy and sell. In this blog post, we will be showing you how to add the MACD indicator to a stock chart using Plotly, pandas-ta and yfinance library, and in addition to that how to remove the time slider to have a better overview of the data.</p><p>Before diving into the code, it’s important to make sure that you have the necessary libraries installed. You can do this by running the following commands in your terminal:</p><pre>pip install plotly<br>pip install pandas-ta<br>pip install yfinance</pre><p>Once you have the libraries installed, you can start by importing them into your script. You will also need to import the datetime module to get today’s date and use it as the end date.</p><pre>import plotly.graph_objects as go<br>import pandas_ta as ta<br>import yfinance as yf<br>from datetime import datetime, timedelta<br>from plotly.subplots import make_subplots</pre><p>The next step is to ask the user for the stock ticker, set the start date to 5 years ago and use the datetime module to get today’s date as the end date. Then, you can use the yfinance library to download the stock data using the yf.download() function.</p><pre># Ask the user for the ticker<br>ticker = input(&quot;Enter the ticker of the stock you want to analyze:&quot;)</pre><pre># Get start and end date<br>start_date = (datetime.now() - timedelta(days=365*5)).strftime(&quot;%Y-%m-%d&quot;)<br>end_date = datetime.now().strftime(&quot;%Y-%m-%d&quot;)<br><br># Download the stock data using yfinance library<br>df = yf.download(ticker, start=start_date, end=end_date)</pre><p>Now that we have the stock data, we can use the make_subplots() function from the plotly.subplots module to create a grid of subplots. This function allows you to create a main chart and a subplot for the MACD indicator. The first step is to create a grid of 2 rows and 1 column.</p><pre># Create a grid of subplots<br>fig = make_subplots(rows=2, cols=1)</pre><p>The next step is to add the candlestick chart to the first subplot.</p><pre># Add the candlestick chart to the first subplot<br>fig.add_trace(go.Candlestick(x=df.index, open=df[&#39;Open&#39;], high=df[&#39;High&#39;], low=df[&#39;Low&#39;], close=df[&#39;Close&#39;]), row=1, col=1)</pre><p>Now, we can use the df.ta.macd() function from the pandas-ta library to calculate the MACD values and add them to the second subplot. We will be adding the MACD, signal and histogram columns to the chart.</p><pre># Add the MACD indicator to the second subplot<br>MACD = df.ta.macd()<br>fig.add_trace(go.Scatter(x=df.index, y=MACD[&#39;MACD_12_26_9&#39;], name=&quot;MACD&quot;), row=2, col=1)<br>fig.add_trace(go.Scatter(x=df.index, y=MACD[&#39;MACDs_12_26_9&#39;], name=&quot;Signal&quot;), row=2, col=1)<br>fig.add_trace(go.Scatter(x=df.index, y=MACD[&#39;MACDh_12_26_9&#39;], name=&quot;Histogram&quot;), row=2, col=1)</pre><p>Lastly, we can remove the time slider using the fig.update_layout() function and passing in the appropriate parameters.</p><pre># Remove the time slider<br>fig.update_layout(xaxis=dict(rangeslider=dict(visible=False)))<br><br># Show the chart<br>fig.show()</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*FL81Cn7U4o0Hftz6pee6-g.png" /><figcaption>Chart of MSFT showing the MACD as a seperate subplot.</figcaption></figure><p>In conclusion, by using the Plotly, pandas-ta, and yfinance libraries, you can easily add the MACD indicator to a stock chart and remove the time slider to have a better overview of the data. This can help you identify trends and make more informed trading decisions. Be sure to customize the appearance of the chart by using the update_layout() function and passing in the appropriate parameters.</p><p>It is worth noting that you can also use other indicators from the pandas-ta library such as RSI, BOLL, CCI and many others to analyze the stock’s performance. Additionally, you can use the update_layout() function to customize the appearance of the chart and make it more informative. You can add titles, axis labels, and change the color scheme to make the chart more visually appealing.</p><p>It is also important to keep in mind that the MACD indicator is just one of the many tools that you can use when trading stocks. It is important to have a well-rounded approach and consider other factors such as the overall market conditions, company fundamentals, and economic indicators.</p><p>In summary, by using the MACD indicator along with other tools and indicators, you can increase your chances of success in the stock market. With the help of Plotly, pandas-ta, and yfinance, you can easily add the MACD indicator to a stock chart and remove the time slider for a better overview of the data. With the right approach, you can make more informed trading decisions and achieve your financial goals.</p><p>At BDPO we have developed a number of strategies that have been back-tested, optimised and most importantly forward-tested on unseen data, to explore our backtests and market signal service along with Forex news alerts, earnings briefings, Golden Cross and RSI oversold / overbought alerts please visit:</p><p><a href="http://www.bdpo.co.uk/">www.BDPO.co.uk</a></p><p>If you have a custom strategy but don’t know how to code, please get visit BDPO and we can create a custom backtest report for your own strategy.</p><p>Full code below:</p><pre>import plotly.graph_objects as go<br>import pandas_ta as ta<br>import yfinance as yf<br>from datetime import datetime, timedelta<br>from plotly.subplots import make_subplots<br><br># Ask the user for the ticker<br>ticker = input(&quot;Enter the ticker of the stock you want to analyze: &quot;)<br><br># Get start and end date<br>start_date = (datetime.now() - timedelta(days=365*5)).strftime(&quot;%Y-%m-%d&quot;)<br>end_date = datetime.now().strftime(&quot;%Y-%m-%d&quot;)<br><br># Download the stock data using yfinance library<br>df = yf.download(ticker, start=start_date, end=end_date)<br><br># Create a grid of subplots<br>fig = make_subplots(rows=2, cols=1)<br><br># Add the candlestick chart to the first subplot<br>fig.add_trace(go.Candlestick(x=df.index, open=df[&#39;Open&#39;], high=df[&#39;High&#39;], low=df[&#39;Low&#39;], close=df[&#39;Close&#39;]), row=1, col=1)<br><br># Add the MACD indicator to the second subplot<br>MACD = df.ta.macd()<br>fig.add_trace(go.Scatter(x=df.index, y=MACD[&#39;MACD_12_26_9&#39;], name=&quot;MACD&quot;), row=2, col=1)<br>fig.add_trace(go.Scatter(x=df.index, y=MACD[&#39;MACDs_12_26_9&#39;], name=&quot;Signal&quot;), row=2, col=1)<br>fig.add_trace(go.Scatter(x=df.index, y=MACD[&#39;MACDh_12_26_9&#39;], name=&quot;Histogram&quot;), row=2, col=1)<br><br>fig.update_layout(xaxis=dict(rangeslider=dict(visible=False)))<br><br># Show the chart<br>fig.show()</pre><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=9f9caf7e302f" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Unlocking the Power of Data: A Comparative Analysis of Stock Market Performance using Python]]></title>
            <link>https://medium.com/@BDPO/unlocking-the-power-of-data-a-comparative-analysis-of-stock-market-performance-using-python-964616b54f08?source=rss-5b69c5e67df1------2</link>
            <guid isPermaLink="false">https://medium.com/p/964616b54f08</guid>
            <category><![CDATA[cryptocurrency]]></category>
            <category><![CDATA[python]]></category>
            <category><![CDATA[finance]]></category>
            <category><![CDATA[trading]]></category>
            <category><![CDATA[technology]]></category>
            <dc:creator><![CDATA[BDPO.io]]></dc:creator>
            <pubDate>Sun, 22 Jan 2023 19:34:33 GMT</pubDate>
            <atom:updated>2023-01-22T19:34:33.250Z</atom:updated>
            <content:encoded><![CDATA[<p><em>Visualize the performance of any company over the last 5 years with the yfinance and Plotly libraries</em></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*ayLTb7wWPtLpoUzw.png" /></figure><p><em>Disclaimer: The material in this article is for purely educational purposes and should not be taken as professional investment advice. Invest at your discretion</em></p><p>As investors, financial analysts, or simply those curious about the stock market, it’s always important to stay informed about the performance of different companies. With this in mind, we will be taking a closer look at how we can use the Python programming language to compare the performance of any company or companies of our choice over the last five years. Whether you’re an investor looking to make a smart investment decision or a financial analyst trying to stay ahead of the competition, this data-driven approach is a powerful tool that can provide valuable insights.</p><p>To start, we will begin by importing the necessary libraries. We will be using the yfinance library to retrieve the stock data and the Plotly library to create the visualization. This is the first step to gaining a deeper understanding of the stock market and the performance of different companies.</p><pre>import yfinance as yf<br>import datetime<br>import plotly.graph_objects as go</pre><p>The next step is to allow the user to input the ticker symbols for the companies that they want to analyze. The user can input as many symbols as they want, separated by commas. This is done by using the input() function to prompt the user for their desired ticker symbols, and then using the split() function to convert the user&#39;s input into a list of symbols. This is the key to unlocking the power of this data-driven approach, as it allows you to compare the performance of any company or companies of your choice.</p><pre>tickers = input(<br>&quot;Enter the ticker symbols for the companies you want to analyze (separated by commas): &quot;<br>).split(&#39;,&#39;)</pre><p>After the user has inputted their desired ticker symbols, we will retrieve the stock data for the last 5 years using the yfinance library. We will be using the current date as the end date and the start date as 5 years ago from the end date. This is done by using the datetime library to get the current date and then subtracting 5 years worth of days from that date to get the start date. The yfinance.download() function is then used to retrieve the stock data for the specified ticker symbols and date range. With this, you&#39;ll have access to the historical data you need to make a well-informed decision.</p><pre>end_date = datetime.datetime.now()<br>start_date = end_date - datetime.timedelta(days=365*5)<br>stock_data = yf.download(tickers, start=start_date, end=end_date)</pre><p>th the stock data in hand, we can now create the comparison line graph to visualize the performance of the chosen companies over the last five years. Using a for loop, we will add a trace for each ticker symbol in the tickers list. We will be using the closing price of each stock and the relative stock price, which is the stock price divided by the stock price at the starting point of the time period and subtracting 1. This will allow us to compare the performance of each symbol in relation to each other over the time period. This step is crucial, as it helps you to identify patterns and trends that you may not have noticed otherwise.</p><pre>fig = go.Figure()<br>for ticker in tickers:<br>    fig.add_trace(go.Scatter(<br>x=stock_data.index, <br>y=((stock_data[&#39;Close&#39;][ticker] / stock_data[&#39;Close&#39;][ticker][0]) - 1) * 100, <br>name=ticker)<br>)</pre><p>Finally, we will update the graph properties to include a title, x-axis label, y-axis label, and legend. We will be using the `update_layout()` function from the Plotly library to add the title and axis labels, and the `show()` function to display the graph. This step is what brings it all together, making it easy to understand and interpret the data. The result is a clear, easy-to-read graph that illustrates the performance of the chosen companies over the last five years in terms of percentage relative to the starting point.</p><pre>fig.update_layout(title=&#39;Stock Price Comparison for the Chosen Companies (Last 5 Years)&#39;,<br>                  xaxis_title=&#39;Year&#39;,<br>                  yaxis_title=&#39;Stock Price (Relative to Starting Point in %)&#39;)<br><br>fig.show()</pre><p>Using the tickers UNP,CSX,GOOG,MSFT and DHR. you would get the below:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*jIPnyf6nA_QWVANyLd3wxA.png" /><figcaption>Performance of UNP,CSX,GOOG,MSFT and DHR</figcaption></figure><p>In conclusion, using the Python programming language, we were able to retrieve stock data for any company or companies that the user chooses and visualize their performance over the last five years. This data-driven approach is a powerful tool that can provide valuable insights and help you make informed decisions, whether you’re an investor, a financial analyst, or just curious about the stock market. With this code, you can easily compare the performance of any symbols of your choice, identify patterns and trends, and make a well-informed decision.</p><p>It’s worth noting that this code can also be easily adapted to compare performance over different time periods or to include additional data points, such as opening or highest prices. Additionally, the visualization can be further customized to include different types of graphs, such as bar or scatter plots, to suit the user’s needs.</p><p>It’s also important to remember that this analysis is based on historical data and past performance is not always indicative of future performance. It’s always a good idea to conduct further research and analysis before making any investment decisions.</p><p>Overall, using the Python programming language and the yfinance and Plotly libraries, we have a powerful tool at our disposal to compare the performance of any company or companies of our choice. With this data-driven approach, we can get valuable insights, identify patterns and trends, and make informed decisions. Whether you’re an investor, a financial analyst, or just curious about the stock market, this code is a great way to stay informed and make smart decisions.</p><p>At BDPO we have developed a number of strategies that have been back-tested, optimised and most importantly forward-tested on unseen data, to explore our backtests and market signal service along with Forex news alerts, earnings briefings, Golden Cross and RSI oversold / overbought alerts please visit:</p><p><a href="http://www.bdpo.co.uk/">www.BDPO.co.uk</a></p><p>If you have a custom strategy but don’t know how to code, please get visit BDPO and we can create a custom backtest report for your own strategy.</p><p>Full code below:</p><pre>import yfinance as yf<br>import datetime<br>import plotly.graph_objects as go<br><br>tickers = input(&quot;Enter the ticker symbols for the companies you want to analyze (separated by commas): &quot;).upper().split(&#39;,&#39;)<br><br>end_date = datetime.datetime.now()<br>start_date = end_date - datetime.timedelta(days=365*5)<br>stock_data = yf.download(tickers, start=start_date, end=end_date)<br><br>fig = go.Figure()<br>for ticker in tickers:<br>    fig.add_trace(go.Scatter(x=stock_data.index, y=((stock_data[&#39;Close&#39;][ticker] / stock_data[&#39;Close&#39;][ticker][0]) - 1) * 100, name=ticker))<br><br>fig.update_layout(title=&#39;Stock Price Comparison for the Chosen Companies (Last 5 Years)&#39;,<br>                  xaxis_title=&#39;Year&#39;,<br>                  yaxis_title=&#39;Stock Price (Relative to Starting Point in %)&#39;)<br><br>fig.show()</pre><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=964616b54f08" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Can you beat the market using Bollinger Bands?]]></title>
            <link>https://medium.com/@BDPO/can-you-beat-the-market-using-bollinger-bands-c415e54e8314?source=rss-5b69c5e67df1------2</link>
            <guid isPermaLink="false">https://medium.com/p/c415e54e8314</guid>
            <category><![CDATA[finance]]></category>
            <category><![CDATA[trading]]></category>
            <category><![CDATA[forex]]></category>
            <category><![CDATA[technology]]></category>
            <category><![CDATA[cryptocurrency]]></category>
            <dc:creator><![CDATA[BDPO.io]]></dc:creator>
            <pubDate>Sat, 07 Jan 2023 23:17:48 GMT</pubDate>
            <atom:updated>2023-01-07T23:17:48.951Z</atom:updated>
            <content:encoded><![CDATA[<h4>Backtesting a Bollinger band trading strategy</h4><p><em>Disclaimer: The material in this article is for purely educational purposes and should not be taken as professional investment advice. Invest at your discretion</em></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1000/1*frFBi5baUk69Q4mYiRUITA.png" /><figcaption>Custom BDPO strategy on NVDA</figcaption></figure><p>In this article, we will do a very simplified backtest of a Bollinger Band trading strategy on the daily timeframe for various stock tickers.</p><p>A common strategy for Bollinger Bands is the use of them as a mean reversion technique, if the price closes above the upper Bollinger band we will consider this a critical value and the price may reverse to the mean, similarly, if the price closes below the lower Bollinger band we can consider this at a critical level and may revert to the mean. The mean here is defined as the middle Bollinger band line aka the moving average.</p><p>This is not the only way you can interpret Bollinger bands, using it as a breakout strategy is also an option among many others, however, for the basis of the article we will be using it as a mean reversion strategy.</p><p>Before we get started we need to install some python requirements.</p><pre>pip install backtrader pandas numpy matplotlib quantstats yfinance</pre><p>Now to set up the strategy. We will load up a very simple Bollinger band indicator using Backtrader’s built-in indicator library, it also supports TA-Lib for those that prefer that.</p><p>Purely as this is meant to be a quick representation of the Bollinger band strategy we will be using Yfinance for the data. For a backtest and optimisation of a strategy we would consider trading, we would look to use more precise data however for Adjusted close prices Yfinance is satisfactory.</p><pre>daysBack = 365 * 8<br>startDate = (datetime.datetime.today() - timedelta(days=daysBack - 1)).date()<br>yesterday = datetime.datetime.now().date() - timedelta(days=1)<br><br>ticker = &quot;SPY&quot;<br><br>data = bt.feeds.PandasData(<br>    dataname=yf.download(ticker, start=startDate, end=yesterday, interval=&quot;1d&quot;)<br>)</pre><p>We will be testing the strategy over a period of 8 years on a daily timeframe using adjusted close prices.</p><p>Now for the logic, we will be using a Bollinger band period of 20 and a standard deviation for the upper and lower bands of 2.0, these are generally accepted as the standard values. Initially, the strategy will be buying if the price falls below the lower Bollinger band and closing the position once the price reverts back to the mean / moving average aka the middle Bollinger band.</p><pre>class bbands(bt.Strategy):<br>    params = (<br>        (&quot;bbStdv&quot;, 2),<br>        (&quot;bbPeriod&quot;, 20),<br>        )<br><br>    def log(self, txt, dt=None):<br>        dt = dt or self.datas[0].datetime.date(0)<br>        print(&quot;%s, %s&quot; % (dt.isoformat(), txt))<br><br>    def __init__(self):<br>        self.dataclose = self.datas[0].close<br><br><br>        self.order = None<br>        self.buyprice = None<br>        self.buycomm = None<br><br>        self.bbands = bt.indicators.BollingerBands(<br>            period=self.params.bbPeriod, plot=True<br>        )<br>        <br>    def notify_order(self, order):<br>        if order.status in [order.Completed]:<br>            if order.isbuy():<br>                self.buyprice = order.executed.price<br>                self.log(&quot;BUY EXECUTED, %.2f&quot; % order.executed.price)<br>            else:<br>                self.sellprice = order.executed.price<br>                self.log(&quot;SELL EXECUTED, %.2f&quot; % order.executed.price)<br>            self.bar_executed = len(self)<br>        elif order.status in [order.Canceled]:<br>            self.log(&quot;Order Canceled/Margin/Rejected&quot;)<br>        self.order = None<br><br>    def next(self):<br>        if self.order:<br>            return<br><br>        # If not in poisition<br>        if not self.position:<br><br>            # Create Buy<br>            if (<br>                (self.dataclose[0] &lt; self.bbands.bot[0]) <br>            ):<br>                self.buy()<br>                self.log(&quot;Create Buy, %.2f&quot; % self.dataclose[0])<br><br>            # Create Sell<br>            if (<br>                (self.dataclose[0] &gt; self.bbands.top[0]) <br>            ):<br>                self.sell()<br>                self.log(&quot;Create Sell, %.2f&quot; % self.dataclose[0])<br><br>        # Close Buy position<br>        if self.position.size &gt; 0:<br>            if (<br>                (self.dataclose[0] &gt;= self.bbands.mid[0]) <br>                ):<br>                self.log(&quot;Close Buy, %.2f&quot; % self.dataclose[0])<br>                self.close()<br><br>        # Close Sell position<br>        if self.position.size &lt; 0:<br>            if (<br>                (self.dataclose[0] &lt;= self.bbands.mid[0]) <br>                ):<br>                self.log(&quot;Close Sell, %.2f&quot; % self.dataclose[0])<br>                self.close()<br><br>        # Close all open position at the end of the backtest<br>        if len(self.dataclose) == (self.data.buflen() - 1):<br>            self.close()<br><br>    # Get the closing value of the portfolio<br>    def stop(self):<br>        self.log(self.broker.getvalue())</pre><p>Now to run the strategy.</p><p>Some points to note:</p><ul><li>In the above, we have calculated the indicators price at each candle close</li><li>It assumes the entry price is the open price of the subsequent candle</li><li>Before the end of the backtest, we close all open orders</li></ul><p>Assumptions:</p><ul><li>Starting capital 1000</li><li>Invest everything available in each trade</li><li>0.1% commission is payable on the opening and closing of each trade</li></ul><pre>if __name__ == &quot;__main__&quot;:<br><br>    cerebro = bt.Cerebro()<br>    cerebro.adddata(data)<br>    cerebro.addstrategy(bbands)<br><br>    cerebro.broker.setcommission(commission=0.001)<br>    cerebro.addsizer(bt.sizers.AllInSizerInt)<br>    cerebro.broker.setcash(1000)<br><br>    cerebro.addanalyzer(bt.analyzers.DrawDown, _name=&quot;drawdown&quot;)<br><br>    print(&quot;Starting Portfolio Value: %.2f&quot; % cerebro.broker.getvalue())<br><br>    results = cerebro.run()<br>    strat = results[0]<br><br>    # cerebro.plot()<br><br>    print(&quot;Final Portfolio Value: %.2f&quot; % cerebro.broker.getvalue())<br>    drawdownDf = strat.analyzers.drawdown.get_analysis()<br>    maxDraw = drawdownDf[&quot;max&quot;][&quot;drawdown&quot;]<br>    print(f&quot;Drawdown: {(round(maxDraw,2))}%&quot;)<br>    print(&quot;************************&quot;)</pre><p>Results</p><ul><li>SPY— Daily timeframe — 8 years</li><li>Initial value: 1000, End value: 1220.50, drawdown: 25.05%</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1000/1*Dj1ckiWx6SLMHpXordDTYg.png" /><figcaption>SPY Bollinger band backtest</figcaption></figure><p>We can see from the above results that by using the standard value Bollinger band strategy it would have made c.20% over the period, while this seems good. If we take a step back and look at just employing the “buy and hold” strategy we would have made more.</p><p>It is also possible to attribute the profit to the nature of the pair, what I mean by this is that the stock in question, the above being “SPY”, may be particularly mean reverting by nature in the fact it generally trades within a tight and volatile range which makes it good for a Bollinger bases strategy.</p><p>Let’s now test another ticker. If this strategy was good it should be able to make a profit on the majority of equities. However, looking at the below we see that our account loses more than 80% if we were to back-test this on AAPL, and this appears to be the case on most stocks we backtest this on.</p><ul><li>SPY — Daily timeframe — 8 years</li><li>Initial value: 1000, End value: 196.87, drawdown: 85.6%%</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1000/1*wPhnJbUUpysq51N1_wiOzA.png" /><figcaption>AAPL Bollinger band backtest</figcaption></figure><p>When looking at the above we see that there are a significant number of trades taken, each one chipping away at our profit with the commission, we also note that while the win rate is around 50% the losing trades outweigh the winning trades in terms of gross value significantly, suggesting adding a tight stop loss might improve results.</p><p>Let&#39;s try and improve the above, we will add a directional filter allowing the strategy to only trade in the underlying direction of the market. We will use two Moving Averages, if the shorter length moving average is above the longer moving average we will establish the market is bullish and we will only allow long trades and when the short MA is below the long MA we will say the market is bearish and hence only allow short trades, we will initially use 50 and 200 as the values for the moving averages.</p><p>Our new entry conditions are below:</p><pre>        self.maFast = bt.indicators.ExponentialMovingAverage(<br>                    period=self.params.maFastPeriod, plot=True<br>        )<br><br>        self.maSlow = bt.indicators.ExponentialMovingAverage(<br>            period=self.params.maSlowPeriod, plot=True<br>        )</pre><pre>            # Create Buy<br>            if (<br>                (self.dataclose[0] &lt; self.bbands.bot[0]) and<br>                (self.maFast[0] &gt; self.maSlow[0])<br>            ):<br>                self.buy()<br>                self.log(&quot;Create Buy, %.2f&quot; % self.dataclose[0])<br><br>            # Create Sell<br>            if (<br>                (self.dataclose[0] &gt; self.bbands.top[0]) and<br>                (self.maFast[0] &lt; self.maSlow[0])<br>            ):<br>                self.sell()<br>                self.log(&quot;Create Sell, %.2f&quot; % self.dataclose[0])</pre><p>Results</p><ul><li>AAPL— Daily timeframe — 8 years</li><li>Initial value: 1000, End value: 602.42, drawdown: 55.95%</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1000/1*devpqJcozDPbOdKeI-xJkA.png" /><figcaption>AAPL Bollinger band back-test</figcaption></figure><p>Once again this is a losing strategy but at least the directional filter has some merit, improving the results from a c.800 loss to a c.400 loss.</p><p>One final change we have made is to adjust the Bollinger band period and the standard deviation from 20 and 2 to 50 and 2.4 respectively (code below).</p><pre>    params = (<br>        (&quot;bbStdv&quot;, 2.4),<br>        (&quot;bbPeriod&quot;, 50),<br>        (&quot;maFastPeriod&quot;, 50),<br>        (&quot;maSlowPeriod&quot;, 200),<br>        )</pre><p>What we see by using the above parameters for the Bollinger band strategy with the moving average filter, is finally the backtest of the strategy becomes profitable, but once again it does not beat the buy and hold strategy.</p><ul><li>AAPL — Daily timeframe — 8 years</li><li>Initial value: 1000, End value: 1565.38, drawdown: 30.54%</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1000/1*UTPERAHtD5vyt-ygn0UkTA.png" /></figure><p>In conclusion, while this is a very specific test and on one timeframe. it does appear that the standard Bollinger band indicator used for mean reversion is not a profitable trading strategy on its own and testing on other pairs and higher timeframes also presents similar results. With optimisation and forward testing results may be better.</p><p>We see this while on its own the strategy is not profitable, however when combined with a moving average filter and a small tweak to the standard deviation and mean line we can improve the results of a backtest from a c.800 loss to a c.500 gain. Leading to the suggestion that with further tweaks, combinations with other indicators and an optimization and forward test of parameters there may be merit for a Bollinger-based strategy. We will look into this further in future articles.</p><p>We must also consider the accuracy of the data used in the backtest and the time scale tested over. We also have not looked at the exit conditions at all, using the opposite Bollinger band line as the close signal may also improve results, again something we will consider in further articles.</p><p>At BDPO we have developed a number of strategies that have been back-tested, optimised and most importantly forward-tested on unseen data, to explore our backtests and market signal service along with Forex news alerts, earnings briefings, Golden Cross and RSI oversold/overbought alerts please visit:</p><p><a href="http://www.bdpo.co.uk/">www.BDPO.co.uk</a></p><p>If you have a custom strategy but don’t know how to code, please get visit BDPO and we can create a custom backtest report for your own strategy.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=c415e54e8314" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Combining RSI and Exponential moving averages to create a profitable trading strategy]]></title>
            <link>https://medium.com/@BDPO/combining-rsi-and-exponential-moving-averages-to-create-a-profitable-trading-strategy-5058f1d04521?source=rss-5b69c5e67df1------2</link>
            <guid isPermaLink="false">https://medium.com/p/5058f1d04521</guid>
            <category><![CDATA[trading]]></category>
            <category><![CDATA[technology]]></category>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[stock-market]]></category>
            <category><![CDATA[cryptocurrency]]></category>
            <dc:creator><![CDATA[BDPO.io]]></dc:creator>
            <pubDate>Tue, 03 Jan 2023 22:54:19 GMT</pubDate>
            <atom:updated>2023-01-03T22:54:19.131Z</atom:updated>
            <content:encoded><![CDATA[<h4>Can you combine the Golden Cross trading strategy and RSI overbought and oversold levels to create a profitable trading strategy?</h4><p><em>Disclaimer: The material in this article is for purely educational purposes and should not be taken as professional investment advice. Invest at your discretion</em></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*iXkBJoxbOAFd_N2tuqgU2w.png" /><figcaption>Custom BDPO strategy on META</figcaption></figure><p>In this article, we will combine what we have done in the previous two reports to create a profitable backtest, hopefully. We will be conducting a very simplified backtest of the combination of RSI oversold/overbought levels alongside two EMA’s (exponential moving averages) to identify trends and hopefully turn what was two previously unprofitable trading systems into one that backtests profit. Our backtest will be on the daily timeframe for various stock tickers.</p><p>The strategy, we will keep this very simple as I want to combine what we have discussed in the previous two articles and demonstrate how crucial identifying and trading with the trend is.</p><p>We will be taking the standard Golden Cross strategy with a 50 and a 200 EMA, but instead of using it as a crossover to generate buy and sell signals we will be using it to identify the trend. We will say that if the 50EMA is above the 200EMA we are in an uptrend and if the 50EMA is below the 200EMA we are in a downtrend. For the entry condition, we will be using the RSI overbought and oversold levels, in particular, if the RSI is below 50 we will be looking to go long and if above 50 looking to go short. We will be adding another condition but this will be discussed later.</p><p>Before we get started we need to install some python requirements.</p><pre>pip install backtrader pandas numpy matplotlib quantstats yfinance</pre><p>Now to set up the RSI strategy. We will load up a very simple RSI indicator using Backtrader’s built-in indicator library, it also supports TA-Lib for those that prefer that.</p><p>Purely as this is meant to be a quick representation of the RSI strategy we will be using Yfinance for the data. For a backtest and optimisation of a system we would consider trading, we would look to use more precise data however for Adjusted close prices Yfinance is satisfactory.</p><pre>daysBack = 365 * 8<br>startDate = (datetime.datetime.today() - timedelta(days=daysBack - 1)).date()<br>yesterday = datetime.datetime.now().date() - timedelta(days=1)<br><br>ticker = &quot;META&quot;<br><br>data = bt.feeds.PandasData(<br>    dataname=yf.download(ticker, start=startDate, end=yesterday, interval=&quot;1d&quot;)<br>)</pre><p>We will be testing the strategy over a period of 8 years on a daily timeframe using adjusted close prices.</p><p>Now for the logic. We will be using an RSI period of 14 as this is generally accepted as the standard value and similar to the EMA’s we will be using the standard Golden Cross values of 50 and 200. To start off the strategy will be buying if the RSI falls below the 50 value and the fast MA is above the slow MA. The reverse is true for the short signals.</p><p>To close the strategy we will be starting off by closing a buy if the 50 EMA cross back below the 200 EMA and the reverse for a short position.</p><pre>class rsi(bt.Strategy):<br>    params = (<br>        (&quot;rsiPeriod&quot;, 14),<br>        (&quot;maFastPeriod&quot;, 50),<br>        (&quot;maSlowPeriod&quot;, 200),<br>        )<br><br>    def log(self, txt, dt=None):<br>        dt = dt or self.datas[0].datetime.date(0)<br>        print(&quot;%s, %s&quot; % (dt.isoformat(), txt))<br><br>    def __init__(self):<br>        self.dataclose = self.datas[0].close<br><br>        self.order = None<br>        self.buyprice = None<br>        self.buycomm = None<br><br>        self.rsi = bt.indicators.RelativeStrengthIndex(<br>            period=self.params.rsiPeriod, plot=True<br>        )<br><br>        self.maFast = bt.indicators.ExponentialMovingAverage(<br>                    period=self.params.maFastPeriod, plot=True<br>        )<br><br>        self.maSlow = bt.indicators.ExponentialMovingAverage(<br>            period=self.params.maSlowPeriod, plot=True<br>        )<br>        <br>    def notify_order(self, order):<br>        if order.status in [order.Completed]:<br>            if order.isbuy():<br>                self.buyprice = order.executed.price<br>                self.log(&quot;BUY EXECUTED, %.2f&quot; % order.executed.price)<br>            else:<br>                self.sellprice = order.executed.price<br>                self.log(&quot;SELL EXECUTED, %.2f&quot; % order.executed.price)<br>            self.bar_executed = len(self)<br>        elif order.status in [order.Canceled]:<br>            self.log(&quot;Order Canceled/Margin/Rejected&quot;)<br>        self.order = None<br><br>    def next(self):<br>        if self.order:<br>            return<br><br>        # If not in poisition<br>        if not self.position:<br><br>            # Create Buy<br>            if (<br>                (self.maFast[0] &gt; self.maSlow[0]) and<br>                (self.rsi[0] &lt; 50) <br>                # (self.dataclose[0] &gt; self.maSlow[0]) <br><br>            ):<br>                self.buy()<br>                self.log(&quot;Create Buy, %.2f&quot; % self.dataclose[0])<br><br>            # Create Sell<br>            if (<br>                (self.maFast[0] &lt; self.maSlow[0]) and<br>                (self.rsi[0] &gt; 50) <br>                # (self.dataclose[0] &lt; self.maSlow[0]) <br><br><br>            ):<br>                self.sell()<br>                self.log(&quot;Create Sell, %.2f&quot; % self.dataclose[0])<br><br>        # Close Buy position<br>        if self.position.size &gt; 0:<br>            if (<br>                (self.maFast[0] &lt; self.maSlow[0]) or<br>                # (self.rsi[0] &gt; 70) or<br>                # (self.dataclose[0] &lt; self.maSlow[0])<br>                ):<br>                self.log(&quot;Close Buy, %.2f&quot; % self.dataclose[0])<br>                self.close()<br><br>        # Close Sell position<br>        if self.position.size &lt; 0:<br>            if (<br>                (self.maFast[0] &gt; self.maSlow[0]) or<br>                # (self.rsi[0] &lt; 30) or <br>                # (self.dataclose[0] &gt; self.maSlow[0])<br>                ):<br>                self.log(&quot;Close Sell, %.2f&quot; % self.dataclose[0])<br>                self.close()<br><br>        # Close all open position at the end of the backtest<br>        if len(self.dataclose) == (self.data.buflen() - 1):<br>            self.close()<br><br>    # Get the closing value of the portfolio<br>    def stop(self):<br>        self.log(self.broker.getvalue())</pre><p>Now to run the strategy.</p><p>Some points to note:</p><ul><li>In the above, we have calculated the indicators price at each candle close</li><li>It assumes the entry price is the open price of the subsequent candle</li><li>Before the end of the backtest, we close all open orders</li></ul><p>Assumptions:</p><ul><li>Starting capital 1000</li><li>Invest everything available in each trade</li><li>0.1% commission payable on the opening and closing of each trade</li></ul><pre>if __name__ == &quot;__main__&quot;:<br><br>    cerebro = bt.Cerebro()<br>    cerebro.adddata(data)<br>    cerebro.addstrategy(rsi)<br><br>    cerebro.broker.setcommission(commission=0.001)<br>    cerebro.addsizer(bt.sizers.AllInSizerInt)<br>    cerebro.broker.setcash(1000)<br><br>    cerebro.addanalyzer(bt.analyzers.DrawDown, _name=&quot;drawdown&quot;)<br><br>    print(&quot;Starting Portfolio Value: %.2f&quot; % cerebro.broker.getvalue())<br><br>    results = cerebro.run()<br>    strat = results[0]<br><br>    cerebro.plot()<br><br>    print(&quot;Final Portfolio Value: %.2f&quot; % cerebro.broker.getvalue())<br>    drawdownDf = strat.analyzers.drawdown.get_analysis()<br>    maxDraw = drawdownDf[&quot;max&quot;][&quot;drawdown&quot;]<br>    print(f&quot;Drawdown: {(round(maxDraw,2))}%&quot;)<br>    print(&quot;************************&quot;)</pre><p>Results</p><ul><li>META— Daily timeframe — 8 years</li><li>Initial value: 1000, End value: 2205.83, drawdown: 49.31%%</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1000/1*eu0Qq4zBHcg0mr865_g6Yg.png" /></figure><p>We can see from the above results that by using the RSI strategy combined with the Golden Cross trend we would have doubled our initial investment and beat the “buy and hold” strategy. However, if we take a step back and look at the drawdown and the nature of the losing trades we can improve.</p><p>It is also possible to attribute the beating of the “buy and hold” to the fact that META has seen a vast drop in the share price in 2022. However, the fact that the strategy opened up a short somewhat close to the start of the downtrend suggests the strategy has some merit.</p><p>Improvements</p><p>Now, let&#39;s add some further entry conditions. We will add that the price now has to be above the slow MA if entering a buy and if entering a short the price needs to be below the slow MA. This should ensure that we aren&#39;t taking any long trades where the price has already broken through the 200EMA or short position where the price is above.</p><pre>        if not self.position:<br><br>            # Create Buy<br>            if (<br>                (self.maFast[0] &gt; self.maSlow[0]) and<br>                (self.rsi[0] &lt; 50) and<br>                (self.dataclose[0] &gt; self.maSlow[0]) <br><br>            ):<br>                self.buy()<br>                self.log(&quot;Create Buy, %.2f&quot; % self.dataclose[0])<br><br>            # Create Sell<br>            if (<br>                (self.maFast[0] &lt; self.maSlow[0]) and<br>                (self.rsi[0] &gt; 50) and<br>                (self.dataclose[0] &lt; self.maSlow[0]) <br><br>            ):<br>                self.sell()<br>                self.log(&quot;Create Sell, %.2f&quot; % self.dataclose[0])</pre><p>Now to address the exit conditions. Instead of closing on the MA Crossover, we will be closing our buy position if the price falls below the 200 EMA and closing the short position if the price moves above the 200 EMA. we will also be closing a buy if RSI is above 70 signifying that it is overbought / overvalued and will also be closing out of a short position if RSI falls below 30 signifying it is oversold and may be subject to upside pressure.</p><pre>        # Close Buy position<br>        if self.position.size &gt; 0:<br>            if (<br>                (self.maFast[0] &lt; self.maSlow[0]) or<br>                (self.rsi[0] &gt; 70) or<br>                (self.dataclose[0] &lt; self.maSlow[0])<br>                ):<br>                self.log(&quot;Close Buy, %.2f&quot; % self.dataclose[0])<br>                self.close()<br><br>        # Close Sell position<br>        if self.position.size &lt; 0:<br>            if (<br>                (self.maFast[0] &gt; self.maSlow[0]) or<br>                (self.rsi[0] &lt; 30) or <br>                (self.dataclose[0] &gt; self.maSlow[0])<br>                ):<br>                self.log(&quot;Close Sell, %.2f&quot; % self.dataclose[0])<br>                self.close()</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1000/1*j0ox2Tm1d9fpkf5pMU3sdw.png" /></figure><ul><li>META — Daily timeframe — 8 years</li><li>Initial value: 1000, End value: 2849.38, drawdown: 36.11%</li></ul><p>This improves results, we have gone from a backtested 2205.83 to 2849.38 with a c 13% reduction in drawdown.</p><p>Finally, by looking at the backtest we see that our close conditions are slightly too aggressive. Let&#39;s remove one of these. We will now only close a position on the MA Crossover or if the RSI drops below 30 or above 70 to close the sell and buy respectively.</p><pre>  # Close Buy position<br>        if self.position.size &gt; 0:<br>            if (<br>                (self.maFast[0] &lt; self.maSlow[0]) or<br>                (self.rsi[0] &gt; 70)<br>                ):<br>                self.log(&quot;Close Buy, %.2f&quot; % self.dataclose[0])<br>                self.close()<br><br>        # Close Sell position<br>        if self.position.size &lt; 0:<br>            if (<br>                (self.maFast[0] &gt; self.maSlow[0]) or<br>                (self.rsi[0] &lt; 30) <br>                ):<br>                self.log(&quot;Close Sell, %.2f&quot; % self.dataclose[0])<br>                self.close()</pre><p>Once again this improves the results going from a backtested 2849.38 to 3384.71 at the detriment of drawdown which has increased to 45% from 36% noting this is still less than the original backtest at 49%.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1000/1*FA1FHpsFBJ0_K16nU-AWjg.png" /></figure><ul><li>META — Daily timeframe — 8 years</li><li>Initial value: 1000, End value: 3384.71, drawdown: 45.51%</li></ul><p>In conclusion, while this is a very specific test and on one timeframe. it does appear that within reason and with a few tweaks you are able to take the standard RSI undersold/over brought indicator, levels and combine this with the Golden Cross strategy for trend analysis and create a profitable backtest. With optimisation and forward testing results may be better.</p><p>We must note of course this is just a backtest and in no way would this be advised to trade with. We would have to consider a number of factors, the post-market trading hours and the spread that it entails, the leverage used and liquidity questions when trading multiple tickers alongside many others.</p><p>We must also consider the accuracy of the data used in the backtest and the time scale tested over. We would suggest some more advanced methods of identifying a trend and then trading solely long or short depending on the trend of the market, we would also like to look into how volatility could be used to improve results, something we will look into in coming articles.</p><p>At BDPO we have developed a number of strategies that have been back-tested, optimised and most importantly forward-tested on unseen data, to explore our backtests and market signal service along with Forex news alerts, earnings briefings, Golden Cross and RSI oversold/overbought alerts please visit:</p><p><a href="http://www.bdpo.co.uk/">www.BDPO.co.uk</a></p><p>If you have a custom strategy but don’t know how to code, please get visit BDPO and we can create a custom backtest report for your own strategy.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=5058f1d04521" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Can you beat the market using the Relative Strength Index?]]></title>
            <link>https://medium.com/@BDPO/can-you-beat-the-market-using-the-relative-strength-index-e41ccb74a68b?source=rss-5b69c5e67df1------2</link>
            <guid isPermaLink="false">https://medium.com/p/e41ccb74a68b</guid>
            <category><![CDATA[finance]]></category>
            <category><![CDATA[trading]]></category>
            <category><![CDATA[forex-trading]]></category>
            <category><![CDATA[technology]]></category>
            <category><![CDATA[cryptocurrency]]></category>
            <dc:creator><![CDATA[BDPO.io]]></dc:creator>
            <pubDate>Sat, 31 Dec 2022 14:19:05 GMT</pubDate>
            <atom:updated>2022-12-31T14:20:53.223Z</atom:updated>
            <content:encoded><![CDATA[<h4>Backtesting an RSI trading strategy</h4><p><em>Disclaimer: The material in this article is for purely educational purposes and should not be taken as professional investment advice. Invest at your discretion</em></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1000/1*sPkPdK8VcMj5JEiKZ-c_Uw.png" /><figcaption>Custom BDPO strategy on AAPL</figcaption></figure><p>In this article, we will do a very simplified backtest of the RSI undersold / overbought trading strategy on the daily timeframe for various stock tickers.</p><p>This is a very common strategy, effectively if the RSI indicator is below 30 it suggests the stock or pair is oversold and may reverse to the upside. The reverse is true if the RSI is above 70, suggesting the asset is overbought and may reverse to the downside.</p><p>Before we get started we need to install some python requirements.</p><pre>pip install backtrader pandas numpy matplotlib quantstats yfinance</pre><p>Now to set up the RSI strategy. We will load up a very simple RSI indicator using Backtrader&#39;s built-in indicator library, it also supports TA-Lib for those that prefer that.</p><p>Purely as this is meant to be a quick representation of the RSI strategy we will be using Yfinance for the data. For a backtest and optimisation of a strategy we would consider trading, we would look to use more precise data however for Adjusted close prices Yfinance is satisfactory.</p><pre>daysBack = 365 * 8<br>startDate = (datetime.datetime.today() - timedelta(days=daysBack - 1)).date()<br>yesterday = datetime.datetime.now().date() - timedelta(days=1)<br><br>ticker = &quot;QQQ&quot;<br><br>data = bt.feeds.PandasData(<br>    dataname=yf.download(ticker, start=startDate, end=yesterday, interval=&quot;1d&quot;)<br>)</pre><p>We will be testing the strategy over a period of 8 years on a daily timeframe using adjusted close prices.</p><p>Now for the logic. We have made the first section of this test a long-only strategy so we can analyse each side of the trading system, we will be using an RSI period of 14 as this is generally accepted as the standard value. The strategy will be buying if the RSI falls below the 30 value and closing the position once above 70.</p><pre>class rsi(bt.Strategy):<br>    params = ((&quot;rsiPeriod&quot;, 14),)<br><br>    def log(self, txt, dt=None):<br>        dt = dt or self.datas[0].datetime.date(0)<br>        print(&quot;%s, %s&quot; % (dt.isoformat(), txt))<br><br>    def __init__(self):<br>        self.dataclose = self.datas[0].close<br><br>        self.order = None<br>        self.buyprice = None<br>        self.buycomm = None<br><br>        self.rsi = bt.indicators.RelativeStrengthIndex(<br>            period=self.params.rsiPeriod, plot=True<br>        )<br><br>    def notify_order(self, order):<br>        if order.status in [order.Completed]:<br>            if order.isbuy():<br>                self.buyprice = order.executed.price<br>                self.log(&quot;BUY EXECUTED, %.2f&quot; % order.executed.price)<br>            else:<br>                self.sellprice = order.executed.price<br>                self.log(&quot;SELL EXECUTED, %.2f&quot; % order.executed.price)<br>            self.bar_executed = len(self)<br>        elif order.status in [order.Canceled]:<br>            self.log(&quot;Order Canceled/Margin/Rejected&quot;)<br>        self.order = None<br><br>    def next(self):<br>        if self.order:<br>            return<br><br>        # If not in poisition<br>        if not self.position:<br><br>            # Create Buy<br>            if self.rsi[0] &lt; 30:<br>                self.buy()<br>                self.log(&quot;Create Buy, %.2f&quot; % self.dataclose[0])<br><br>        # Close position<br>        if self.position.size &gt; 0:<br>            if self.rsi[0] &gt;= 70:<br>                self.log(&quot;Close Buy, %.2f&quot; % self.dataclose[0])<br>                self.close()<br><br>        # Close all open position at the end of the backtest<br>        if len(self.dataclose) == (self.data.buflen() - 1):<br>            self.close()<br><br>    # Get the closing value of the portfolio<br>    def stop(self):<br>        self.log(self.broker.getvalue())</pre><p>Now to run the strategy.</p><p>Some points to note:</p><ul><li>In the above, we have calculated the indicators price at each candle close</li><li>It assumes the entry price is the open price of the subsequent candle</li><li>Before the end of the backtest, we close all open orders</li></ul><p>Assumptions:</p><ul><li>Starting capital 1000</li><li>Invest everything available in each trade</li><li>0.1% commission payable on the opening and closing of each trade</li></ul><pre>if __name__ == &quot;__main__&quot;:<br><br>    cerebro = bt.Cerebro()<br>    cerebro.adddata(data)<br>    cerebro.addstrategy(rsi)<br><br>    cerebro.broker.setcommission(commission=0.001)<br>    cerebro.addsizer(bt.sizers.AllInSizerInt)<br>    cerebro.broker.setcash(1000)<br><br>    cerebro.addanalyzer(bt.analyzers.DrawDown, _name=&quot;drawdown&quot;)<br><br>    print(&quot;Starting Portfolio Value: %.2f&quot; % cerebro.broker.getvalue())<br><br>    results = cerebro.run()<br>    strat = results[0]<br><br>    cerebro.plot()<br><br>    print(&quot;Final Portfolio Value: %.2f&quot; % cerebro.broker.getvalue())<br>    drawdownDf = strat.analyzers.drawdown.get_analysis()<br>    maxDraw = drawdownDf[&quot;max&quot;][&quot;drawdown&quot;]<br>    print(f&quot;Drawdown: {(round(maxDraw,2))}%&quot;)<br>    print(&quot;************************&quot;)</pre><p>Results</p><ul><li>QQQ — Daily timeframe — 8 years</li><li>Initial value: 1000, End value: 1722.15, drawdown: 28.09%</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1000/1*CYf6724fH7a17CqLwGFQzQ.png" /><figcaption>QQQ Backtest using the RSI — Long only</figcaption></figure><p>We can see from the above results that by using the long only 30 / 70 RSI strategy it would have made 70% over the period, while this seems good. If we take a step back and look at just employing the “buy and hold” strategy we would have made more.</p><p>It is also possible to attribute the profit of the long-only strategy to the fact that the underlying market was bullish this is also confirmed as when it turned to the downside we see equity falling.</p><p>Let&#39;s now look at the sell signals. If this strategy was good it should be able to make a profit in any market condition. However, looking at the below we see that our account almost halves if we were just to take the sell signals.</p><ul><li>QQQ — Daily timeframe — 8 years</li><li>Initial value: 1000, End value: 515.31, drawdown: 69.2%</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1000/1*B1X4FaW-G9vOEk-9Pdp2GQ.png" /><figcaption>QQQ Backtest using the RSI — Short only</figcaption></figure><p>While the market is trading within a reasonably tight range at the start of the data the strategy is profitable, however, once the underlying market turns bullish we start seeing the downfall of trading this RSI strategy. We also note that the win rate actually remains above 50% hence if we were to put in place a tight stop loss we may be able to improve profitability.</p><p>Now finally let&#39;s make the strategy trade both long and short and see the results on a different pair.</p><ul><li>SPY— Daily timeframe — 8 years</li><li>Initial value: 1000, End value: 805.92, drawdown: 48.99%</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*D5scUepI8ZYCdYhIHgfJ0w.png" /><figcaption>SPY Backtest using the RSI — Long and Short</figcaption></figure><p>In conclusion, while this is a very specific test and on one timeframe. it does appear that the standard RSI undersold/over brought indicator is not a profitable trading strategy on its own and testing on other pairs and higher timeframes also present similar results. With optimisation and forward testing results may be better.</p><p>By looking at the individual short and long-side performance we can see that the strategy works better when trading in the direction of the market and can be profitable when the market is ranging. Therefore, if we were to add an indicator that can be used to determine the underlying direction of the market (possibly utilising moving averages) and adjust the RSI signals accordingly this strategy may become profitable. We will look into this in a further article.</p><p>We must also consider the accuracy of the data used in the backtest and the time scale tested over. We would suggest some method of identifying a trend and then trading solely long or short depending on the trend of the market.</p><p>At BDPO we have developed a number of strategies that have been back-tested, optimised and most importantly forward-tested on unseen data, to explore our backtests and market signal service along with Forex news alerts, earnings briefings, Golden Cross and RSI oversold / overbought alerts please visit:</p><p><a href="http://www.bdpo.co.uk/">www.BDPO.co.uk</a></p><p>If you have a custom strategy but don’t know how to code, please get visit BDPO and we can create a custom backtest report for your own strategy.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=e41ccb74a68b" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[The Golden Cross trading strategy]]></title>
            <link>https://medium.com/@BDPO/the-golden-cross-trading-strategy-71e8ef7ae02?source=rss-5b69c5e67df1------2</link>
            <guid isPermaLink="false">https://medium.com/p/71e8ef7ae02</guid>
            <category><![CDATA[forex-trading]]></category>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[technology]]></category>
            <category><![CDATA[python]]></category>
            <category><![CDATA[trading]]></category>
            <dc:creator><![CDATA[BDPO.io]]></dc:creator>
            <pubDate>Tue, 27 Dec 2022 12:16:01 GMT</pubDate>
            <atom:updated>2022-12-27T12:16:01.173Z</atom:updated>
            <content:encoded><![CDATA[<h4>Can you beat the market trading a 50 and 200 moving average crossover?</h4><p><em>Disclaimer: The material in this article is for purely educational purposes and should not be taken as professional investment advice. Invest at your own discretion</em></p><figure><img alt="A backtest of one of the BDPO custom stratgies" src="https://cdn-images-1.medium.com/max/1024/1*rg5IJRZbjc4foOB4DwKQsw.png" /></figure><p>In the coming months, we will be doing a series of posts analysing popular / common trading strategies.</p><p>In this article, we will be doing a very simplified backtest of the Golden Cross, 50 200 MA crossover strategy on the daily timeframe for various stock tickers.</p><p>Before we get started we need to install some python requirements.</p><pre>pip install backtrader pandas numpy matplotlib quantstats yfinance</pre><p>Now to set up the golden cross strategy. We won’t talk through the Backtrader package in this article but will instead focus on the results of trading the golden cross.</p><pre>class goldenCross(bt.Strategy):<br>    params = (<br>        (&#39;mafastPeriod&#39;, 50),<br>        (&#39;maslowPeriod&#39;, 200),<br>        )<br><br>    def log(self, txt, dt=None):<br>        dt = dt or self.datas[0].datetime.date(0)<br>        print(&#39;%s, %s&#39; % (dt.isoformat(), txt))<br><br><br>    def __init__(self):    <br>        self.dataclose = self.datas[0].close<br>        self.datahigh = self.datas[0].high<br>        self.datalow = self.datas[0].low<br>        self.dataopen = self.datas[0].open<br>        self.datavolume = self.datas[0].volume<br><br>        self.order = None<br>        self.buyprice = None<br>        self.buycomm = None<br><br>        self.maFast = bt.indicators.ExponentialMovingAverage(period=self.params.mafastPeriod, plot=True)<br>        self.maSlow = bt.indicators.ExponentialMovingAverage(period=self.params.maslowPeriod, plot=True)<br><br><br>  <br>    def notify_order(self, order):<br>        if order.status in [order.Completed]:<br>            if order.isbuy():<br>                self.buyprice = order.executed.price<br>                self.log(&#39;BUY EXECUTED, %.2f&#39; % order.executed.price)<br>            else: <br>                self.sellprice = order.executed.price<br>                self.log(&#39;SELL EXECUTED, %.2f&#39; % order.executed.price)<br>            self.bar_executed = len(self)<br>        elif order.status in [order.Canceled]:<br>            self.log(&#39;Order Canceled/Margin/Rejected&#39;)<br>        self.order = None<br><br><br><br>    def next(self):<br>        if self.order:<br>            return<br><br># If not in poisition<br>        if not self.position:<br><br># Create Buy<br>          if (<br>              self.maFast[0] &gt; self.maSlow[0] and <br>              self.maFast[-1] &lt; self.maSlow[-1]<br>              ):<br>                  self.buy()<br>                  self.log(&#39;Create Buy, %.2f&#39; % self.dataclose[0])<br><br># Position open long<br>        if self.position.size &gt; 0:<br>            if (<br>              self.maFast[0] &lt; self.maSlow[0] and <br>              self.maFast[-1] &gt; self.maSlow[-1]<br>              ):<br>                self.log(&#39;Close Buy, %.2f&#39; % self.dataclose[0])<br>                self.close()<br><br># Close all open position at the end of the backtest<br>        if len(self.data) == (self.data.buflen()-1):<br>            self.close()<br><br># Get the closing value of the portfolio<br>    def stop(self):<br>        self.log(<br>            self.broker.getvalue()<br>            )</pre><p>What we have done in the above code is import the data and code the basic 50/200 ma crossover. Once the fast moving average (50 ema) crosses over the slow moving average (200 ema) then we open a buy position, once a position is open we then wait until 50 ema crosses back below the 200 ema to close it.</p><p>Some points to note:</p><ul><li>In the above we have calculated the indicators price at each candle close</li><li>It assumes the entry price is the open price of the subsequent candle</li><li>Before the end of the backtest we close all open orders</li></ul><p>Now to run the golden cross strategy.</p><pre>if __name__ == &#39;__main__&#39;:<br><br>    cerebro = bt.Cerebro()<br>    cerebro.adddata(data)<br>    cerebro.addstrategy(goldenCross)<br><br><br>    cerebro.broker.setcommission(commission=0.001)<br>    cerebro.addsizer(bt.sizers.AllInSizerInt)<br>    cerebro.broker.setcash(1000)<br><br>    <br><br>    cerebro.addobserver(bt.observers.Value)<br>    cerebro.addobserver(bt.observers.BuySell)<br>    cerebro.addanalyzer(bt.analyzers.DrawDown, _name=&#39;drawdown&#39;)<br><br><br>    print(&#39;Starting Portfolio Value: %.2f&#39; % cerebro.broker.getvalue())<br><br>    results = cerebro.run()<br>    strat = results[0]<br><br>    print(&#39;Final Portfolio Value: %.2f&#39; % cerebro.broker.getvalue())<br>    drawdownDf = strat.analyzers.drawdown.get_analysis()<br>    maxDraw = drawdownDf[&#39;max&#39;][&#39;drawdown&#39;]<br>    print(f&#39;Drawdown: {(round(maxDraw,2))}%&#39;) <br>    print(&#39;************************&#39;)</pre><p>Assumptions:</p><ul><li>Starting capital 1000</li><li>Invest everything available on each trade</li><li>0.1% commission payable on the opening and closing of each trade</li></ul><p>After running the strategy on Microsoft 1 hour timeframe data for the last two years:</p><p>Ticker = MSFT period = 2 years timeframe = 1 hour (long only)</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1000/1*DoOXdZh-_dyMN6zm2l8xJw.png" /></figure><p>Final Portfolio Value: 950.79 | Drawdown: 24.66%</p><p>As you can see you would lose money if you traded this strategy over the last two years on Microsoft. Note that we have been in a downward trend for the past year and hence will reduce the profitability of the buy only strategy.</p><p>Taking QQQ hourly data for the last two years we get similar results to Microsoft, totalling a loss of c.29.</p><p>Ticker = QQQ period = 2 years timeframe = 1 hour (long only)</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1000/1*14QYLBaKan7KUzJUCJTVPQ.png" /></figure><p>Final Portfolio Value: 971.78 | Drawdown: 12.79%</p><p>Conversely, if we identify that QQQ is in a bearish trend and we adjust the strategy to be short only we get a profit, however, this relies on being able to identify the trend and change the strategy accordingly.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1000/1*5w3G5ARCz3u-5me4IN_BQg.png" /></figure><p>Final Portfolio Value: 1068.12 | Drawdown: 16.71%</p><p>In conclusion, while this is a very specific test and on one timeframe. it does appear that the standard 50 / 200 ema crossover is not a profitable trading strategy on its own and testing on other pairs and higher timeframes also present similar results. With optimisation and forward testing results may be better.</p><p>We must also consider the accuracy of the data used in the backtest and the time scale tested over. We would suggest some method of identifying a trend and then trading solely long or short depending on the trend of the market.</p><p>At BDPO we have developed a number of strategies that have been back tested, optimised and most importantly forward tested on unseen data, to explore our back tests and market signal service along with Forex news alerts, earnings briefings, Golden Cross and RSI oversold / overbought alerts please visit:</p><p><a href="http://www.bdpo.co.uk/">www.BDPO.co.uk</a></p><p>If you have a custom strategy but don’t know how to code, please get visit BDPO and we can create a custom backtest report for your own strategy.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=71e8ef7ae02" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>