import pandas as pd
import numpy as np
import yfinance as yf
import ta
import logging
from datetime import datetime, timedelta
from dataclasses import dataclass
import argparse
from scipy.stats import linregress
import matplotlib.pyplot as plt
import multiprocessing as mp
from sklearn.ensemble import RandomForestRegressor
from sklearn.model_selection import TimeSeriesSplit
import joblib
from itertools import product
import numba
from numba import njit
from numba.typed import List
@dataclass
class StrategyParams:
basis_type: str
basis_len: int
offset_sigma: int # Only used for ALMA
offset_alma: float # Only used for ALMA
offset_lsma: int # Only used for LSMA
stop_loss: float
take_profit: float
use_res: bool
int_res: int
delay_offset: int
trade_type: str
timeframe: str
code
def get_param_dict(self):
"""Convert parameters to dictionary for easy storage/comparison"""
return {
'basis_type': self.basis_type,
'basis_len': self.basis_len,
'offset_sigma': self.offset_sigma if self.basis_type == 'ALMA' else None,
'offset_alma': self.offset_alma if self.basis_type == 'ALMA' else None,
'offset_lsma': self.offset_lsma if self.basis_type == 'LSMA' else None,
'stop_loss': self.stop_loss,
'take_profit': self.take_profit
}
import re
match = re.match(r'(\d+)([mhd])', timeframe.lower())
if match:
num, unit = match.groups()
base_unit = timeframe_map.get(timeframe, 'D')
return f"{int(num) * int_res}{base_unit}"
return f"{int_res}D"
def apply_strategy(data, params: StrategyParams):
"""Apply the trading strategy to the data."""
logging.info(f"Calculating {params.basis_type} moving averages with period {params.basis_len}")
def fetch_data(ticker, start, end, timeframe):
"""Fetch data from Yahoo Finance with proper timeframe handling."""
valid_intervals = ['1m', '2m', '5m', '15m', '30m', '60m', '90m',
'1h', '1d', '5d', '1wk', '1mo', '3mo']
code
if timeframe not in valid_intervals:
raise ValueError(f"Invalid interval: {timeframe}. Must be one of {valid_intervals}")
if timeframe in ['1m', '2m', '5m', '15m', '30m', '60m', '90m']:
end_date = pd.Timestamp(end)
start_date = pd.Timestamp(start)
if (end_date - start_date).days > 7:
logging.warning("Yahoo Finance limits intraday data to 7 days. Adjusting start date.")
start = (end_date - pd.Timedelta(days=7)).strftime('%Y-%m-%d')
try:
data = yf.download(ticker, start=start, end=end, interval=timeframe)
if data.empty:
raise ValueError(f"No data found for {ticker}")
return data
except Exception as e:
logging.error(f"Error fetching data for {ticker}: {e}")
return None
def optimize_with_brute_force(data, ticker, timeframe):
"""Run brute-force parameter optimization with conditional parameters."""
from itertools import product
code
# Define base parameter grids
basis_types = ['SMA', 'EMA', 'TEMA', 'HullMA', 'LSMA', 'ALMA']
basis_lens = range(10, 51, 10) # 10, 20, 30, 40, 50
stop_losses = [round(x * 0.5, 1) for x in range(1, 11)] # 0.5 to 5.0
take_profits = [round(x * 0.5, 1) for x in range(1, 11)] # 0.5 to 5.0
# Create parameter combinations for each MA type separately
parameter_combinations = []
# Basic MAs (SMA, EMA, TEMA, HullMA)
basic_mas = ['SMA', 'EMA', 'TEMA', 'HullMA']
for ma_type in basic_mas:
params = product(
[ma_type],
basis_lens,
[6], # dummy offset_sigma
[0.85], # dummy offset_alma
[0], # dummy offset_lsma
stop_losses,
take_profits
)
parameter_combinations.extend(params)
# ALMA specific parameters
offset_sigmas = range(1, 6) # 1 to 5
offset_almas = [round(x * 0.1, 1) for x in range(1, 11)] # 0.1 to 1.0
alma_params = product(
['ALMA'],
basis_lens,
offset_sigmas,
offset_almas,
[0], # dummy offset_lsma
stop_losses,
take_profits
)
parameter_combinations.extend(alma_params)
# LSMA specific parameters
offset_lsmas = range(-5, 6) # -5 to 5
lsma_params = product(
['LSMA'],
basis_lens,
[6], # dummy offset_sigma
[0.85], # dummy offset_alma
offset_lsmas,
stop_losses,
take_profits
)
parameter_combinations.extend(lsma_params)
logging.info(f"Total parameter combinations to evaluate: {len(parameter_combinations)}")
# Prepare arguments for the worker function
eval_args = [(params, data, timeframe) for params in parameter_combinations]
# Utilize multiprocessing Pool
n_cores = max(1, mp.cpu_count() - 1)
logging.info(f"Using {n_cores} cores for parallel processing")
with mp.Pool(n_cores) as pool:
results = pool.map(evaluate_params, eval_args)
# Find the best parameters
best_params, best_profit = max(results, key=lambda x: x[1])
logging.info(f"Best Profit: {best_profit} with parameters: {best_params}")
return best_params, best_profit
def calculate_portfolio_metrics(all_results, initial_capital=10000):
"""Calculate portfolio metrics including percentage returns."""
total_profit = sum(r['total_profit'] for r in all_results)
percentage_return = (total_profit / initial_capital) * 100
code
return {
'total_profit': total_profit,
'percentage_return': percentage_return,
'avg_win_rate': np.mean([r['win_rate'] for r in all_results]),
'total_trades': sum(r['total_trades'] for r in all_results)
}
logging.info("\n" + "=" * 80)
logging.info("BACKTEST SUMMARY FOR ALL TICKERS")
logging.info("=" * 80)
# Print individual performance
logging.info("\nIndividual Performance:")
logging.info(f"{'Ticker':<10} {'Return %':<12} {'Win Rate':<12} {'Trades':<8} {'Params':<40}")
logging.info("-" * 80)
for result in sorted(all_results, key=lambda x: x['total_profit'], reverse=True):
return_pct = (result['total_profit'] / (initial_capital / len(all_results))) * 100
params = result['params'].get_param_dict()
param_str = f"{params['basis_type']}({params['basis_len']})"
# Add specific parameters based on MA type
if params['basis_type'] == 'ALMA':
param_str += f" σ={params['offset_sigma']} α={params['offset_alma']:.2f}"
elif params['basis_type'] == 'LSMA':
param_str += f" offset={params['offset_lsma']}"
logging.info(f"{result['ticker']:<10} "
f"{return_pct:>8.2f}% "
f"{result['win_rate']:>8.2f}% "
f"{result['total_trades']:>6} "
f"{param_str:<40}")
# Print portfolio summary
logging.info("\nPortfolio Summary:")
logging.info("-" * 80)
logging.info(f"Total Portfolio Return: {metrics['percentage_return']:.2f}%")
logging.info(f"Average Win Rate: {metrics['avg_win_rate']:.2f}%")
logging.info(f"Total Number of Trades: {metrics['total_trades']}")
# Print best parameters
best_result = max(all_results, key=lambda x: x['total_profit'])
logging.info("\nBest Strategy Parameters:")
logging.info("-" * 80)
best_params = best_result['params'].get_param_dict()
for param, value in best_params.items():
if value is not None: # Only print relevant parameters
logging.info(f"{param}: {value}")
def main():
parser = argparse.ArgumentParser(description="Trading Bot with Multi-Timeframe Support")
parser.add_argument('-t', '--tickers', nargs='+', required=True,
help='List of tickers to analyze')
parser.add_argument('-s', '--start', required=True,
help='Start date (YYYY-MM-DD)')
parser.add_argument('-e', '--end', required=True,
help='End date (YYYY-MM-DD)')
parser.add_argument('-tf', '--timeframe',
choices=['1m', '2m', '5m', '15m', '30m', '1h', '4h', '1d'],
default='1d',
help='Trading timeframe')
parser.add_argument('-o', '--optimize', action='store_true',
help='Run parameter optimization')
parser.add_argument('--no-plot', action='store_true',
help='Disable plotting')
parser.add_argument('--initial-capital', type=float, default=10000,
help='Initial capital for percentage calculations')
code
args = parser.parse_args()
all_results = []
# Process all tickers
for ticker in args.tickers:
logging.info(f"\nProcessing {ticker}")
logging.info("=" * 50)
try:
data = fetch_data(ticker, args.start, args.end, args.timeframe)
if data is None or data.empty:
continue
if args.optimize:
best_params_tuple, best_profit = optimize_with_brute_force(data, ticker, args.timeframe)
# Unpack best_params_tuple
basis_type, basis_len, offset_sigma, offset_alma, offset_lsma, stop_loss, take_profit = best_params_tuple
strategy_params = StrategyParams(
basis_type=basis_type,
basis_len=basis_len,
offset_sigma=offset_sigma if basis_type == 'ALMA' else 6,
offset_alma=offset_alma if basis_type == 'ALMA' else 0.85,
offset_lsma=offset_lsma if basis_type == 'LSMA' else 0,
stop_loss=stop_loss,
take_profit=take_profit,
use_res=True,
int_res=2,
delay_offset=0,
trade_type='BOTH',
timeframe=args.timeframe
)
else:
strategy_params = StrategyParams(
basis_type='EMA',
basis_len=20,
offset_sigma=6,
offset_alma=0.85,
offset_lsma=0,
stop_loss=2.0,
take_profit=4.0,
use_res=True,
int_res=2,
delay_offset=0,
trade_type='BOTH',
timeframe=args.timeframe
)
# Apply strategy and run backtest
strategy_data = apply_strategy(data.copy(), strategy_params)
total_profit, win_rate, total_trades = backtest(strategy_data, strategy_params)
# Calculate percentage return based on allocated capital
allocated_capital = args.initial_capital / len(args.tickers)
percentage_return = (total_profit / allocated_capital) * 100
# Store results
result = {
'ticker': ticker,
'timeframe': args.timeframe,
'total_profit': percentage_return, # Store as percentage
'win_rate': win_rate,
'total_trades': total_trades,
'params': strategy_params,
'trades': [] # Trades are not stored in this example
}
all_results.append(result)
if not args.no_plot:
plot_backtest(strategy_data, strategy_params, ticker, percentage_return, win_rate)
except Exception as e:
logging.error(f"Error processing {ticker}: {str(e)}")
continue
# Print final summary with percentage returns
if all_results:
print_summary(all_results, args.initial_capital)
if name == "main":
try:
main()
except KeyboardInterrupt:
logging.info("\nExecution interrupted by user")
except Exception as e:
logging.error(f"Unexpected error: {str(e)}")
finally:
logging.info("\nExecution completed")
Certainly! Let's thoroughly examine your Python trading bot code to identify and explain potential errors, including syntax issues, logical flaws, and compatibility problems. Here's a comprehensive analysis:
1. Incorrect Mapping in get_resample_rule Function
Issue:
In the get_resample_rule function, the timeframe_map dictionary is used to map specific timeframes to pandas resample rules. However, after extracting the numerical and unit components using regex, the function incorrectly attempts to retrieve the base_unit using the full timeframe string instead of just the unit.
The timeframe_map uses specific timeframes like '1m', '2m', etc., as keys.
After regex matching, unit captures only the unit part ('m', 'h', 'd'), but the code attempts to map using the entire timeframe (e.g., '3h'), which may not exist in timeframe_map.
This leads to incorrect resample rules defaulting to 'D' when the exact timeframe isn't found.
Solution:
Modify the mapping to use the unit extracted from regex to determine the base_unit. Here's the corrected code:
python
def get_resample_rule(timeframe, int_res):
"""Convert timeframe to proper resample rule using updated pandas offset aliases."""
timeframe_map = {
'm': 'T',
'h': 'H',
'd': 'D',
'wk': 'W'
}
import re
match = re.match(r'(\d+)([mhdwk]+)', timeframe.lower())
if match:
num, unit = match.groups()
base_unit = timeframe_map.get(unit, 'D') # Corrected mapping
return f"{int(num) * int_res}{base_unit}"
return f"{int_res}D"
Additional Notes:
Expanded the regex to include 'wk' for weeks.
Ensured that the unit is correctly mapped to pandas' offset aliases.
2. Undefined Variable params_trade_type in backtest_numba Function
Issue:
The backtest_numba function utilizes the variable params_trade_type, which is not passed as an argument nor defined within the function's scope.
Problematic Code:
python
@njit
def backtest_numba(close_prices, signals, params_stop_loss, params_take_profit):
"""Numba-accelerated backtesting logic."""
...
if signal == 1 and (params_trade_type in [1, 3]): # LONG or BOTH
...
elif signal == -1 and (params_trade_type in [2, 3]): # SHORT or BOTH
...
Why It's an Error:
params_trade_type is defined as a global variable outside the JIT-compiled function.
Numba's njit does not support accessing global variables in the same way regular Python functions do.
This will lead to a NameError or compilation failure.
Solution:
Modify the backtest_numba function to accept params_trade_type as an explicit argument and pass it from the calling function.
Modify the backtest Function to Pass params_trade_type:
python
def backtest(data, params: StrategyParams):
"""Perform backtesting of the strategy using Numba."""
if params.trade_type == 'LONG':
params_trade_type = 1
elif params.trade_type == 'SHORT':
params_trade_type = 2
else:
params_trade_type = 3 # BOTH
close_prices = data['Close'].values
signals = data['Signal'].values.astype(np.int8)
total_profit, win_rate, total_trades = backtest_numba(
close_prices,
signals,
params.stop_loss,
params.take_profit,
params_trade_type # Pass the trade type here
)
return total_profit, win_rate, total_trades
3. Improper Initialization of Numba Typed Lists in backtest_numba
Issue:
The Numba List is initialized without specifying the data type, which can lead to type inference issues during compilation.
Problematic Code:
python
from numba.typed import List
@njit
def backtest_numba(...):
...
profit_loss = List() # Missing type specification
trades = List()
...
Why It's an Error:
Numba requires typed lists to have their data types explicitly defined to ensure type safety and optimize performance.
Omitting type specifications can lead to compilation errors or unexpected behavior.
Solution:
Initialize typed lists with a predefined data type using List.empty_list(dtype).
Corrected Code:
python
from numba.typed import List
from numba import float64
@njit
def backtest_numba(close_prices, signals, params_stop_loss, params_take_profit, params_trade_type):
"""Numba-accelerated backtesting logic."""
...
profit_loss = List.empty_list(float64) # Specify data type
trades = List.empty_list(float64) # Specify data type if needed
...
Additional Notes:
If you plan to store different data types in trades, you'd need to define them accordingly or use separate lists for different types of data.
4. Division by Zero Risk in linregress_numba Function
Issue:
The linregress_numba function computes the slope as cov_xy / var_x without checking if var_x is zero, potentially leading to a division by zero error.
Problematic Code:
python
@njit
def linregress_numba(x, y):
"""Numba-accelerated linear regression."""
...
slope = cov_xy / var_x # No check for var_x == 0
intercept = y_mean - slope * x_mean
return slope, intercept
Why It's an Error:
If all x values are identical, var_x becomes zero, causing a division by zero.
Although in lsma_numba, x is generated using np.arange(len(y)), which ensures variability, defensive programming is still recommended.
Solution:
Add a check to handle cases where var_x is zero.
Setting slope to 0.0 when var_x is zero ensures that the regression line is horizontal, which is a reasonable default behavior.
5. Misaligned Percentage Calculations in print_summary Function
Issue:
In the print_summary function, return_pct is calculated by dividing result['total_profit'] by allocated capital and then multiplying by 100. However, result['total_profit'] is already stored as a percentage, leading to an incorrect scaling.
result['total_profit'] is already a percentage return based on the allocated capital.
Dividing it again by (initial_capital / len(all_results)) and multiplying by 100 artificially inflates the percentage.
Solution:
Remove the unnecessary division and multiplication. Directly use result['total_profit'] as the percentage return.
Corrected Code:
python
def print_summary(all_results, initial_capital=10000):
...
for result in sorted(all_results, key=lambda x: x['total_profit'], reverse=True):
return_pct = result['total_profit'] # Already a percentage
...
logging.info(f"{result['ticker']:<10} "
f"{return_pct:>8.2f}% "
...
)
6. Incorrect Portfolio Metrics Calculation in calculate_portfolio_metrics Function
Issue:
The calculate_portfolio_metrics function sums up percentage returns across all results and then divides by the initial capital to compute the overall percentage return. This approach is incorrect as it conflates absolute profit with percentage returns.
Problematic Code:
python
def calculate_portfolio_metrics(all_results, initial_capital=10000):
"""Calculate portfolio metrics including percentage returns."""
total_profit = sum(r['total_profit'] for r in all_results) # Sum of percentages
percentage_return = (total_profit / initial_capital) * 100 # Incorrect calculation
...
Why It's an Error:
Summing percentage returns across different assets or strategies doesn't provide a meaningful portfolio return.
Dividing by the initial_capital again misinterprets the percentage values as absolute profits.
Solution:
If all_results stores percentage returns based on allocated capital per ticker, the overall portfolio return should be the average of these percentages, not the sum. Alternatively, if you track absolute profits, sum them and then calculate the percentage based on total capital.
Corrected Code (Assuming total_profit is Percentage Return per Ticker):
python
def calculate_portfolio_metrics(all_results, initial_capital=10000):
"""Calculate portfolio metrics including percentage returns."""
average_profit = np.mean([r['total_profit'] for r in all_results]) # Average percentage
return {
'total_profit': average_profit,
'percentage_return': average_profit, # Same as average profit
'avg_win_rate': np.mean([r['win_rate'] for r in all_results]),
'total_trades': sum(r['total_trades'] for r in all_results)
}
Alternative Approach (If Tracking Absolute Profits):
Ensure total_profit in all_results is stored as an absolute amount (not percentage). Then:
python
def calculate_portfolio_metrics(all_results, initial_capital=10000):
"""Calculate portfolio metrics including percentage returns."""
total_profit = sum(r['total_profit'] for r in all_results) # Sum of absolute profits
percentage_return = (total_profit / initial_capital) * 100 # Percentage based on total capital
return {
'total_profit': total_profit,
'percentage_return': percentage_return,
'avg_win_rate': np.mean([r['win_rate'] for r in all_results]),
'total_trades': sum(r['total_trades'] for r in all_results)
}
Recommendation:
Decide whether all_results['total_profit'] should store absolute profits or percentage returns. Keep it consistent throughout the code to avoid confusion.
7. Summing Percentage Returns Directly for Portfolio Performance
Issue:
In the print_summary function, portfolio performance is calculated by summing percentage returns of individual tickers directly. This approach is mathematically incorrect as it doesn't account for the relative investment sizes or compounding effects.
Summing percentage returns assumes that each percentage is additive, which isn't the case in portfolio performance.
This method ignores the proportional allocation of capital and the impact of each asset's performance on the overall portfolio.
Solution:
Compute the portfolio return by aggregating absolute profits based on allocated capital per ticker, then convert to a percentage.
Corrected Approach:
Ensure all_results['total_profit'] captures absolute profits relative to allocated_capital per ticker.
python
def print_summary(all_results, initial_capital=10000):
"""Print comprehensive summary with percentage returns."""
metrics = calculate_portfolio_metrics(all_results, initial_capital)
logging.info("\n" + "=" * 80)
logging.info("BACKTEST SUMMARY FOR ALL TICKERS")
logging.info("=" * 80)
# Print individual performance
logging.info("\nIndividual Performance:")
logging.info(f"{'Ticker':<10} {'Return %':<12} {'Win Rate':<12} {'Trades':<8} {'Params':<40}")
logging.info("-" * 80)
for result in sorted(all_results, key=lambda x: x['total_profit'], reverse=True):
return_pct = result['total_profit'] # Already calculated as percentage in main
...
logging.info(f"{result['ticker']:<10} "
f"{return_pct:>8.2f}% "
...
)
...
Additional Notes:
Avoid directly summing percentages. Instead, average them or calculate the weighted return based on capital allocation.
Ensure consistency in how profits are represented (absolute vs. percentage) across all functions.
8. Potential Explosion in Parameter Combinations During Optimization
Issue:
While not a direct syntax or logical error, the optimize_with_brute_force function uses brute-force parameter optimization, which can lead to an exponential increase in parameter combinations, especially with broader parameter ranges.
Problematic Code:
python
basis_lens = range(10, 51, 10) # 10, 20, 30, 40, 50
stop_losses = [round(x * 0.5, 1) for x in range(1, 11)] # 0.5 to 5.0
take_profits = [round(x * 0.5, 1) for x in range(1, 11)] # 0.5 to 5.0
# Create parameter combinations for each MA type separately
parameter_combinations = []
# Basic MAs (SMA, EMA, TEMA, HullMA)
basic_mas = ['SMA', 'EMA', 'TEMA', 'HullMA']
for ma_type in basic_mas:
params = product(
[ma_type],
basis_lens,
[6], # dummy offset_sigma
[0.85], # dummy offset_alma
[0], # dummy offset_lsma
stop_losses,
take_profits
)
parameter_combinations.extend(params)
# ALMA specific parameters
offset_sigmas = range(1, 6) # 1 to 5
offset_almas = [round(x * 0.1, 1) for x in range(1, 11)] # 0.1 to 1.0
alma_params = product(
['ALMA'],
basis_lens,
offset_sigmas,
offset_almas,
[0], # dummy offset_lsma
stop_losses,
take_profits
)
parameter_combinations.extend(alma_params)
# LSMA specific parameters
offset_lsmas = range(-5, 6) # -5 to 5
lsma_params = product(
['LSMA'],
basis_lens,
[6], # dummy offset_sigma
[0.85], # dummy offset_alma
offset_lsmas,
stop_losses,
take_profits
)
parameter_combinations.extend(lsma_params)
logging.info(f"Total parameter combinations to evaluate: {len(parameter_combinations)}")
Why It's a Concern:
Combinatorial Explosion: For example, for ALMA, there are:
5 basis_lens
5 offset_sigmas
10 offset_almas
10 stop_losses
10 take_profits
Total: 5 * 5 * 10 * 10 * 10 = 25,000 combinations
With multiple MA types, the total number can grow significantly, leading to:
Increased computation time
High memory usage
Potential system performance issues
Solution:
Implement strategies to reduce the number of parameter combinations, such as:
Grid Reduction: Use fewer steps or narrower ranges for certain parameters.
Random Sampling: Instead of evaluating all combinations, randomly sample a subset.
Sequential Optimization: Use more efficient optimization techniques like Bayesian Optimization, Genetic Algorithms, or Sequential Model-Based Optimization.
Example Adjustment:
python
# Reduce parameter ranges
basis_lens = range(10, 51, 10) # Keep as is or reduce further if needed
stop_losses = [1.0, 2.5, 5.0] # Reduced set
take_profits = [1.0, 2.5, 5.0] # Reduced set
# Rest of the code remains the same
Additional Notes:
Balancing between parameter granularity and computational feasibility is crucial.
Consider parallel processing limits and system capabilities when determining the breadth of parameter exploration.
9. Inconsistent Naming for offset_sigma and offset_alma Parameters
Issue:
There's an inconsistency in naming and usage of offset_sigma and offset_alma between the StrategyParams dataclass and how they're used in the alma_numba function and elsewhere.
Problematic Code:
python
@dataclass
class StrategyParams:
...
offset_sigma: int # Only used for ALMA
offset_alma: float # Only used for ALMA
...
The StrategyParams class uses offset_sigma, implying a relationship with sigma in ALMA.
In alma_numba, the parameter is named sigma.
This can lead to confusion and potential mismatches if not consistently handled.
Solution:
Ensure consistent naming conventions across the dataclass and all function parameters to maintain clarity and avoid misassignments.
Corrected Code:
python
@dataclass
class StrategyParams:
...
alma_sigma: int # Renamed for clarity
alma_offset: float # Renamed for clarity
...
def alma(src, length, sigma=6, offset=0.85):
"""Arnaud Legoux Moving Average using Numba."""
alma_padded = alma_numba(src.values, length, sigma, offset)
return pd.Series(alma_padded, index=src.index)
Additionally:
Update all instances where offset_sigma and offset_alma are used to alma_sigma and alma_offset respectively.
This reduces ambiguity and clarifies that these parameters are specific to the ALMA moving average.
10. Missing Handling for Optimization Failures
Issue:
In the optimize_with_brute_force function, if all parameter evaluations fail or return -np.inf, attempting to find the maximum using max(results, key=lambda x: x[1]) will still return a tuple, potentially with -np.inf.
If all parameter combinations raise exceptions and return -np.inf, the max function will still select one of them, leading to selecting invalid or ineffective parameters.
This can cause the bot to proceed with nonsensical strategy parameters, possibly leading to further errors or poor performance.
Solution:
Add a check to ensure that at least one parameter combination was successfully evaluated. If not, handle the situation gracefully.
Corrected Code:
python
def optimize_with_brute_force(data, ticker, timeframe):
...
with mp.Pool(n_cores) as pool:
results = pool.map(evaluate_params, eval_args)
# Filter out failed evaluations
valid_results = [res for res in results if res[1] != -np.inf]
if not valid_results:
logging.error("All parameter evaluations failed. Optimization aborted.")
return None, None
# Find the best parameters
best_params, best_profit = max(valid_results, key=lambda x: x[1])
logging.info(f"Best Profit: {best_profit} with parameters: {best_params}")
return best_params, best_profit
Additionally:
In the main function, handle the case where optimization returns None for parameters.
This prevents the bot from attempting to apply invalid strategies.
python
if args.optimize:
best_params_tuple, best_profit = optimize_with_brute_force(data, ticker, args.timeframe)
if best_params_tuple is None:
logging.error("Optimization failed for this ticker. Skipping.")
continue
...
Summary of Identified Errors and Solutions
Incorrect Mapping in get_resample_rule: Mapped full timeframe string instead of just the unit. Solution: Map based on the extracted unit.
Undefined Variable params_trade_type in backtest_numba: Not passed as an argument. Solution: Pass params_trade_type explicitly to the function.
Improper Initialization of Numba Typed Lists: Missing type specifications. Solution: Initialize with List.empty_list(float64).
Division by Zero Risk in linregress_numba: No check for var_x == 0. Solution: Add a conditional check to handle zero variance.
Misaligned Percentage Calculations in print_summary: Incorrect scaling of already percentage-based profits. Solution: Use result['total_profit'] directly without further manipulation.
Incorrect Portfolio Metrics Calculation: Summing percentages inaccurately represents portfolio performance. Solution: Calculate portfolio return based on aggregated absolute profits or properly weighted percentages.
Summing Percentage Returns Directly: Mathematically incorrect to sum percentages without weighting. Solution: Average percentages or compute weighted returns based on capital allocation.
Potential Explosion in Parameter Combinations: Brute-force approach may lead to excessive computations. Solution: Limit parameter ranges or adopt more efficient optimization methods.
Inconsistent Naming for offset_sigma and offset_alma: Causes confusion and potential mismatches. Solution: Use consistent and clear naming conventions across the codebase.
Missing Handling for Optimization Failures: Selecting invalid parameters when all evaluations fail. Solution: Add checks to ensure at least one valid parameter set exists before proceeding.
By addressing these issues, your trading bot will not only be more robust and error-free but also more efficient and reliable in its operations. Always ensure to test each component thoroughly after making corrections to validate their effectiveness.