fix: Handle dynamic stats keys and improve error handling in multi-ticker backtest

This commit is contained in:
Bobby (aider) 2025-02-14 00:02:49 -08:00
parent 282b740144
commit 0b9742eb61

View File

@ -477,25 +477,31 @@ def run_multi_ticker_backtest(tickers: list, start_date: datetime, end_date: dat
bt = Backtest(df, DynamicStrategy, cash=100000, commission=.002)
stats = bt.run()
# Store results
# Print raw stats for debugging
print("Debug - Available stats keys:", stats.keys())
# Store results with error handling for each metric
result = {
'Ticker': ticker,
'Return [%]': stats['Return [%]'],
'Sharpe Ratio': stats['Sharpe Ratio'],
'Max Drawdown [%]': stats['Max. Drawdown [%]'],
'Win Rate [%]': stats['Win Rate [%]'],
'Number of Trades': stats['# Trades']
'Return [%]': stats.get('Return [%]', stats.get('Return', 0)),
'Sharpe Ratio': stats.get('Sharpe Ratio', 0),
'Max Drawdown [%]': stats.get('Max. Drawdown [%]', stats.get('Max Drawdown', 0)),
'Win Rate [%]': stats.get('Win Rate [%]', stats.get('Win Rate', 0)),
'Number of Trades': stats.get('# Trades', stats.get('Number of Trades', 0))
}
all_results.append(result)
print(f"{ticker} - Return: {stats['Return [%]']:.2f}%, "
f"Sharpe: {stats['Sharpe Ratio']:.2f}, "
f"Drawdown: {stats['Max. Drawdown [%]']:.2f}%")
print(f"{ticker} - Return: {result['Return [%]']:.2f}%, "
f"Sharpe: {result['Sharpe Ratio']:.2f}, "
f"Drawdown: {result['Max Drawdown [%]']:.2f}%")
except Exception as e:
print(f"Error processing {ticker}: {str(e)}")
continue
if not all_results:
raise ValueError("No valid results were generated from any ticker")
return pd.DataFrame(all_results)
def display_backtest_results(results: Dict):