can you please add optimization gui elemnts and operation to this app for optimizing the indicator periods and threshold vaes and equity as explained in documentation : DOCUMENTATION:
Backtesting
Let's see how our strategy performs on historical Google data. The Backtest instance is initialized with OHLC data and a strategy class (see API reference for additional options), and we begin with 10,000 units of cash and set broker's commission to realistic 0.2%.
Backtest.run() method returns a pandas Series of simulation results and statistics associated with our strategy. We see that this simple strategy makes almost 600% return in the period of 9 years, with maximum drawdown 33%, and with longest drawdown period spanning almost two years ...
Backtest.plot() method provides the same insights in a more visual form.
bt.plot()
Row(
id = '1450', …)
Optimization
We hard-coded the two lag parameters (n1 and n2) into our strategy above. However, the strategy may work better with 15–30 or some other cross-over. We declared the parameters as optimizable by making them class variables.
We optimize the two parameters by calling Backtest.optimize() method with each parameter a keyword argument pointing to its pool of possible values to test. Parameter n1 is tested for values in range between 5 and 30 and parameter n2 for values between 10 and 70, respectively. Some combinations of values of the two parameters are invalid, i.e. n1 should not be larger than or equal to n2. We limit admissible parameter combinations with an ad hoc constraint function, which takes in the parameters and returns True (i.e. admissible) whenever n1 is less than n2. Additionally, we search for such parameter combination that maximizes return over the observed period. We could instead choose to optimize any other key from the returned stats series.
We can look into stats['_strategy'] to access the Strategy instance and its optimal parameter values (10 and 15).
stats._strategy
<Strategy SmaCross(n1=10,n2=15)>
bt.plot(plot_volume=False, plot_pl=False)
Row(
id = '2059', …)
Strategy optimization managed to up its initial performance on in-sample data by almost 50% and even beat simple buy & hold. In real life optimization, however, do take steps to avoid overfitting.
Trade data
In addition to backtest statistics returned by Backtest.run() shown above, you can look into individual trade returns and the changing equity curve and drawdown by inspecting the last few, internal keys in the result series.
Learn more by exploring further examples or find more framework options in the full API reference.
CODE TO EXTEND : import tkinter as tk
from tkinter import ttk
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
from backtesting.lib import crossover
from matplotlib.backends.backend_tkagg import FigureCanvasTkAgg
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
from backtesting.lib import crossover
import matplotlib.pyplot as plt
import matplotlib.dates as mdates
if name == "main":
root = tk.Tk()
gui = GUI(root)
root.mainloop()
To add optimization GUI elements and operations to your app, you can modify your code to include options for parameter ranges, steps, and optimization controls, and then use the Backtest.optimize() method to perform the optimization as explained in the documentation.
Here's how you can proceed:
1. Modify the Strategy Class to Use Optimizable Parameters
First, adjust your TradingStrategy class to define the parameters you want to optimize as class variables. This is necessary for the Backtest.optimize() method to recognize and adjust these parameters during optimization.
2. Modify the GUI to Include Optimization Parameters
Add GUI elements to specify optimization ranges and steps for each parameter you want to optimize. For example, for rsi_length, you can add entries for minimum value, maximum value, and step size:
Add an optimize method to your GUI class that reads the optimization ranges from the GUI, prepares the parameter grid, and runs the optimization using Backtest.optimize().
python
def optimize(self):
# Get parameter ranges from entries
optimizable_parameters = {}
if self.rsi_include.get():
optimizable_parameters['rsi_length'] = range(
int(self.rsi_length_min_entry.get()),
int(self.rsi_length_max_entry.get()) + 1,
int(self.rsi_length_step_entry.get())
)
optimizable_parameters['rsi_threshold_buy'] = [float(self.rsi_threshold_buy_entry.get())]
optimizable_parameters['rsi_threshold_sell'] = [float(self.rsi_threshold_sell_entry.get())]
# Similar for other parameters and include checkboxes
# Fetch data
ticker = self.ticker_entry.get()
exchange = ccxt.binance()
data = exchange.fetch_ohlcv(ticker, timeframe='1h', since=1609459200000, limit=10000)
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)
# Run optimization
bt = Backtest(df, TradingStrategy, cash=1000000, commission=.02)
stats = bt.optimize(
**optimizable_parameters,
maximize='Equity Final [$]',
constraint=lambda param: param.rsi_length < param.bollinger_bands_window # Example constraint
)
# Display optimization results
print(f"Optimal Parameters: {stats._strategy}")
print(stats)
# Plot the equity curve of the best found strategy
bt.plot()
4. Adjust the Backtest Function (Optional)
If you have a separate backtest method, ensure it handles both regular backtesting and uses default parameters when optimization is not performed. You might need to adjust the way parameters are retrieved.
5. Present Optimization Results in the GUI
You can display the optimization results directly in the console or enhance your GUI to show them. For example, you could display the optimal parameters in a label or text area.
python
# In the optimize method, after printing stats
optimal_params_label_text = f"Optimal Parameters:\n{stats._strategy}"
self.optimal_params_label = tk.Label(root, text=optimal_params_label_text)
self.optimal_params_label.pack()
6. Handle Multiprocessing Issues (Important)
Since Backtest.optimize() uses multiprocessing, ensure your code is compatible with multiprocessing. This might require moving your strategy class to the top level of the script or ensuring that the code runs in the if __name__ == "__main__": block to avoid pickling errors.
Complete Example
Here's a condensed version of how these modifications might look in your code:
python
import tkinter as tk
from tkinter import ttk
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
from backtesting.lib import crossover
import matplotlib.pyplot as plt
# Strategy class adjusted with class variables
class TradingStrategy(Strategy):
rsi_length = 14
macd_fast = 12
# ... (other parameters as shown above)
def init(self):
# Use self.parameter_name
# ...
def next(self):
# Use self.parameter_name
# ...
class GUI:
def __init__(self, root):
# Existing GUI code
# Add entries for optimization ranges
# ...
# Add Optimize button
self.optimize_button = tk.Button(root, text="Optimize", command=self.optimize)
self.optimize_button.pack()
def optimize(self):
# Fetch parameter ranges from GUI
# ...
# Fetch data
# ...
# Run optimization
bt = Backtest(df, TradingStrategy, cash=1000000, commission=.02)
stats = bt.optimize(
**optimizable_parameters,
maximize='Equity Final [$]'
)
# Display results
print(f"Optimal Parameters: {stats._strategy}")
print(stats)
bt.plot()
# Optionally display in GUI
# ...
# Existing backtest method
# ...
if __name__ == "__main__":
root = tk.Tk()
gui = GUI(root)
root.mainloop()
Additional Notes
Constraints: If certain parameter combinations are invalid (e.g., n1 should not be greater than n2), use the constraint parameter in bt.optimize() as shown.
Performance: Optimization can be computationally intensive. Start with small ranges and steps to test your implementation.
Error Handling: Add error handling to manage invalid inputs or exceptions during optimization.
User Feedback: Provide feedback to the user during optimization, such as displaying a progress bar or status messages, since optimization might take some time.
By implementing these changes, you'll add optimization capabilities to your app, allowing users to find the best parameters for their trading strategies based on historical data.
I hope this helps you extend your application! If you have any questions or need further clarification, feel free to ask.