Skip to content
The Chat Archive
gpt-3.5-turbo-0613· OpenAI WildChat-4.8M (AI2)

Give me as a code best EMA strategy with EMA10, 20, 50, 100 please

  1. User

    Give me as a code best EMA strategy with EMA10, 20, 50, 100 please

  2. Assistant

    Sure, here's an example of an EMA strategy using EMA10, EMA20, EMA50, and EMA100 in Python:

    import pandas as pd
    import numpy as np
    
    def calculate_ema(data, period):
        weights = np.exp(np.linspace(-1., 0., period))
        weights /= weights.sum()
        
        ema = np.convolve(data, weights, mode='full')[:len(data)]
        ema[:period] = ema[period]
        
        return ema
    
    def ema_strategy(data):
        # Calculate EMAs
        ema10 = calculate_ema(data, 10)
        ema20 = calculate_ema(data, 20)
        ema50 = calculate_ema(data, 50)
        ema100 = calculate_ema(data, 100)
        
        # Generate trading signals
        signals = pd.Series(index=data.index)
        signals[10:] = np.where(ema10[10:] > ema20[10:], 1, 0)  # Buy signal
        signals[10:] = np.where(ema10[10:] < ema20[10:], -1, signals[10:])  # Sell signal
        
        # Apply 50- and 100-day EMA filter
        signals[50:] = np.where(ema50[50:] > ema100[50:], signals[50:], 0)
        
        return signals
    
    # Example usage
    data = pd.read_csv('your_data.csv')  # replace 'your_data.csv' with your own data
    data['Date'] = pd.to_datetime(data['Date'])
    data.set_index('Date', inplace=True)
    
    ema_signals = ema_strategy(data['Close'])
    

    In this example, your_data.csv should be replaced with your own data file containing a 'Date' column and a 'Close' column. The strategy will generate trading signals based on crossing of EMA10 and EMA20, with additional filtering based on EMA50 and EMA100.

    Keep in mind that this code is a basic example and can be further customized according to your specific requirements and risk management rules. Additionally, make sure to test the strategy thoroughly and adapt it to the asset and time frame you intend to trade.

  3. User

    Okay, I have this code: def signal_generator(df): if df is None: return ''

    ema_analysis = []
    candle_analysis = []
    
    df['EMA10'] = df['Close'].ewm(span=10, adjust=False).mean()
    df['EMA5'] = df['Close'].ewm(span=5, adjust=False).mean()
    
    if (
        df['EMA5'].iloc[-1] > df['EMA10'].iloc[-1] and
        df['EMA5'].iloc[-2] < df['EMA10'].iloc[-2]
    ):
        ema_analysis.append('golden_cross')
    
    elif (
        df['EMA5'].iloc[-1] < df['EMA10'].iloc[-1] and
        df['EMA5'].iloc[-2] > df['EMA10'].iloc[-2]
    ):
        ema_analysis.append('death_cross')
    

    Can you set this strategy here please

  4. Assistant

    Certainly! You can integrate the given code into the ema_strategy function from the previous example. Here's the modified code incorporating the provided signal_generator function:

    import pandas as pd
    import numpy as np
    
    def calculate_ema(data, period):
        weights = np.exp(np.linspace(-1., 0., period))
        weights /= weights.sum()
        
        ema = np.convolve(data, weights, mode='full')[:len(data)]
        ema[:period] = ema[period]
        
        return ema
    
    def signal_generator(df):
        if df is None:
            return ''
    
        ema_analysis = []
        candle_analysis = []
    
        df['EMA10'] = df['Close'].ewm(span=10, adjust=False).mean()
        df['EMA5'] = df['Close'].ewm(span=5, adjust=False).mean()
    
        if (
            df['EMA5'].iloc[-1] > df['EMA10'].iloc[-1] and
            df['EMA5'].iloc[-2] < df['EMA10'].iloc[-2]
        ):
            ema_analysis.append('golden_cross')
    
        elif (
            df['EMA5'].iloc[-1] < df['EMA10'].iloc[-1] and
            df['EMA5'].iloc[-2] > df['EMA10'].iloc[-2]
        ):
            ema_analysis.append('death_cross')
        
        return ema_analysis
    
    def ema_strategy(data):
        # Calculate EMAs
        ema10 = calculate_ema(data, 10)
        ema20 = calculate_ema(data, 20)
        ema50 = calculate_ema(data, 50)
        ema100 = calculate_ema(data, 100)
        
        # Generate trading signals
        signals = pd.Series(index=data.index)
        signals[10:] = np.where(ema10[10:] > ema20[10:], 1, 0)  # Buy signal
        signals[10:] = np.where(ema10[10:] < ema20[10:], -1, signals[10:])  # Sell signal
        
        # Apply 50- and 100-day EMA filter
        signals[50:] = np.where(ema50[50:] > ema100[50:], signals[50:], 0)
        
        # Additional signal generation based on given code
        ema_analysis = signal_generator(data)
        if 'golden_cross' in ema_analysis:
            signals[:] = 1 # Buy signal
        elif 'death_cross' in ema_analysis:
            signals[:] = -1 # Sell signal
        
        return signals
    
    # Example usage
    data = pd.read_csv('your_data.csv')  # replace 'your_data.csv' with your own data
    data['Date'] = pd.to_datetime(data['Date'])
    data.set_index('Date', inplace=True)
    
    ema_signals = ema_strategy(data['Close'])
    

    In this updated code, the ema_strategy function now incorporates the additional signals generated by the signal_generator function. It first calculates the EMA crossover signals as before, and then further modifies the signal based on the ema_analysis list returned by signal_generator. If a 'golden_cross' is found, it sets all signals to buy (1). Similarly, if a 'death_cross' is found, it sets all signals to sell (-1).

    You can replace 'your_data.csv' with your own data file, and adapt the code according to your specific needs. Remember to test the strategy and customize it based on your risk management rules.