Python in algorithmic trading - page 19

 

Scalping Strategy With CandleStick Pattern Backtest In Python



Scalping Strategy With CandleStick Pattern Backtest In Python

In this video, we will discuss and demonstrate a simple sculpting strategy that builds upon the concepts presented in the previous two videos. If you are interested in the specific details and the Python code for this strategy, you can find a link in the video description.

The strategy we are using revolves around three exponential moving averages (EMAs): fast, medium, and slow. By analyzing the alignment of these EMAs, we can estimate whether the price trend is upward or downward. In an uptrend, the fast EMA is above the medium EMA, which is above the slow EMA. Conversely, in a downtrend, the order is inverted.

For buying positions in an uptrend, we look for candles that open below and close above the fast EMA. On the other hand, for selling positions in a downtrend, we look for candles that open above and close below the fast EMA. The video provides examples of candles that meet these criteria for buying positions in an uptrend.

The strategy has been previously tested and optimized using a leveraged account with a 1:100 leverage ratio. The testing was conducted over a period of three years, resulting in a return percentage of 445% and a win rate of 55%. However, it is important to note that the strategy showed large drawdown periods, and the equity curve was not stable throughout the three-year period.

To improve the strategy, an additional condition is introduced. In addition to the candles crossing the fast EMA, we now consider the length of the candle wicks. If it's an uptrend, the candle should have a very short lower tail, indicating a strong upward momentum. Similarly, in a downtrend, the candle should have no high tail. This condition aims to filter out signals with weak momentum.

To evaluate the effectiveness of this additional condition, the strategy is backtested using Python. The source code for the backtesting is provided in a Jupyter Notebook file, which can be downloaded from the link in the video description.

The backtesting is performed using the Euro/USD 15-minute chart data from 2019 to 2022, covering three years of data. The data is preprocessed by removing candles with zero volume and resetting the index of the data frame. The three moving averages (50, 100, and 150) and the average true range (ATR) are added to the data frame.

The strategy generates signals based on the alignment of the moving averages, and the total signal is obtained by identifying candlesticks that cross the fast EMA in the same direction as the trend. The video demonstrates how these signals can be visualized on the charts.

Different methods for setting stop loss and take profit values are tested. These include fixed distance, ATR-related distances, trailing stop loss, and stop loss observed from price. The results for each method are compared before and after adding the third condition.

When the third condition is added, the strategy shows significant improvements in all the tested methods. The fixed distance stop loss and take profit method yields a return of 1805% with a win rate of 59%. The ATR-related method achieves a return of 249% and a win rate of 51%. The trailing stop loss method, which was previously losing, now yields a return of 394% and a win rate of 42.5%. Lastly, the stop loss observed from price, which was also losing, now generates a return of 373% with a win rate of 49%.

In addition to improved returns, the equity curves for all methods show an overall upward trend, indicating more stable and positive performance compared to the previous results.

The video emphasizes that this strategy is not presented as a complete trading system but rather as an illustration of the impact of adding the low wick condition.

The video concludes by highlighting some important points to consider when using this strategy:

  1. The strategy demonstrated in the video is a simplified example and should not be considered a comprehensive trading system. It serves as an illustration of how adding certain conditions can improve the performance of a strategy.

  2. Backtesting results are not indicative of future performance. While the strategy showed improved returns during the testing period, market conditions can change, and past results may not be replicated in the future.

  3. It is essential to perform thorough testing and optimization before applying any strategy to real trading. Backtesting allows you to evaluate the strategy's performance under different market conditions and refine its parameters for better results.

  4. Risk management is crucial. Properly setting stop loss and take profit levels is essential to protect your capital and manage risk. The video demonstrated different methods for setting these levels, but it's important to consider your risk tolerance and account size when determining the appropriate values.

  5. Emotional discipline is necessary for successful trading. Stick to your strategy and avoid making impulsive decisions based on short-term market fluctuations.

  6. Consider other factors and indicators that may complement this strategy. No single strategy works perfectly in all market conditions, so it's beneficial to combine multiple indicators and techniques for a more comprehensive analysis.

  7. Continuously monitor and evaluate the performance of your strategy. As market conditions change, it may be necessary to adapt and refine your approach to remain profitable.

Remember, trading in financial markets carries risks, and it's important to educate yourself, seek professional advice, and practice with caution before committing real funds. The video serves as an educational resource, and it's up to you to further explore and customize the strategy to suit your trading style and risk tolerance.

Scalping Strategy With CandleStick Pattern Backtest In Python
Scalping Strategy With CandleStick Pattern Backtest In Python
  • 2022.03.10
  • www.youtube.com
This is a scalping Trading Strategy optimization using CandleStick Wick length pattern to confirm price momentum along with 3 moving exponential averages to ...
 

Simple EMA Scalping Trading Strategy Backtest In Python (Part 1)


Simple EMA Scalping Trading Strategy Backtest In Python (Part 1)

Today, we are embarking on a journey to test scalping strategies. I know many of you have been requesting this lately, and I must admit, I usually avoid low time frames and scalping because I find it to be a risky approach and often emotionally draining.

However, when it comes to algorithmic methods, things might be easier. With algorithms, we can test our strategy and have a clear understanding of the expected outcomes. So, hopefully, there will be no unpleasant surprises since our model is already backtested. As usual, the Python code is available for download from the link in the video description if you're interested in the coding part. If not, you can simply enjoy the video and see what kind of results our strategy might yield.

To start, I've chosen something relatively simple: we will be using three exponential moving averages. One is fast, another is medium, and the third one is slow. We will use these moving averages to detect trends. When these moving averages are aligned in a specific order (fast above medium above slow moving average), we have an uptrend. Conversely, the opposite order indicates a downtrend.

To ensure the accuracy of the trends, I've also added one more condition. The slopes of these curves should be pointing in the same direction. In an uptrend, the three curves should have positive slopes, and in a downtrend, the slopes should be negative.

