import pandas as pd def calculate_macd(prices, fast_length=12, slow_length=26, signal_length=9): """ Calculates the Moving Average Convergence Divergence (MACD) along with the Signal line. Parameters: - prices (pd.Series): A pandas Series containing the stock's closing prices. - fast_length (int): The length of the fast EMA. Defaults to 12. - slow_length (int): The length of the slow EMA. Defaults to 26. - signal_length (int): The length of the signal line. Defaults to 9. Returns: - pd.DataFrame: A DataFrame containing the MACD, Signal line, and MACD Histogram. """ # Calculate the Fast and Slow EMAs ema_fast = prices.ewm(span=fast_length, adjust=False).mean() ema_slow = prices.ewm(span=slow_length, adjust=False).mean() # Calculate the MACD and Signal line macd = ema_fast - ema_slow signal_line = macd.ewm(span=signal_length, adjust=False).mean() macd_histogram = macd - signal_line macd_df = pd.DataFrame(data={ 'MACD': macd, 'Signal_Line': signal_line, 'MACD_Histogram': macd_histogram }) return macd_df if __name__ == "__main__": # Example usage data = {'Close': [22, 24, 23, 25, 26, 28, 27, 29, 30, 32, 31, 33]} prices = pd.Series(data['Close']) # User-defined parameters for MACD fast_length = 12 slow_length = 26 signal_length = 9 # Calculate MACD macd_df = calculate_macd(prices, fast_length, slow_length, signal_length) print(macd_df)