Fibonacci Sequence in Trading with Python

A guide to using Fibonacci retracement and extension levels in trading, with Python examples and data from EODHD APIs.

EODHD APIs
8 min readSep 24, 2024

Fibonacci Extensions and Retracements in Python Using EODHD APIs Financial Data

The Fibonacci sequence is a fascinating concept that has gained popularity among writers, mathematicians, and beyond.

At its core, the Fibonacci sequence is a series of numbers where each number is the sum of the two preceding ones, starting with 1, 1, 2, 3, 5, 8, 13, 21, and so on.

As the sequence progresses, the ratio between each successive pair of Fibonacci numbers approaches 1.618, or its inverse 0.618, which is widely recognized as the Golden Ratio.

This Golden Ratio intriguingly appears not only in natural patterns, such as spirals in leaves and flower petal counts, but also in artificial systems like financial markets, which is the central focus of this article.

The Golden Ratio in Fibonacci sequences: 8/13 = 0.618 (61.8%), 21/34 = 0.618 (61.8%), 34/55 = 0.618 (61.8%), 55/89 = 0.618 (61.8%), and so on.

Mathematicians began exploring additional ratios that could be linked to the Fibonacci sequence.
These ratios, derived from different combinations of Fibonacci numbers, have also found applications in various fields, including trading and market analysis.

Fibonacci Retracement and Extensions for Trading in Python

Fibonacci retracement measures the potential percentage of a correction following a price movement.

The key Fibonacci retracement levels include 23.6%, 38.2%, 50%, 61.8%, 78.6%, and 100%, while the extension levels are set at 138.2%, 161.8%, 200%, and 261.8%.

For example, if we take the Fibonacci sequence 0, 1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89 and divide 55 by 89, we get 0.618; dividing 34 by 89 gives 0.382; and dividing 21 by 89 gives 0.236. The square root of 0.618 is 0.786. Although 50% is not an official Fibonacci ratio, it is often used in trading.

These retracement levels are useful in identifying potential support and resistance areas in the market. They can be drawn between two significant price points, such as a high and a low. On charts, Fibonacci levels appear similar to support and resistance lines.

On the other hand, Fibonacci extensions project price targets beyond the usual range, helping traders identify areas of potential support or resistance when the price is entering uncharted territory.

Calculating Fibonacci levels in Python for trading

To perform this, we first need trading data, which can be obtained through the EODHD APIs. The platform offers both paid and free-tier options. For this demonstration, we’ll use the S&P 500 index (^GSPC) data through the EODHD API’s Python Financial Library within Google Colab, a free tool that allows running Python code without local installation.

If you prefer to run the code locally on your desktop, it will work just as well.

Let’s begin by retrieving data for the S&P 500 using the EODHD API in Python on Google Colab. Note that a subscription is required for this data, but there’s a free demo API key that provides access to Apple stock data (AAPL.US).

We now have 207 days of S&P 500 data stored in a Pandas dataframe called “df”. This can now be plotted as follows:

To calculate Fibonacci retracements, we need to determine the following:

  1. The highest price within the selected range.
  2. The lowest price within the selected range.
  3. Whether the market is in an uptrend or downtrend.

Getting the high and low prices is easy…

The S&P 500 currently appears to be in a downtrend visually. To confirm this, you can use a simple check, like the following…

We have added two simple moving averages (SMA50 and SMA200) to the dataset, where SMA50 is the 50-day rolling average and SMA200 is the 200-day rolling average. As of October 21, 2022, SMA50 is below SMA200, indicating a long-term downtrend.

Now, the goal is to figure out how far this downtrend will extend and where potential reversals might occur. Fibonacci retracement levels can be very helpful for making these projections in trading using Python.

The calculations are as follows:

  • Uptrend Retracement = High — ((High — Low) * Percentage)
  • Uptrend Extension = High + ((High — Low) * Percentage)
  • Downtrend Retracement = Low + ((High — Low) * Percentage)
  • Downtrend Extension = Low — ((High — Low) * Percentage)

For this example, we will use the “Downtrend Retracement” formula:

Low + ((High — Low) * Percentage)

For 23.6% retracement:

  • 23.6% = 3577.03 + ((4796.5601–3577.03) * 0.236)
  • 23.6% = 3577.03 + (1219.5301 * 0.236)
  • 23.6% = 3577.03 + 287.8091036
  • 23.6% = 3864.8391036

You can repeat this calculation for other Fibonacci levels.

Here is how you can calculate the Fibonacci percentages programmatically in Python.

Here’s the Python code that you can use in Google Colab:

Low = df["adjusted_close"].min()
High = df["adjusted_close"].max()

Diff = High - LowFib100 = High
Fib764 = Low + (Diff * 0.764)
Fib618 = Low + (Diff * 0.618)
Fib50 = Low + (Diff * 0.5)
Fib382 = Low + (Diff * 0.382)
Fib236 = Low + (Diff * 0.236)

Fib0 = LowFib100, Fib764, Fib618, Fib50, Fib382, Fib236, Low

Here is how you can plot the Fibonacci retracement levels using Matplotlib in Python:

plt.figure(figsize=(30,10))
plt.plot(df["adjusted_close"], color="black", label="Price")
plt.axhline(y=Fib100, color="limegreen", linestyle="-", label="100%")
plt.axhline(y=Fib764, color="slateblue", linestyle="-", label="76.4%")
plt.axhline(y=Fib618, color="mediumvioletred", linestyle="-", label="61.8%")
plt.axhline(y=Fib50, color="gold", linestyle="-", label="50%")
plt.axhline(y=Fib236, color="darkturquoise", linestyle="-", label="23.6%")
plt.axhline(y=Fib0, color="lightcoral", linestyle="-", label="0%")

plt.ylabel("Price")
plt.xticks(rotation=90)
plt.title("S&P 500 (^GSPC) Daily")
plt.legend()
plt.show()

Under Fibonacci extensions, the calculation would look like this for an uptrend:

Fib2618 = High + (Diff * 2.618)
Fib2000 = High + (Diff * 2)
Fib1618 = High + (Diff * 1.618)
Fib1382 = High + (Diff * 1.382)
Fib1000 = High + (Diff * 1)
Fib618 = High + (Diff * 0.618)

The Pandas dataframe displays 207 days of data, but you might only want to focus on data starting from mid-August. Since Fibonacci retracement only requires a high and low point, you can truncate the dataset as follows.

df_subset = df.tail(48)

plt.figure(figsize=(30,10))
plt.plot(df_subset["adjusted_close"], color="black", label="Price")
plt.ylabel("Price")
plt.xticks(rotation=90)
plt.title("S&P 500 (^GSPC) Daily")
plt.legend()
plt.show()

We will compute the new Fibonacci levels using the following approach.

Low = df_subset["adjusted_close"].min()
High = df_subset["adjusted_close"].max()
Diff = High - Low

Fib100 = High
Fib764 = Low + (Diff * 0.764)
Fib618 = Low + (Diff * 0.618)
Fib50 = Low + (Diff * 0.5)
Fib382 = Low + (Diff * 0.382)
Fib236 = Low + (Diff * 0.236)
Fib0 = Low

Fib100, Fib764, Fib618, Fib50, Fib382, Fib236, Low

We will then plot the newly calculated data for visualization.

plt.figure(figsize=(30,10))
plt.plot(df_subset["adjusted_close"], color="black", label="Price")
plt.axhline(y=Fib100, color="limegreen", linestyle="-", label="100%")
plt.axhline(y=Fib764, color="slateblue", linestyle="-", label="76.4%")
plt.axhline(y=Fib618, color="mediumvioletred", linestyle="-", label="61.8%")
plt.axhline(y=Fib50, color="gold", linestyle="-", label="50%")
plt.axhline(y=Fib236, color="darkturquoise", linestyle="-", label="23.6%")
plt.axhline(y=Fib0, color="lightcoral", linestyle="-", label="0%")

plt.ylabel("Price")
plt.xticks(rotation=90)
plt.title("S&P 500 (^GSPC) Daily")
plt.legend()
plt.show()

You can observe that the Fibonacci retracement levels act as potential support and resistance points on the chart.

EODHD Python Financial Library

Retrieve the data just as before, or use any dataset you prefer for your analysis.

Two key points to note:

  1. The -U argument was used during the PIP install to ensure that the existing "eodhd" library is upgraded to the latest version.
  2. The version in use on Google Colab is confirmed to be 1.0.8.

Now, onto the exciting part!

from eodhd import EODHDGraphs
graphs = EODHDGraphs()

We can render all our graphs as follows:

graphs.fibonacci_retracement(df, "downtrend", "adjus")
graphs.fibonacci_retracement(df, "uptrend", "adjusted_close")
graphs.fibonacci_extension(df, "uptrend", "adjusted_close")
graphs.fibonacci_extension(df, "downtrend", "adjusted_close")

By default, the graphs will be displayed without saving them. Two optional arguments have been added to the functions:

  • save_file="fibonacci.png" ← Default is "", meaning it won't save the file.
  • quiet=True ← Default is False, meaning it will display the graph.

Here’s how you can save the graph without displaying it:

graphs.fibonacci_retracement(df, "downtrend", save_file="fibonacci.png", quiet=True)

We hope you found this article useful! If so, feel free to follow us for future content and give it a clap to support our work. Your engagement helps us continue providing valuable insights 🙂

Please note that this article is for informational purposes only and should not be taken as financial advice. We do not bear responsibility for any trading decisions made based on the content of this article. Readers are advised to conduct their own research or consult with a qualified financial professional before making any investment decisions.

For those eager to delve deeper into such insightful articles and broaden their understanding of different strategies in financial markets, we invite you to follow our account and subscribe for email notifications.

Stay tuned for more valuable articles that aim to enhance your data science skills and market analysis capabilities.

A Message from InsiderFinance

Thanks for being a part of our community! Before you go:

--

--

EODHD APIs

eodhd.com — stock market fundamental and historical prices API for stocks, ETFs, mutual funds and bonds all over the world.