Python in algorithmic trading - page 18

 

Does this Crypto Scalping Indicator Actually Work!



Does this Crypto Scalping Indicator Actually Work!

Today, we are going to explore a sculpting strategy using the Volume Weighted Average Price (VWAP) in backtesting on the Bitcoin market. We will write a Python algorithm to implement this strategy and analyze the results.

First, let's set the context. The VWAP is a powerful tool for algorithmic trading as it provides dynamic support and resistance values. It remains independent of the time frame being used, making it advantageous for algorithmic trading since it reduces the number of parameters to optimize.

In this strategy, we will use a 15-minute time frame for Bitcoin-US Dollar trading prices. We will consider two indicators: the 100-day moving average (DMA) and the VWAP. By analyzing the price movements relative to these indicators, we can determine the market trend. When a certain number of candles trade below or above the 100 DMA, it indicates a downtrend or an uptrend, respectively. Similarly, if the candles are trading below or above the VWAP curve, it confirms the trend direction.

In an uptrend, we will only look for buying positions, while in a downtrend, we will focus on selling positions. The entry point for our positions will be triggered when the price is within a certain fixed distance to the VWAP curve.

To implement this strategy in Python, we will use the pandas_ta package to compute the VWAP and the 100 DMA. We will then create two new columns in our data frame: the EMA signal and the VWAP signal. The EMA signal will count the number of back candles that fall below or above the EMA curve to confirm a downtrend or an uptrend. Similarly, the VWAP signal will count the number of back candles that are below or above the VWAP curve.

We will merge these signals into a total signal column in our data frame, which will serve as the trigger for our buying and selling positions. For buying positions, we will check if the total signal is equal to 2 and there are no open trades. We will also verify if the price is close enough to the VWAP curve. Similarly, for selling positions, we will consider a total signal of 1 and check the distance of the price from the VWAP curve.

We can visualize the signals on a chart, plotting the candles along with the buying (purple) and selling (green) signals.

To backtest the strategy, we will calculate the Average True Range (ATR) as a measure of volatility. The stop loss distance will be set to 0.8 times the current ATR, and the take profit distance will be twice the stop loss distance. With these parameters, we can trigger buying and selling positions, taking into account the stop loss and take profit values. We will start with a cash amount of $100,000 and a leverage of 5.

Running the backtest, we can observe the results of our trading system. The algorithm shows a high return percentage, with an equity final of around $10 million after three years. In comparison, the buy and hold strategy only achieved a 248% return. However, it's important to note that the algorithm's performance fluctuates, and it might struggle during certain periods. This highlights the need for dynamic adaptation to changing market conditions.

To assess the stability of the equity, we can plot the equity curve over the years. The algorithm performed exceptionally well for two years but faced challenges in the last year. This underscores the passive nature of the algorithm, which relies on fixed parameters and may require adjustments to adapt to market changes.

The VWAP-based strategy showcased here is a good investment of attention and time. It has demonstrated significant returns over a long period, albeit with some limitations. Further optimizations and the inclusion of additional filters and indicators can be explored to enhance.

Does this Crypto Scalping Indicator Actually Work!
Does this Crypto Scalping Indicator Actually Work!
  • 2022.06.02
  • www.youtube.com
This video describes a trading strategy using VWAP for Crypto such as the Bitcoin. The strategy algorithm is tested in Python and the code details are explai...
 

How to Backtest A Stock Market Strategy Using Python On The S&P 500


How to Backtest A Stock Market Strategy Using Python On The S&P 500

Hello everyone, today we are going to conduct a detailed test of a simple sculpting strategy using historical data from the S&P 500. We will explain the basics of the strategy and write the code in Python for backtesting purposes. We have three years' worth of data, which should provide us with enough information to evaluate the strategy's performance and results.

As usual, the code for this strategy is available for download through the link in the description below. We will be using a 15-minute timeframe for this test, although you can experiment with different timeframes if desired. Lower timeframes can be more challenging to control due to increased noise and fluctuations.

The strategy revolves around identifying engulfing patterns, which can be either bearish or bullish signals. We will add two conditions to refine the signals. The first condition is the minimum engulfing height, which is the difference between the closing price of the previous candle and the opening price of the engulfing candle. We will set a minimum distance requirement for the engulfing candle's opening price to validate the signal. In other words, the opening price should be higher than the minimum engulfing height.

The second condition is the maximum candle tail length, which refers to the length of the candle's tail or wick. We will set a limit for the maximum tail length and ensure it is smaller than the specified parameter. This condition helps filter out certain patterns.

To increase the number of signals throughout our trading time, we will introduce a variation to the normal engulfing pattern. Instead of strictly requiring one candle to engulf the previous one, we will allow two or more consecutive candles to achieve the engulfment as long as they are in the opposite direction and meet the engulfing conditions. The number of candles allowed to achieve the engulfment will be a variable in the code, allowing for flexibility and experimentation.

At this point, we can start writing the program and test the results through backtesting. We will use a Jupyter Notebook file for this demonstration. First, we load the historical data into a DataFrame called df_spy using the read_csv function. We specify the 15-minute timeframe and the date range from 2019 to 2022. The index of the DataFrame is set to the GMT time column.

