what are all the errors i have here?
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")
The code you've provided is a comprehensive trading bot that incorporates various technical indicators, backtesting, and optimization routines. However, there are several errors and issues throughout the code that may prevent it from running correctly. Below is a detailed analysis of the errors and suggestions on how to fix them:
1. Numba Compatibility Issues
Problem in alma_numba Function:
Use of Unsupported Functions: The alma_numba function uses np.convolve and np.concatenate, which are not supported in Numba's nopython mode.
Rewrite the Function Without Unsupported Functions: Implement the convolution manually within Numba-supported operations.
Recommendation: For simplicity, it's advisable to remove the @njit decorator from alma_numba and potentially from alma as well since the performance gain might not outweigh the complexity of rewriting the function.
2. Global Variables in Numba Functions
Problem in backtest_numba Function:
Use of Undefined Global Variable: The variable params_trade_type is used inside the Numba-accelerated function backtest_numba, but it's not passed as an argument.
python
@njit
def backtest_numba(close_prices, signals, params_stop_loss, params_take_profit):
...
if signal == 1 and (params_trade_type in [1, 3]): # LONG or BOTH
...
Numba Limitation: Numba's nopython mode does not allow access to Python globals that are not compile-time constants.
3. Inconsistencies in Portfolio Return Calculations
Problem with total_profit and percentage_return:
Inconsistent Use of total_profit: In the main function, total_profit is calculated as the sum of price differences, but later it's treated as a percentage.
python
percentage_return = (total_profit / allocated_capital) * 100
result = {
'total_profit': percentage_return, # Store as percentage
...
}
Incorrect Summation: In calculate_portfolio_metrics, the total portfolio profit is calculated by summing up percentage_returns, which is conceptually incorrect.
python
def calculate_portfolio_metrics(all_results, initial_capital=10000):
total_profit = sum(r['total_profit'] for r in all_results)
percentage_return = (total_profit / initial_capital) * 100
...
Solution:
Store Actual Profit Values: Store total_profit as actual profit in dollars, not as a percentage.
python
result = {
'total_profit': total_profit, # Store as actual profit in dollars
...
}
def fetch_data(ticker, start, end, timeframe):
yf_timeframe = TIMEFRAME_MAP.get(timeframe)
if yf_timeframe is None:
raise ValueError(f"Invalid timeframe: {timeframe}")
...
data = yf.download(ticker, start=start, end=end, interval=yf_timeframe)
...
Adjust Valid Intervals and Argument Parsing Accordingly.
5. Potential Multiprocessing Errors with Unpicklable Objects
Problem in optimize_with_brute_force Function:
Data Passing in Multiprocessing: The data object passed to worker functions may not be picklable, especially if it contains non-serializable components.
python
eval_args = [(params, data, timeframe) for params in parameter_combinations]
with mp.Pool(n_cores) as pool:
results = pool.map(evaluate_params, eval_args)
Solution:
Avoid Passing Large Data Objects Directly: Consider sharing data using global variables or other shared memory mechanisms like multiprocessing.Manager().
Use Thread-Based Parallelism: If data sharing is minimal and CPU-bound processing is acceptable, consider using concurrent.futures.ThreadPoolExecutor instead.
Ensure Data is Picklable: Verify that the data object is picklable. If not, reduce its size or simplify its structure.
6. Miscellaneous Errors and Improvements
Issue with variant_ma Function for Hull Moving Average:
Potential Calculation Error: The computation of the Hull Moving Average may not be correct due to incorrect input types.
Use Distinct Variable Names: Rename inner variables to avoid shadowing outer variables.
Summary of Actions to Fix Errors
Remove or Fix Numba Decorators: Modify functions like alma_numba to remove unsupported operations or remove the Numba decorator.
Pass All Required Variables to Numba Functions: Ensure all variables used in Numba functions are passed as arguments.
Standardize Profit Calculations: Store and calculate profits consistently, avoiding mixing absolute values and percentages without clear conversions.
Correct Timeframe Handling: Map user-friendly timeframes to those accepted by yfinance and adjust the code accordingly.
Adjust Multiprocessing Data Passing: Ensure that data passed to worker processes is picklable or restructure the multiprocessing approach.
Review and Fix Calculation Functions: Check functions like variant_ma and resampling logic for correctness.
Improve Variable Naming for Clarity: Use clear and distinct variable names to avoid confusion and potential bugs.
By addressing these issues, your code should become more robust, easier to maintain, and free from the errors that currently prevent it from running as intended. It's also recommended to include unit tests for critical functions to catch any future errors early in the development process.