Once we have a clear trend signal, we will look for our entry point. For example, if we are looking for a buying position, we will wait for a candle that opens below the fast moving average and closes above it. This candle indicates the continuation of the uptrend and serves as our entry point.

The interesting aspect here is that we can code all of this in Python and backtest the strategy. Initially, we won't focus much on optimization since I want to keep this video concise. However, in a future video, we will attempt to optimize the parameters and see if we can achieve a winning combination in our trades.

Now, let's dive into the Python code and examine the backtesting results. We'll be using the Euro/USD currency pair with 15-minute candlesticks from 2019 to 2022. The data frame consists of 105,000 rows, with each row representing a 15-minute candle. We clean the data frame by removing rows with a volume of zero, which corresponds to weekends and days off when there are no market movements.

Next, we import the pandas_ta (Pandas Technical Analysis) module and compute the three different moving averages: EMA 50, EMA 100, and EMA 150. We also calculate the slopes of these moving averages using a rolling window of 10 candles.

At this stage, our data frame includes the open, high, low, and close prices, volume, three moving averages, and their corresponding slopes. We can now check the conditions for trend detection. If the fast moving average is below the medium moving average, and the medium moving average is below the slow moving average, and all three slopes are negative, it indicates a downtrend. Conversely, if the fast moving average is above the medium moving average, the medium moving average is above the slow moving average, and all three slopes are positive, it signals an uptrend. These conditions are added as columns in our data frame.

To visualize the signals on our charts, we define a function that plots points above or below the candlesticks based on the total signal. The total signal represents the entry points, with 1 indicating a selling signal and 2 indicating a buying signal. The points positions are added as a column in the data frame.

We plot the signals and candlesticks for a specific range of candles.

We plot the signals and candlesticks for a specific range of candles, allowing us to visually analyze the strategy's performance. The green circles indicate buying signals, while the red circles indicate selling signals. This visual representation helps us understand how the strategy would have performed in real-time.

After visualizing the signals, we calculate the strategy's performance. We start with a capital of $10,000 and iterate through each candle. If we receive a buying signal, we enter a long position with a fixed size. If we receive a selling signal, we exit the long position and calculate the profit/loss based on the change in price since the entry. We track the cumulative profit/loss and the number of trades executed.

At the end of the backtesting period, we calculate the total profit/loss, the number of winning trades, the number of losing trades, the winning percentage, and the average profit/loss per trade.

In the video, I present the backtesting results for the given strategy. Please keep in mind that the results are specific to the chosen time frame and currency pair. The strategy may perform differently in other market conditions or with different parameters.

To summarize the results, the backtesting shows that the strategy performed relatively well, generating a positive return over the backtesting period. However, it's important to note that past performance is not indicative of future results, and additional testing and optimization may be required.

Simple EMA Scalping Trading Strategy Backtest In Python (Part 1)
Simple EMA Scalping Trading Strategy Backtest In Python (Part 1)
  • 2022.02.24
  • www.youtube.com
Simple scalping Trading strategy using 3 exponential moving averages backtested in python, the scalping strategy is explained and the python code also in Jup...
 

Simple EMA Scalping Trading Strategy Backtest In Python (Part 2 Optimization)



Simple EMA Scalping Trading Strategy Backtest In Python (Part 2 Optimization)

Hi there! Welcome back to this video, which is a continuation of our previous video. In this video, we aim to optimize the sculpting strategy that was introduced earlier. To briefly recap, we will focus on optimizing the parameter called 'back rolling n,' which determines the number of candles to consider when calculating the slopes of the moving averages. By varying the number of candles, such as 20, 10, or 5, we can calculate the average slope for these moving averages. Additionally, we will explore the possibility of adding conditions on the moving average slopes, such as testing for slopes less than a specific threshold, like -10 to -4. By experimenting with these parameters, we aim to create a better filter for identifying trends.

Furthermore, we will explore different trade management approaches, including fixed stop loss and take profit values, trailing stop loss, and ATR (Average True Range) related stop loss and take profit. By examining these different approaches, we hope to determine which trade management strategy yields the most favorable results.

It's important to note that this sculpting system is not designed for fast trading styles, as we are working with a 15-minute timeframe. However, the same system can be tested on lower timeframes, although it may be more challenging due to increased market noise.

Before we dive into the code, it's recommended that you watch the previous video where we explained the strategy in detail. This will provide you with a better understanding of the optimization process we're about to present.

Now, let's move on to our Jupyter Notebook file. We start by creating a data frame and cleaning the data. Next, we compute three different moving averages and calculate the slopes of these moving averages. This is where we begin testing our strategy.

Initially, we consider a rolling window of 10 candles, which means we average the slope for the fast, medium, and slow moving averages using the data from these 10 candles. We execute this code to ensure everything is functioning correctly, including the signals we introduced in the previous video.

To facilitate testing, we establish a time scale by considering that four candles represent one hour, given that we're working with 15-minute candles. With this setup, we can select a specific slice of our data frame to test our strategy. For example, we can choose a three-month period by specifying the starting index as 37,000 and selecting the corresponding length.

After loading the data for the selected period, we can execute our backtest. Our initial lot size is set to 30% of our equity, and we consider a stop loss of 40 pips and a take profit of 45 pips. We also apply a margin of 1 over 100, reflecting a leveraged account with a cash balance of 100 as the starting point.

Running the backtest, we observe a return of 107% for the three-month period. However, to ensure the robustness of our model, it's crucial to test the strategy on different time slices. By changing the starting index, we can select various periods and evaluate the performance. For instance, we try a different starting index of 47 and execute the backtest, yielding a return of 30%.

We can repeat this process with different starting indices to analyze the strategy's performance across multiple periods. However, to test for longer periods, we must select a smaller portion of our data frame. For instance, we can choose a 10-month or 12-month slice to assess the annual performance.

Testing the strategy over a full year, we achieve a return of 100%, effectively doubling the initial amount. While this is positive, the frequency of trades is relatively low, with only 193 trades during the year. The win rate is around 44%, indicating room for improvement.

To enhance our strategy, we will explore different values for the "back rolling n" parameter. By testing different numbers of candles, such as 20, 10, or 5, we can assess their impact on the performance of our strategy. For instance, we can modify our code to set the "back rolling n" value to 20 and rerun the backtest.

Upon testing with a "back rolling n" of 20, we observe a return of 90% for the three-month period, slightly lower than our initial setting of 10. This suggests that a smaller "back rolling n" may be more effective in capturing shorter-term trends.

Next, we introduce additional conditions based on the slopes of the moving averages. For example, we can implement a requirement that the slopes of all three moving averages must be less than -4. This means that we only enter a trade if all three slopes are negative and below -4. We modify our code accordingly and execute the backtest.

By implementing the additional conditions, we can further refine our strategy. Upon testing, we observe a return of 127% for the three-month period, indicating an improvement compared to our initial results. However, it's important to note that these conditions may also reduce the frequency of trades, as they provide a more stringent filter.

Now let's explore different trade management approaches. We start by implementing a fixed stop loss and take profit strategy, where we set predetermined values for both parameters. For instance, we can set a fixed stop loss of 40 pips and a take profit of 45 pips. After modifying the code and running the backtest, we analyze the results.

With the fixed stop loss and take profit approach, we observe a return of 95% for the three-month period. While this is slightly lower than our initial results, it provides a controlled risk management system. However, it's important to assess the performance over longer periods and different market conditions to evaluate its effectiveness.

Next, we explore a trailing stop loss strategy. Instead of using fixed values, the stop loss dynamically adjusts as the trade progresses in our favor. For instance, we can set a trailing stop loss of 30 pips, which means that if the price moves in our favor by 30 pips, the stop loss is moved to breakeven. We modify our code accordingly and rerun the backtest.

With the trailing stop loss approach, we achieve a return of 120% for the three-month period. This demonstrates the potential of dynamically adjusting the stop loss to protect profits and maximize gains. However, it's essential to evaluate its performance over different timeframes and market conditions to ensure its robustness.

Finally, we explore a trade management strategy based on the Average True Range (ATR). The ATR provides a measure of market volatility, which can be utilized to set stop loss and take profit levels. By incorporating the ATR into our strategy, we can adapt our risk management to prevailing market conditions. We modify our code to implement the ATR-based stop loss and take profit levels and execute the backtest.

By incorporating the ATR-based stop loss and take profit levels, we achieve a return of 110% for the three-month period. This indicates the potential effectiveness of adapting our risk management to market volatility.

In conclusion, through the optimization process, we explored different parameters and trade management approaches to improve our sculpting strategy. By varying the "back rolling n" parameter, implementing additional conditions based on moving average slopes, and exploring different trade management techniques, we were able to enhance the performance of the strategy. However, it's important to conduct further testing on different timeframes, market conditions, and evaluate the strategy's robustness before applying it in live trading.

Simple EMA Scalping Trading Strategy Backtest In Python (Part 2 Optimization)
Simple EMA Scalping Trading Strategy Backtest In Python (Part 2 Optimization)
  • 2022.03.03
  • www.youtube.com
This is a continuation of the previous video, here we optimize our simple EMA Scalping trading strategy and we try to backtest the different parameters sets ...
 

High Return Trading Strategy Using Leverage Effect



High Return Trading Strategy Using Leverage Effect

Hello everyone, and welcome back to my channel. Today, we're going to delve into a topic we haven't covered before—leverage. I must admit that I have been quite skeptical about it due to the inherent risks involved. However, I want to emphasize that these videos are primarily for educational purposes. I am not recommending that you blindly adopt a leveraged trading system without fully understanding its implications. So, in this video, we will take a previously used trading strategy that we have already discussed in previous videos and explore the effects of incorporating leverage into our trading system.

Let's begin with a brief introduction to how leverage works. Typically, leverage is represented by a ratio, such as 1:10 up to 1:1000, although it is more common to find ratios between 1:10 and 1:50. This means that if you have an account with $1,000, you would be allowed to buy or sell positions with a value as high as $10,000 if you choose a 1:10 leverage ratio. By increasing the leverage ratio, let's say to 1:50, the same $1,000 in your account would enable you to make purchases with a value of up to $50,000. The specific leverage options available to you depend on your broker, the country in which it operates, regulations, and other factors related to your account type.

However, it's important to note that leverage is not without its costs. While it can amplify your potential profits, it also magnifies the risks and can quickly deplete your account balance. Beginners are often targeted by larger traders or brokers who take advantage of their lack of experience. It is crucial to keep this in mind.

There are two key rules to bear in mind when using leverage. First, leveraging can help magnify profits if your strategy has a high winning rate. Conversely, it will also magnify your losses if your strategy has a low winning rate. The definition of a high or low winning rate depends on various factors such as the strategy type, the stop loss and take profit values, and your money management approach. Always remember that leveraging comes with a price. If you can buy or sell positions with 100 times the amount of money you own, it means that your funds are primarily there to cover potential losses, which can occur rapidly when trading with significantly larger amounts.

In this video, we will utilize Python to backtest the strategy we previously discussed. We will start by checking the returns using a normal trading account and then introduce a leveraged account into our algorithmic trading strategy. We will backtest these variations, examine the results, and assess the advantages and risks associated with using a leveraged account. The advantage of using Python is that we can modify any parameter as desired and observe the effects on our return percentage. This computational power allows us to test and gain insights into the advantages and disadvantages of using a leveraged account.

The Python code we will use is similar to the code used in the previous video on the martingale approach in trading. The initial cell involves loading and cleaning the data, resetting the index, and performing other necessary steps. I won't spend much time on the code today, as we have covered it in previous videos. We will utilize support and resistance functions, along with candlestick pattern recognition, to detect trend reversals and generate trading signals. For this strategy, we will focus on rejection candlestick patterns occurring near support or resistance levels as potential trend reversal signals.

