Python in algorithmic trading - page 20

 

How To Code A Trail Stop In Python Strategy Backtesting



How To Code A Trail Stop In Python Strategy Backtesting

Today, I have an exciting coding tutorial for you in Python. We will be learning how to implement a trailing stop in our trading strategy and analyze its impact on our equity and returns. If you are new to this channel, I recommend watching the previous videos in this playlist, particularly the last two or three, where we discussed the strategy in detail. You can also find the Python code in the Jupiter notebook, which is available for download from the link in the description. This will allow you to fine-tune the parameters and experiment on your own.

Before we dive into the coding part, let's briefly recap the strategy we will be using. In a nutshell, we have automated the detection of support and resistance levels, as well as the identification of candlestick patterns occurring around these levels. Based on these signals, we will execute our trading orders. For instance, if we identify a buying signal, such as a bullish engulfing pattern preceded by a strong rejection candle, we will enter a long position. To manage the risk, we need to set a stop-loss order, which determines the maximum loss we are willing to tolerate. Traditionally, the stop-loss is fixed at a certain distance from the entry price. However, in this tutorial, we will replace it with a trailing stop.

A trailing stop follows the price movement in the profitable direction, allowing us to capture more gains during an uptrend. In our example, since we are in a buying position, the trailing stop will trail along with the price as it rises, maintaining a certain distance behind it. However, if the price attempts to reverse and reaches the stop-loss level, our trade will be closed to prevent further losses. This trailing stop mechanism helps maximize profits, especially during prolonged price trends, instead of using a fixed take-profit level that might limit our potential gains.

Now, let's apply this concept to our previously discussed strategy. We will use the same program we detailed before. If you're not familiar with it, please refer to the playlist and watch the last two or three videos, which cover candlestick patterns and the automation of support and resistance levels detection. The only difference this time is that instead of using a fixed stop-loss or take-profit ratio, we will implement the trailing stop. Towards the end of this tutorial, I will backtest the strategy and demonstrate the potential returns achievable with this trailing stop method.

To begin, we load our data, which is the daily candlestick chart for the EUR/USD currency pair from 2003 to 2021. We have a set of functions that help detect support and resistance levels, as well as various candlestick patterns like engulfing patterns, shooting stars, and rejection patterns. If you're interested in the implementation details of these functions, please refer to the previous videos.

Next, we generate our trading signals. A buying signal is denoted by a value of 2, a selling signal by 1, and if there is no signal, the value is set to 0. This information is added as a new column in our data frame. Here's how our data frame looks now, with columns for the opening price, high, low, closing price, volume (which we won't use in this strategy), and the signal column.

To backtest our strategy, we will utilize the backtesting package introduced in the last video of this playlist. We define a class called "MyCandleStrategy" that inherits from the "Strategy" class provided by the backtesting package. We override two functions: "initialize" and the next function called at each candlestick. In the initialize function, we define the variable "stop_loss_trail," which represents the distance (in pips) for our trailing stop. This value can be experimented with to find the optimal trailing stop value for our strategy.

In the next function, we implement the logic for our trailing stop. We start by checking if we have an open position. If we do, we calculate the current stop-loss level by subtracting the trailing stop value from the highest price since we entered the position. This ensures that the stop-loss level trails behind the price as it rises. We then check if the current price has reached or fallen below the stop-loss level. If it has, we close the position and update our trading statistics.

Now that we have implemented the trailing stop logic, we can proceed with running the backtest and analyzing the results. Here's an example of how to run the backtest and print the equity curve: This will generate a plot showing the equity curve of our strategy with the trailing stop applied. You can also access other performance metrics and statistics provided by the backtesting package to evaluate the strategy's performance.

Finally, to fine-tune the trailing stop value, you can iterate over a range of values and run multiple backtests to compare the results. This will help you find the optimal trailing stop value that maximizes your returns.

That concludes our tutorial on implementing a trailing stop in our trading strategy. Remember to experiment with different values and test the strategy thoroughly before applying it to real trading. If you have any questions or need further assistance, feel free to ask. Happy coding and happy trading!

How To Code A Trail Stop In Python Strategy Backtesting
How To Code A Trail Stop In Python Strategy Backtesting
  • 2021.10.22
  • www.youtube.com
Trailing stop, or stop loss strategy is presented and coded in python for algorithmic trading methods. The strategy is Backtested showing high profitability...
 

How To Backtest A Trading Strategy in Python



How To Backtest A Trading Strategy in Python

Hello, everyone, and welcome back to another video. Today, I would like to discuss a topic that is very important for our trading strategies, which is backtesting. So far, we have presented different strategies and relied only on statistical counts to check the reliability of our model's estimations for trading. However, backtesting our strategy brings additional information, which is the amount of profit that can be made within a certain time.

This profit percentage is important to define if you are considering any kind of investment in your strategy. Before we continue, as usual, the code is a Jupyter Python notebook that you can download from the link in the description of this video. This topic was proposed by one of your messages, so thank you again for sharing your thoughts. We are getting really interesting ideas from your feedback, and I apologize if I didn't have the time to discuss all the proposed ideas, but I'm keeping a list, and I think we are going to cover them in the future.

Now, let's talk about backtesting tools. There are many available libraries online, but I personally prefer to code my own functions. This way, I know exactly what is happening inside my code, especially when it comes to backtesting. We need something reliable and robust. However, among the proposed packages, I had two choices. One was using a package called "vectorbt," which I found a bit difficult to learn within a couple of hours and start using it for my own strategies. The documentation was scarce, and I had to search through forums and online examples to find many details. Although it has a huge potential and offers many options, I didn't want to spend a month getting familiar with the necessary functions just for the sake of testing one simple strategy.

So, for this video, I went with the second choice, which is a package called "backtesting.py." In my opinion, it offers a simpler approach. Now, let's jump into it and see how much money our strategy would have made. For this example, I'm going to test the previous strategy we discussed in the resistance and support automated detection and candlestick patterns detection video. These are two indicators that we will combine and use in this video.

First, I'll load and clean the data. Then, I'll apply the support and resistance functions for detection. If this is your first time watching on this channel, I recommend going back and checking the previous videos on how to detect support and resistance functions, as well as the one where we explain how to detect engulfing patterns, shooting stars, hanging man, and other candlestick patterns.

Next, we compute our signal, whether it's a buying signal, selling signal, or no signal at all, based on the approach mentioned earlier. We label both our signals and fill one column in our data frame. We can check the number of signals we obtained just to ensure that our functions are working properly.

Now, I'll change the column titles to make them compatible with the backtesting.py package. This step is case-sensitive, so we need to ensure the names match exactly. Then, I select a series of rows to work with.

After setting up our data frame, we move on to the most interesting part: defining our strategy and backtesting it. I'll import the required libraries, including the "strategy" module, and remove the example on crossover of slow versus fast moving averages.

Next, I define a new class called "MyCandlesStrategy" that extends the "Strategy" class and overrides its two abstract methods: __init__ and next. The __init__ method is used to initialize the first variables or functions at the beginning of the strategy. It's run only once, ideally to pre-compute any indicators and signals the strategy depends on.

Overall, backtesting is a crucial aspect of trading strategies, as it provides valuable information about the potential profitability of a strategy over a specific time period. In this video, we will delve into backtesting and its significance for our trading strategies.

Before we proceed, as usual, the code for this discussion is available as a Jupyter Python notebook, which you can download from the link provided in the video description. The topic of backtesting was suggested by one of our viewers, and I appreciate the interesting ideas and feedback I receive from all of you. Although I may not have the opportunity to discuss all the proposed ideas immediately, I maintain a list and strive to cover them in future videos.

When it comes to backtesting tools, there are numerous libraries available online. While I am not familiar with all of them, personally, I prefer coding my own functions. This approach allows me to have complete control and understanding of the code's inner workings, which is particularly crucial for backtesting. We need a robust and reliable solution for assessing our trading models.

Among the suggested packages, I had two options. The first was a package called "Vectorbt," which, although powerful and feature-rich, had a steep learning curve. The documentation for this package was somewhat limited, and I had to search through forums and online examples to gather the necessary information. While Vectorbt has immense potential, I didn't want to spend excessive time familiarizing myself with its functions solely for the purpose of testing a simple strategy in this video.

Therefore, I opted for the second choice, a package called "backtesting.py." In my opinion, this package offers a simpler approach to backtesting, making it more suitable for our needs. With that said, let's dive into it and see how much profit our strategy would have generated.

In this example, I will test the previous strategy we discussed, which involved automated detection of resistance and support levels, as well as candlestick pattern detection. These two indicators will be combined to form our strategy. For a detailed explanation of detecting support and resistance levels and candlestick patterns, I encourage you to watch the corresponding videos on our channel.

To begin, we load and clean the data as usual. Next, we implement the support and resistance functions for detection. If you are new to this channel, I recommend checking out the previous videos on support and resistance detection and candlestick pattern identification for a better understanding.

Once we have computed our signals, which determine whether it is a buying, selling, or no signal situation, we count the number of signals to ensure our functions are working correctly.

Moving forward, we need to adjust the column names in our DataFrame to be compatible with the "backtesting.py" package. It is essential to respect the case sensitivity and naming conventions required by the package. Additionally, we select a series of rows and make the necessary column changes.

To summarize, our DataFrame contains the following columns: time, opening, high, low, and closing prices, as well as volume (which we won't use at the moment), and the signal column that we computed earlier.

Next, we define a signal function that returns the signal column from our DataFrame. This function will be needed later when we define our strategy class.

Now we reach the most interesting part, where we define our strategy and perform backtesting. To accomplish this, we follow the guidelines provided in the backtesting.py documentation. They suggest that a new strategy should extend the Strategy class and override its two abstract methods: init and next.

The init method is responsible for initializing the variables and functions required by the strategy. It is invoked before the strategy is run and is typically used to pre-compute any indicators or signals that the strategy relies on. By overloading this function, we can define the necessary indicators using regular Python functions and examples provided in the backtesting.py documentation.

In our init method, we define the necessary indicators for our strategy. In this case, we will use the signal function we created earlier to obtain the signal column from our DataFrame. We also set the commission fee to zero, as we won't consider any trading fees for this example.

The next method is the heart of our strategy. It is called for each trading bar and is responsible for making the trading decisions based on the current market conditions. In our implementation, we check if there is a buy signal (signal equals 1) and we don't currently have a position. If these conditions are met, we enter a long position (buy).

Similarly, if there is a sell signal (signal equals -1) and we have a long position, we exit the position (sell). We don't consider short positions in this example, so we only have buy and sell signals.

Once we have defined our strategy, we create an instance of it and pass our DataFrame and signal function as arguments. We then create an instance of the Backtest class from the backtesting.py package, passing our strategy instance and DataFrame as arguments.

Finally, we run the backtest by calling the run method on our Backtest instance. This method executes the strategy and produces the results.

The results include various performance metrics such as total return, annualized return, maximum drawdown, and more. We can access these metrics using the corresponding attributes of the Backtest instance.

In addition to the performance metrics, the Backtest instance provides various plotting functions to visualize the results. We can plot the equity curve, which shows the growth of the trading account over time, as well as other useful plots such as drawdowns and trade log.

In our example, we plot the equity curve and print the summary of the backtest results, including the performance metrics.

After running the code, we can observe the equity curve plot, which shows the growth of our trading account over time. The summary of the backtest results provides valuable information about the performance of our strategy.

By backtesting our strategy, we can assess its profitability and evaluate its performance. This process allows us to gain insights into the effectiveness of our trading model and make informed decisions about its potential use in real trading scenarios.

That concludes our discussion on backtesting using the backtesting.py package. I hope you found this video informative and that it provided you with a practical approach to backtesting your trading strategies. Remember to experiment with different strategies, indicators, and parameters to find the ones that work best for your trading goals.

As always, feel free to leave comments, questions, or suggestions for future videos. Your feedback is highly appreciated. Thank you for watching, and I'll see you in the next video!

How To Backtest A Trading Strategy in Python
How To Backtest A Trading Strategy in Python
  • 2021.10.07
  • www.youtube.com
In this video I am presenting a backtesting method using the backtesting.py package. We will backtest a winning strategy using python, we already detailed th...
 

Automated Price Action Trading Strategy In Python



Automated Price Action Trading Strategy In Python

In this video, we will discuss a trading strategy that utilizes candlestick patterns and support and resistance levels. The main objective of this strategy is to automate the process of detecting price action patterns and apply it to historical data of the Euro versus US Dollar.

To begin, let's take a look at the key components of this strategy. Candlestick patterns are graphical representations of price movements in the form of bars or candles. These patterns provide valuable information about market sentiment and potential trend reversals. By analyzing these patterns, traders can make informed decisions about when to enter or exit trades.

Support and resistance levels, on the other hand, are specific price points where the market has historically shown a tendency to reverse or stall. These levels act as psychological barriers for traders and can be used to identify potential entry and exit points.

Now, let's move on to the implementation of this strategy in Python. We will use historical data of the Euro versus US Dollar, which can be obtained from various financial data sources or APIs. For this example, we will assume that we have already collected and preprocessed the necessary data.

We will automate the strategy using Python and a few popular libraries. The first step is to import the required libraries, including pandas for data manipulation, matplotlib for plotting, and talib for technical analysis indicators. Talib is a widely used library that provides a collection of technical analysis functions, including candlestick pattern recognition.

Once the libraries are imported, we can load the historical data into a pandas DataFrame. The DataFrame should contain the necessary columns such as date, open, high, low, close, and volume. These columns are commonly used in technical analysis and are required for calculating indicators and patterns.

Next, we can define a function to detect candlestick patterns. In this example, we will focus on a simple pattern, the bullish engulfing pattern. This pattern occurs when a small bearish candle is followed by a larger bullish candle that completely engulfs the previous candle. The function will iterate over the DataFrame and identify instances of the bullish engulfing pattern.

To enhance the strategy, we can also incorporate support and resistance levels. These levels can be manually identified by analyzing the historical price chart or by using technical analysis techniques. In this example, we will assume that we have already identified the relevant support and resistance levels and stored them in a separate DataFrame.

Once we have the candlestick patterns and support and resistance levels, we can proceed to automate the strategy. We will iterate over the DataFrame and check if the current bar satisfies the conditions for a bullish engulfing pattern and if the current price is near a support level. If these conditions are met, we generate a buy signal.

Conversely, if the current bar satisfies the conditions for a bearish engulfing pattern and the current price is near a resistance level, we generate a sell signal. These signals will be used to trigger buy or sell orders in a live trading environment.

To visualize the results of our strategy, we can plot the historical price chart with the identified candlestick patterns and support and resistance levels. This will help us understand the effectiveness of our strategy and identify any areas for improvement.

Finally, we can evaluate the performance of our strategy by backtesting it on the historical data. Backtesting involves simulating trades based on historical data and assessing the profitability and risk of the strategy. We can calculate various performance metrics such as total return, annualized return, maximum drawdown, and more.

By backtesting our strategy, we can gain insights into its performance and make informed decisions about its potential use in real trading scenarios. It is important to note that backtesting is a crucial step in strategy development, as it helps us assess the viability and profitability of our approach.

This video presented a simple trading strategy that combines candlestick patterns and support and resistance levels. The strategy was automated and tested in Python using historical data of the Euro versus US Dollar. By leveraging these technical analysis techniques, traders can potentially identify profitable trading opportunities and make informed decisions in the financial markets.

Automated Price Action Trading Strategy In Python
Automated Price Action Trading Strategy In Python
  • 2021.09.09
  • www.youtube.com
This video presents a simple trading strategy using candlestick patterns and support and resistance values. The strategy can be automated for price action d...
 

Automated Support and Resistance Detection in PYTHON



Automated Support and Resistance Detection in PYTHON

Hello everyone, and welcome back to this video. In this video, we will be providing a detailed explanation of how to automate the detection of support and resistance levels using Python. This idea was proposed by one of the comments, so a big thank you for that. As usual, don't forget that the program is available for download from the link in the description below. It's a Jupyter Notebook file that you can use for your own experiments. You may want to try this on different currencies or different time frames, and you can also modify the variables provided in the code.

While it's easy to visually identify support and resistance levels by looking at a price movement chart, defining them programmatically may seem complicated. However, with a proper algorithm, the process can be automated. It's important to note that the algorithm we present in this video is not the only one for detecting support and resistance levels. There are different approaches, but we have chosen one that is relatively simple to implement in code.

The figure you see here was produced using the code we are about to explain, and as you can see, the support and resistance levels were correctly detected by our program. This approach works for any currency and in any market condition. However, it's not a perfect algorithm, and you may notice that some levels were not detected. We will address this later in the video.

The basic idea behind defining support and resistance levels is to look back within a certain time period, such as a month or two, depending on how many levels you want to include in your strategy. The more data you have, the more levels you will discover. For example, if you are considering a daily chart like the one shown here and want to proceed with a trade on a specific date, you would look back within a certain time frame, such as a month, to discover the support and resistance levels that occurred during that period. This is what we will simulate in our program by considering a limited period of time for level detection. If we tried to detect support and resistance levels using all the available data, we would end up with a large number of levels, which is not practical for a trading strategy. So, it's best to focus on a few months preceding the current date.

Now let's dive into the algorithm itself. For support levels, we will look for a certain number of decreasing lows that precede the candle of interest. The candle of interest should have a lower low value than the other candles. Additionally, we need to have three increasing lows after the candle of interest. When all these conditions are met for a group of candles, we can identify a support level, which is defined as the lowest price among these candles. The same principle applies to resistance levels. We need to have increasing highs before the candle of interest and a higher high for the candle of interest. Then, we should have decreasing highs after the candle of interest. This allows us to find the resistance level, which is the highest price among these candles.

An interesting parameter at this stage is how many candles we should consider before and after the candle of interest. This can be customized based on the user's preference, and it would be good to experiment with different values. In our program, we define these as two variables called n1 and n2. The index of the candle of interest is represented by the variable l.

Now, let's see how we can implement this algorithm in Python. We will be using a Jupyter Notebook for this demonstration. First, we import the necessary libraries, including pandas for data manipulation. We load the data using the read_csv function, and in this example, we are using the EUR/USD daily charts from 2003 to 2021, which is approximately 18 years of data.

Next, we will use the support and resistance levels stored in the ss and rr lists to plot lines on the candlestick chart. We will loop through each support level in ss and add a horizontal line to the chart at that price level. Similarly, we will loop through each resistance level in rr and add a horizontal line for each level. This will make it easier to visualize the support and resistance levels in relation to the price movement.

By running the code, you will generate a candlestick chart with support levels displayed as purple dashed lines and resistance levels displayed as blue dashed lines. The chart will provide a visual representation of the detected support and resistance levels, making it easier to identify key price levels for trading decisions.

Remember, the algorithm presented here is one of several approaches to detecting support and resistance levels. You can experiment with different values of n1 and n2 to see how they affect the detection and merging of levels. Additionally, you can modify the condition for merging levels by adjusting the threshold value in the code.

Keep in mind that automated detection of support and resistance levels is a useful tool, but it should be used in conjunction with other technical analysis techniques and market insights to make informed trading decisions.

Automated Support and Resistance Detection in PYTHON
Automated Support and Resistance Detection in PYTHON
  • 2021.08.19
  • www.youtube.com
This video describes an algorithm to detect support and resistance levels in python language. 🍓 If you want to follow structured courses with more details a...
 

Automated Price Action Patterns Analysis In Python


Automated Price Action Patterns Analysis In Python

This video provides an explanation on how to combine Candlestick Analysis Patterns in Python and check the number of signals as well as the accuracy of the price action predictions. The methods are compatible with automated trading. A good method to look for relatively strong signal from price action movements, Candle Stick Analysis, Engulfing Patterns, Price Action Analysis.

00:00 Price Action Candles Introduction
00:35
Shooting Star, Hammer, Hanging Man, Engulfing Pattern
03:10 Python Price Action Detection
12:13 Price Action Analysis Results
18:45 Plotting Price Candles In Python

 

Engulfing Price Action Patterns Automated in Python



Engulfing Price Action Patterns Automated in Python

Hello everyone, and welcome back to this video. In today's discussion, we will be focusing on engulfing candles, specifically the bullish and bearish engulfing patterns. For those of you who are already familiar with these patterns, you understand their significance as indicators in trading.

To analyze the validity of these patterns, we will utilize historical data of the EUR/USD currency pair spanning approximately 10 years. Our objective is to apply simple statistical techniques in Python to determine whether these patterns hold statistical significance or if they are merely a myth. This information is crucial, especially if you are considering incorporating candlestick patterns into your trading strategy as indicators.

For your convenience, you can find the complete code used in this analysis by following the link provided in the description below. The code is available as a Jupyter Notebook file, enabling you to relax and enjoy this video while simultaneously exploring the code.

Engulfing patterns can be observed in two different forms. The bullish pattern occurs when multiple downtrend candles are followed by a single uptrend candle. This uptrend candle begins at or below the closing price of the last downtrend candle and closes higher than the opening price of the previous candle. This pattern typically indicates an upcoming uptrend in the market.

On the other hand, the bearish engulfing pattern is the symmetrical opposite of the bullish pattern. It occurs when uptrend candles are followed by a bearish engulfing candle. A bearish engulfing candle starts at or above the closing price of the previous candle and closes below the opening price of the same candle. This pattern signifies a forthcoming downward movement in price.

In this video, our goal is to verify whether these claims hold true. We aim to determine if these patterns truly indicate specific market behaviors. Typically, a bullish engulfing pattern suggests that buyers are stronger than sellers in the market, while a bearish engulfing pattern suggests the opposite. To accomplish this verification, we will write Python code to detect bullish and bearish engulfing candles. Subsequently, we will analyze the following few candles (ranging from one to three candles or more) to ascertain if the price moves in the expected direction.

To be more precise, we will consider the closing price of the last engulfing candle. In the case of a bullish engulfing pattern, we will consider the high values of the subsequent candles and calculate the difference between the high and closing prices of the engulfing candle. This will result in three distinct values, which we will denote as "d." Next, we will test whether any of these differences exceed a certain limit, represented by a variable I will define. This limit can be set to 20, 30, or 40 pips, depending on your preference. We will then calculate the percentage of times that this difference exceeds the pip limit.

Similarly, for the bearish engulfing pattern, we will consider the low values of the subsequent candles. We will compare the difference between the closing price of the engulfing candle and these low values with the variable X. Once again, we are looking for instances where this difference exceeds X. In essence, we are evaluating whether the price surpasses a bullish or bearish threshold within two to three candles following the engulfing pattern. We will calculate the percentage of instances where the price behaves as expected after these patterns occur.

It's important to note that only one of these differences needs to exceed the variable X. We are not requiring all three differences to surpass this pip limit simultaneously. Therefore, if the price falls below the closing value of the engulfing candle by a specific number of pips, the prediction of this pattern is considered successful. The same principle applies to the bullish engulfing pattern, but in an upward direction.

Now, let's proceed with checking the Python code and observing its behavior.

If I'm doing this for the trend equal one, meaning for the bearish engulfing pattern and downtrend prediction, I can calculate the precision by summing up the values in the results column where the trend is equal to one and dividing it by the total number of signals for the bearish engulfing pattern. Similarly, I can calculate the precision for the bullish engulfing pattern and uptrend prediction.

Now, let's create a new function called "calculate_precision" that takes the data frame as an input and calculates the precision for both patterns. First, we initialize the variables "bearish_signals" and "bullish_signals" to count the total number of signals for each pattern. Then, we iterate through the data frame and increment the corresponding signal counter based on the signal value.

Next, we calculate the precision for the bearish engulfing pattern by summing up the values in the results column where the trend is equal to one and dividing it by the total number of bearish signals. We do the same for the bullish engulfing pattern and uptrend prediction.

Finally, we return the precision values for both patterns. Now, let's call this function on our data frame to calculate the precision.

After calculating the precision, we can print the results to see how well our predictions align with the actual trend. It's important to note that these precision values are based on the specific parameters and conditions we've set in our code. You can experiment with different parameters and conditions to optimize the precision for your specific trading strategy.

In conclusion, this video focused on engulfing candle patterns in trading and aimed to determine if these patterns have statistical significance or if they are merely a myth. By analyzing historical data of the EUR/USD currency pair using Python, we detected bearish and bullish engulfing candle patterns and examined the subsequent trend behavior within a specified number of candles. Through calculating precision, we gained insights into the accuracy of our predictions. Remember to consider the limitations of this analysis and continue refining your trading strategy based on your own preferences and goals.

Thank you for watching, and don't forget to check the link in the video description to download the complete code in the Jupyter Notebook format. Enjoy your trading journey and best of luck in your endeavors!

Engulfing Price Action Patterns Automated in Python
Engulfing Price Action Patterns Automated in Python
  • 2021.07.08
  • www.youtube.com
This video describes the Engulfing Candlestick Patterns, bullish and bearish engulfing candles and statistics are carried out in python to check if these pat...
 

Automated Candlestick Strategy in Python | testing the shooting star



Automated Candlestick Strategy in Python | testing the shooting star

In today's session, we will delve into the fascinating world of Candlestick patterns and learn how to program them in Python. Our goal is to create a code that can identify specific patterns and potentially detect price trend reversals. Additionally, we will perform backtesting on a strategy that utilizes Candlestick signals, employing a simple statistical approach to assess the chances of developing a winning automated bot based on Candlestick predictions. If you're intrigued by this content, you can download the program file from the link provided in the description below. We hope you enjoy this informative session.

Before we proceed, let's clarify that this video assumes you already have some knowledge about Candlestick patterns. We won't be going into detail explaining each pattern since we will focus on the most well-known forms. Please note that this list is not exhaustive, as there are many more patterns out there. For now, we will stick to the basics. You may already be familiar with the Doji, which represents an undecided market. Another important pattern is the Shooting Star, characterized by a long tail above the Candlestick's body. It can appear in two forms, but what matters most is the presence of the long tail. When you encounter a Shooting Star during an uptrend, it could indicate a trend reversal, suggesting a shift to a downtrend. Similarly, we have the Hammer pattern, which is similar to the Shooting Star but inverted. It signifies a rejection point during an uptrend, with a long lower tail. This pattern suggests that the uptrend is nearing its end and a downtrend retracement may follow.

Moving on, let's discuss the Bullish Engulfing pattern. This occurs during a downtrend, where the last red Candlestick is completely covered by a larger upward Candlestick. This reversal pattern signals the end of the downtrend and the beginning of an uptrend. Conversely, we have the Bearish Engulfing pattern, which is the opposite of the Bullish Engulfing pattern. It occurs during an upward trend, where an upward Candlestick is followed by a larger Candlestick, covering the previous one. This indicates the end of the uptrend and the start of a downtrend. Keep in mind that there are several other Candlestick patterns that we won't cover in detail here, such as the Three Crows, among others. However, in this video, we will specifically focus on the Shooting Star and the Hammer patterns, particularly when a downtrend reverses into an uptrend.

The Shooting Star and Hammer patterns are personal favorites of mine due to their clear indication of market reaction to an uptrend. It's evident that sellers have stepped into the market, rejecting a specific price level. This is why I tend to trust these patterns more than others. Of course, individual preferences may vary, depending on how you utilize and combine these patterns with other indicators or strategies. For the purpose of this video, let's consider the Shooting Star as a compelling example of price rejection and the strong reaction of sellers, which gives this Candlestick its distinct form. We'll focus on coding this pattern in Python and teaching our bot to recognize such patterns. While you can extend the concepts we'll discuss to other patterns that interest you, our primary focus will be on the Shooting Star and the Hammer.

It's important to note that relying solely on Candlestick patterns is not sufficient to generate accurate buy or sell signals. These patterns should be combined with your favorite indicators. In our case, we will combine them with the Relative Strength Index (RSI). You may choose to incorporate different technical indicators or even fundamental analysis alongside Candlestick patterns. Using candlesticks alone is not comprehensive.

To evaluate the success rate of our prediction approach, we need to combine it with the RSI in combination with the Candlestick pattern is to add an additional confirmation to the signal. A higher RSI value indicates a stronger buying pressure, which aligns with the potential trend reversal suggested by the shooting star pattern.

If all the conditions are met, we can generate a buy signal. We assign a value of 1 to the signal column for the corresponding row in the data frame. Otherwise, we assign a value of 0, indicating no signal. This process is repeated for each row in the data frame, effectively scanning through the entire dataset to identify potential buy signals.

Next, we move on to defining the stop loss and take profit levels for the identified buy signals. We calculate the stop loss value by subtracting the average true range (ATR) from the buy price. The ATR provides a measure of volatility and helps determine an appropriate distance for the stop loss. A wider ATR indicates a more volatile market, requiring a larger stop loss, while a smaller ATR suggests a less volatile market, allowing for a tighter stop loss.

For the take profit level, we multiply the take profit-stop loss ratio (which we set to 2) by the ATR and add it to the buy price. This ensures that the take profit level is twice as far from the buy price as the stop loss level. The take profit level represents the potential profit target for the trade.

Now that we have the buy signals and corresponding stop loss and take profit levels, we can proceed with backtesting the strategy. We iterate through each row in the data frame and simulate the trades based on the generated signals.

If the price reaches the stop loss level first, we consider it a losing trade. Conversely, if the price reaches the take profit level first, we consider it a winning trade. We keep track of the number of winning and losing trades.

To evaluate the strategy's performance, we calculate the winning rate as the percentage of winning trades out of the total trades. In this case, since we set the take profit-stop loss ratio to 2, each winning trade compensates for two losing trades. Therefore, to have a winning system, we need to be right at least 34% of the time.

It's important to note that this evaluation does not account for trading costs, such as fees and overnight swap values. Additionally, this is a simplified example, and in real-world trading, it's essential to consider other factors, such as market conditions, risk management, and overall market analysis.

By combining Candlestick patterns, RSI, and a systematic approach to trade management, we aim to develop a trading strategy that can potentially generate profitable trades. However, it's crucial to thoroughly test and validate the strategy using historical data and consider ongoing market analysis to adapt to changing market conditions.

In conclusion, this video tutorial provides an introduction to programming Candlestick patterns in Python, demonstrates how to recognize specific patterns, and outlines a backtesting approach to evaluate the performance of a strategy based on these patterns. It's an opportunity to explore the potential of Candlestick patterns as a tool for predicting price trend reversals and developing automated trading bots.

Automated Candlestick Strategy in Python | testing the shooting star
Automated Candlestick Strategy in Python | testing the shooting star
  • 2021.04.21
  • www.youtube.com
This video is a walkthrough coding the candlestick patterns in Python language. After a general introduction we focus mainly on the shooting star rejection p...
 

Avoid Common Mistakes in Algorithmic Trading And Machine Learning



Avoid Common Mistakes in Algorithmic Trading And Machine Learning

Have you ever wondered what it would be like to have a winning trading bot that executes profitable trades on your behalf while you're sleeping or enjoying your free time? Maybe you've spent hours, months, or even years trying to crack the code and find that elusive program that could revolutionize your lifestyle.

When it comes to machine learning, many people believe it has the power to work wonders in various fields such as marketing and sales. However, there are two areas where machine learning still struggles: weather data prediction and price market forecasting. The highly random nature of the numbers in these fields makes it challenging to accurately predict prices using machine learning alone.

But here's the catch: it is possible to predict prices using machine learning, but only if it's coupled with an appropriate trading strategy. This means that the type of prediction you make must align with the trading strategy you employ.

Now, let's dive into some common mistakes that can hinder the success of your trading model and what you can do to avoid them.

Mistake #1: Fitting price values into a machine learning model as a regressor. Trying to predict the next market value by directly inputting price values into a machine learning regressor is a common beginner's mistake. While this approach may work well for correlated values like predicting house prices based on surface area, it doesn't apply to stock or currency markets. These markets don't exhibit a clear correlation with the time variable alone, making direct regression ineffective.

Mistake #2: Using absolute values as the model input. Using raw price or technical indicator values as input is another pitfall. Simply providing open, close, high, low prices, along with moving averages and other indicators, doesn't guarantee accurate future price predictions. Our brains process information differently, focusing on the overall image and the slopes of price movements rather than individual values. Similarly, your model needs to consider the overall trends and patterns rather than individual data points.

Mistake #3: Sampling data using random train-test data splitting. While random train-test splitting is a common practice in machine learning, it can be problematic when working with time series analysis, especially in price markets. Randomly splitting your data for training and testing can lead to a situation where the test set closely resembles the training set. This similarity can make the model appear accurate during backtesting but fail to perform well with new live data.

Mistake #4: Relying solely on technical analysis. While technical indicators play a significant role in machine learning models, relying only on them is not enough for long-term success. It's crucial to consider external factors, such as economic calendars and major events, which can significantly impact market behavior. Ignoring these factors may lead to poor results and discredit an otherwise sound model.

Mistake #5: Not considering a strategy that fits the model's precision. Model precision alone does not determine its profitability. Combining the model's accuracy with an optimized trading strategy, such as a favorable take-profit to stop-loss ratio, can turn a seemingly losing model into a profitable one. A precision above 33% can be sufficient if paired with the right strategy.

Mistake #6: Skipping an entry strategy and relying solely on the model's predictions. Even if your model delivers accurate predictions, knowing when to enter the market and execute trades is crucial. Defining a market entry strategy that complements the model's predictions is essential for maximizing profits. A correct trend prediction is not enough if you enter the market at the wrong moment and get stopped out before hitting your target.

Mistake #7: Not considering trading fees and commissions. Disregarding fees and commissions can have a significant impact on the profitability of your trading strategy. While a winning strategy may have a slight advantage, trading fees can erode those gains. It's important to consider fees when designing your strategy, such as closing trades within the same day to avoid overnight or weekend fees.

Next, it's crucial to backtest your model over an extended period. Testing your model under different market conditions is essential to ensure its effectiveness. Don't rely solely on short-term performance, as it may not reflect the model's long-term viability. Aim to backtest your model over a minimum of six months and assess whether it consistently yields positive gains.

Lastly, avoid getting impatient and interfering with trades. A high-precision model tends to wait for strong signals before executing trades. While this may cause you to miss some opportunities, it's important not to interfere with the model's decisions. Avoid opening new trades or closing existing ones based on impatience. Sometimes, having zero trades is better than making a losing trade.

In conclusion, these insights should help you improve your trading experience. Remember that if your algorithm is not market-ready yet, it's best not to overfocus on it. Take a break, order a nice hot pizza slice, and remember to have fun.

Avoid Common Mistakes in Algorithmic Trading And Machine Learning
Avoid Common Mistakes in Algorithmic Trading And Machine Learning
  • 2021.03.05
  • www.youtube.com
This video presents 9 very common mistakes that every algorithmic trader might fall in especially when using Machine Learning models to predict price movemen...
 

How To Calculate Technical Indicators For Trading Using Pandas



How To Calculate Technical Indicators For Trading Using Pandas

Hello everyone, and welcome back to this video. Today, we will dive into analyzing forex market prices using Python and exploring whether statistics can reveal any correlations between technical indicators and future price direction. You don't need to be an expert in trading or programming to follow along, but some familiarity with basic technical indicators like moving averages and the relative strength indicator (RSI) would be helpful. If you're here for a quick introduction to machine learning applications in trading, you're also in the right place as we'll keep things simple.

In this video, we will cover the following topics:

  1. Downloading currency exchange data: We will visit the cascope.com website and select the historical data feed, specifically for the USD/CHF (US dollar versus Swiss franc) currency pair. We'll choose the hourly candlestick timeframe for our data.

  2. Loading data into Python using pandas: We'll use the pandas library's read_csv function to load the downloaded file into a pandas DataFrame. We'll also check if the data is loaded correctly by inspecting the last five rows of the DataFrame.

  3. Data cleaning and initial analysis: Understanding the data is crucial, so we'll clean the data by removing rows with zero volume and checking for missing values. Additionally, we'll perform a short statistical analysis to identify patterns or correlations within the data.

  4. Adding technical indicators: We'll import the necessary libraries, including numpy and pandas_ta (pandas technical analysis), which provides various technical analysis indicators. We'll add several indicators to our DataFrame, such as the average true range (ATR), RSI, moving averages, and calculate their slopes.

  5. Defining the target: To make predictions based on technical indicators, we need to define our target. Instead of predicting the future average price, which can be challenging, we'll categorize the trends into three categories: upward, downward, and no clear trend.

  6. Plotting histograms: We'll visualize the distributions of various features using histograms. This includes volume, ATR, RSI, mid prices, moving averages, slopes, and the target categories. The histograms will provide a quick overview of the data and help identify any outliers.

  7. Analyzing the RSI: We'll focus on the RSI as a trend indicator and create separate DataFrames for the three target categories: upward, downward, and unclear trends. We'll plot histograms for the RSI values in each category to see if there are any distinguishable differences.

However, keep in mind that relying solely on the RSI may not be sufficient to predict price trends accurately. It's recommended to explore other technical indicators or combinations of indicators to gain an advantage in predicting price trends.

That wraps up the content for this video. I hope you find the information helpful. If you have any specific questions or need further clarification, feel free to ask in the comments section. Happy coding!

How To Calculate Technical Indicators For Trading Using Pandas
How To Calculate Technical Indicators For Trading Using Pandas
  • 2021.02.22
  • www.youtube.com
If you're a beginner looking to learn how to calculate technical indicators and download price history, then you don't want to miss this video! These indicat...
 

Backtesting.py - Full course in python



Backtesting.py - Full course in python

During the tutorial, the instructor discusses the positives and negatives of using backtesting.py as a library for backtesting trading strategies. The library is designed to focus solely on the essentials of backtesting, omitting features such as an indicator library or integration with brokers or other platforms. This simplicity allows the library to be lightweight and straightforward to use. The documentation provided is clear and easy to understand, enabling users to quickly grasp the concepts and functionality of the library.

One significant advantage of backtesting.py is its speed, especially when testing single strategies. The library is optimized for performance, allowing users to run backtests efficiently and obtain results in a timely manner. This speed is beneficial when iterating through multiple strategies or parameter combinations to find the optimal settings.

However, there are a few limitations to consider when using backtesting.py. Firstly, the library does not support trading with multiple assets. It is primarily designed for testing strategies on a single asset or security. Additionally, backtesting.py does not provide support for fractional shares, which may be a drawback for users interested in trading with smaller position sizes.

Despite these limitations, backtesting.py remains an excellent choice for those who want to focus exclusively on backtesting their trading strategies. Its simplicity and lightweight nature make it easy to understand and integrate into existing workflows.

In the tutorial, the instructor demonstrates the usage of backtesting.py by walking through the steps to create a virtual environment and install the necessary dependencies. By importing the required components, such as testing data for Google stock prices from 2006 to 2013, the instructor sets the stage for performing a backtest.

The instructor then proceeds to create a strategy class where the two essential functions, __init__ and next, are defined. In the __init__ function, the instructor calculates the indicator value of the Relative Strength Index (RSI). The next function is used to evaluate the criteria for buying based on the RSI values.

Next, the instructor explains how to implement a simple crossover strategy using pre-calculated values fed into the next function. The crossover library from backtesting.py is imported to compare the RSI with upper and lower bound values. When the RSI exceeds a certain value, a sell signal is generated, and when it falls below another value, a buy signal is triggered. The instructor defines the upper and lower bound values and assigns them to the class for access in the next function.

To test the strategy, the instructor sets up a backtest by providing the data, selecting the initial amount of cash, and printing out the statistics. The instructor emphasizes the ease of plotting backtesting results using backtesting.py and highlights how the red and green boxes on the screen indicate the months.

The instructor proceeds to provide an overview of the backtesting.py dashboard, which offers a comprehensive view of trade information, profits and losses, portfolio value, and indicators, among other useful metrics. The instructor demonstrates how strategy optimization can be achieved using backtesting.py by defining different ranges for the upper and lower bounds of the RSI window. The optimizer generates statistics such as the Sharpe ratio and simulates various combinations to find the most valuable function. The instructor emphasizes that users can define custom metrics and apply constraints to improve the optimization results.

Furthermore, the instructor explains how to apply constraints to select a subset of values using lambda functions that return true or false based on specific parameters. The video demonstrates how to optimize the strategy using the optimizer function to maximize the Sharpe ratio and how to define the optimization function as a regular Python function. The instructor also discusses the creation of a metric to maximize profits while minimizing the time spent in the market.

In the tutorial, the instructor adds a minimum number of trades filter to the optimization function to prevent overfitting. By including this filter, the backtesting function is compelled to look beyond a single swing period, increasing the chances of discovering more profitable parameter combinations. Additionally, the instructor shows how to create HTML files of the backtest results, which can be helpful when running multiple backtests and need to keep track of different parameter combinations. The instructor also provides guidance on naming and organizing the generated files to avoid cluttering the working directory.

The tutorial further explores the use of the optimize function in backtesting.py to optimize a strategy efficiently without having to test every possible combination. By setting a maximum number of tries, the program performs a randomized grid search of the combinations, reducing the time spent on backtesting and the risk of overfitting. The instructor demonstrates how to generate heatmaps to visualize the effects of different values on the strategy by varying the upper and lower bounds. A pandas group by statement is used to group the columns by the upper and lower bounds, and the mean is calculated to obtain average values for each combination.

The speaker explains how the function in backtesting.py finds all unique combinations of the specified columns, such as the upper and lower bounds. These combinations are then grouped together, and an aggregation function, such as the mean, is applied. The resulting output is a heatmap that can be plotted using the Seaborn module. The instructor demonstrates optimizing for the Sharpe ratio and changing the colormap for the heatmap. Additionally, the instructor shows how to use the inbuilt function plot_heat_maps to plot multiple heatmaps for more than two parameters.

The instructor demonstrates how to use heatmaps for parameter optimization and implementing multi-time frame strategies using the resample apply function from the backtesting.py library. Heatmaps provide a visual representation of how variations in different parameters affect trading strategies. By combining different time frames using the resample apply function, traders can build more complex strategies that consider different market conditions.

The instructor explains how different time frames can be used in a trading strategy using the backtesting.py library. By downsampling and applying functions, the library can perform forward fill and re-index back to the smaller time frame, facilitating the analysis of different time frames. In the example provided, the strategy involves using daily and weekly RSI to trigger trades only when a crossover occurs and the RSI is above or below a certain threshold. The instructor mentions that the strategy can be optimized by adjusting the parameters and that the library supports experimenting with different order types, such as stop loss and take profit.

The presenter demonstrates how to initiate a short position when the RSI goes below the lower bound and close any short positions when buying. Similarly, the presenter demonstrates that when the RSI goes above the upper bound, it sells any long positions and initiates a short position. However, the presenter notes that there is no code to prevent the program from taking multiple positions, which leads to the program losing 80 percent of the invested equity. The presenter explains how to fix this issue by adding a clause to only initiate a new trade if there is no current position or if there exists a long/short position in the portfolio.

The instructor demonstrates how to use stop-loss and take-profit orders in backtesting.py. By setting a stop-loss at a specific percentage below the current price, the strategy can limit losses on each trade, while setting a take-profit level allows for exiting trades at a certain profit level. The instructor also shows how to adjust the size parameter in the buying process to allocate a specific percentage of available funds to each trade. While there are some issues with the selling tactics in the example, the video provides useful insights into using backtesting.py for building and testing trading strategies.

The video discusses different ways to implement position sizing in backtesting. One approach is to buy and sell one share at a time rather than a percentage of available cash. This approach can be useful for strategies involving laddering into a position or dollar cost averaging. The video demonstrates modifying a crossover strategy to a strategy based on the RSI indicator. In this modified strategy, trades are executed when the latest RSI value is smaller than the lower bound. The video also highlights that trades can be extracted from the backtest as a pandas dataframe, including entry and exit dates and other important metrics. These trade data can be exported to other visualization tools, such as Excel or other Python scripts, for further analysis and examination.

The creator of backtesting.py introduces the "bars since" function, which is a powerful tool for optimizing strategies and avoiding the need to write numerous if statements to compare data for preceding days. The function allows users to determine the number of bars since a particular trading condition was last met. This feature provides a convenient way to optimize strategies based on specific time-based conditions. Furthermore, the creator emphasizes the open-source nature of backtesting.py, encouraging users to customize the library according to their specific needs and preferences.

In conclusion, the tutorial on backtesting.py concludes with the instructor encouraging viewers to reach out with any questions or concerns. The instructor wishes them luck in their backtesting endeavors and reminds them to have fun while exploring the possibilities of backtesting and optimizing trading strategies using backtesting.py. The instructor emphasizes the importance of referring to the backtesting.py documentation for more details and to discover additional features available for building and optimizing backtesting infrastructure.

Overall, the tutorial provides a comprehensive overview of backtesting.py, its advantages, limitations, and various features. It guides users through the process of creating a backtest environment, implementing strategies, optimizing parameters, using heatmaps for analysis, incorporating multiple time frames, and applying position sizing techniques. By following the tutorial, viewers gain valuable insights and practical knowledge that can help them effectively test and refine their trading strategies using backtesting.py.

  • 00:00:00 The instructor discusses the positives and negatives of backtesting.py. The library focuses only on the essentials of backtesting and does not include an indicator library or integration with brokers or other platforms. The documentation is straightforward and easy to understand. Additionally, it is very fast, especially when testing single strategies. On the downside, it does not allow trading with multiple assets or fractional shares. Overall, the library is lightweight and simple, making it an excellent choice for those looking to focus solely on backtesting. The instructor also walks through the steps to create a virtual environment and install the necessary dependencies for the tutorial.

  • 00:05:00 We see the author of the backtesting.py library import the necessary components required to run a backtest, such as the testing data for Google stock prices from 2006 to 2013, and the creation of a strategy class where the two functions, init and next, are defined. In init, we calculate the indicator value of RSI, and next function is used to evaluate the criteria for buying, based on the calculation of values for the RSI.

  • 00:10:00 The instructor discusses how to implement a simple crossover strategy using pre-calculated values that are being fed into next year. They import the crossover library from backtesting.py to compare the RSI with upper and lower bound values. When the RSI gets above a certain value, it sells, and when it goes below, it buys. They also define upper and lower bound values and assign them to the class to access them in the function. The instructor then sets a backtest for the strategy and provides the data, selects the amount of cash, and prints out the stats. They explain how backtesting can be easily plotted and how the red and green boxes on the screen indicate the months.

  • 00:15:00 The speaker provides an overview of the dashboard that can be used to visualize backtesting results using backtesting.py. The dashboard provides information about trades, profits and losses, portfolio value, and indicators, among other things. The speaker also demonstrates how strategy optimization can be achieved using backtesting.py by defining different ranges of values for upper and lower bounds and the RSI window. The optimizer generates statistics such as the Sharpe ratio and simulates various combinations to find the highest-valued function. The speaker notes that users can define custom metrics to optimize and apply constraints to generate better optimization results.

  • 00:20:00 The instructor explains how to apply constraints to select a subset of values and create lambda functions that return true or false based on any parameters. The video demonstrates how to optimize the strategy, how to use the optimizer function to maximize the sharp ratio, and how to define the optimization function as a regular Python function. The instructor also discusses how to create a metric that figures out how to make the most money while staying in the market for the least amount of time.

  • 00:25:00 The instructor explains how to add a minimum number of trades filter to the optimization function to prevent overfitting. By adding this filter, the backtesting function is forced to look beyond a single swing period, increasing the chances of discovering more profitable parameter combinations. The instructor also shows how to create HTML files of the backtest results, which can be useful when running multiple backtests and need to keep track of the different parameter combinations used. Lastly, the instructor discusses how to name and organize the generated files to avoid clogging up the working directory.

  • 00:30:00 The instructor explains how to use the optimize function in backtesting.py to optimize a strategy quickly without having to perform every possible combination. By setting a max number of tries, the program performs a randomized grid search of the combinations, reducing the time spent on backtesting and the risk of overfitting. The instructor also demonstrates how to generate heat maps to visualize the different values and their effects on the strategy when varying upper and lower bounds. A pandas group by statement is used to group the columns by the upper and lower bounds, and the mean is taken to calculate the average values for each combination.

  • 00:35:00 The speaker explains how the function finds all unique combinations of the columns mentioned, such as the upper and lower bounds. The function then groups these combinations together and applies an aggregation function, in this case, the mean. The resulting output is a heatmap that can be plotted using the Seaborn module. The speaker demonstrates how to optimize for the Sharpe ratio and change the colormap for the heatmap. Finally, the speaker shows how to use an inbuilt function, plot_heat_maps, to plot multiple heatmaps for more than two parameters.

  • 00:40:00 The instructor demonstrates how to use heat maps for parameter optimization and how to implement multi-time frame strategies using the resample apply function from the backtesting library. By using heat maps, users can visualize how variations in different parameters affect their trading strategies. The resample apply function allows users to resample data to different time frames, such as weekly and daily, in order to use them together in a multi-time frame strategy. By combining different time frames, traders can build more complex strategies that take into account different market conditions.

  • 00:45:00 The instructor explains how to use different time frames in a trading strategy using the backtesting.py library. By down-sampling and applying functions, the library can perform forward fill and re-index back to the smaller time frame, making it easier to analyze different time frames. The strategy in this example involves using daily and weekly RSI to trigger trades only when a crossover occurs and the RSI is above or below a certain threshold. The strategy could be optimized by tweaking the parameters, and the library could be used to experiment with different order types such as stop loss and take profit.

  • 00:50:00 The presenter demonstrates how to initiate a short position when the RSI goes below the lower bound and then closes any short positions when buying. Similarly, he demonstrates that when the RSI goes above the upper bound and sells any long positions, the program initiates a short position as well. However, there is no code to stop the program from taking multiple positions, which leads to the program losing 80 percent of the equity being invested. The presenter explains how to fix this by adding a clause to only initiate a new trade if there is no current position or there exists a long/short position in the portfolio.

  • 00:55:00 The instructor demonstrates how to use stop-loss and take-profit orders in backtesting.py. By setting stop-loss at a specific percentage below the current price, the strategy can avoid losing more than a certain amount on each trade, while setting take-profit allows for exiting trades at a certain profit level. The instructor also shows how to adjust the size parameter in the buying process to allocate a specific percentage of available funds to each trade. While there are some issues with the selling tactics in this example, the video provides useful insights into using backtesting.py for building and testing trading strategies.

  • 01:00:00 The video discusses different ways to implement position sizing in backtesting. One way is to buy and sell one share at a time rather than a percentage of available cash, which can be useful for laddering into a position or dollar cost averaging. The video demonstrates modifying a crossover strategy to a strategy based on the RSI indicator, which buys when the latest RSI value is smaller than the lower band. The video also shows that trades can be extracted from the backtest as a pandas dataframe, including entry and exit dates and other important metrics. The trades can be exported to other visualization tools, such as Excel or other Python scripts.

  • 01:05:00 The creator introduces the "bars since" function in backtesting.py, which can be used to determine the number of bars since a particular trading condition was last met. This function can be an excellent tool for optimizing strategies and preventing the need for writing many if statements to compare the data for preceding days. The creator uses the example of selling only when the daily rsi is above the upper bound for three consecutive days. Additionally, he discusses how to extract raw trade data for further analysis and how the open-source nature of backtesting.py makes it easy for users to customize the library for their specific needs. The tutorial's conclusion invites the learners to explore the backtesting.py documentation to discover more details and features available for them to build and optimize their backtesting infrastructure.

  • 01:10:00 The speaker concludes the course on backtesting.py by encouraging viewers to reach out to him with any questions or concerns. He also wishes them luck in their backtesting endeavors and reminds them to have fun.
Backtesting.py - Full course in python
Backtesting.py - Full course in python
  • 2022.04.26
  • www.youtube.com
A full course covering all you need to know about the backtesting.py python library. Backtesting.py is a lightweight backtesting framework in the style of Ba...
Reason: