The Fibonacci Algorithmic Trading Strategy is a popular method among traders to identify potential support and resistance levels in the market. This strategy leverages Fibonacci retracement levels, which are derived from the Fibonacci sequence, a mathematical series where each number is the sum of the two preceding ones. Key levels, like 38.2%, 50%, and 61.8%, are used to predict potential price reversals. To apply this strategy, traders first identify a significant price move, either upward or downward, and then plot the Fibonacci levels from the start to the end of this move. The retracement levels help traders pinpoint areas where the price might pull back before continuing in the original direction. By placing buy orders near these support levels or sell orders at resistance levels, traders can capitalize on price movements with better accuracy. Fibonacci trading is particularly effective in volatile markets, where price movements can be rapid and significant. It’s essential to combine Fibonacci levels with other indicators, like moving averages or trend lines, to increase the strategy’s effectiveness. With its blend of mathematical precision and market psychology, the Fibonacci Algorithmic Trading Strategy is a powerful tool for traders aiming to enhance their trading performance.
import yfinance as yf
import pandas as pd
import matplotlib.pyplot as plt
from pandas.tseries.holiday import AbstractHolidayCalendar, Holiday
# Define a class for NSE Holidays
class NSEHolidayCalendar(AbstractHolidayCalendar):
rules = [
Holiday('New Year', month=1, day=1),
# Add more specific holidays as required
]
# Function to calculate Fibonacci Retracement levels
def fibonacci_levels(price_high, price_low):
levels = [0.236, 0.382, 0.5, 0.618, 0.786]
colors = ['red', 'blue', 'green', 'purple', 'orange']
return {level: (price_high - (price_high - price_low) * level, color) for level, color in zip(levels, colors)}
# Load data from Yahoo Finance and exclude non-trading days
def load_data(ticker):
data = yf.download(ticker, start='2024-01-01', end='2024-05-31')
data = data[data.index.dayofweek < 5] # Exclude weekends
cal = NSEHolidayCalendar()
holidays = cal.holidays(start=data.index.min(), end=data.index.max())
data = data[~data.index.isin(holidays)]
return data['Close']
# Analyzing stock data and plotting buy/sell signals
def analyze_stock(ticker):
data = load_data(ticker)
price_max = data.max()
price_min = data.min()
fib_levels = fibonacci_levels(price_max, price_min)
buy_price = fib_levels[0.618][0]
sell_price = buy_price * 1.10
stop_loss_price = buy_price * 0.98
plt.figure(figsize=(12, 6))
plt.title(f"Fibonacci Retracement Levels for {ticker}")
plt.plot(data, label='Price')
for level, (price, color) in fib_levels.items():
plt.axhline(y=price, color=color, linestyle='--', label=f'Fib {level*100}%: {price:.2f}')
percentage_returns = []
in_position = False
purchase_price = 0
for date, price in data.items():
if not in_position and price <= buy_price:
plt.scatter(date, price, color='green', marker='^', alpha=1)
plt.annotate(f'Buy @ {price:.2f} on {date.strftime("%Y-%m-%d")}', (date, price), textcoords="offset points", xytext=(0,10), ha='center', color='green')
in_position = True
purchase_price = price
elif in_position:
if price <= purchase_price * 0.98:
plt.scatter(date, price, color='darkred', marker='v', alpha=1)
plt.annotate(f'Stop-Loss Sell @ {price:.2f} on {date.strftime("%Y-%m-%d")}', (date, price), textcoords="offset points", xytext=(0,-15), ha='center', color='darkred')
percentage_returns.append((price - purchase_price) / purchase_price* 100)
in_position = False
elif price >= sell_price:
plt.scatter(date, price, color='red', marker='v', alpha=1)
plt.annotate(f'Sell @ {price:.2f} on {date.strftime("%Y-%m-%d")}', (date, price), textcoords="offset points", xytext=(0,-15), ha='center', color='red')
percentage_returns.append((price - purchase_price) / purchase_price * 100)
in_position = False
plt.legend()
plt.show()
# Calculate total percentage return
total_percentage_return = sum(percentage_returns)
print(f'Total percentage return for the period: {total_percentage_return:.2f}%')
# Example analysis for an NSE stock
analyze_stock('sbin.NS')