top of page
Search

# Exponential Moving Average(EMA) Calculation with Python

Updated: Apr 29

## Exponential Moving Average Python

Here's an example Python code that calculates the exponential moving average (EMA) for a given stock using the pandas library:

```import pandas as pd

# Read stock data from a CSV file

# Set the smoothing factor
smoothing_factor = 0.5

# Calculate the initial SMA
sma = df['Close'].rolling(window=5).mean()

# Calculate the EMA using the first value of the SMA as the starting point
ema = [sma]

for i in range(1, len(df)):
close_price = df['Close'][i]
ema_value = (close_price * smoothing_factor) + (ema[i-1] * (1 - smoothing_factor))
ema.append(ema_value)

# Add the EMA values as a new column to the dataframe
df['EMA'] = ema

# Print the final dataframe with the EMA column
print(df)```

In this example, we first read the stock data from a CSV file using the pandas library. We then set the smoothing factor to 0.5 and calculate the initial SMA using the rolling() function. We then use a loop to calculate the EMA for each data point using the formula we discussed earlier. Finally, we add the EMA values as a new column to the dataframe and print the final dataframe with the EMA column.

Note that you will need to have a CSV file with stock data in order to run this code, and you may need to modify the code depending on the format and structure of your data.

bottom of page