Next, we define a function called is_engulfing that takes two parameters: the DataFrame and the index of the current candle. This function tests whether the candle achieves an engulfing pattern. We set parameters for the maximum number of candles allowed to achieve the engulfing pattern, the engulfing difference, and the maximum candle tail length. The function checks various conditions for both bearish and bullish engulfing patterns and returns a signal of 1 for bearish and 2 for bullish signals.

We create a copy of the DataFrame, filtering out candles with no movement (where the high is equal to the low). This step removes weekends and bank holidays. We store the filtered data in a DataFrame called df. We also define a new list called signal to store the signals for each row/candle.

For each row in the DataFrame df, we compute the signal using the is_engulfing function with the corresponding index and DataFrame as parameters. We store the signals in the signal list. Finally, we add the signal list as a new column in the DataFrame.

To visualize the signals, we use a plotting function that plots the candlestick chart with dots below or above the candles to represent bullish or bearish signals. We can select a specific range of candles to plot and observe the signals.

To facilitate the visualization, we reset the index of the DataFrame to an integer index and remove the date/GMT time index. Then we select a range of candles to plot and observe the signals.

Here's a summary of the steps involved in backtesting a trading strategy using candlestick charts:

  1. Data Preparation: Obtain historical price data for the desired financial instrument (e.g., stocks, cryptocurrencies) that includes the open, high, low, and close prices for each time period (e.g., minute, hour, day). Ensure the data is in a format that can be easily analyzed.

  2. Strategy Definition: Define the trading strategy based on candlestick patterns. For example, you might look for bullish patterns like a bullish engulfing pattern or bearish patterns like a shooting star. Determine the rules for entering and exiting trades based on these patterns.

  3. Signal Generation: Analyze the historical price data and generate signals based on the defined strategy. Identify the occurrence of specific candlestick patterns that meet the entry or exit criteria.

  4. Portfolio Simulation: Simulate the trading strategy by tracking a hypothetical portfolio. Start with a fixed amount of capital and simulate trades based on the generated signals. Keep track of the portfolio's value and performance throughout the backtesting period.

  5. Performance Evaluation: Evaluate the performance of the trading strategy using various metrics such as profitability, risk-adjusted returns, drawdowns, and other relevant measures. Compare the strategy's performance to a benchmark or alternative strategies to assess its effectiveness.

  6. Visualization: Visualize the backtested results using candlestick charts. Plot the historical price data and indicate the generated signals (entry and exit points) on the chart. This visualization can help in understanding the strategy's performance and identifying areas for improvement.

By following these steps, you can backtest a trading strategy using candlestick charts. It's important to note that backtesting provides historical performance and does not guarantee future results. Additionally, it's crucial to consider other factors such as transaction costs, slippage, and market conditions when developing and implementing a trading strategy.

How to Backtest A Stock Market Strategy Using Python On The S&P 500
How to Backtest A Stock Market Strategy Using Python On The S&P 500
  • 2022.05.26
  • www.youtube.com
This is a high profit trading strategy coded and tested in python. The strategy is easy to use and suitable for beginners, it was tested on SP500 stock marke...
 

Price Action Strategy For Algorithmic Trading In Python



Price Action Strategy For Algorithmic Trading In Python

Hello, everyone! Welcome to the third video on Huffman's inventory retracement bar. This strategy has won several trading competitions, so I thought of trying to create an automated version that can provide positive returns over a few months or even a longer period. To keep this video concise, I recommend watching the two previous videos where we explain the strategy in detail. You can find the link to those videos in the description.

In brief, the strategy involves identifying retracement bars and maintaining a specific slope for trend definition. In an uptrend, we look for a particular shape for the bars, and in a downtrend, we look for the inverted shape of the retracement bar. However, in this video, we will add one more condition. We require the retracement bar to be higher (in an uptrend) or lower (in a downtrend) than the previous and future bars. Essentially, we are looking for a retracement bar that acts as a pivot point, indicating a strong reaction from sellers or buyers trying to reverse the trend.

Implementing this additional condition into an algorithmic trading strategy is more challenging than explaining the concept. In the example shown, we have an uptrend and identify a Huffman retracement bar that acts as a high pivot point. Additionally, we observe a break above the high of this Huffman bar, indicating a likely continuation of the upward trend. We will incorporate all these conditions into our Python algorithm and assess if they improve the results obtained in previous videos.

To provide a brief overview, we load the historical data for the EUR/USD currency pair at a one-hour timeframe from 2003 to 2022. We calculate the exponential moving average (EMA) and the average true range (ATR), which might be useful for setting stop-loss and take-profit values. We compute the slope of the EMA as it is one of the conditions for the Huffman strategy. Additionally, we introduce two new parameters: the total signal back candles (left and right), which determine the number of candles to compare with the high or low of the Huffman candle.

The algorithm defines the conditions for identifying a Huffman bar in an uptrend or downtrend. In this video, we add an extra condition to check if the Huffman bar also acts as a pivot point. We compare the low (in a downtrend) or high (in an uptrend) of the Huffman bar with the previous and future candles within the specified range. If the condition is met, we assign a value of 1 for a downtrend or 2 for an uptrend and store the signals in a new column called "tot signal" in the data frame.

