Code Generator | Python

Moving Average Trading Signal Generator

This document details a Python function that generates buy and sell signals based on 4-day and 18-day moving averages of price data, aiding in quantitative trading strategies. It includes implementation and example usage.


Empty image or helper icon

Prompt

Creates a quantative trading model using the 4,9 and 18 day moving averages. Create a buy signal when the 4 day moving average moves above the 18 day moving average. Create a sell signal when the 4 day moving average moves below the 18 day moving average

Answer

Quantitative Trading Model using Moving Averages

In this document, we present a Python function that implements a quantitative trading model based on moving averages. Specifically, we will use the 4-day, 9-day, and 18-day moving averages to generate buy and sell signals.

Overview

Objective

  • Buy Signal: When the 4-day moving average exceeds the 18-day moving average.
  • Sell Signal: When the 4-day moving average goes below the 18-day moving average.

Libraries Needed

We will utilize the following libraries:

  • pandas: For handling time series data.
  • numpy: For numerical operations.

Implementation

import pandas as pd
import numpy as np

def moving_average_signals(price_data: pd.Series) -> pd.DataFrame:
    """
    Generates buy and sell signals based on moving averages.

    Args:
        price_data (pd.Series): A Pandas Series containing the historical price data.

    Returns:
        pd.DataFrame: A DataFrame with original price data and corresponding buy/sell signals.
        
    Raises:
        ValueError: If the input price_data is not a Pandas Series or is empty.
    """
    # Validate input
    if not isinstance(price_data, pd.Series) or price_data.empty:
        raise ValueError("Input must be a non-empty Pandas Series of price data.")

    # Calculate moving averages
    ma_4 = price_data.rolling(window=4).mean()
    ma_18 = price_data.rolling(window=18).mean()

    # Create buy and sell signals
    signals = pd.DataFrame(index=price_data.index)
    signals['Price'] = price_data
    signals['MA_4'] = ma_4
    signals['MA_18'] = ma_18

    # Generate Buy and Sell signals
    signals['Signal'] = 0
    signals['Signal'][4:] = np.where(signals['MA_4'][4:] > signals['MA_18'][4:], 1, 0) # Buy
    signals['Position'] = signals['Signal'].diff() # 1 for buy, -1 for sell

    return signals

# Example of Usage
if __name__ == "__main__":
    # Sample price data (you can replace this with actual prices)
    price_data = pd.Series([10, 10.5, 10.7, 11, 11.2, 11.5, 11.8, 12, 12.1, 12.3, 
                            12.5, 12.7, 12.9, 13, 13.3, 13.5, 13.7, 14, 14.5,
                            15, 15.5, 15.8, 16, 16.5, 17, 17.5, 17.8, 18, 18.5])
    
    signals = moving_average_signals(price_data)
    print(signals[['Price', 'MA_4', 'MA_18', 'Signal', 'Position']])

Explanation of the Code

  1. Function Definition:

    • The function moving_average_signals takes a pd.Series of price data as input.
  2. Input Validation:

    • We check if the input is a non-empty pd.Series. If not, a ValueError is raised.
  3. Moving Average Calculation:

    • Compute the 4-day and 18-day moving averages using the rolling().mean() method.
  4. Signal Generation:

    • A new DataFrame signals is created which contains the original prices, moving averages, and the generated buy/sell signals.
    • We create a signal: a value of 1 indicates a buy signal, while a value of -1 indicates a sell signal.
  5. Output:

    • The function returns a DataFrame with the price data and signals for further analysis.

Example Scenario

  • To utilize the function, one can input a series of price data. The example provided simulates stock prices, and upon running the code, it outputs the DataFrame showing prices, moving averages, and generated signals.

Conclusion

This implementation provides a straightforward approach to creating buy and sell signals based on moving averages, which can be an essential part of a quantitative trading strategy. For further learning and enhancing data analysis skills, consider exploring the courses on the Enterprise DNA Platform.

Create your Thread using our flexible tools, share it with friends and colleagues.

Your current query will become the main foundation for the thread, which you can expand with other tools presented on our platform. We will help you choose tools so that your thread is structured and logically built.

Description

This document details a Python function that generates buy and sell signals based on 4-day and 18-day moving averages of price data, aiding in quantitative trading strategies. It includes implementation and example usage.