import pandas as pd
import numpy as np
# Load historical price data
# Assumes 'data' is a pandas DataFrame with 'Close' column and date as index
data = pd.read_csv('historical_data.csv', index_col='Date', parse_dates=True)
# Calculate Fibonacci levels
def calculate_fibonacci_levels(df):
max_price = df['Close'].max()
min_price = df['Close'].min()
diff = max_price - min_price
levels = {
'level_23.6': max_price - 0.236 * diff,
'level_38.2': max_price - 0.382 * diff,
'level_50.0': max_price - 0.500 * diff,
'level_61.8': max_price - 0.618 * diff,
'level_78.6': max_price - 0.786 * diff
}
return levels
# Backtest Fibonacci Trading Strategy
def backtest_fibonacci_strategy(df, levels):
# Initialize
in_position = False
entry_price = 0.0
stop_loss = 0.0
take_profit = 0.0
for index, row in df.iterrows():
close_price = row['Close']
if not in_position:
# Buy Signal: Price near Fibonacci retracement level in an uptrend
if close_price <= levels['level_38.2']:
in_position = True
entry_price = close_price
stop_loss = levels['level_61.8'] # Set a stop loss below the next Fibonacci level
take_profit = entry_price + (entry_price - stop_loss) * 2 # Example 2:1 risk-reward ratio
print(f"Buy at {close_price} on {index}")
else:
# Sell Signal: Either hit the stop loss or the take profit
if close_price <= stop_loss:
in_position = False
print(f"Stop Loss hit at {close_price} on {index}")
elif close_price >= take_profit:
in_position = False
print(f"Take Profit hit at {close_price} on {index}")
# Calculate Fibonacci levels using historical data
fibonacci_levels = calculate_fibonacci_levels(data)
# Backtest strategy
backtest_fibonacci_strategy(data, fibonacci_levels)