High Return Trading Strategy Using Leverage Effect
High Return Trading Strategy Using Leverage Effect
  • 2022.02.17
  • www.youtube.com
Here we Backtest an Algorithmic Trading Strategy using Python on a Leverage Account. The leverage can be a variable depending on the strategy you are intend...
 

Martingale Swing Trading Strategy Algorithmic Backtest In Python



Martingale Swing Trading Strategy Algorithmic Backtest In Python

Today, we're going to delve into the fascinating topic of the martingale approach when combined with a winning trading strategy. If you haven't already watched our previous video on the martingale method or other videos on this channel that describe the strategy we'll be using, I highly recommend checking them out first. These videos cover support and resistance levels, candle patterns, and provide a solid foundation for understanding our approach in this video. I'll include some links in the video description for your convenience.

Additionally, for those who are interested, you can download the Python code I'm using to backtest this strategy from the link provided in the description. This code will allow you to follow along and explore the results for yourself.

Now, let's do a quick recap for those who are new to our channel or just joining us. The martingale method involves doubling our position size every time we close a losing trade. The idea behind this approach is to recover previous losses with one big win. In a previous video, we explained and applied the martingale method to a completely random trading strategy that randomly chooses between buying and selling positions.

In this video, we're taking a different approach. We will be applying the martingale method to a winning trading strategy. Our strategy involves identifying support and resistance levels, as well as specific candle patterns that indicate potential trend reversals. When we detect a candle pattern near a support or resistance level, we execute our trade accordingly. The stop-loss and take-profit values are determined based on a ratio called the take-profit/stop-loss ratio.

Now, it's important to note that the results of this strategy were already tested in previous videos and have shown positive returns. The objective here is to see if we can further increase the profits by adding the martingale approach to this strategy.

Okay, let's dive into the Python code. First, we load and clean the EUR/USD daily data from 2003 to 2021 for this video. We then check if the data frame is loaded correctly by printing the tail of the data frame.

Next, we have the functions for detecting support and resistance levels, which we'll use in our program. If you need a detailed explanation of these functions, please refer to our previous videos.

We also have other functions called "is_engulfing," "is_star," and "close_to_resistance" or "close_to_support" levels. These functions help us identify specific candlestick patterns and determine if they are close to support or resistance levels. These patterns will be used to generate our trading signals.

In the signal generation cell, we generate our signals based on the candle patterns we detect. If we find a bearish engulfing pattern or any other selling signal near a resistance level, we consider it a selling signal and assign a value of 1 to the signal column in our data frame. Similarly, if we find a bullish engulfing pattern or any other buying signal near a support level, we consider it a buying signal and assign a value of 2 to the signal column. In all other cases, the signal value is 0, indicating no signal.

Now, we can include the backtesting.py package to backtest our strategy. We define a function called "signal" that returns the signal values for each row in our data frame. This function is used inside our custom class called "CandleStrategy," which inherits from the strategy class of the backtesting.py module.

In our CandleStrategy class, we initialize the size of our trading position to 0.05, which represents 5% of the equity we hold. We trade with this position size every time we receive a signal.

If the signal value is 1 (selling signal), we check if we have any open positions. If we do, we close the existing position and set the position size to zero. Then, we enter a new short position with the position size defined earlier.

On the other hand, if the signal value is 2 (buying signal), we follow a similar process. We check if we have any open positions, close them if necessary, and enter a new long position with the predefined position size.

Now, we define our take-profit and stop-loss levels. The take-profit level is calculated by multiplying the entry price by the take-profit/stop-loss ratio. The stop-loss level is calculated by multiplying the entry price by the negative value of the take-profit/stop-loss ratio. These values ensure that our take-profit level is further from the entry price than the stop-loss level.

Finally, we execute our backtest using the CandleStrategy class and print the results. We calculate various performance metrics such as total return, average daily return, maximum drawdown, and the number of trades executed.

Now, let's run the backtest and analyze the results.

After running the backtest, we can observe the results. The total return, average daily return, and maximum drawdown are important metrics to evaluate the performance of our strategy.

In our case, the total return is 256.17%, which means that our initial investment has increased more than two-fold. The average daily return is 0.04%, indicating a consistent positive return over the backtested period. The maximum drawdown is 10.98%, which represents the largest drop in the equity curve from a peak to a subsequent low point.

These results indicate that our winning trading strategy, combined with the martingale approach, has been profitable over the tested period. However, it's important to note that past performance is not indicative of future results, and this strategy should be thoroughly evaluated and validated before using it in live trading.

In conclusion, the martingale approach, when combined with a winning trading strategy, can potentially enhance the overall profitability of the strategy. However, it's essential to carefully consider the risks involved, such as the potential for large drawdowns and the need for sufficient capital to sustain multiple doubling of position sizes.

Thank you for joining me in this video, and I hope you found it informative and useful. If you have any questions or suggestions, please leave them in the comments below. Don't forget to like and subscribe to our channel for more trading strategies and tutorials. Happy trading!

Martingale Swing Trading Strategy Algorithmic Backtest In Python
Martingale Swing Trading Strategy Algorithmic Backtest In Python
  • 2022.02.10
  • www.youtube.com
Python algorithmic strategy used for backtesting the Martingale Swing Trading Strategy, a winning indicator that was presented in previous videos. Martingale...
 

Martingale Trading Strategy Backtesting For Algorithmic Trading



Martingale Trading Strategy Backtesting For Algorithmic Trading

Today, we're going to discuss the Martingale approach, which can be incorporated into any trading strategy to compensate for losing trades. We will backtest this method using Python and delve into the advantages and risks involved when implementing Martingale.

Let's imagine entering a casino with twenty dollars in our pocket and deciding to play roulette, only betting on colors. We'll wager one dollar on either red or black. If our first bet on red loses, we'll be left with 19 dollars. In the next round, we'll double our bet to two dollars since we had a losing bet previously. If this bet also loses, we'll be left with 17 dollars. We continue doubling our bet each time we lose, aiming to compensate for the previous losses. Eventually, we will have a winning bet that covers the previous losses and adds a small profit. In this example, we end up with a total of 21 dollars, slightly more than our initial amount. This approach, doubling the bet after a loss, is known as the Martingale approach.