To ensure the algorithm is working correctly, we plot the signals on a chart, visualizing the purple points representing the Huffman bars. We can confirm that the algorithm is correctly identifying the bars based on their characteristics.

Next, we incorporate the EMA signal as a confirmation signal for the trend direction. We also implement the Huffman break signal function, which detects breaks above or below Huffman bars and assigns signals accordingly.

To backtest the strategy, we set the stop-loss and take-profit values, which can vary depending on the specific conditions and indicators used. In this case, we use the ATR to define the stop-loss and a take-profit/stop-loss ratio of 1.5. We conduct the backtest with a starting deposit of $10,000, a margin of 1:50, and one trade at a time.

Initially, the results are not satisfactory, with a return of -70% and a large drawdown. However, this does not necessarily imply that the strategy or indicator is inherently bad. It highlights the importance of considering other factors, such as money management and the selection of stop-loss and take-profit values, which can significantly influence the strategy's performance.

To improve the performance of the strategy, we can optimize the parameters and adjust the money management rules. In this example, we will optimize the total signal back candles parameter, which determines the number of candles to compare with the high or low of the Huffman bar. We will test different values ranging from 2 to 10 and assess the results.

After optimizing the parameter, we obtain better performance with a return of 187% and a reduced drawdown. This demonstrates the importance of parameter optimization in algorithmic trading strategies.

To further enhance the strategy, we can consider incorporating additional filters or conditions. For example, we can implement a trend filter using a higher timeframe, such as the daily or weekly chart. This can help ensure that trades are taken only in the direction of the overall trend.

We can also explore different exit strategies, such as trailing stops or dynamic take-profit levels based on price action or volatility. These additional components can be tested and integrated into the algorithm to potentially improve its performance.

It's important to note that past performance does not guarantee future results. The strategy should be thoroughly tested and validated using historical data and robust backtesting methods. It's also crucial to consider transaction costs, slippage, and other practical aspects of trading when implementing the strategy in a real-time trading environment.

In conclusion, the Huffman's inventory retracement bar strategy can be a useful tool in identifying potential pivot points and trend reversals in the market. By incorporating additional conditions and optimizing parameters, we can improve the performance of the strategy. However, it's essential to conduct thorough testing and consider other factors such as money management and exit strategies to develop a comprehensive and effective trading system.

That wraps up our video on implementing the Huffman's inventory retracement bar strategy in Python. I hope you found this series informative and helpful in your trading endeavors. If you have any questions or comments, please feel free to leave them below. Thank you for watching, and happy trading!

Price Action Strategy For Algorithmic Trading In Python
Price Action Strategy For Algorithmic Trading In Python
  • 2022.05.12
  • www.youtube.com
This is a continuation of the previous videos, on price action trading strategy, about the Hoffman Inventory Retracement Bar indicator, and the previously in...
 

How to Code Retracement Bar Trading Strategy In Python



How to Code Retracement Bar Trading Strategy In Python

Hello everyone, and welcome to this continuation of the Hoffman's Inventory Bar Retracement method. In the previous video, we introduced this method and explained the code to detect specific candle shapes and price trends. If you're interested in the code, you can download the Jupyter Notebook file from the link provided in the description below.

In this video, we will use the Hoffman's bars we identified earlier in a trading strategy, backtest the system, and evaluate the results. The strategy focuses on identifying specific candle shapes in an uptrend or downtrend and checking for breakouts above the high or below the low of these candles.

Let's consider an example where we have an uptrend. We detect a Hoffman's retracement bar where the upper tail is at least 45% of the entire candle's volume. This indicates that sellers are trying to counter the uptrend movement. However, in the following candle, we observe that the closing price is higher than the high of the preceding Hoffman's candle. This suggests that buyers are still stronger in the market and are likely to continue driving the price up.

To implement this strategy in Python, we will iterate through each candle's closing price and check among its previous neighboring candles if any of them form a Hoffman's retracement bar. We'll define a parameter called "back_candles," which determines the number of candles to consider when searching for the Hoffman's bar. This parameter can be adjusted to experiment with different values.

If a breakout occurs above the high or below the low of the Hoffman's candle, we will place a buying or selling position, respectively, depending on the current price trend. We can also set stop-loss and take-profit values, which can be based on the average true range (ATR) or the highest/lowest values of the previous candles, depending on the price trend.

Now let's write the strategy in Python and backtest it using a few months of historical data to evaluate the results. The Jupyter Notebook file contains the code, which starts by loading 59 days of data using the yfinance module in a 15-minute timeframe. We calculate the exponential moving average (EMA), ATR, and slope of the moving average.

Next, we identify the Hoffman's bars based on the slope of the moving average and the shape of the candles. We visualize the signals on a chart and then define a new function called "hofmann_break_signal" that takes two parameters: the current candle's index and the number of back candles to consider when searching for the Hoffman's candle pattern.

Inside the function, we iterate through each candle and check if the conditions for a Hoffman's bar and breakout are met. If so, we return a buying signal for an uptrend or a selling signal for a downtrend.

We apply this function to each row of the data frame and store the results in a series. Finally, we visualize the signals and check if the Hoffman's candles are detected properly.

After verifying the candle detection, we proceed to backtest the strategy. We set the stop-loss based on the minimum price among the previous candles and take profit using a ratio relative to the stop-loss. In this example, we use an ATR-based approach with a stop-loss ratio of 1.5.

We test the strategy over the three months of data and calculate the return, percentage of winning trades, and equity curve. In this initial test, the return is positive at 51%, but the equity curve does not show a stable increase.

We also explore a different method of setting stop-loss and take-profit levels, considering the highest high or lowest low of the previous candles. However, in this case, the return is negative at -4.8%, indicating that this money management strategy did not perform well.

Please note that this strategy has not been optimized in this video. It was developed quickly to demonstrate the Python implementation. If you find this strategy interesting, feel free to copy the code and further customize it by adding additional technical indicators.

Thank you for watching this video. Stay tuned for the next one, trade safely, and see you next time!

How to Code Retracement Bar Trading Strategy In Python
How to Code Retracement Bar Trading Strategy In Python
  • 2022.05.05
  • www.youtube.com
This video is a continuation of the previous one on the Hoffman Inventory Retracement Bar Automated In Python. This algorithmic trading strategy enabled Hoff...
 

Retracement Bar Coded In Python For Algorithmic Trading


Retracement Bar Coded In Python For Algorithmic Trading

Hello, in this video, we will introduce the Huffman's Inventory Retracement Bar and demonstrate how to automate its detection in Python. If you're interested in the code, you can download the Jupyter Notebook file from the link provided in the description.

The first rule of this strategy is to detect the trend of the price by checking if the 20-day moving average (MA) slope forms a 45-degree angle with the horizontal line. Note that the 20-day MA is used as an example, and you can experiment with different periods for the moving average. If you're following a downtrend, the negative slope should also form an angle of at least 45 degrees with the horizontal line. However, it's important to mention that relying solely on this 45-degree angle as a signal is mathematically meaningless, as it's impossible to accurately define this angle on a trading chart. Algorithmic trading provides a solution to this issue, which we'll explore later in the video.

The second rule of this strategy involves identifying candles where the tail is at least 45% of the entire candle's length. For example, in an uptrend, we look for candles with an upper tail greater than 45% of the total movement of the candle. Similarly, in a downtrend, we look for candles with a lower tail greater than 45% of the candle's volume. This candle pattern signifies moments when sellers or buyers try to resist or reverse the trend. By understanding the market dynamics through candle patterns, we can define our custom strategy.

In the example, we identify these specific candles and wait for the market to break above the high values. When a candle closes above the high of a Huffman's candle, it indicates that sellers couldn't resist the buying trend, and buyers still have the upper hand. This suggests that the upward trend is likely to continue, and we can enter a long position with the buyers. Analyzing the outcomes of these assumptions, we observe that in most cases, the price follows our expectations.

However, to determine the long-term outcome of this indicator, we need to perform a backtest using our Python code. In this video, we focus on explaining how to detect Huffman's candles and generate a signal when they occur. In a separate video, we will utilize this indicator in a complete trading strategy and perform a proper backtest.

To begin, we download the data using the yfinance module. The example downloads Euro/USD data for a 59-day period with a 15-minute timeframe. If you need more data, you can download it in batches and concatenate the data frames. After downloading the data, we compute the exponential moving average (EMA) with a length of 20 and calculate the slope of the moving average. The slope values are stored in a new column called slope_ema in the data frame.

Next, we compute the signal by iterating over each row. If the slope of the current candle is negative and exceeds the slope limit, indicating a downtrend, we check if the lower tail of the candle divided by the high-low range is greater than the percentage limit. This signifies a Huffman's candle in a downtrend, and the total signal is set to 1. Similarly, if the slope is positive and exceeds the slope limit, indicating an uptrend, and the upper tail of the candle divided by the high-low range is greater than the percentage limit, we have a Huffman's candle in an uptrend, and the total signal is set to 2.

Once we compute the signal and store the results in a list called signal, we add it as a new column called tot_signal to the data frame. We can then visualize the signals on a graph using Plotly.

Here's a step-by-step explanation of the Huffman's Inventory Retracement Bar strategy without the code:

  1. Download the price data: Obtain the historical price data for the desired financial instrument, such as a stock or currency pair. You can use libraries like yfinance in Python to retrieve the data.

  2. Compute the Exponential Moving Average (EMA): Calculate the EMA of the closing prices using a specific time period. The EMA is a commonly used indicator that helps identify trends and potential reversals in the price data.

  3. Compute the slope: Calculate the slope of the EMA line at each data point. The slope indicates the direction and strength of the trend. You can use mathematical techniques like gradient or regression to calculate the slope.

  4. Set parameters: Define the parameters for signal detection. In Huffman's Inventory Retracement Bar strategy, you typically set a slope limit and a tail percentage limit. The slope limit determines the minimum slope value for a potential signal, while the tail percentage limit sets the minimum percentage of the candle's range that the upper or lower tail should be.

  5. Identify signals: Iterate through the data and compare the current and previous slopes. If both slopes are below the negative slope limit, check if the lower tail of the current candle is larger than the tail percentage limit. If it is, mark it as a bullish signal. Similarly, if both slopes are above the positive slope limit, check if the upper tail of the current candle is larger than the tail percentage limit. If it is, mark it as a bearish signal.

  6. Visualize signals: Create a chart or graph of the price data. Plot the signals on the chart to visualize the Huffman's candles. You can use plotting libraries like Plotly or Matplotlib to create the chart and mark the signal points.

Remember that the strategy is not limited to these steps, and you can customize and refine it based on your requirements and trading preferences. Additionally, implementing risk management techniques, such as setting stop-loss orders or position sizing, is essential for successful trading.

Retracement Bar Coded In Python For Algorithmic Trading
Retracement Bar Coded In Python For Algorithmic Trading
  • 2022.04.28
  • www.youtube.com
This video details the IRB or the inventory retracement bar as described and used by Hoffman and the algorithm that detects this bar in an automated method i...
 

How to Automate Trading Patterns In Python | Head And Shoulders Pattern



How to Automate Trading Patterns In Python | Head And Shoulders Pattern

To automate the detection of head and shoulders patterns in Python, we can follow the algorithm steps outlined in the text. Here's a detailed explanation of each step:

  1. Detect Pivot Points:

    • This step involves identifying high and low values in the price data that are higher or lower than the neighboring candles.
    • Two types of pivot points are detected: strong pivot points and weak pivot points.
    • Strong pivot points are compared to a wide range of neighboring candles, while weak pivot points are compared to a smaller number of neighbors.
  2. Visualize Pivot Points:

    • The detected strong pivot points and weak pivot points are plotted on a candlestick chart.
    • Strong pivot points are represented by purple points above the candles, while weak pivot points are represented by red points below the candles.
  3. Detect Head and Shoulders Pattern:

    • To detect the head and shoulders pattern, we iterate through the candle IDs in the specified range.
    • For each candle ID, we check if it is a pivot point (neither a strong pivot nor a weak pivot) and proceed further.
    • If a strong pivot point is found, we record the coordinates of the maximas and minimas within a window of candles on both sides of the pivot.
    • We keep track of the counts of minimas and maximas before and after the central pivot candle.
    • If the counts of minimas and maximas are less than one on either side, the pattern formation is not possible, and we skip to the next candle.
    • If the counts of minimas and maximas satisfy the condition, we fit a linear regression line to the minimas and calculate its slope and intercept.
    • We find the index of the head within the maximas using the argmax function.
    • Finally, we check if the conditions for the head and shoulders pattern are met:
      • The difference between the maximum of the head index and the maximum before the head should be greater than a threshold.
      • The difference between the maximum of the head index and the maximum after the head should also be greater than the threshold.
      • The absolute slope of the minimas should be less than or equal to a threshold.
    • If all conditions are satisfied, we have detected a head and shoulders pattern.
menting risk management techniques, such as setting stop-loss orders or position sizing, is essential for successful trading.
How to Automate Trading Patterns In Python | Head And Shoulders Pattern
How to Automate Trading Patterns In Python | Head And Shoulders Pattern
  • 2022.04.21
  • www.youtube.com
This video details the head and shoulders candles or candlesticks pattern, and an algorithm is automated in Python language to detect this specific form of c...
 

Triangle Price Pattern Detection In Python | Algorithmic Trading Indicator



Triangle Price Pattern Detection In Python | Algorithmic Trading Indicator

In this video, we will explore automated detection of triangle patterns using specific algorithms. We will present a simple method for detecting different shapes of price movement triangles and write a Python code to test it on forex data. At the end, we will plot the discovered patterns to visualize the results. If you are interested in the coding part, you can download the Jupyter Notebook file containing the Python code from the link provided in the video description.

Triangle patterns are of particular interest to traders when they are used in trading strategies. For example, some traders trade the breakout of triangles. In the examples shown, the price follows a future trend in the direction of the breakout. In one example, the price broke out of the triangle edges, following a downtrend. In another example, the price broke out of the triangle edge, following an uptrend. In both cases, there was a continuation of the breakout trend.

The steps of the method are as follows:

  1. Compute pivot points: Pivot points are price values that are greater than their neighbors. For pivot lows, the low of a candle should be lower than the lows of a specified number of candles before and after it. For pivot highs, the high of a candle should be higher than the highs of the specified number of candles before and after it.

  2. Fit maximas and minimas in linear slopes: For maximas, compare the high values and look for a central candle with a high that is higher than the specified number of candles before and after it. For minimas, compare the low values and look for a central candle with a low that is lower than the specified number of candles before and after it.

  3. Detect triangle forms: Depending on the desired triangle form, identify patterns based on the slopes of maximas and minimas. For example, a converging triangle can be detected when the maxima slope is negative and the minima slope is positive. A descending triangle can be detected when the maxima slope is negative and the minima slope is close to zero or a horizontal line.

Now, let's write the code in Python to implement this method and see how it works. The Jupyter Notebook file contains the code for importing the data, cleaning it, computing pivot points, visualizing the pivot candles, and detecting triangle patterns. We use libraries such as Pandas, NumPy, and Plotly to handle the data manipulation and visualization tasks.

After importing the necessary libraries and the data, we define a function called "pivot_id" to identify pivot points based on the specified number of neighbors. This function adds a new column called "pivot" to the data frame, indicating whether a candle is a pivot low (1) or a pivot high (2).

We then define a function called "points_position" to plot the candles and add points above and below them based on their pivot status. This function uses the "point_position" column to determine the y-coordinates of the points.

Using the Plotly library, we plot the candles and the pivot points to visualize the results. This allows us to verify that the pivot points are correctly identified.

Next, we implement the code to detect triangle patterns. We select a specific candle and scan a specified number of candles before it to check if a triangle pattern is present in that area. We iterate over the candles and store the coordinates of the maximas and minimas in separate NumPy arrays. We then fit these points into linear slopes using linear regression and calculate the slopes for maximas and minimas.

We plot the candles, pivot points, and the slopes of maximas and minimas to visualize the triangle pattern. By checking the conditions defined for the shape of the triangle, such as the correlation factors (r_min and r_max), we can determine if a triangle pattern is present. If the conditions are met, we mark the triangle pattern on the plot.

Finally, we iterate through all the candles in the dataset and repeat the process of detecting triangle patterns. Each time a pattern is found, we store the coordinates of the triangle in separate lists for later visualization.

At the end of the code, we use Plotly to plot the candles, pivot points, and the detected triangle patterns. This provides a visual representation of the identified triangles in the price data.

By running the code and examining the plot, we can see the detected triangle patterns and analyze their shapes. This information can be useful for traders who want to incorporate triangle patterns into their trading strategies.

Remember that the code provided in the Jupyter Notebook file is just one possible implementation of detecting triangle patterns. There are various ways to approach this problem, and you can explore different algorithms or modify the existing code to suit your specific requirements.

Triangle Price Pattern Detection In Python | Algorithmic Trading Indicator
Triangle Price Pattern Detection In Python | Algorithmic Trading Indicator
  • 2022.04.14
  • www.youtube.com
This video details the algorithm for triangle price pattern detection in python, this technical indicator can be programmed in python to detect all shapes of...
 

Python AlgoTrading Backtest: Using RSI and ADX with Moving Average for Buy/Sell Signals



Python AlgoTrading Backtest: Using RSI and ADX with Moving Average for Buy/Sell Signals

Hello everyone! In this video, we will be conducting a detailed test of a sculpting strategy based on the Average Directional Index (ADX) and the Relative Strength Indicator (RSI), along with other confirmation indicators. This strategy is advertised as a profitable approach for scalping. We will be focusing on the purple points located just below the red arrows on the price chart, which are automatically generated by the algorithm we will describe.

In this specific example, the purple points represent selling signals, and it is worth noting that these signals are followed by a drop in price. This suggests that this strategy holds promise, as these signals have resulted in winning trades. To delve deeper into the coding aspect, you can download the Python code, a Jupyter Notebook file, from the link provided in the description.

Our aim is to develop an automated sculpting strategy in Python that allows us to set up trades, leave the code running, and potentially profit while we sleep. However, it is important to acknowledge that achieving success may not be as simple as it initially sounds.

We will commence testing on the five-minute timeframe, as recommended for this particular strategy. To determine the price trend, we will utilize the 50 Exponential Moving Average (EMA). If the price is trading above this curve, it indicates an uptrend, and we will focus solely on buying positions. Conversely, if the price is trading below the 50 EMA, it indicates a downtrend, and we will exclusively consider selling positions.

Additionally, we will incorporate the RSI with a period of 3 and trigger levels set at 20 and 80. When the RSI falls below 20, it suggests that the market is oversold, triggering a buying signal. Conversely, when the RSI exceeds 80, it indicates that the market is overbought, resulting in a selling signal.

Our strategy also incorporates the Average Directional Index (ADX) with a period of five. If the ADX surpasses 30, it indicates a strong trend, serving as a confirmation index for both uptrends and downtrends. In both cases, we are searching for levels above 30.

When all these conditions are met, the first part of our signal is generated. To further validate this signal, we will employ a candle pattern approach, specifically searching for an engulfing candle aligned with the trend. If the trend is upward, we will seek a bullish engulfing candle; if the trend is downward, we will seek a bearish engulfing candle.

Fortunately, all these indicators can be automated in Python and tested on historical data. The example we will be using was randomly selected from the dataset. Initial observations indicate positive signals, as the selling signals tend to be followed by a drop in price, while the buying signals are often succeeded by an increase in price.

To put this strategy to the ultimate test, we will employ Python to conduct backtesting and allow the results to determine its viability. We will import the historical data for the EUR/USD currency pair from 2019 to 2022, specifically using five-minute candlesticks. We will also clean the data by removing periods of no trading activity, such as weekends and bank holidays.

