Skip to content
TheChatArchiveThe Chat Archive
Claudeclaude-3-5-haiku-20241022· AnthropicHugging Face LMArena Human Preference 140K

Help me backtest a strategy or write a simple bot using Python (e.g., for crypto trading…

From a Chatbot Arena battleThe same person sent this prompt to two anonymous models at once. Compare it with Mistralmistral-medium-2505’s answer.
  1. User

    Help me backtest a strategy or write a simple bot using Python (e.g., for crypto trading on Binance or similar platforms.

  2. Claude Assistant

    I'll provide a comprehensive Python script for backtesting a cryptocurrency trading strategy using the Binance API. This example will demonstrate a simple trend-following strategy with risk management.

    Prerequisites

    Before running the script, install these libraries:

    pip install ccxt pandas numpy matplotlib backtrader
    

    Complete Python Backtesting Script

    import ccxt
    import pandas as pd
    import numpy as np
    import matplotlib.pyplot as plt
    from datetime import datetime, timedelta
    
    class CryptoTradingBot:
        def __init__(self, symbol='BTC/USDT', timeframe='1h', 
                     initial_balance=10000, risk_per_trade=0.02):
            # Exchange Configuration
            self.exchange = ccxt.binance({
                'enableRateLimit': True,
                'options': {
                    'defaultType': 'future'  # Futures trading
                }
            })
            
            # Strategy Parameters
            self.symbol = symbol
            self.timeframe = timeframe
            self.initial_balance = initial_balance
            self.risk_per_trade = risk_per_trade
            
            # Trading Variables
            self.current_balance = initial_balance
            self.trades = []
    
        def fetch_historical_data(self, start_date, end_date):
            """Fetch historical price data"""
            ohlcv = self.exchange.fetch_ohlcv(
                self.symbol, 
                self.timeframe, 
                since=self.exchange.parse8601(start_date),
                limit=1000
            )
            
            df = pd.DataFrame(ohlcv, columns=[
                'timestamp', 'open', 'high', 'low', 'close', 'volume'
            ])
            df['timestamp'] = pd.to_datetime(df['timestamp'], unit='ms')
            df.set_index('timestamp', inplace=True)
            
            return df
    
        def calculate_indicators(self, df):
            """Calculate trading indicators"""
            # 50-day and 200-day Exponential Moving Averages
            df['EMA50'] = df['close'].ewm(span=50, adjust=False).mean()
            df['EMA200'] = df['close'].ewm(span=200, adjust=False).mean()
            
            # Relative Strength Index (RSI)
            delta = df['close'].diff()
            gain = (delta.where(delta > 0, 0)).rolling(window=14).mean()
            loss = (-delta.where(delta < 0, 0)).rolling(window=14).mean()
            
            rs = gain / loss
            df['RSI'] = 100 - (100 / (1 + rs))
            
            return df
    
        def generate_signals(self, df):
            """Generate buy/sell signals"""
            df['Signal'] = 0
            
            # Long Entry Conditions
            long_condition = (
                (df['close'] > df['EMA50']) & 
                (df['close'] > df['EMA200']) & 
                (df['RSI'] > 50) & 
                (df['RSI'] < 70)
            )
            
            # Short Entry Conditions
            short_condition = (
                (df['close'] < df['EMA50']) & 
                (df['close'] < df['EMA200']) & 
                (df['RSI'] < 50) & 
                (df['RSI'] > 30)
            )
            
            df.loc[long_condition, 'Signal'] = 1
            df.loc[short_condition, 'Signal'] = -1
            
            return df
    
        def backtest_strategy(self, start_date, end_date):
            """Backtest trading strategy"""
            # Fetch and prepare data
            df = self.fetch_historical_data(start_date, end_date)
            df = self.calculate_indicators(df)
            df = self.generate_signals(df)
            
            # Simulate trading
            position = 0
            entry_price = 0
            
            for index, row in df.iterrows():
                if row['Signal'] == 1 and position == 0:
                    # Enter long position
                    position = 1
                    entry_price = row['close']
                    trade_size = self.current_balance * self.risk_per_trade
                    
                elif row['Signal'] == -1 and position == 0:
                    # Enter short position
                    position = -1
                    entry_price = row['close']
                    trade_size = self.current_balance * self.risk_per_trade
                
                # Exit conditions (simplified)
                if position == 1 and row['close'] < entry_price * 0.98:
                    # Stop loss for long position
                    self.current_balance -= trade_size
                    position = 0
                
                elif position == -1 and row['close'] > entry_price * 1.02:
                    # Stop loss for short position
                    self.current_balance -= trade_size
                    position = 0
            
            # Performance metrics
            profit_percentage = ((self.current_balance - self.initial_balance) / self.initial_balance) * 100
            
            return {
                'Initial Balance': self.initial_balance,
                'Final Balance': self.current_balance,
                'Profit Percentage': profit_percentage
            }
    
        def plot_results(self, df):
            """Visualize strategy performance"""
            plt.figure(figsize=(15,7))
            plt.plot(df.index, df['close'], label='Price')
            plt.plot(df.index, df['EMA50'], label='EMA 50')
            plt.plot(df.index, df['EMA200'], label='EMA 200')
            plt.title(f'{self.symbol} Trading Strategy')
            plt.legend()
            plt.show()
    
    # Main Execution
    if __name__ == '__main__':
        bot = CryptoTradingBot(symbol='BTC/USDT')
        
        # Backtest Parameters
        start_date = '2023-01-01T00:00:00Z'
        end_date = '2024-01-01T00:00:00Z'
        
        # Run Backtest
        results = bot.backtest_strategy(start_date, end_date)
        print("Backtest Results:", results)
    

    Key Strategy Components

    1. Entry Conditions:

      • Long Entry: Price above EMA50/EMA200, RSI between 50-70
      • Short Entry: Price below EMA50/EMA200, RSI between 30-50
    2. Risk Management:

      • Risk per trade: 2% of account balance
      • Stop-loss: 2% from entry price
    3. Performance Metrics:

      • Initial balance tracking
      • Profit percentage calculation

    Limitations and Considerations

    • Simulated Trading: This is a basic backtest, not live trading
    • No Transaction Fees: Real trading includes fees
    • Limited Exit Strategy: Simplified stop-loss mechanism
    • Market Complexity: Real markets are more unpredictable

    Next Steps

    1. Refine Strategy: Add more complex exit conditions
    2. Implement Live Trading: Convert to live trading bot
    3. Add More Indicators: Incorporate volume, volatility indicators
    4. Risk Management: Implement more sophisticated position sizing

    Recommendations

    • Always use a demo account first
    • Start with small positions
    • Continuously monitor and adjust

    Would you like me to elaborate on any part of the script or discuss how to adapt it for live trading?

Responses were produced in different, uncontrolled contexts (system prompts, settings, prior turns). This is not a benchmark.