Spaces:
Running
Running
Create ema.py
Browse files- indicators/ema.py +31 -0
indicators/ema.py
ADDED
@@ -0,0 +1,31 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
import pandas as pd
|
2 |
+
|
3 |
+
def calculate_ema(prices, period=20):
|
4 |
+
"""
|
5 |
+
Calculates the Exponential Moving Average (EMA) for the given period.
|
6 |
+
|
7 |
+
Parameters:
|
8 |
+
- prices (pd.Series): A pandas Series containing the stock's closing prices.
|
9 |
+
- period (int): The period over which to calculate the EMA. Defaults to 20.
|
10 |
+
|
11 |
+
Returns:
|
12 |
+
- pd.Series: A pandas Series containing the EMA values.
|
13 |
+
"""
|
14 |
+
ema = prices.ewm(span=period, adjust=False).mean()
|
15 |
+
return ema
|
16 |
+
|
17 |
+
if __name__ == "__main__":
|
18 |
+
# Example usage
|
19 |
+
# Create a sample pandas Series of closing prices
|
20 |
+
data = {'Close': [22, 24, 23, 25, 26, 28, 27, 29, 30, 32, 31, 33]}
|
21 |
+
prices = pd.Series(data['Close'])
|
22 |
+
|
23 |
+
# Calculate the 20-period EMA
|
24 |
+
ema20 = calculate_ema(prices, 20)
|
25 |
+
print("20-period EMA:")
|
26 |
+
print(ema20)
|
27 |
+
|
28 |
+
# Calculate the 50-period EMA
|
29 |
+
ema50 = calculate_ema(prices, 50)
|
30 |
+
print("\n50-period EMA:")
|
31 |
+
print(ema50)
|