Initially, the Martingale method seems promising and can give the impression of quick and substantial profits. However, it's essential to understand the risks associated with this approach. To better understand this method and its risks, we will backtest the strategy using a Monte Carlo approach. This approach uses random numbers to generate signals for buying or selling positions, completely disregarding technical indicators or custom predictions. The signals are based solely on a uniform random distribution.

To implement the backtest, we'll write Python code. We start by importing the necessary libraries, such as pandas for data manipulation. We load and clean the data, removing rows with zero trading volumes. After preparing the data, we generate the random signals using the numpy module's random function. For each candlestick, we generate a random number between 0 and 1. If the number is below 0.5, we assign a selling signal (1), and if it's above 0.5, we assign a buying signal (2).

Next, we define a strategy class called "MyStrategy" that inherits from the backtesting library's strategy class. The initial position size is set to 10 units. We also define a variable, "my_size," to keep track of the position size, which will change based on the Martingale approach. If a positive signal is generated and there are no open trades, we open a new trade with a position size equal to "my_size" multiplied by 2, following the Martingale approach. If there are closed trades and the last trade was profitable, we reset the position size to the initial size. This ensures that after a winning trade, we go back to the initial position size. If a buying or selling signal is generated, and there are no open trades, we set the stop loss and take profit levels relative to the last closing price and execute the corresponding trade.

With the strategy defined, we run the backtest using an initial capital of $10,000 and no commissions. The backtest statistics show a return of -4.8%, indicating a loss. The equity plot reveals that the strategy initially had some gains but started declining at a certain point. The win rate is close to 50%, as expected since the signals are random. The total number of trades is 100.

To investigate further, we modify the stop loss and take profit levels to 400 pips and rerun the backtest. However, this adjustment does not solve the problem. The declining equity is a result of not having sufficient funds to continue doubling the position size after a series of losing trades. To address this, we decrease the initial position size to 5 and set the stop loss and take profit levels to 300 pips. After making these adjustments, we rerun the backtest. The updated strategy yields a return of -0.7%, indicating a smaller loss compared to the previous version. However, the equity plot still shows a declining trend, although at a slower pace. The win rate remains close to 50%, and the total number of trades is still 100.

From these results, we can observe that even with adjustments to the position size, stop loss, and take profit levels, the Martingale approach does not provide a profitable outcome in this random signal scenario. The declining equity indicates the potential risk of significant drawdowns and the possibility of depleting the trading account.

It's important to note that this backtest was conducted under the assumption of random signals. In real-world trading, strategies based on technical analysis or fundamental analysis are usually employed to generate trading signals. These strategies aim to identify patterns, trends, or opportunities based on market data, rather than relying on random signals. In such cases, the Martingale approach may not be suitable or effective.

Furthermore, the Martingale approach carries a high level of risk. It assumes that losing streaks will be followed by winning streaks, allowing the trader to recover losses. However, in reality, there is no guarantee that winning trades will follow losing trades, and there is always a possibility of consecutive losses. Doubling the position size after each loss can quickly lead to significant losses and account depletion, especially if the market conditions are unfavorable or volatile.

While the Martingale approach may seem appealing due to its potential for quick recovery and profits, it's crucial to consider the associated risks and carefully evaluate its suitability for your trading strategy. Implementing risk management techniques, such as setting strict stop loss levels, maintaining proper position sizing, and diversifying your trading approach, can help mitigate the risks involved.

In summary, the Martingale approach can be a risky strategy, particularly when used with random signals. It's important to thoroughly test and evaluate any trading strategy, considering both the potential gains and the associated risks.

Martingale Trading Strategy Backtesting For Algorithmic Trading
Martingale Trading Strategy Backtesting For Algorithmic Trading
  • 2022.02.03
  • www.youtube.com
Testing the Martingale trading strategy for algorithmic trading in python, I hope you'll enjoy it.Are you interested in algorithmic trading and looking for a...
 

Moving Average Trading Strategy Backtesting In Python



Moving Average Trading Strategy Backtesting In Python

It's often the case that simple strategies are overlooked in favor of more complex models. However, we shouldn't underestimate the power of simplicity. Today, I will present to you a straightforward method that can compete with complex trading systems and yield positive returns. The advantage of simple rules is that they can be easily automated for algorithmic trading using Python. We can backtest this strategy on different currencies to ensure its profitability.

Let's dive into the details of this simple strategy. First, we'll consider the 200-day moving average curve as our indicator. If the candles are above the curve, it indicates an uptrend and suggests a buying position. Conversely, if the candlesticks are below the moving average curve, it signals a downtrend and implies a selling position.

To determine the entry point for a buying position, we'll examine the preceding candles. We'll compare the lowest value of the current candle to the lowest values of the preceding candles. If the low value of the current candle is below all these preceding values, we've identified the entry point for a buying position. The same concept applies in the opposite direction for a selling position.

While this strategy may appear simple, it does come with its own set of challenges. The first parameter to consider is the length of the moving average. Should it be 200, 100, or something different? This can be fine-tuned through backtesting on a specific currency pair to maximize returns. Another parameter is the number of preceding candles to consider. Should we analyze 7, 8, 10, or 20 candles? By experimenting with different values, we can assess the impact on strategy performance.

This indicator part is relatively straightforward, but to make the strategy effective, we need to combine it with a trade management approach. This involves defining the stop-loss and take-profit values. We have two options for setting these values: they can be related to the average true range (ATR) of the market, or we can use fixed values for all trades. It's important to choose the appropriate trade management approach to ensure positive returns. Additionally, a trailing stop loss can be employed, which adjusts the stop-loss value based on the ATR.

In the code, we can experiment with various combinations of these parameters to find the optimal settings and evaluate the strategy's performance. Despite being a simple strategy, there are a relatively large number of parameters to consider.

To implement this strategy in Python, we use a Jupyter Notebook file. We load the data, apply the exponential moving average (EMA) and ATR calculations using the pandas-technical-analysis module. Then, we define functions for generating EMA signals and high-low signals. We plot the data with the EMA curve to visually verify that everything is working correctly.

Next, we apply the EMA signal and high-low signal functions to our data frame, resulting in signals for buying or selling positions. By examining the plotted signals, we can validate their accuracy and effectiveness in identifying trends and entry points.

To test the strategy, we define a function that uses the signals to determine buying or selling positions and sets the stop-loss and take-profit values based on the ATR or fixed ratios. Backtesting this strategy on the Euro-US Dollar four-hour charts between 2003 and 2021 shows a positive return of around 29%.

However, it's crucial to assess the equity curve and understand that while the strategy may perform well in trending markets, it may struggle during periods of horizontal price movements. By experimenting with different stop-loss and take-profit configurations, such as using fixed values instead of ATR-based values, we can analyze the strategy's performance and adapt accordingly.

In conclusion, even the simplest strategies require careful consideration of parameters and trade management approaches to ensure their effectiveness. While this strategy relies on a basic indicator like the moving average, it can still generate profitable trading signals when combined with appropriate trade management techniques.

Once we have implemented the strategy and conducted backtesting, it's essential to evaluate its performance metrics. Some key metrics to consider are the total number of trades, the win rate (percentage of profitable trades), the average profit per trade, the maximum drawdown (the largest peak-to-trough decline), and the risk-reward ratio.

By analyzing these metrics, we can determine if the strategy meets our expectations and aligns with our risk tolerance. It's important to remember that no strategy is foolproof, and there will always be risks involved in trading. Therefore, proper risk management and diversification of investments are crucial for long-term success.

Additionally, it's recommended to perform robustness testing on the strategy. This involves assessing its performance under different market conditions, such as different time periods, currency pairs, or asset classes. By doing so, we can gauge the strategy's adaptability and ensure that its profitability is not limited to specific scenarios.

Furthermore, it's worth considering the limitations of this simple strategy. It may not capture all market nuances or perform optimally during periods of high volatility or sudden price fluctuations. In such cases, more sophisticated trading systems or additional indicators may be necessary to enhance its performance.

As a final note, it's essential to continuously monitor and adapt the strategy as market conditions evolve. Regularly reviewing its performance, making necessary adjustments, and staying informed about market trends and news will contribute to the strategy's long-term viability.

Remember, successful trading is a result of a well-defined strategy, disciplined execution, and continuous learning and adaptation. Best of luck with your trading endeavors!

Moving Average Trading Strategy Backtesting In Python
Moving Average Trading Strategy Backtesting In Python
  • 2022.01.20
  • www.youtube.com
Welcome to this video on a beginner-friendly automated trading strategy using Python. In this video, we will be discussing a simple yet effective trading str...
 

Trailing Stop Backtest For Algorithmic Trading in Python



Trailing Stop Backtest For Algorithmic Trading in Python

Hello everyone and welcome to this video. Today, we will be exploring various methods of implementing stop-loss in algorithmic trading. Specifically, we will focus on stop-loss techniques that can be easily incorporated into trading bots by coding them in numerical programs.

It's important to note that while there are different ways to determine stop-loss values, some methods are more complex to include in a program. In this video, we will backtest a strategy using support and resistance levels, as well as candlestick patterns that we have previously discussed in other videos. However, we will vary the stop-loss values by considering four different cases.

The first method involves using a constant stop-loss distance, which is predetermined by the trader for all trades. Regardless of the buying position, the stop-loss distance remains the same.

The second method is more dynamic and utilizes the average true range (ATR). Here, the stop-loss distance is directly related to the ATR, meaning it varies depending on the market's volatility at a specific position.

The third method is a fixed distance trailing stop-loss. This is a commonly used trailing stop-loss strategy, where the same distance is maintained for all positions, acting as a trailing stop-loss.

The fourth and final method is a trailing stop-loss that considers the average true range at the moment the trading position is executed. This means the stop-loss distance is chosen based on the ATR, which reflects the market's volatility at that precise moment.

In summary, we will test the same strategy using these four different methods of defining stop-loss values. It's worth noting that the choice of stop-loss values will also impact our take-profit values. Most of the time, the take-profit values will be determined based on the ratio between the take-profit distance and the stop-loss distance.

Now, let's dive into the Jupyter Notebook file to see how these methods are implemented. The file begins by importing the necessary modules and loading the CSV file containing the price data for the EUR/USD currency pair from 2003 to 2021. We clean the data, add the average true range (ATR) column, and define functions for support and resistance levels, as well as candlestick patterns.

We also introduce functions to check for engulfing patterns, as well as proximity to support and resistance levels. These functions help us build the strategy based on candlestick patterns close to support or resistance levels. We add a signal column to our data frame, which categorizes the signals as bearish, bullish, or no signal.

To backtest our strategy, we utilize the backtesting module and define the first stop-loss method, which involves a fixed stop-loss and take-profit distance set manually by the trader. We start with a cash amount of $10,000 and obtain the results of the backtest, including returns, winning rate, best and worst trades, and maximum drawdown.

Next, we implement the second method, which utilizes the ATR to define the stop-loss and take-profit distances. We introduce factors to adjust the distances based on the ATR values and backtest the strategy. We compare the results with the previous method and observe the differences in returns and other performance metrics.

Moving on, we implement the third method, which is a trailing stop-loss with a fixed distance. Here, we only need to specify the initial stop-loss distance, and the trailing stop-loss adjusts accordingly. We backtest the strategy using a fixed distance of 500 pips for the EUR/USD pair.

Finally, we analyze the results and find that the trailing stop-loss method with a fixed distance yields the highest return of approximately 131%. While the other methods also provide favorable returns, the trailing stop-loss method shows better performance in this case.

In conclusion, we have tested the same strategy using four different stop-loss methods, each offering different advantages and considerations. The choice of stop-loss method ultimately depends on the trader's preferences and the specific market conditions.

The constant stop-loss method provides simplicity and ease of implementation. It allows for consistent risk management across all trades, regardless of market conditions. However, it may not effectively adapt to changing volatility levels, potentially leading to wider stop-loss distances during highly volatile periods or tighter stop-loss distances during low volatility periods.

The ATR-based stop-loss method addresses the issue of adapting to market volatility. By using the ATR as a measure of volatility, the stop-loss distance dynamically adjusts to current market conditions. This can help protect against larger losses during high volatility and provide more breathing room during low volatility. However, it may result in wider stop-loss distances during periods of high volatility, potentially leading to more frequent stop-outs.

The fixed distance trailing stop-loss method combines the advantages of a trailing stop-loss with the simplicity of a fixed distance. It allows for potential profit maximization by trailing the stop-loss behind the price as it moves in favor of the trade. This method is especially useful in trending markets, where it can capture larger gains. However, it may not effectively protect against rapid price reversals, as the fixed distance may not provide enough buffer in highly volatile situations.

The ATR-based trailing stop-loss method combines the benefits of the ATR-based method and trailing stop-loss. By considering the ATR at the time of trade entry, it adjusts the trailing stop-loss distance based on the market's volatility at that moment. This provides a more adaptive and responsive approach to risk management. It can help capture larger trends while still providing protection against sudden reversals. However, it may result in wider stop-loss distances during high volatility, potentially leading to more frequent stop-outs.

It's important for traders to carefully consider their risk tolerance, trading style, and market conditions when selecting a stop-loss method. Backtesting and analyzing the performance of different methods can help in making an informed decision. Additionally, risk management should not solely rely on stop-loss orders but also consider position sizing, diversification, and overall portfolio management.

Remember that no stop-loss method is foolproof, and losses can still occur. Proper risk management and continuously monitoring market conditions are essential to successful trading.

Trailing Stop Backtest For Algorithmic Trading in Python
Trailing Stop Backtest For Algorithmic Trading in Python
  • 2021.11.27
  • www.youtube.com
This video tests the Stop Loss VS Trailing Stop methods for Algorithmic Trading using python. Backtests are applied to one trading strategy showing the diffe...
 

RSI Divergence Automated In Python | Algorithmic Trading



RSI Divergence Automated In Python | Algorithmic Trading

Hello everyone and welcome aboard this video. Today, we are going to discuss the RSI divergence and explore different strategies using this indicator in trading. Before we dive in, I have provided a download link in the description where you can access the Jupyter Notebook file used in this video.

To begin, we need to write a code that can detect the local minima and maxima of both the price and the RSI. These points are marked as purple dots on the graph. The algorithm used here identifies a high of a candle as a maximum if it is higher than the five neighboring candles on each side. Similarly, a low value of a candle is considered a minimum if it is lower than the five candles on the left and right sides. You can adjust these numbers based on your preference for detecting extreme points.

Next, we fit the detected minima and maxima of the price and RSI into linear slopes. This involves finding the best-fitting straight lines that pass through these points. We end up with two different slopes: one for the price (green) and one for the RSI (purple). These slopes represent the trend direction of the respective indicators.

We can then compare the slopes of the price and the RSI to determine if there is a divergence. In an uptrend, both slopes should be positive, indicating higher lows in the price and higher highs in the RSI. Conversely, in a downtrend, both slopes should be negative. If the slopes have different signs, such as a positive slope for the price and a negative slope for the RSI, or vice versa, it indicates a divergence.

While there are various approaches to analyzing divergence, we will explore two methods in this video. The first method involves fitting multiple extreme points using polynomial regression, allowing us to consider more than two points at once. The second method focuses on comparing the last two minima and maxima of the price and the RSI. By comparing the differences between these points, we can identify divergences.

Although strategies using the RSI divergence are often discussed in manual trading, they usually focus on the trend between two consecutive points. In this video, we introduce a numerical approach, utilizing slope fitting and polynomial regression to enable the analysis of multiple points simultaneously.

Throughout the video, we will code these divergence methods in Python using Jupyter Notebook. The provided Notebook file imports the necessary libraries, reads the candle data from a CSV file, calculates the RSI, and defines functions to detect pivot points for both the price and the RSI. These functions categorize each candle as a pivot high, pivot low, both, or neither.

By the end of the video, you will have a clear understanding of the RSI divergence and how to implement these strategies in your trading. If you find this content helpful, I encourage you to support the channel by liking the video. Your feedback is valuable to us, so please feel free to leave comments.

Now, let's dive into the Jupyter Notebook file and see how we can code these concepts in Python.

Continuing from where we left off, we have added the "pivot" column to our data frame, which categorizes each candle as a pivot high, pivot low, both, or neither. Now let's move on to the next step in our code.

Next, we define a function called "get_slope" that calculates the slope between two points given their x and y coordinates. This function will be used to calculate the slopes for the price and RSI data.

After that, we define another function called "fit_slope" that takes in a data frame and a pivot category (pivot high or pivot low) as parameters. This function identifies the pivot points based on the given category and fits a linear slope to those points using the "get_slope" function. It returns the slope value for the fitted line.

Now we can proceed to use these functions to calculate the slopes for the price and RSI data. We create two new columns in our data frame: "price_slope" and "rsi_slope." For the "price_slope" column, we call the "fit_slope" function with the data frame and the pivot category as parameters. We repeat the same process for the RSI data, calculating the slope for the RSI pivot points and storing the result in the "rsi_slope" column.

At this point, we have obtained the slopes for both the price and RSI data. Now we can compare these slopes to determine the trend direction. We add another column called "trend" to our data frame, which will indicate whether the trend is upward, downward, or undefined.

To determine the trend, we check the signs of the price_slope and rsi_slope columns. If both slopes are positive, it indicates an uptrend, so we assign the value "Up" to the trend column. If both slopes are negative, it indicates a downtrend, so we assign the value "Down" to the trend column. In all other cases, where the signs of the slopes are different or one of the slopes is zero, we assign the value "Undefined" to the trend column.

With the trend information available, we can now check for divergences between the price and RSI data. We add another column called "divergence" to our data frame, which will indicate whether a divergence is present or not.

To check for divergences, we compare the signs of the price_slope and rsi_slope columns. If the signs are opposite, it indicates a divergence. In such cases, we assign the value "Divergence" to the divergence column. If the signs are the same or one of the slopes is zero, there is no divergence, and we assign the value "No Divergence" to the divergence column.

Finally, we can print the resulting data frame to see the calculated slopes, trend directions, and divergences for each candle.

Overall, the code performs the following steps:

  1. Imports necessary libraries and defines helper functions.
  2. Reads the candle data and calculates the RSI.
  3. Adds a pivot column to categorize each candle as a pivot high, pivot low, both, or neither.
  4. Calculates the slopes for the price and RSI data based on the pivot points.
  5. Determines the trend direction based on the signs of the slopes.
  6. Checks for divergences between the price and RSI data based on the signs of the slopes.
  7. Prints the resulting data frame with the calculated slopes, trend directions, and divergences.

This code provides a way to analyze RSI divergences and their relationship to price trends, allowing traders to potentially identify trading opportunities.

RSI Divergence Automated In Python | Algorithmic Trading
RSI Divergence Automated In Python | Algorithmic Trading
  • 2021.11.12
  • www.youtube.com
The RSI Divergence Detection is programmed in python as an automated indicator for algorithmic trading, the Jupyter notebook file is available from the link:...
 

Price Trend Channels Automated In Python



Price Trend Channels Automated In Python

Hello everyone, thank you for joining us today for this video. We are excited to present an algorithm in Python that detects price movement channels. You can download the code as a Jupyter Notebook file from the link in the description below.

First of all, credit goes to Mr. or Mrs. M from the comment section for proposing this idea. We appreciate your patience as it has been more than a month of waiting. We hope this video won't disappoint you.

Before we begin, let's clarify the purpose of this channel. Our goal is to provide educational content, so we won't simply provide programs for you to download and use as a black box. Instead, we aim to explain the thinking process and how the program was built. By the end of this video, you should be able to build your own algorithm, inspired by the one presented here, and even add your own extensions.

However, it's important to acknowledge the limitations of numerical models when applied to dynamic and non-linear environments like the market. Price trends and predictions are still an open field of study, with ongoing research trying to find the best approaches. The market is highly dynamic, and trends and their speed of change can vary over time. So, please accept the limitations and complexities inherent in predicting price movements.

Now, let's dive into the algorithm. The algorithm we're presenting is based on simple information gathered through this channel and our imagination. The approach involves positioning ourselves at a specific candle or date and looking back in time for a certain number of candles.

We divide this time into equal parts or time windows. In each window, we identify the highest and lowest price points, known as maxima and minima. We repeat this process for all the time windows and fit the minima and maxima points into separate first-degree polynomial fits, which are straight lines.

However, these slopes don't necessarily wrap around the price because they go through the points. To address this, we need to improve the intercept values of these slopes. There are different ways to do this. One approach is to adjust the intercepts so that the curves pass through specific points, such as the minimum point closest to the middle of the time window or the highest and lowest points found within the window.

Another aspect to consider is the length of the time window. Depending on your preference, you can choose different values for the number of back candles. For example, you can take 30 bars behind the present candle plus or minus 20 bars, allowing the program to roam around within that range. The program will then evaluate different slopes and return the number of candles that provide the most parallel situation between the two slopes, indicating the detection of a channel.

We have provided a Jupyter Notebook file that you can download from the link in the video description. The file includes the Python code for implementing the algorithm. To begin, we import the pandas library and load the data from a CSV file containing Euro versus Dollar candlestick data from 2003 to 2021.

Next, we search for the maxima and minima within the time window defined by the number of back candles. We slice the window into smaller windows and find the maximum and minimum points within each window. These points are stored in numpy arrays.

After obtaining the minima and maxima, we use the numpy polyfit function to fit the points to first-degree polynomial lines. The results, which include the slopes and intercepts, are stored in variables.

To visualize the slopes, we plot the candlestick chart and add the lines corresponding to the slopes. At this stage, the slopes may not perfectly wrap around the price, but they provide a reasonable fit.

To improve the fit, we can modify the intercepts of the slopes. One approach is to adjust the intercepts so that they pass through the highest and lowest points within each time window. We calculate the highest and lowest points within the time window and update the intercepts of the slopes accordingly.

To determine the optimal channel, we iterate through different values of the number of back candles and evaluate the parallelism between the two slopes. We calculate the angle between the two slopes and check if it falls within a predefined threshold. If it does, we consider it a valid channel and store the number of back candles and the angle for further analysis.

Finally, we can visualize the detected channels by plotting the candlestick chart and overlaying the lines corresponding to the channels. This provides a visual representation of the identified price movement channels.

It's important to note that this algorithm is a simplified approach and may not capture all types of price movement channels. The market is complex, and there can be various patterns and dynamics that go beyond the scope of this algorithm. However, this algorithm serves as a starting point for detecting channels and can be extended or customized based on individual requirements and preferences.

We encourage you to download the Jupyter Notebook file and explore the code in detail. Experiment with different parameters, test it on different datasets, and see how it performs. Feel free to modify and enhance the algorithm to suit your needs and ideas.

We hope this video and the accompanying code provide you with insights and inspiration for developing your own channel detection algorithm. Remember, the key is to understand the underlying concepts and adapt them to your specific needs and market conditions.

Thank you for watching, and we look forward to your feedback and questions. Happy coding!

Price Trend Channels Automated In Python
Price Trend Channels Automated In Python
  • 2021.10.30
  • www.youtube.com
This video is about detecting price trend and price channels and how to automate this process in Python. The algorithm is presented and explained then the co...
Reason: