**Introduction**

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)**

**Fibonacci Retracement**

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.

**Other articles**

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.

**Python Example**

As in the previous article, the first step is to import the libraries:

Next, we implement the function * download_data* with parametes

*,*

**stock_name***and*

**start***:*

**end**Inside * download_data*, the variables

*and*

**security***handle the connection to Yahoo Finance to download the SPY daily data.*

**data**The following image shows the first seven rows of the dataset:

**Trading Strategy**

There are multiple ways to implement the Fibonacci Retracement strategy. This tutorial will implement a simple rule:

**Buy **when:

And

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***and*

**roc, trend_size,***. The first part is to create*

**level***, which is the highest value between*

**val_***and*

**trend_size***; subsequently,*

**roc***,*

**pclose***and*

**plow,***are the locations in numbers of the variables*

**phigh***,*

**Close***and*

**Low,***in the data frame.*

**High**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 (

*). Then, we get the closing price and calculate the maximum and minimum value of the last 50 days (*

**returns=0***,*

**close***and*

**min_val,***) to obtain the*

**max_val***.*

**retracement**Next, we estimate * trend = close – level*data.iloc[i-int(trend_size), plow]*. After that, we calculate the retracement condition

*and the trend condition*

**close <= (max_val – retracement)***; inside of this condition, we set*

**trend>0***and*

**signal_=1***.*

**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

*, the*

**closing_price = close + retracement***is a number and not*

**closing_price***.*

**None**In the next condition (* elif closing_price != None*), we want to obtain the exit signal (

*); in case, both conditions are true, then*

**close > closing_price***and*

**signal_=0***, these values indicate that there are no positions in our portfolio.*

**closing_price = None**Next, in case the * signal_ = 1*, and the trend is negative (

*), we close the position (*

**trend <0***and*

**signal_=0***).*

**closing_price=None**In the last part of the previous image, we append * signal_* to the list

*. This list will have zero (0) or one (1) values. When*

**signal_list***indicates a long position, while*

**signal_=1***indicates that there is no position.*

**signal_=0**The following image shows the implementation of the * fibonacci* function:

**Equity Curve**

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

*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,*

**roc***is the number of days to estimate the trend; it is more likely to have an upward trend with fewer days.*

**trend_size****More ETFs**

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: