Automating Fibonacci Retracement for Potential Price Reversals
- Stephens Systems
- Dec 19, 2023
- 3 min read
Updated: Jan 10, 2024
Instead of trying to figure out where to start your fibonacci retracement tool, let's automate this process using python and yahoo finance! In this Free Jupyter Notebook and on my YouTube channel I review the coding process to automate the fibonacci retracement.
Example Output!
Free Jupyter Notebook for Intrendias Essentials Members (Free Tier!)
Please See the Code Below If Jupyter Download Does Not Work
import numpy as np import pandas as pd import matplotlib.pyplot as plt import yfinance as yf def get_stock_data(symbol, start_date, end_date, interval): df = yf.download(symbol, start=start_date, end=end_date, interval = interval) return df ticker = 'SPY'df = get_stock_data(ticker, '2021-01-01', '2023-12-18', '1d')def calculate_fractals(df): highs = df['High'] lows = df['Low'] # Identify potential fractals is_fractal_high = (highs.shift(1) < highs) & (highs.shift(-1) < highs) is_fractal_low = (lows.shift(1) > lows) & (lows.shift(-1) > lows) df['fractal_highs'] = np.where(is_fractal_high, highs, np.nan) df['fractal_lows'] = np.where(is_fractal_low, lows, np.nan) return df# Calculate fractals df = calculate_fractals(df)### Visualize the Fractals plt.figure(figsize=(20,10))plt.plot(df['High'], label='High Prices', color='blue')plt.plot(df['Low'], label='Low Prices', color='orange')plt.scatter(df.index, df['fractal_highs'], marker='^', color='green', label='Fractal Highs')plt.scatter(df.index, df['fractal_lows'], marker='v', color='red', label='Fractal Lows')plt.title('Stock Prices with Fractals')plt.xlabel('Date')plt.ylabel('Price')plt.legend()plt.show()def fibonacci_retracement(df): max_fractal_price = df['fractal_highs'].tail(120).max() min_fractal_price = df['fractal_lows'].tail(120).min() #Calculate the difference between high and low price price_range = max_fractal_price - min_fractal_price #Calculate retracement levels retracement_0 = max_fractal_price retracement_23_6 = max_fractal_price - 0.236 * price_range retracement_38_2 = max_fractal_price - 0.382 * price_range retracement_50 = max_fractal_price - 0.5 * price_range retracement_61_8 = max_fractal_price - 0.618 * price_range retracement_78_6 = max_fractal_price - 0.786 * price_range retracement_1 = min_fractal_price #Create a dictionary to store retracement levels retracement_levels = { '0%':retracement_0, '23.6%':retracement_23_6, '38.2%':retracement_38_2, '50%': retracement_50, '61.8%':retracement_61_8, '78.6%':retracement_78_6, '100%':retracement_1 } return retracement_levelsretracement_levels = fibonacci_retracement(df)#Display retracement levelsfor level, price in retracement_levels.items(): print(f'{level}:{price}') plt.figure(figsize=(20,10))plt.plot(df['Close'],label='Close Prices', color='black')plt.scatter(df.index, df['fractal_highs'], marker='^', color='green',label='High Fractals')plt.scatter(df.index, df['fractal_lows'], marker='v', color='red',label='Low Fractals')for level, price in retracement_levels.items(): plt.axhline(y=price, color="orange", linestyle='--', label=f'{level} Retracement') plt.title(f'{ticker} Close Prices with Fibonacci Retracement Lines')plt.xlabel('Date')plt.ylabel('Price')plt.legend()plt.show()Why Use Fibonnacci?
The Fibonacci retracement tool is a technical analysis tool used in financial markets, particularly in stocks and other securities, to identify potential levels of support and resistance. It is based on the Fibonacci sequence, a mathematical concept where each number is the sum of the two preceding ones (e.g., 0, 1, 1, 2, 3, 5, 8, 13, and so on).
The Fibonacci retracement tool consists of horizontal lines drawn on a price chart at key Fibonacci levels, which are typically expressed as percentages. The most commonly used Fibonacci retracement levels are 23.6%, 38.2%, 50%, 61.8%, and 78.6%. These levels represent the percentage of a prior price movement that a stock or security is expected to retrace.
Traders and investors use the Fibonacci retracement tool to identify potential areas of support or resistance where the price of an asset may reverse direction. The idea is that these Fibonacci levels may correspond to natural psychological and technical levels in the market, influencing trader behavior. For example, if a stock is in an uptrend, a trader might use the Fibonacci retracement tool to identify potential support levels where the stock is likely to find buying interest.
While the Fibonacci retracement tool is not foolproof and should be used in conjunction with other technical analysis tools, it remains a popular method for assessing potential price reversal points and determining entry or exit levels in the financial markets.
How Do I Know Where to Start My Fibonacci Retracement Tool?
You want to see a clear trend to start your Fibonacci retracement. To do this we can use William Fractals. A bullish (upward) fractal occurs when the middle bar has the highest high and is flanked by two lower highs on each side. Conversely, a bearish (downward) fractal occurs when the middle bar has the lowest low and is flanked by two higher lows on each side.
Traders often use these fractal patterns, along with other indicators from Bill Williams' trading system, to identify potential turning points in the market. Keep in mind that the use and effectiveness of specific trading tools or concepts can vary, and it's always advisable to combine them with other forms of analysis and risk management strategies.
Since William Fractals can potentially pinpoint reversals, the auto Fibonacci algorithm will use these fractal signals as starting and ending points.
Automating the Fibonacci Retracement
Check out the jupyter notebook and the YouTube video on my channel on automating the Fibonacci retracement tool using python and yahoo finance data for potential price reversals!












Comments