This article will explain and implement the Fibonacci retracement strategy in Python. At the same time, it will implement different Python functions to build this strategy.
Related reading: –Algorithmic trading strategies Python (Backtesting, Code, List, And Plenty of Coding Examples)
This method is a trading indicator to indicate entry points when there is a downtrend or an upward trend. It is necessary to estimate Fibonacci’s ratios to identify the buy and sell signals.
Leonardo Bonacci (or Leonardo da Pisa) was a mathematician from the Republic of Pisa (Italy) who discovered Fibonacci’s sequence, where each value in the sequence is the sum of the last two values. The first elements of the series are:
When you see the first Fibonacci number (2), it is the sum of the last two elements (1+1), the second Fibonacci number (3), it is again the sum of the former two values (1+2), etc. The important point is the ratio between the Fibonacci numbers:
The previous image shows the ratios from the Fibonacci Numbers. The ratio 0.618 is the division between the previous Fibonacci value and its current value, for example, 34/55=0.618, 89/55=0.618, etc. Meanwhile, the element 0.786 from the third column is the square root from =0.786. Subsequently, to obtain the elements is the division between 21/55=0.382, 34/89=0.382, etc. Finally, the division is 55/13=0.235, 89/21=0.236, etc.
In a downtrend, Fibonacci’s ratios are 1/0.618=1.618, 1/0.786=1.272, 1/0.382=2.618, and 1/0.236=4.237.
This article takes part of its code from other articles on our website. In case of any doubts, please visit the following links:
- How To Build A Profitable VWAP Trading Strategy With Python
- How I Made A Profitable OBV Strategy Using Python
- How I Made a Weighted Moving Average Trading Strategy Using Python (Rules, Backtest)
- How to Build a Simple SMA Trading Strategy Using Python
- How To Calculate The Sharpe Ratio In Python
Data to Use
We will use the following financial instruments:
The first example will use the SPY ETF, and the second example will use the other ETFs.
The initial and end dates in both examples are 2020-01-01 and 2023-10-23, respectively.
As in the previous article, the first step is to import the libraries:
Next, we implement the function download_data with parametes stock_name, start and end:
Inside download_data, the variables securityand data handle the connection to Yahoo Finance to download the SPY daily data.
The following image shows the first seven rows of the dataset:
There are multiple ways to implement the Fibonacci Retracement strategy. This tutorial will implement a simple rule:
The following chart shows an example of the first condition:
In the previous image, we calculate the Fibonacci band as follows:
It is important to highlight that 0.236 is one of the bands already calculated in the second table as is 55/13=0.235, 89/21=0.236. You can use any other Fibonacci band value.
With the previous Fibonacci band (138.2), we will wait until the closing price is under $138, at that moment we generate a buy order.
The other condition is to identify the trend; we want to be sure that the stock price is in an upward trend because the idea with this strategy is to place a trade when the price retraces in an upward trend.
Therefore, we need to make a workaround to validate the direction of our trend. Our rule is simple, we compare ; if the previous inequality is True, we will say there is an upward trend. You can use any other method to estimate the direction of the trend.
Let’s see how to calculate the previous rules in Python:
The previous image shows the Fibonacci function with five parameters: data, band, roc, trend_size, and level. The first part is to create val_, which is the highest value between trend_size and roc; subsequently, pclose, plow, and phigh are the locations in numbers of the variables Close, Low, and High in the data frame.
The other important part is the loop; the iteration is over all the elements of the dataset len(data.index); we wait the first 50 days, and during that time, the returns are zero (returns=0). Then, we get the closing price and calculate the maximum and minimum value of the last 50 days (close, min_val, and max_val) to obtain the retracement.
Next, we estimate trend = close – level*data.iloc[i-int(trend_size), plow]. After that, we calculate the retracement condition close <= (max_val – retracement) and the trend condition trend>0; inside of this condition, we set signal_=1 and closing_price=close+retracement.
It is important to mention that closing_price is the signal to close our position, and every time that the loop calculates closing_price = close + retracement, the closing_price is a number and not None.
In the next condition (elif closing_price != None), we want to obtain the exit signal (close > closing_price); in case, both conditions are true, then signal_=0 and closing_price = None, these values indicate that there are no positions in our portfolio.
Next, in case the signal_ = 1, and the trend is negative (trend <0), we close the position (signal_=0 and closing_price=None).
In the last part of the previous image, we append signal_ to the list signal_list. This list will have zero (0) or one (1) values. When signal_=1 indicates a long position, while signal_=0 indicates that there is no position.
The following image shows the implementation of the fibonacci function:
When we implement the function equity_curve, we get:
The plot is:
Although our strategy has positive returns, it underperforms its benchmark (SPY). The main reason is the scarce number of buy signals; the blue line has too many horizontal intervals and indicates periods with no trades.
One recommendation is to reduce the size of trend_size and roc to generate more signals. The variable roc is the number of days to calculate the maximum and minimum value; therefore, a lower value implies fewer days to calculate the minimum and maximum value. Meanwhile, trend_size is the number of days to estimate the trend; it is more likely to have an upward trend with fewer days.
This section intends to put into practice the previous trading strategy to see the performance with more financial instruments. The following chart shows the performance of the strategy against an equal-weighted strategy in six ETFs:
The equity curve is: