Python in algorithmic trading - page 17

 

Channel Break Out Indicator In Python



Channel Break Out Indicator In Python

Hi! Today, we're going to take a deep dive into price channel breakout examples generated by an algorithm. Later on, I'll show you the code, which you can download for free from the link in the description below. Let's begin by understanding what price channel breakout is.

Price channel breakout is a technical analysis tool used by traders to identify potential breakouts in price. It works by plotting a channel around the price action, representing the high and low points of the price over a specific period. When the price breaks out of this channel, it can indicate a potential trend change or a market opportunity.

The interesting part is that we can automate the process of identifying channels and potential breakouts using Python. In this video, I'll walk you through the algorithm steps and provide the code, allowing you to modify and fine-tune it according to your trading preferences and the asset you'll be using it on.

Let's analyze the examples shown on the chart. The black stars represent the breakouts detected by the algorithm. The stars below the candles signal a future uptrend, while the stars above the candles indicate a future downtrend. These breakouts are based on channels identified by the algorithm.

To explain the algorithm, let's consider the first example. We have a downtrend, followed by a breakout below a certain channel. The star below the candle indicates a future downtrend. It's important to note that this particular channel is different from the one shown on the chart. The algorithm detects channels based on previous candles.

Another example is a breakout above a channel, signaling a future uptrend. We can observe these breakouts and their relationship with the channels detected by the algorithm. The algorithm uses three detection points: pivot points, channel detection, and breakout detection.

First, it detects pivot points, which are candles with high values compared to neighboring candles or low values compared to neighboring candles. The algorithm checks for two candles on each side as pivot highs or lows. These pivot points serve as reference points for fitting lines to define channels.

Next, the algorithm fits lines to the pivot highs and lows, creating the channel. This step identifies the upper and lower boundaries of the channel. The channel represents the potential range of price movement.

The third phase is breakout detection. The algorithm determines if a breakout has occurred by comparing the current candle with the channel. The breakout condition is defined based on the position of the opening and closing prices relative to the channel. In this video, we consider breakouts above and below the channel.

In Python, you have the flexibility to modify the breakout conditions and define your own patterns based on your trading preferences and the asset you're trading. The code provided in the link will serve as a starting point for your experimentation.

The algorithm seems to work well based on the examples shown using the daily time frame and Euro/US dollar prices. However, further testing and analysis are required. Now, let's dive into the code.

In the Jupyter Notebook file, we import the necessary libraries: pandas, numpy, plotly, and scipy.stats. We also import a CSV data file containing Euro/US dollar daily candlestick prices from 2003 to 2023.

The code starts by defining a function to detect if a candle is a pivot point. It takes two arguments: the candle index to be tested and the window parameter, which determines the number of neighboring candles to consider. The function checks if the high and low of the current candle are higher or lower than the highs and lows of neighboring candles. It assigns labels (0, 1, 2, or 3) based on the pivot type (high, low, or both).

To detect price channel breakouts in a Candlestick chart, you can follow these steps:

  1. Define the number of back candles you want to consider for channel detection. This determines the length of the channels.
  2. Iterate over the candles in the chart.
  3. For each candle, collect the low and high values of the previous back candles.
  4. Use linear regression to calculate the slope and intercept of the lines that connect the pivot lows and pivot highs.
  5. Check if the slope values are not NaN (not a number), indicating that a valid channel could be formed.
  6. If a valid channel is detected, plot the channel lines (dashed lines) and the pivot points (blue dots for lows, red dots for highs) on the Candlestick chart.

The general idea is to identify the trendlines that encompass the price movements within the specified number of back candles. By detecting breakouts from these channels, you can potentially identify significant price movements and make informed trading decisions.

It's important to note that the code provided earlier is a simplified example, and depending on your specific trading requirements, you may need to modify and fine-tune the code to suit your needs. Additionally, consider incorporating risk management strategies, other indicators, and factors relevant to your trading approach when using channel breakout techniques for real trading purposes.

Channel Break Out Indicator In Python
Channel Break Out Indicator In Python
  • 2023.02.23
  • www.youtube.com
In this video, you'll learn how to use Python to implement the Price Channel Breakout Indicator and how it can be used to identify profitable trading opportu...
 

ChatGPT Trading Strategy Challenge



ChatGPT Trading Strategy Challenge

Hi and welcome to our latest experiment. In this video, I will showcase the power of AI by pitting it against the experience of a real human trader. We will delve into the price channel breakout strategy and challenge our AI model, ChatGPT, to see how it performs. If we discover anything interesting, I will write my own algorithm in the next video and compare the performance results. Later on, I will also share the Python code I will be using in this video. You can download it from the link in the description below if you're curious and willing to experiment and extend our strategy. So, sit back, relax, and let's enjoy this.

When we talk about channel breakout indicators, we usually consider candlestick chart patterns and fractal points. The breakout typically occurs when the price moves beyond a channel, and after the breakout, we expect the trend to continue in the same direction, at least for a while. Today, we'll try to make ChatGPT generate the code for us, specifically for the price channel breakout strategy.

Before we dive into our experiment with ChatGPT, I'm going to program the same strategy, the price channel breakout, my way in the next video. This will allow us to compare the results and highlight the control we have over every single detail in our program. So, stay tuned and let's get started.

Now, let's start by defining the price breakout strategy. This trading approach involves identifying key levels of support and resistance using technical analysis tools like trendlines and chart patterns. Pay close attention to levels that have been tested several times in the past and observe the price action at those levels. Once we have identified the key levels, we can set up entry and exit rules.

Setting up entry and exit rules is the most challenging part of the strategy. It involves deciding at what price level you will enter a trade and when you will exit to take profits or limit potential losses. Monitoring the asset's price movements is crucial once we open a position. We should use stop loss orders to limit potential losses in case the trade goes against us.

After setting up the entry rules and managing the trade, we need to monitor the open trades. If the price continues to move in the expected direction, we can consider adjusting our exit strategy to capture additional profits. This requires continuous monitoring and adaptation based on the changing market conditions.

Here's a breakdown of the strategy:

  1. Identify key levels of support and resistance: Use technical analysis tools like trendlines and chart patterns to identify levels that have been tested multiple times in the past. These levels act as support or resistance and form the channels.

  2. Define the breakout level: Once you have identified the channels, determine the breakout level. This is the price level at which the price moves beyond the channel boundaries. It indicates a potential trend continuation.

  3. Set entry and exit rules: Determine the criteria for entering a trade when a breakout occurs. This can be when the price closes above the upper channel boundary for a bullish breakout or below the lower channel boundary for a bearish breakout. Additionally, set criteria for exiting the trade, such as taking profits at a certain target level or using a trailing stop loss to protect against adverse price movements.

  4. Monitor open trades: Once a trade is entered, monitor the price movement closely. Adjust the exit strategy if the price continues to move favorably. This could involve trailing the stop loss to protect profits or setting a new target level to capture additional gains.

  5. Manage risk: Implement risk management techniques to limit potential losses. This can include setting a stop loss order at a predetermined level to exit the trade if the price moves against the expected trend.

  6. Continuous adaptation: Adapt the strategy based on changing market conditions. The price channel breakout strategy requires ongoing monitoring and adjustment to capture the best trading opportunities.

By following these steps and applying them to the specific market and timeframe you are trading, you can implement the price channel breakout strategy. Remember that the effectiveness of the strategy may vary depending on various factors, and it's important to backtest and validate the strategy before applying it in real-time trading.

ChatGPT Trading Strategy Challenge
ChatGPT Trading Strategy Challenge
  • 2023.02.03
  • www.youtube.com
In this video, we will be exploring the use of ChatGPT in generating a profitable trading strategy. The goal of this strategy is to beat the performance of a...
 

Master FOREX Grid Trading with Automated Hedging Strategy using Python


Master FOREX Grid Trading with Automated Hedging Strategy using Python

In the previous video, we tested the grid trading system on the Forex Market and found that it yielded good results with high returns and an outstanding sharp ratio. However, based on your comments, we realized that some details needed to be corrected to conduct a more accurate backtest. As a result, we made the proposed changes to our algorithm.

If you haven't watched the previous video where we detailed the grid strategy, I recommend checking it out first as it provides a deeper understanding of the strategy. You can find the link to that video in the description below. Additionally, you can download the updated version of the Python code from the link provided.

After implementing the code changes, we still have a potentially preferable system, depending on the set of parameters used. Please note that I haven't spent much time optimizing the parameters, so you can download the code and experiment with tuning them to your liking. This will allow you to adjust the risk level according to your preferences. You can either include more risk at the expense of decreasing the sharp ratio or decrease the risk and returns while increasing the sharp ratio.

Now, let's discuss the specific changes made to the previous version of the code. Firstly, we removed one of the parameters related to the take profit/stop loss ratio. We realized that this ratio should be modified within the strategy itself, so it doesn't need to be set at this point. The functions used in the previous version remain the same.

The first significant modification was related to the lot size. In the previous version, the lot size was set to a value below one, indicating a percentage of the current equity. However, this violated the rules of the grid strategy because we were trading in both directions with different lot sizes. To correct this, we set the lot size as a fixed value (50 in this example).

The second important modification is related to the backtest function. Previously, when we opened a trade and then tried to open an opposite trade or a trade in the opposite direction, the backtesting function would close the previous trade. This meant that if we sold first and then bought the same amount, the backtesting function would close our selling position. To allow backtesting to open two trades independently in opposite directions, we used the hedging parameter set to true. This allows positions in the opposite direction on the same asset at the same time. Additionally, we set the exclusive orders parameter to false, meaning one order will not cancel the previous order.

For the stop loss values, we set them at 1.5 times the grid distance, and the take profit is set at 0.5 times the grid distance. The take profit/stop loss ratio is set to 0.5. Please note that these are random parameters used for the example. In a real system, it's important to ensure that the stop loss is further than the take profit, as the strategy relies on market choppiness to generate profits.

Using these parameters, a cash account of $500, and a margin of 1 to 10, we obtained the following results over two months of data: a return percentage of 13.49, a sharp ratio of 3.8, and a win rate of 72%. The equity curve shows an increasing slope with some drawdown areas.

To decrease the risk and increase the sharp ratio, you could consider starting with additional cash or adjusting the margin. For example, by starting with $1,000 and maintaining a margin of 1 to 10, the return decreased to 1.7% over two months, but the sharp ratio increased to 4.9. This indicates that the risk decreased with this parameter change.

Keep in mind that there are many parameters to work with in this system, and finding the right balance is crucial. You can experiment with changing the stop loss and take profit ratios as well.

It's important to note that not all brokers allow hedging trades, meaning they may not allow you to open opposite positions at the same time on the same asset. This can depend on the broker and your location. Some viewers from the United States mentioned in the comments that this is not allowed in their region. Therefore, it's advisable to discuss with your broker before implementing this strategy to ensure it aligns with their policies.

Finally, remember that backtesting is the first step in studying a system, but it's not enough. It's crucial to test the strategy live on the market using a paper account, as this will include the spread of the currency being traded and may impact the expected results.

Master FOREX Grid Trading with Automated Hedging Strategy using Python
Master FOREX Grid Trading with Automated Hedging Strategy using Python
  • 2023.01.19
  • www.youtube.com
Learn how to enhance your FOREX grid trading with an Automated Hedging Strategy using Python!📈💻 In this video, we'll delve into the concept of grid trading...
 

Hedging Strategy For Trading In Python



Hedging Strategy For Trading In Python

Hello everyone, today we will be testing the grid trading strategy. This strategy is known for its simplicity and does not require any technical indicators to determine the trend. This means we don't need to guess the trend in advance. Grid trading involves trading in both long and short directions simultaneously, making it suitable for algorithmic trading.

To evaluate this strategy, we will conduct a backtest using Python language. We will use historical data spanning two months, with a five-minute timeframe. The backtest results show a steady increase in equity over the testing period, and the strategy yields impressive performance ratios. The Sharpe ratio, which measures risk-adjusted returns, scores around 5.7.

If you are interested in the coding part, you can download the Jupyter Notebook file from the link provided in the description below. The strategy has a personal significance for the author, as they recall turning a small account into a considerable sum using this system when they first started trading as a hobby.

The concept behind the grid trading strategy is to create a grid of price levels on the chart. Whenever the price crosses these grid lines, we open both long and short positions. The take profit level is set at the next grid line for each position. As shown in a sample chart, the strategy involves opening the initial long and short positions, followed by closing the winning position at the next grid level. Then, two additional positions are opened, one long and one short, every time a grid line is crossed.

One challenge with this strategy is managing the losing trades that remain open on the edges of the grid. Some positions may never reach their take profit values, creating a difficulty in the system. Various approaches can be employed to handle this situation. Some traders may choose to close the remaining trades at the end of the trading day, while others may calculate if they are in an overall profit situation every few hours and close everything to start afresh with a new grid. The solution will depend on additional parameters, such as the time frame, maximum allowed number of parallel trades, and grid distance.

In the coding part, the author applies a stop loss value for each trade using the Average True Range (ATR). This stop loss value is calculated based on the grid distance initially, but then the ATR is used to refine it. The ATR takes into account the volatility of the market at the time of placing the trades. The author mentions that this might not be the best approach and encourages experimentation with different parameters to find the optimal scenario for the strategy.

The reason this system might work in many cases is that it takes advantage of market noise. As long as the market oscillates around the grid, the strategy benefits from price fluctuations and opens positions in both long and short directions. The system is expected to perform better on lower time frames, where there is more price oscillation and, therefore, potentially higher profits.

The strategy offers two advantages. First, it eliminates the need to guess the trend, as it does not follow any specific trend. Second, it simplifies the trading process by focusing on managing open losing trades. There is only one adjustable parameter in this strategy, which is the grid distance. However, choosing the appropriate time frame and grid distance for the specific asset being traded is crucial.

The Jupyter Notebook file provided demonstrates the implementation of the strategy in Python. The code imports various libraries, including yfinance for data retrieval, pandas and numpy for data manipulation, and pandas_ta for technical analysis functions such as computing the ATR. The data for the EUR/USD pair is downloaded using a specific timeframe.

The grid distance, take profit/stop loss ratio, and mid-price of the grid are defined as variables. The mid-price serves as the average price around which the grid is built. The generate_grid() function is defined to generate the grid levels based on the mid-price and grid distance. The function calculates the upper and lower levels of the grid using a loop.

Next, the strategy logic is implemented. The backtest starts by initializing variables such as the initial balance, position size, and stop loss level. A for loop is used to iterate through each bar in the historical data.

Inside the loop, the current price is checked to determine if it crosses any of the grid levels. If a cross occurs, new positions are opened in both the long and short directions. The take profit and stop loss levels are set based on the grid levels and stop loss distance.

The loop also checks if any open positions hit their take profit or stop loss levels. If a position reaches either level, it is closed, and the corresponding profit or loss is recorded.

At the end of the backtest, the equity curve is plotted, showing the growth of the account balance over time. The performance metrics, including the total profit, number of trades, win rate, and Sharpe ratio, are calculated and displayed.

It's important to note that while the grid trading strategy may have shown promising results in the backtest, it's essential to thoroughly evaluate and validate any trading strategy before deploying it in real trading. Backtesting helps assess the historical performance, but it does not guarantee future profitability.

To fully understand the implementation details and explore the code, I encourage you to download the Jupyter Notebook file provided in the description. The notebook contains the complete code with detailed comments to guide you through the process.

Remember that trading involves risk, and it's always recommended to consult with a professional financial advisor before making any investment decisions.

Hedging Strategy For Trading In Python
Hedging Strategy For Trading In Python
  • 2023.01.12
  • www.youtube.com
Welcome ! In this video we test the grid trading strategy, a simple approach that doesn't require any technical indicators. We use python to test and trade, ...
 

How To Build A Trading Bot In Python



How To Build A Trading Bot In Python

Hi, in this video, I'm going to show you how you can automate your trading strategy using Python. In other words, I'll guide you through the process of building your own free trading bot that can automatically execute trades on your behalf, following a specific strategy. The code I will be using is available for download from the link in the description below, so you can follow along with the video and then download the file to use it as you like.

What I'm going to demonstrate in this video can work for any trading strategy that can be implemented as a Python function. It can be an excellent way to test your strategy on live market data instead of simply backtesting it on past data. If you want to test your strategy on future or live data, you can utilize the techniques presented in this video.

Let's begin by opening our Jupyter Notebook file. First, I will download some historical data for testing purposes. It's important to note that we won't use this data for live trading; it's mainly for testing our signal functions. To download the data, I'm using the YFinance module and fetching the Euro to US Dollar exchange data between two specific dates, with a 15-minute timeframe.

One thing to keep in mind is that when downloading data for low timeframes like the 15-minute interval, Yahoo Finance only allows the last 60 days of data to be downloaded. So, we can't download more than 60 days at once, and these must be the last 60 days from the current date. If you encounter any issues with the downloaded file, please double-check the specified start and end dates.

Once we have downloaded the data, we can test it by checking the downloaded rows. By removing the '-1' in the code, we can view the entire data frame, which consists of around 3973 rows. The data frame includes columns for date, time, open, high, low, close, and adjusted close prices. In this video, we won't be using volume data, but feel free to incorporate it into your strategy if needed.

The next step is to define our signal generator, which is a function responsible for generating trading signals. This function takes a data frame as input because when we are streaming live data for our trading bot, we will acquire a data frame and feed it into this function. The function will then determine if there is a signal present, such as a buy signal, sell signal, or no clear pattern. In this example, we will be focusing on detecting engulfing candlestick patterns, but please note that this is not a complete trading strategy. It serves the purpose of this video, and you can insert your own signal generator strategy within this function.

The signal generator function reads the open and closing prices of the current candle and the previous candle by using the index -1 and -2, respectively. Based on the conditions defined in the function, such as detecting a bearish engulfing pattern or a bullish engulfing pattern, it returns a signal value of 1 for selling, 2 for buying, or 0 for no signal. To verify that the function is working correctly, we can test it using a few lines of code. By looping over the data frame rows and checking each row for engulfing patterns using the signal generator function, we can store the generated signals in a list. We can then add this list as an additional column in the testing data frame. Printing the data frame shows the added column, and by performing a value count, we can see the number of each signal type present in the data set.

Please note that this is a simplified example for the purpose of this video, and it's essential to develop a comprehensive trading strategy based on your specific needs.

Now that we have our signal generator function in place, the next step is to define the trading bot. The trading bot is responsible for executing the trades based on the generated signals. In this example, we'll create a simple trading bot that buys when it receives a signal value of 2 (indicating a buy signal) and sells when it receives a signal value of 1 (indicating a sell signal). Again, this is just a basic example, and you can modify the trading bot according to your specific trading strategy.

The trading bot function takes the data frame and the generated signals as input. It initializes the portfolio balance and holds a position flag to keep track of whether we currently have a position open or not. Then, it loops over each row of the data frame, checks the signal value, and performs the corresponding buy or sell action.

When a buy signal is received and we don't have an open position, the trading bot buys the specified amount of the asset and deducts the cost from the portfolio balance. It also sets the position flag to indicate that we now have an open position. When a sell signal is received and we have an open position, the trading bot sells the entire position and adds the selling amount to the portfolio balance. It then resets the position flag to indicate that we don't have any open positions.

To test the trading bot, we can call the function with the testing data frame and the generated signals. We can also specify an initial portfolio balance and the amount of the asset to buy or sell. After running the trading bot function, we can print the final portfolio balance to see the result.

In this example, we're not considering transaction costs, slippage, or other factors that may affect real trading scenarios. It's important to take these factors into account when developing your own trading bot and strategy.

Finally, let's discuss how you can implement this code for live trading. The code we've developed so far is suitable for backtesting and testing your strategy on historical data. To implement it for live trading, you would need to connect it to a real-time data feed and a trading API provided by your broker or exchange. This involves handling the data streaming and making real-time trading orders based on the signals generated by the trading bot.

There are various Python libraries and packages available that can assist you in connecting to real-time data feeds and trading APIs, such as Alpaca, Binance, or Interactive Brokers API. You would need to research and choose the one that best fits your requirements and integrates well with your chosen exchange or broker.

Remember, live trading involves real money, so it's crucial to thoroughly test your code and strategy in a simulated environment before deploying it for live trading. Start with small positions and gradually increase your exposure as you gain confidence in your trading bot's performance.

That's it for this video! I hope you found it helpful in understanding how to automate your trading strategy using Python. Remember to download the code from the link in the description and modify it according to your specific needs and strategy. If you have any questions, feel free to leave them in the comments below. Thanks for watching, and happy trading!

How To Build A Trading Bot In Python
How To Build A Trading Bot In Python
  • 2022.12.08
  • www.youtube.com
This video shows how to use APIs in python to build a live trading bot. The market is scanned by the bot and the prices are downloaded for analysis. A simple...
 

Python Backtest: Profitable Scalping Strategy with VWAP, Bollinger Bands and RSI Indicators



Python Backtest: Profitable Scalping Strategy with VWAP, Bollinger Bands and RSI Indicators

Hello everyone! Today, I am excited to announce that we have a winner. In this video, I will be sharing a scalping strategy using V-WAP (Volume Weighted Average Price) Bollinger Bands and RSI (Relative Strength Index) for confirmation. Before sharing this strategy, I thoroughly backtested it to ensure its effectiveness.

Firstly, I want to mention that this is the first scalping strategy we are showcasing on this channel. Scalping can be challenging for algorithms due to the noisy data on lower time frames. However, I believe this strategy overcomes those challenges.

If you are new to this channel, you can download the Python code from the link in the description. Don't forget to support us by subscribing and dropping a comment with your ideas to be shared. Your feedback is valuable.

After three years of backtesting, the total return for this strategy is approximately 300 percent. What I particularly like about this strategy is its average trade duration, which is around 51 minutes. This makes it the fastest trade closing strategy we have demonstrated so far. The benefit of quick trade closure is reduced overnight fees and less stress, as you can immediately see the results of your executed trades.

In the comments section, someone asked about the Sharpe ratio. I have included it in this strategy, and it is approximately 1.65. However, please note that this value may change with modifications to the parameters in the Python code. You can maximize the Sharpe ratio by experimenting with different parameter values.

Let's dive into the details of the strategy. I am using the 5-minute timeframe and V-WAP curve. To determine the trend, I look for 15 candles to be consistently above or below the V-WAP curve, represented by the blue line. If 15 candles are above the V-WAP curve, it indicates an uptrend. If we are below the V-WAP curve, I consider it a downtrend.

For entry positions, I use Bollinger Bands with a length of 14 and a standard deviation of 2. In an uptrend above the V-WAP curve, I look for buying positions when a candle closes below the lower Bollinger Band. In a downtrend, below the V-WAP curve, I wait for a candle to close above the upper Bollinger Band as a selling signal.

To confirm the signals, I use the RSI. If the RSI is below 45, it confirms a buy signal. If the RSI is above 55, it confirms a selling signal.

For setting the take profit and stop loss levels, I utilize the ATR (Average True Range). I look back at the last seven candles, calculate the ATR value, and multiply it by a coefficient to determine the stop loss distance. The take profit is calculated by multiplying the stop loss distance with the take profit-stop loss ratio, which represents the risk-reward ratio.

As you can see, there are several parameters that can be tuned in the Python code. You can modify the ATR length, coefficient, take profit-stop loss ratio, and other indicator parameters to see how they affect the strategy's performance over the three-year backtesting period. Feel free to download the code and experiment on your own.

In the Python code, I have provided all the necessary steps for data loading, cleaning, adding technical indicators (V-WAP, RSI, Bollinger Bands), computing the total signal, and visualizing the signals on the price chart. The code also includes the backtesting part, where I compute the ATR, set the stop loss and take profit levels, and execute the trades.

In the backtesting results, I achieved a return of 197 percent and a peak equity of $313. Starting with an initial capital of $10,000, the strategy generated a profit of $19,700, reaching a final equity of $29,700.

Now, let's discuss the key performance metrics of this strategy. The win rate, which represents the percentage of profitable trades, is approximately 56%. This means that out of all the trades executed, 56% resulted in a profit. The average profit per trade is around $33.10, while the average loss per trade is approximately $23.45.

To assess the risk associated with this strategy, we can look at the maximum drawdown, which measures the largest peak-to-trough decline in equity during the backtesting period. The maximum drawdown for this strategy is approximately 9%, indicating a moderate level of risk.

It's important to note that these performance metrics are based on historical data and past performance does not guarantee future results. Market conditions can change, and it's crucial to continuously monitor and adapt the strategy to current market dynamics.

In summary, this scalping strategy utilizing V-WAP, Bollinger Bands, and RSI has shown promising results during the backtesting period, with a total return of 300% and an average trade duration of 51 minutes. However, it's essential to thoroughly test and validate any strategy before applying it to real trading, and consider factors such as transaction costs, slippage, and market conditions.

Remember, trading involves inherent risks, and it's always recommended to educate yourself, practice risk management, and consider seeking professional advice before engaging in live trading. I hope you find this strategy insightful, and feel free to download the Python code provided in the description to further explore and customize it to your liking.

If you have any questions or need further clarification, please don't hesitate to ask. Happy trading!

Python Backtest: Profitable Scalping Strategy with VWAP, Bollinger Bands and RSI Indicators
Python Backtest: Profitable Scalping Strategy with VWAP, Bollinger Bands and RSI Indicators
  • 2022.10.13
  • www.youtube.com
This video shows a profitable scalping strategy fully backtested in python, this strategy uses the VWAP, Bollinger Bands and the RSI indicators for confirmat...
 

Heiken Ashi Candles In Python For Trading Systems


Heiken Ashi Candles In Python For Trading Systems

Today, we will delve into the process of adding Hiken Ashi candles in Python and explore two related strategies using these candles. Hiken Ashi candles are derived from normal candlesticks typically used in trading. Each Hiken Ashi candle is calculated using specific formulas. The Heiken Ashi closing price is obtained by averaging the open price, high, low, and closing price of the current candle. The Heiken Ashi open price is obtained from the closing value of the previously calculated Heiken Ashi candle. The Heiken Ashi high value is the maximum among the high of the normal candlestick, the open of the Heiken Ashi candle, or the closing value of the Heiken Ashi candle. Similarly, the Heiken Ashi low value is the minimum among the lowest price of the current candle, the open price of the current Heiken Ashi candle, or the closing price of the current Heiken Ashi candle.

In summary, apart from the high and low values, the Heiken Ashi candle is composed of averaged values, giving the Hiken Ashi chart a smoother appearance compared to normal candles, which some traders may find less noisy. However, it's important to note that Heiken Ashi candles are not the real values of the market and should not be used for trading or backtesting strategies based on the actual market values.

The purpose of this tutorial is not to present a winning Heiken Ashi system but rather to demonstrate how to build these candles in Python and develop an algorithmic strategy to backtest the results. We will explore two strategies using Heiken Ashi candles.

The first strategy utilizes two moving averages: a fast moving average and a slow moving average. The trend is determined based on the relative positions of these moving averages. If the fast moving average is above the slow moving average, it indicates an uptrend, and if the fast moving average is below the slow moving average, it suggests a downtrend. The strategy generates a trading signal when the Heiken Ashi candle crosses the fast moving average in the trend direction. For example, if the fast moving average is below the slow moving average, and a Heiken Ashi candle crosses from above to below the fast moving average, it triggers a selling signal. Conversely, in an uptrend, a green Heiken Ashi candle crossing from below to above the fast moving average triggers a buying signal.

The second variation of this strategy adds an additional condition. It looks for a doji candle followed by a short-tailed candle in the direction of the trend. For example, in a downtrend, if a doji candle is followed by a short-tailed candle opening above the fast moving average and closing below it, a selling signal is triggered. The absence of long wicks or tails in these candles indicates strong downward or upward momentum, depending on the trend being analyzed.

Both strategies have their own challenges, such as determining the optimal time frame, defining the appropriate stop-loss positions, and designing effective exit strategies. These aspects can significantly impact the profitability and success of the strategies.

To implement these strategies in Python, we will use Jupyter Notebook. We start by importing the necessary libraries and downloading the stock data for the Russell 1000 index from 2012 to 2022. After removing unnecessary columns, we compute the Hiken Ashi closing and opening prices, as well as the Heiken Ashi high and low values, based on the formulas described earlier. We add these columns to our data frame.

Next, we can add additional technical indicators, such as moving averages and the Relative Strength Index (RSI), using the pandas technical analysis package. This allows us to visualize the Heiken Ashi candles and the associated indicators on a chart. Now that we have our trading signals and stop loss levels defined, we can proceed with the backtesting process. The next step is to compute the returns for each trade based on the entry and exit points.

To calculate the returns, we first need to determine the entry and exit prices for each trade. For a buying position, the entry price is the closing price of the candle when the buying signal is triggered. The exit price is the lowest price between the current candle and the previous two candles, as determined by the stop loss level.

Similarly, for a selling position, the entry price is the closing price of the candle when the selling signal is triggered, and the exit price is the highest price between the current candle and the previous two candles.

Once we have the entry and exit prices, we can compute the returns using the formula:

Return = (Exit Price - Entry Price) / Entry Price

We will store the returns in a list called "trade_returns" for further analysis. Next, we need to calculate the cumulative returns to track the overall performance of the strategy over time. This is done by multiplying each trade's return with the previous cumulative return and adding 1. The formula for calculating the cumulative return is:

Cumulative Return = Cumulative Return * (1 + Return)

We will store the cumulative returns in a list called "cumulative_returns." Finally, we can plot the cumulative returns to visualize the performance of the strategy over the backtesting period.

After performing the backtesting process and calculating the trade returns and cumulative returns, we can analyze the results to evaluate the performance of the trading strategy. One important metric to consider is the overall profitability of the strategy. You can calculate the total return by subtracting 1 from the final cumulative return value. For example, if the cumulative return is 1.2, it means a 20% return on the initial investment.

Additionally, you may want to calculate other performance metrics such as the average return per trade, the number of winning trades, the number of losing trades, the percentage of winning trades, and the maximum drawdown. The average return per trade can be obtained by dividing the sum of all trade returns by the total number of trades. This metric provides an indication of the average profitability of each trade.

To calculate the number of winning and losing trades, you can count the number of trade returns that are greater than or equal to 0 (winning trades) and the number of trade returns that are less than 0 (losing trades). The percentage of winning trades can be calculated by dividing the number of winning trades by the total number of trades and multiplying by 100.

The maximum drawdown measures the largest peak-to-trough decline in the cumulative returns during the backtesting period. It provides insight into the potential risk and downside volatility of the strategy. By analyzing these performance metrics, you can gain valuable insights into the effectiveness of the trading strategy and make informed decisions regarding its future use or potential modifications.

Remember that backtesting is a historical simulation and does not guarantee future results. It's essential to consider various factors and conduct thorough analysis before applying a trading strategy in real-world scenarios.

Heiken Ashi Candles In Python For Trading Systems
Heiken Ashi Candles In Python For Trading Systems
  • 2022.09.24
  • www.youtube.com
Heiken Ashi candlesticks are popular candlestick in technical analysis. In this video, I will show you how to use Heiken Ashi candles for trading systems in ...
 

Revolutionize Your Stock Trading Strategy with Automated Trading in Python



Revolutionize Your Stock Trading Strategy with Automated Trading in Python

Today, we will explore a trading strategy specifically designed for long positions using the Relative Strength Index (RSI) and Average Directional Index (ADX). Despite its simplicity, this strategy has shown promising results. The idea was proposed by someone in the comments section, and the parameters seemed both familiar and convincing. So, I decided to put it to the test and share the outcomes, which turned out to be quite satisfying.

The equity curve generated by the backtest exhibited a nearly consistent increase throughout the testing period, reaching a peak return of 360. If you're new to this channel, you can find the code available for download in the description. Don't forget to support us by subscribing and leaving a comment. We appreciate hearing new ideas, just like the one this video is all about.

Now, let's dive into the strategy itself. We'll be using the daily timeframe and entering a long position when two conditions are met: First, when the two-day RSI is below 25, indicating an oversold condition, and second, when the ADX (14) is above 20, suggesting a trending market. We exit the long position when the RSI crosses above 75.

To avoid false signals and prevent trades from remaining open for too long when the RSI struggles below the 75 threshold, I added two additional conditions. The first condition involves checking if the candles are trading above a simple moving average curve, indicating an uptrend. Only in this case are we allowed to take long positions. The second condition involves setting a stop-loss value, which is taken as the lowest price among the last two candles minus a certain percentage. In this backtest, I set the stop-loss percentage to two percent. You can adjust this value based on your preferences or when testing with different data.

To implement these conditions in Python, I wrote the necessary code and conducted a backtest. In the code, we load the data, clean it by removing days with no movements, and print the data frame to verify its contents. Then, we calculate the exponential moving average (EMA) with a length of 200 for trend detection, as well as the RSI with a length of 2 and the ADX with a length of 14. We clean the data frame again and print a slice to check the columns we'll be using.

Next, I implemented a function called add_ema_signal, which determines the trend based on the number of candles trading above or below the moving average curve. I set this number to six, as it has worked well in previous videos. Then, I created a function called total_signal, where we compute the signal for entering a long position. We iterate through each row of the data frame and check if the RSI is below or equal to 25, the ADX is above 20, and the EMA signal is equal to two (indicating an uptrend). When these conditions are met, we store a signal value of two in the data frame.

By printing the data frame, we can visualize the signals on the bar chart. The purple points represent the buy signals. Although I won't go into the details of every line in the code, you can find comprehensive explanations in previous videos on this channel, specifically in the Python for Algorithmic Trading playlist.

Moving on to the backtesting part, I utilized the backtesting.py package. Without going into the specifics, I set the stop-loss percentage to 2% and included additional conditions to close trades that have been open for a certain number of days or if the RSI exceeds 75. It's worth noting that the code still contains lines related to short positions, even though this strategy focuses solely on long positions. These lines can be modified or removed if you decide to expand the strategy to include short positions.

If the signal equals two and there are no open trades, we enter the market with a long position using the stop-loss value. The trade size is set to 99% of the current equity. The backtest starts with $1,000 in cash and a leverage of 1:5 (margin of 1/5). No commissions were considered for the sake of comparison with previous strategies.

The backtest results indicate a return of $200 and a peak equity of $3,595. The win rate is 73%, and a total of 102 trades were executed over the ten-year testing period. This translates to an average of 10 trades per year on the daily timeframe. Plotting the equity curve shows a consistent increase in value, with minor drawdowns during certain periods.

It's important to note that I didn't modify any of the suggested parameters in the comments section. The RSI length remains at 2, ADX length at 14, and the EMA length at 200. However, you can still fine-tune these values and experiment with different stocks or markets to potentially improve the results and find a more satisfying configuration.

This strategy offers a simple yet effective approach for long positions. I encourage you to download the code from the link in the description and experiment with it. The code is relatively short and beginner-friendly. Enjoy exploring this strategy and stay tuned for our next video. Trade safe, and see you next time!

Revolutionize Your Stock Trading Strategy with Automated Trading in Python
Revolutionize Your Stock Trading Strategy with Automated Trading in Python
  • 2022.09.08
  • www.youtube.com
This video tests an automated trading strategy backtest for long positions on stocks, the rules are simple using RSI and the ADX indicators on stock market v...
 

Automated Rayner Teo Bollinger Bands Strategy Optimized For High Return



Automated Rayner Teo Bollinger Bands Strategy Optimized For High Return

Hello everyone! In this video, we are excited to present an extreme optimization approach that demonstrates the effects of certain parameters on our trading system. We believe this is the best optimization we have achieved so far. As you can see, we have achieved an impressive return of around three thousand percent, with a consistently increasing equity curve. The details of the trades are also displayed on the graph, and we will explain them in this video. We have plotted all the trades on the price charts, and we will walk through them as well. So, stay tuned!

Before we proceed, we want to emphasize that the way we have achieved a 30,000 percent return with this strategy is not the safest approach for real trading. We do not recommend using these parameters in an actual trading scenario. However, we believe that the strategy itself is solid and has great potential. If you are new here, the strategy relies on the Rhino Theo Bollinger Band strategy for trending markets. We have previously tested it in a video with excellent results and minimal risk. If you haven't seen it, you can find the link to the first backtest video in the description, along with the Python code if needed.

In this video, we will attempt to apply extreme parameters to generate relatively large returns. We do this mainly for the fun of testing and playing around with the Python code. Additionally, we hope to gain valuable insights during the process and potentially discover a setup that could lead to realistic high returns.

Now, let's jump into the code and see how it all unfolds. The first cell of our Jupyter notebook file is dedicated to loading the data. We are using the "yfinance" module, which is a convenient way to load daily historical data from databases. With just a single line of code, we can load the data for a specific stock, such as the Russell 1000 index between 2011 and 2021, as an example. We clean the data by removing days with no price movements, such as weekends and holidays. Then, we reset the index and print the head of the data frame to verify that the data is correctly formatted.

Next, we utilize the "pandas_ta" (pandas technical analysis) module to compute various technical indicators. In this case, we calculate two moving averages: the 200-day exponential moving average (EMA) and the 150-day simple moving average (SMA). By comparing the fast moving average (EMA2) with the slower moving average (EMA), we can determine whether the market is in an uptrend or downtrend. We also calculate the 12-day relative strength index (RSI) using the same module. Additionally, we modify the parameters of the Bollinger Bands by setting the length to 14 (instead of 20) and the standard deviation to 2.0 (instead of 2.5). These modifications aim to make the system less selective, resulting in more frequent trading signals and a higher number of trades during the backtest.

Instead of using the RDMI signal or the exponential moving average signal discussed in the previous videos, we employ the two EMA signal. This means we consider two moving averages, one faster and one slower. If the fast moving average is above the slow moving average, we identify an uptrend. Conversely, if the fast moving average is below the slow moving average, we recognize a downtrend. We add this signal, referred to as the EMA signal, as a new column in our data frame.

The function for generating the trading signals is similar to the previous videos. We check if the closing price is below the lower Bollinger Band and if the EMA signal indicates an uptrend (equal to 2), which triggers a buying signal.

In this video, the presenter demonstrates an extreme optimization approach to showcase the effects of various parameters on a trading system. The goal is to achieve high returns by applying extreme parameters, although it's important to note that these parameters are not recommended for real trading due to their associated risks. However, the presenter believes that the strategy itself has great potential if used with caution.

The strategy being employed is based on the Rhino Theo Bollinger Band strategy for trending markets. The presenter refers to a previous video where they tested this strategy with excellent results and relatively low risk. The first step in the optimization process is to load the necessary data using the Y Finance module. The presenter loads the Russell 1000 index data from 2011 to 2021, covering a period of 10 years.

Once the data is loaded, the presenter cleans it by removing days with no price movements, such as weekends and holidays. The data is then prepared by calculating technical indicators using the pandas_ta (pandas technical analysis) module. Two moving averages are calculated: a 200-day exponential moving average (EMA) and a 150-day simple moving average (SMA). These moving averages help determine the trend: if the faster EMA is above the slower SMA, it indicates an uptrend, and vice versa.

The presenter also calculates the 12-day Relative Strength Index (RSI) using the pandas_ta module. Additionally, the length and standard deviation parameters of the Bollinger Bands are modified. Instead of using a length of 20 and a standard deviation of 2.5 as in previous videos, the presenter uses a length of 14 and a standard deviation of 2.0. This modification aims to make the system less selective, resulting in more frequent trading signals.

Instead of using the RSI or EMA signals as in the previous videos, the presenter introduces a new signal called EMA signal. It is based on the relationship between the two moving averages: if the faster EMA is above the slower SMA, the EMA signal is set to 2, indicating an uptrend. If the faster EMA is below the slower SMA, the EMA signal is set to 1, indicating a downtrend.

The entry strategy is similar to the previous videos. The presenter checks if the closing price is below the lower Bollinger Band and if the EMA signal indicates an uptrend (EMA signal = 2). In this case, a buying signal is generated at the closing price of the current candle. If the closing price is above the upper Bollinger Band and the EMA signal indicates a downtrend (EMA signal = 1), a selling signal is generated at the closing price of the current candle.

To exit trades, the presenter introduces additional criteria. A trade is closed if it has been open for more than 10 days, as longer-term trades are not desired. Additionally, a trade is closed if it is a long trade and the RSI goes above 75, or if it is a short trade and the RSI goes below 25. If the RSI condition alone is not sufficient to trigger an exit, a stop-loss mechanism is implemented.

The stop-loss is calculated as the minimum value between the current low of the candle and the low of the previous candle, multiplied by (1 - a certain percentage). The percentage is determined by the user and represents the allowable loss before triggering the stop-loss. For example, a percentage of 2 means that the stop-loss is set 2% below the lowest point between the last two candles. Additionally, a take-profit level is set at twice the distance of the stop-loss.

The presenter evaluates the strategy by running a backtest using the optimized parameters. They plot the trades on the price chart and provide detailed explanations for each trade. The backtest results show an impressive return of around three thousand percent, with a consistently increasing equity curve.

Finally, the presenter emphasizes that while this extreme optimization approach yields high returns in the backtest, it is not recommended for real trading due to the associated risks. The purpose of this exercise is to explore the effects of different parameters and gain insights into the strategy's behavior.

Automated Rayner Teo Bollinger Bands Strategy Optimized For High Return
Automated Rayner Teo Bollinger Bands Strategy Optimized For High Return
  • 2022.07.22
  • www.youtube.com
This video is a continuation of the previous 2 videos describing the Rayner Teo Bollinger Bands Strategy. Here we present an optimized version leading to hig...
 

Optimizing Rayner Teo's Bollinger Bands Strategy for Better Results



Optimizing Rayner Teo's Bollinger Bands Strategy for Better Results

Today, we are diving into the optimization of the Reiner Theo Bollinger Band strategy that was previously backtested in a video. If you haven't watched the previous video, it is recommended to do so before proceeding with this optimization part. The video provides a link in the description for easy access. Additionally, for those interested in the coding aspect, the Python code is available for download via a link in the description as well.

The strategy being optimized has shown promising potential with a win rate of 91% and a consistently increasing equity curve over a 10-year backtest. However, one of the motivations behind this optimization is the low number of trades observed during the backtest. Over the course of 10 years, only 23 trades were executed, averaging around two trades per year. To address this, two potential solutions are presented. The first involves running the program on multiple stocks simultaneously, aiming for around 20 trades per year. However, this approach raises concerns about correlated markets and other related issues. The second solution involves lowering the time frame to increase the number of trades.

The strategy incorporates several technical indicators for generating entry and exit signals. It utilizes a moving average indicator (referred to as EMA, Exponential Moving Average, in the code) and Bollinger Bands for entry signals, while the Relative Strength Index (RSI) is used for exit signals. The video provides further details on the execution process, which are not reiterated here.

Moving on to the program itself, the data is loaded in the first cell, focusing on the four-hour time frame for analysis. Two different stocks are used for the optimization. The data is cleansed by removing candlesticks with no movement, where the high and low prices are equal. Technical indicators such as the moving average (either exponential or simple) and the RSI are added, and their lengths can be modified. In this particular case, the moving average length is set to 900 candles, and the RSI length is set to 12. For daily charts, a 200-day EMA and a 2-day RSI are used for exit signals. The Bollinger Bands parameters remain the same as the daily charts, with a length of 20 and a standard deviation of 2.5.

The program also includes a check for whether the candles are trading above or below the moving average. In this case, the number is set to six, representing six consecutive candles above or below the moving average curve. Since we are working with a four-hour time frame, six times four equals 24 hours. Hence, if the price has been trading above or below the moving average for 24 hours straight, an uptrend or a downtrend can be concluded. The parameter for the percentage position of the order on the market is set to zero percent to increase the number of executed trades.

The visualization part of the program displays the Bollinger Bands, the moving average curve, and the trend direction, which is determined as an uptrend. Entry signals are represented by purple points on the chart, indicating buying signals. The video showcases some of these entry points, emphasizing their effectiveness in trendy markets. By selecting different random positions within the chart, various entry points can be examined, allowing for analysis of their viability.

The presenter points out that the Bollinger Band parameters related to entry signals are working well, so there is no need for modification at this point. The focus for optimization lies in other parts of the algorithm. While the video does not delve into all the details of the backtesting process, certain parameters are worth noting.

In this optimization process, the RSI threshold for exit is set to 45. This lower threshold value aims to capture shorter and more frequent trades by allowing for quicker exits. The presenter mentions that the choice of RSI threshold is subjective and can be adjusted based on individual preferences and risk tolerance.

To evaluate the performance of the strategy, the program calculates various metrics, including the total number of trades, the win rate, the average trade duration, and the equity curve. These metrics provide insights into the effectiveness and profitability of the strategy.

The optimization process involves adjusting the parameters of the strategy to find the optimal combination that maximizes the number of trades while maintaining a high win rate. The parameters that are being optimized include the moving average length, the RSI length, and the RSI exit threshold.

The video demonstrates how to use a nested loop to iterate through different parameter combinations and evaluate the strategy's performance for each combination. The program keeps track of the best-performing parameter combination and displays the corresponding metrics and equity curve.

By running the optimization process, the presenter finds that using a moving average length of 700, an RSI length of 4, and an RSI exit threshold of 45 yields the best results. These parameter values increase the number of trades while still maintaining a high win rate. The video showcases the equity curve generated by the optimized strategy, which exhibits a smoother upward trajectory with more frequent trades compared to the original version.

The presenter concludes by highlighting the importance of optimization in improving the performance of trading strategies. Through systematic testing and adjustment of parameters, it is possible to enhance the profitability and efficiency of a strategy. However, it is crucial to exercise caution and consider the limitations and risks associated with optimization, such as overfitting to historical data.

It is important to note that the details provided here are a summary of the video, and for a more comprehensive understanding, it is recommended to watch the original video, which includes visual demonstrations and further explanations of the optimization process.

Optimizing Rayner Teo's Bollinger Bands Strategy for Better Results
Optimizing Rayner Teo's Bollinger Bands Strategy for Better Results
  • 2022.07.08
  • www.youtube.com
This is a continuation of the previous video on the Bollinger Bands Winning Trading Strategy published by Rayner Teo. The backtest optimization is done in Py...
Reason: