netflypsb commited on
Commit
4707543
1 Parent(s): a9e37d5

Create macd.py

Browse files
Files changed (1) hide show
  1. indicators/macd.py +46 -0
indicators/macd.py ADDED
@@ -0,0 +1,46 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import pandas as pd
2
+
3
+ def calculate_macd(prices, fast_length=12, slow_length=26, signal_length=9):
4
+ """
5
+ Calculates the Moving Average Convergence Divergence (MACD) along with the Signal line.
6
+
7
+ Parameters:
8
+ - prices (pd.Series): A pandas Series containing the stock's closing prices.
9
+ - fast_length (int): The length of the fast EMA. Defaults to 12.
10
+ - slow_length (int): The length of the slow EMA. Defaults to 26.
11
+ - signal_length (int): The length of the signal line. Defaults to 9.
12
+
13
+ Returns:
14
+ - pd.DataFrame: A DataFrame containing the MACD, Signal line, and MACD Histogram.
15
+ """
16
+ # Calculate the Fast and Slow EMAs
17
+ ema_fast = prices.ewm(span=fast_length, adjust=False).mean()
18
+ ema_slow = prices.ewm(span=slow_length, adjust=False).mean()
19
+
20
+ # Calculate the MACD and Signal line
21
+ macd = ema_fast - ema_slow
22
+ signal_line = macd.ewm(span=signal_length, adjust=False).mean()
23
+ macd_histogram = macd - signal_line
24
+
25
+ macd_df = pd.DataFrame(data={
26
+ 'MACD': macd,
27
+ 'Signal_Line': signal_line,
28
+ 'MACD_Histogram': macd_histogram
29
+ })
30
+
31
+ return macd_df
32
+
33
+ if __name__ == "__main__":
34
+ # Example usage
35
+ data = {'Close': [22, 24, 23, 25, 26, 28, 27, 29, 30, 32, 31, 33]}
36
+ prices = pd.Series(data['Close'])
37
+
38
+ # User-defined parameters for MACD
39
+ fast_length = 12
40
+ slow_length = 26
41
+ signal_length = 9
42
+
43
+ # Calculate MACD
44
+ macd_df = calculate_macd(prices, fast_length, slow_length, signal_length)
45
+
46
+ print(macd_df)