Using the Pandas TA (Technical Analysis) package, we will add four additional columns to our data frame: the 50 EMA, RSI with a period of 3, ADX with a period of 5, and Average True Range (ATR). The latter will be utilized for calculating the stop-loss distance. The EMA trend signal will indicate whether the candles are trading below or above the 50 EMA curve, determining whether we are in a downtrend or an uptrend, respectively.

If we are in a downtrend, we will check if the RSI is below 20, indicating an oversold condition. If both the downtrend and oversold conditions are met, we will generate a selling signal.

Similarly, if we are in an uptrend, we will check if the RSI is above 80, indicating an overbought condition. If both the uptrend and overbought conditions are met, we will generate a buying signal.

To further validate these signals, we will look for engulfing candle patterns aligned with the trend. For a selling signal, we will search for a bearish engulfing candle, where the current candle's body completely engulfs the previous candle's body in a downward direction. For a buying signal, we will search for a bullish engulfing candle, where the current candle's body completely engulfs the previous candle's body in an upward direction.

Once the signals are generated, we will calculate the stop-loss distance using the Average True Range (ATR). The ATR provides an estimate of the average price range over a specified period, which can help us determine a reasonable stop-loss level.

In the backtesting phase, we will iterate through the historical data and apply these rules to generate and evaluate trading signals. For each signal, we will simulate a trade, assuming we enter the position at the opening price of the next candle after the signal is generated. We will also define a fixed take-profit level based on a certain reward-to-risk ratio.

During the simulation, we will track the profit or loss for each trade and calculate key performance metrics such as total profit, total loss, win rate, and average return per trade. This will help us assess the effectiveness of the strategy and determine its profitability.

It's important to note that backtesting results on historical data do not guarantee future performance. Market conditions can change, and strategies that work well in the past may not work as effectively in the future. Therefore, it's crucial to continuously evaluate and adapt trading strategies based on real-time market conditions.

In conclusion, we have outlined a sculpting strategy based on the Average Directional Index (ADX), Relative Strength Indicator (RSI), and engulfing candle patterns. We have discussed the process of automating this strategy using Python and conducting backtesting on historical data. The results of the backtesting will provide insights into the strategy's performance and help assess its viability as a profitable approach for scalping.

Python AlgoTrading Backtest: Using RSI and ADX with Moving Average for Buy/Sell Signals
Python AlgoTrading Backtest: Using RSI and ADX with Moving Average for Buy/Sell Signals
  • 2022.04.07
  • www.youtube.com
This is a backtested strategy using the ADX and the RSI, the algotrading code is built in python and the backtest is conducted using backtesting.py package. ...
 

How To Use The Volume Indicator For Trading Strategy Analysis In Python


How To Use The Volume Indicator For Trading Strategy Analysis In Python

Today, we are embarking on an exciting journey as we test a volume trading strategy. This particular strategy operates on the daily time frame and is known for its safety, as it involves minimal risk in theory. I have aptly named it the "Volume Trading Strategy" due to its reliance on volume and other technical indicators.

Our objective is to develop a code that can automatically test this strategy using historical data spanning up to 18 years. By doing so, we can gain a comprehensive understanding of the strategy's performance. For those interested in the coding aspect, you can find the Jupyter Notebook Python file in the video description. There's a link available for you to download the complete file that we will be using for this testing.

To begin, we will utilize the 200-day exponential moving average (EMA) as our first indicator. If the price is trading below this curve, it signifies a downtrend, whereas trading above the 200 EMA indicates an uptrend. Our first rule is straightforward: when we identify a downtrend, we will only consider sell positions, and in the case of an uptrend, we will solely focus on buy positions.

Now, let's delve into the specifics of our strategy. We will be searching for four consecutive candles that move counter to the prevailing trend, i.e., retracing the price closer to the moving average. It is important to note that the number of candles can be adjusted based on the user's preference. In our Jupyter Notebook, we have provided the flexibility to modify this parameter at any time. For now, we will stick with a minimum of four candles.

Next, we examine the following candle, which should align with the trend's direction. For instance, if we are in a downtrend, we look for a bearish candle. At the end of the trading day, once the candle has closed, we check its volume. If the volume exceeds that of the previous candle, it serves as a sell signal in a downtrend. Conversely, in an uptrend, we search for at least four consecutive bearish candles followed by a bullish candle with higher volume than the previous candle. This signifies a buying position.

Now comes the intricate part: determining the stop loss and take profit levels. In this video, we explore two different approaches and evaluate their outcomes. The first method involves using an Average True Range (ATR)-related stop-loss distance, such as twice or three times the ATR from our selling or buying positions. The second method considers the highest high among the previous few candles as our stop loss for a downtrend and selling position. The number of candles to consider for setting the stop loss is a variable in our Python program, allowing us to experiment and test different scenarios. Typically, I begin with four candles, similar to the number used for checking our trade signals. For an uptrend and buying position, we look for the lowest low among the previous few candles.

Now, let's examine the code and see how it all works together. In our Jupyter Notebook file, we start by importing the necessary libraries, including Pandas, which we'll use to read the CSV data file containing the daily EUR/USD exchange rates from 2003 to 2022. Additionally, we load data for other assets like the Amazon, eBay, and Volkswagen stocks, as we intend to test this strategy on the stock market as well. Since we are working with daily data, the initial dataset consists of 6,858 rows, which will be further reduced during the data cleaning process. We also ensure that the column titles align with our requirements, renaming them to "Time," "Open," "High," "Low," "Close," and "Volume" for consistency across different data files.

After plotting the signals on the chart, we move on to defining our stop loss and take profit levels. In this example, two methods are tested. The first method involves using the Average True Range (ATR) to determine the stop loss distance. The stop loss is set at a certain multiple of the ATR from the entry point. The second method considers the highest high for selling positions or the lowest low for buying positions among a specified number of previous candles to determine the stop loss level.

Once the stop loss and take profit levels are defined, we calculate the profit and loss (P&L) for each trade. We check if the total signal is a buy or sell signal and calculate the P&L accordingly. If it's a buy signal, we calculate the P&L as the difference between the closing price of the next candle and the entry price. If it's a sell signal, we calculate the P&L as the difference between the entry price and the closing price of the next candle.

The cumulative P&L is then computed by adding up the individual trade P&Ls. We also calculate the total number of trades and the win rate (percentage of winning trades) based on the positive P&Ls.

Finally, we print out the results, including the total P&L, the number of trades, and the win rate.

The code provided in the Jupyter Notebook allows for further customization and testing of the strategy. You can modify parameters such as the number of back candles to consider for trend determination, the number of previous candles for price signal generation, the multiple of ATR for stop loss calculation, and the number of previous candles to consider for stop loss level determination.

The code implements a volume trading strategy based on technical indicators such as the 200-day Exponential Moving Average (EMA), volume, and price movements. It tests the strategy over a specified period of historical data and calculates the profitability and performance metrics.

How To Use The Volume Indicator For Trading Strategy Analysis In Python
How To Use The Volume Indicator For Trading Strategy Analysis In Python
  • 2022.03.24
  • www.youtube.com
Welcome to my video on how to use the volume indicator for trading strategy analysis in Python. In this video, I will be sharing a daily timeframe volume tra...
 

Automated RSI Scalping Strategy Tested In Python



Automated RSI Scalping Strategy Tested In Python

Today, we are going to test a scalping strategy based on the RSI (Relative Strength Index). The strategy incorporates two indicators: the Exponential Moving Average (EMA) and the RSI. We will conduct backtesting using Python code, which you can download from the link provided in the video description.

For the backtest, we will use three different versions of the strategy based on different time frames: one for one-minute candles, another for 15-minute candles, and a third for one-hour candles. The focus of this video will be on the 15-minute time frame, but we will cover all three versions.

The strategy follows specific rules. First, we analyze the current price in relation to the 200 EMA. If the price is trading above the 200 EMA, we consider it an uptrend. Conversely, if the price is trading below the 200 EMA, we consider it a downtrend. In an uptrend, we only look for buying positions, while in a downtrend, we only look for selling positions.

Next, we examine the RSI values of two consecutive candles. Initially, we use a two-candle RSI for the one-minute time frame. However, since backtesting over several years with one-minute candles would generate a massive amount of data, we will start with the 15-minute time frame. In this case, we may adjust the RSI length to three or four candles, depending on the time frame. For the one-minute time frame, we will use a two-candle RSI and test levels below 10 and above 90.

In an uptrend, we wait for the RSI to drop below 10 before executing a buying position. For selling positions, we wait for the RSI to rise above 90. These RSI levels act as entry points for our trades. The video provides visual examples of how the strategy identifies entry positions based on the price and RSI criteria.

The next step is to determine the stop-loss and take-profit values for the trades. Various methods can be used, such as fixed distance stop-loss, ATR-related stop distance, or trailing stop values. Similarly, the take-profit can be set at a fixed distance or related to the stop-loss distance with a certain take-profit/stop-loss ratio.

To evaluate the strategy's effectiveness, we write Python code to conduct backtesting over one to three years of data. Additionally, we introduce a step to check the robustness of the strategy by testing it on new data that has been kept separate to avoid bias.

The video proceeds to analyze the code in a Jupyter Notebook. It begins by loading the data, cleaning it by removing zero volume entries (indicating weekends or bank holidays), and computing the 200 EMA and RSI values. The Average True Range (ATR) is also calculated for potential stop-loss distance determination.

Once the necessary signals are computed, the video demonstrates the visualization of these signals on a chart. The price candles, 200 EMA curve, and entry positions (buying and selling) are plotted to analyze the behavior of the indicators visually.

After analyzing the signals, the video explains the importance of backtesting the strategy over an extended period to assess its profitability. Initially, the strategy was tested over shorter periods, but the outcome varied. Therefore, backtesting over a longer period is crucial to evaluate the strategy's overall effectiveness.

The video emphasizes the need for backtesting and checking the strategy's performance over a significant period. By examining the end results of the backtest, we can determine whether the strategy is profitable and robust.

Automated RSI Scalping Strategy Tested In Python
Automated RSI Scalping Strategy Tested In Python
  • 2022.03.17
  • www.youtube.com
An Automated RSI Scalping Strategy is presented and backtested using python algorithmic trading over 3 years of data showing positive returns. The Test deta...
Reason: