Certainly! I've revised your code to fix the issues with the dropdown and period boxes and to conform to your requirements. Below is the corrected and enhanced code, along with explanations of the changes made:
import tkinter as tk
import pandas as pd
import ccxt
from ta.momentum import RSIIndicator, StochasticOscillator
from ta.volatility import BollingerBands
from ta.trend import MACD
from backtesting import Backtest, Strategy
import matplotlib.pyplot as plt
from matplotlib.backends.backend_tkagg import FigureCanvasTkAgg
class TradingStrategy(Strategy):
# Define default parameter values
rsi_threshold = 30
macd_fast = 12
macd_slow = 26
bollinger_bands_window = 20
stochastic_oscillator_window = 14
# Define which indicators to use
use_rsi = True
use_macd = True
use_bollinger = True
use_stochastic = True
# Parameter names for optimization
params = ('rsi_threshold', 'macd_fast', 'macd_slow',
'bollinger_bands_window', 'stochastic_oscillator_window',
'use_rsi', 'use_macd', 'use_bollinger', 'use_stochastic')
def init(self):
# Convert data columns to pandas.Series
self.close = pd.Series(self.data.Close)
self.high = pd.Series(self.data.High)
self.low = pd.Series(self.data.Low)
# Initialize indicators based on selected options
if self.use_rsi:
self.rsi = self.I(RSIIndicator, self.close, window=14)
if self.use_macd:
self.macd = self.I(MACD, self.close, window_slow=self.macd_slow, window_fast=self.macd_fast)
if self.use_bollinger:
bb_indicator = BollingerBands(self.close, window=self.bollinger_bands_window, window_dev=2)
self.bollinger_mavg = self.I(lambda x: bb_indicator.bollinger_mavg(), self.close)
self.bollinger_hband = self.I(lambda x: bb_indicator.bollinger_hband(), self.close)
self.bollinger_lband = self.I(lambda x: bb_indicator.bollinger_lband(), self.close)
if self.use_stochastic:
self.stochastic = self.I(StochasticOscillator, self.high, self.low, self.close,
window=self.stochastic_oscillator_window)
def next(self):
# RSI Strategy
if self.use_rsi:
if self.rsi.rsi()[-1] < self.rsi_threshold:
self.buy()
elif self.rsi.rsi()[-1] > self.rsi_threshold + 20:
self.sell()
# MACD Strategy
if self.use_macd:
if self.macd.macd_diff()[-1] > 0 and self.macd.macd_diff()[-2] <= 0:
self.buy()
elif self.macd.macd_diff()[-1] < 0 and self.macd.macd_diff()[-2] >= 0:
self.sell()
# Bollinger Bands Strategy
if self.use_bollinger:
if self.close[-1] < self.bollinger_lband[-1]:
self.buy()
elif self.close[-1] > self.bollinger_hband[-1]:
self.sell()
# Stochastic Oscillator Strategy
if self.use_stochastic:
if self.stochastic.stoch()[-1] > self.stochastic.stoch_signal()[-1]:
self.buy()
elif self.stochastic.stoch()[-1] < self.stochastic.stoch_signal()[-1]:
self.sell()
class GUI:
def __init__(self, root):
self.root = root
self.root.title("Trading Strategy Backtester")
self.root.geometry("800x600")
# Ticker Entry
tk.Label(root, text="Ticker:").pack()
self.ticker_entry = tk.Entry(root)
self.ticker_entry.insert(0, 'BTC/USDT')
self.ticker_entry.pack()
# Timeframe Entry
tk.Label(root, text="Timeframe (e.g., '1m', '5m', '1h'):").pack()
self.timeframe_entry = tk.Entry(root)
self.timeframe_entry.insert(0, '1m')
self.timeframe_entry.pack()
# Indicator Selection
tk.Label(root, text="Select Indicators:").pack()
self.use_rsi_var = tk.BooleanVar(value=True)
tk.Checkbutton(root, text="RSI", variable=self.use_rsi_var).pack()
self.use_macd_var = tk.BooleanVar(value=True)
tk.Checkbutton(root, text="MACD", variable=self.use_macd_var).pack()
self.use_bollinger_var = tk.BooleanVar(value=True)
tk.Checkbutton(root, text="Bollinger Bands", variable=self.use_bollinger_var).pack()
self.use_stochastic_var = tk.BooleanVar(value=True)
tk.Checkbutton(root, text="Stochastic Oscillator", variable=self.use_stochastic_var).pack()
# RSI Parameters
self.rsi_threshold_label = tk.Label(root, text="RSI Threshold:")
self.rsi_threshold_label.pack()
self.rsi_threshold_entry = tk.Entry(root)
self.rsi_threshold_entry.insert(0, '30')
self.rsi_threshold_entry.pack()
# MACD Parameters
self.macd_fast_label = tk.Label(root, text="MACD Fast Period:")
self.macd_fast_label.pack()
self.macd_fast_entry = tk.Entry(root)
self.macd_fast_entry.insert(0, '12')
self.macd_fast_entry.pack()
self.macd_slow_label = tk.Label(root, text="MACD Slow Period:")
self.macd_slow_label.pack()
self.macd_slow_entry = tk.Entry(root)
self.macd_slow_entry.insert(0, '26')
self.macd_slow_entry.pack()
# Bollinger Bands Parameters
self.bollinger_window_label = tk.Label(root, text="Bollinger Bands Window:")
self.bollinger_window_label.pack()
self.bollinger_window_entry = tk.Entry(root)
self.bollinger_window_entry.insert(0, '20')
self.bollinger_window_entry.pack()
# Stochastic Oscillator Parameters
self.stochastic_window_label = tk.Label(root, text="Stochastic Oscillator Window:")
self.stochastic_window_label.pack()
self.stochastic_window_entry = tk.Entry(root)
self.stochastic_window_entry.insert(0, '14')
self.stochastic_window_entry.pack()
# Backtest and Plot Buttons
tk.Button(root, text="Backtest", command=self.backtest).pack()
tk.Button(root, text="Plot Results", command=self.plot).pack()
# Text widget to display backtest statistics
self.stats_text = tk.Text(root, height=10, width=80)
self.stats_text.pack()
def backtest(self):
# Fetch user inputs
ticker = self.ticker_entry.get()
timeframe = self.timeframe_entry.get()
exchange = ccxt.binance()
limit = 1000 # Maximum limit for fetching data
data = exchange.fetch_ohlcv(ticker, timeframe=timeframe, limit=limit)
df = pd.DataFrame(data, columns=['timestamp', 'Open', 'High', 'Low', 'Close', 'Volume'])
df['timestamp'] = pd.to_datetime(df['timestamp'], unit='ms')
df.set_index('timestamp', inplace=True)
# Define strategy parameters
strategy_params = {
'rsi_threshold': int(self.rsi_threshold_entry.get()),
'macd_fast': int(self.macd_fast_entry.get()),
'macd_slow': int(self.macd_slow_entry.get()),
'bollinger_bands_window': int(self.bollinger_window_entry.get()),
'stochastic_oscillator_window': int(self.stochastic_window_entry.get()),
'use_rsi': self.use_rsi_var.get(),
'use_macd': self.use_macd_var.get(),
'use_bollinger': self.use_bollinger_var.get(),
'use_stochastic': self.use_stochastic_var.get(),
}
# Run backtest
self.backtest_instance = Backtest(df, TradingStrategy, cash=100000, commission=.002)
self.stats = self.backtest_instance.run(**strategy_params)
self.display_stats()
def display_stats(self):
# Clear previous stats
self.stats_text.delete('1.0', tk.END)
# Display backtest statistics
stats_to_display = {
'Start Balance': self.stats['Start'],
'End Balance': self.stats['End'],
'Net Profit': self.stats['Net Profit'],
'Sharpe Ratio': self.stats['Sharpe Ratio'],
'Max Drawdown': self.stats['Max Drawdown'],
'Win Rate': self.stats['Win Rate [%]'],
'Trades': self.stats['_trades']
}
for key, value in stats_to_display.items():
self.stats_text.insert(tk.END, f"{key}: {value}\n")
def plot(self):
# Plot backtest results
if hasattr(self, 'backtest_instance'):
self.backtest_instance.plot()
else:
tk.messagebox.showwarning("Warning", "Please run a backtest first.")
if __name__ == "__main__":
root = tk.Tk()
gui = GUI(root)
root.mainloop()
Explanation of Changes:
-
Indicator Selection Fix:
- Replaced the single-option menu for indicators with individual checkboxes for each indicator (
RSI, MACD, Bollinger Bands, Stochastic Oscillator). This allows users to select multiple indicators.
- Used
tk.BooleanVar to keep track of the state (selected or not) of each checkbox.
-
Parameter Assignment Fix:
- Adjusted the
TradingStrategy class to accept parameters and use them correctly.
- Defined default parameter values and included additional parameters for indicator usage (
use_rsi, use_macd, etc.).
- In the
backtest method, fetched the parameter values from the GUI entries and checkbox states, passing them to the strategy via the run method.
-
Backtesting and Performance Display:
- The
backtest method now runs the strategy with the selected indicators and parameters.
- Added a
display_stats method to output key performance metrics such as Net Profit, Sharpe Ratio, Maximum Drawdown, and Win Rate to a tk.Text widget in the GUI.
-
Plotting Results:
- Simplified the
plot method to use the built-in plotting function from the Backtest class.
- Added a check to ensure that a backtest has been run before attempting to plot the results.
-
GUI Improvements:
- Grouped related widgets together and labeled them appropriately for better user experience.
- Included a timeframe entry to allow users to specify the data frequency.
- Added a warning message if the user tries to plot results without running a backtest first.
-
Code Corrections:
- Fixed parameter access in the
TradingStrategy class to use class attributes instead of indexing params.
- Replaced incorrect usage of data columns (e.g.,
self.data['Close']) with the correct attribute access (self.data.Close).
- Ensured indicators are only calculated and used if the corresponding checkbox is selected.
-
Commission Correction:
- Adjusted the commission rate in the backtest from (2%) to (0.2%), which is more typical for trading commissions.
Note:
- This code assumes that you have the required libraries installed (
ccxt, ta, backtesting, matplotlib, etc.).
- You may need to handle exceptions and edge cases as per your specific requirements.
- For a production environment, consider adding more robust error handling and input validation.
How to Use the Improved GUI:
-
Select the Ticker and Timeframe:
- Enter the desired trading pair (e.g.,
BTC/USDT) in the Ticker field.
- Specify the timeframe for the historical data (e.g.,
1m for 1-minute data).
-
Choose Indicators:
- Check the boxes next to the indicators you want to include in your strategy.
-
Set Indicator Parameters:
- For each selected indicator, input the desired parameters (e.g., RSI Threshold, MACD Fast and Slow periods).
-
Run Backtest:
- Click the Backtest button to run the strategy with the selected settings.
-
View Performance Metrics:
- The backtest statistics will be displayed in the text area at the bottom of the GUI.
-
Plot Results:
- Click the Plot Results button to visualize the strategy's performance over time.
Feel free to customize and extend this code to further meet your requirements!