+1 (315) 557-6473 

Create a Program to Implement Moving Average in Python Assignment Solution.


Write a python assignment program to implement moving average.

Requirements and Specifications

program to implement moving average in python

Source Code

font-family:newtimeroman;font-size:225%;text-align:center;border-radius: 30px 50px;"> πŸ“ˆ Moving Average Trading Strategy πŸ“ˆ

Moving averages are without a doubt the most popular trading tools. Moving averages are great if we know how to use them but most traders, however, make some fatal mistakes when it comes to trading with moving averages.

### What is the best moving average? EMA or SMA?

All traders ask the same questions, whether they should use the EMA (exponential moving average) or the SMA (simple/smoothed moving average). The differences between the two are usually subtle, but the choice of the moving average can make a big impact on your trading.

There is really only one difference when it comes to EMA vs. SMA and it’s speed. The EMA moves much faster and it changes its direction earlier than the SMA. The EMA gives more weight to the most recent price action which means that when price changes direction, the EMA recognizes this sooner, while the SMA takes longer to turn when price turns.

There is no better or worse when it comes to EMA vs. SMA. The pros of the EMA are also its cons:

The EMA reacts faster when the price is changing direction, but this also means that the EMA is also more vulnerable when it comes to giving wrong signals too early. For example, when price retraces lower during a rally, the EMA will start turning down immediately and it can signal a change in the direction way too early. The SMA moves much slower and it can keep you in trades longer when there are short-lived price movements and erratic behavior. But, of course, this also means that the SMA gets you in trades later than the EMA


The EMA gives you more and earlier signals, but it also gives you more false and premature signals. The SMA provides less and later signals, but also less wrong signals during volatile times.

### import libraries

import pandas as pd

import numpy as np

import matplotlib.pyplot as plt

import matplotlib.dates as mdates

%matplotlib inline

import seaborn as sns

sns.set(style='darkgrid', context='talk', palette='Dark2')


import yfinance as yf # import Yahoo! Finance


!pip install yfinance # install Yahoo! Finance

import yfinance as yf # import Yahoo! Finance

### importing data

df = yf.download("TSLA")


# Plot the closing prices


# Show the plot


# Calculating the short-window simple moving average

short_rolling = df.rolling(window=20).mean()


# Calculating the long-window simple moving average

long_rolling = df.rolling(window=100).mean()


start_date = '2020-01-01'

end_date = '2020-12-31'

fig, ax = plt.subplots(figsize=(16,9))

ax.plot(df.loc[start_date:end_date, :].index, df.loc[start_date:end_date, 'Close'], label='Close')

ax.plot(long_rolling.loc[start_date:end_date, :].index, long_rolling.loc[start_date:end_date, 'Close'], label = '100-days SMA')

ax.plot(short_rolling.loc[start_date:end_date, :].index, short_rolling.loc[start_date:end_date, 'Close'], label = '20-days SMA')


ax.set_ylabel('Price in $')


- We need to provide a lag value, from which the decay parameter is automatically calculated. To be able to compare with the short-time SMA we will use a span value of 20 .

# Using Pandas to calculate a 20-days span EMA. adjust=False specifies that we are interested in the recursive calculation mode.

ema_short = df.ewm(span=20, adjust=False).mean()

fig, ax = plt.subplots(figsize=(15,9))

ax.plot(df.loc[start_date:end_date, :].index, df.loc[start_date:end_date, 'Close'], label='Price')

ax.plot(ema_short.loc[start_date:end_date, :].index, ema_short.loc[start_date:end_date, 'Close'], label = 'Span 20-days EMA')

ax.plot(short_rolling.loc[start_date:end_date, :].index, short_rolling.loc[start_date:end_date, 'Close'], label = '20-days SMA')


ax.set_ylabel('Price in $')


# Taking the difference between the prices and the EMA timeseries

trading_positions_raw = df - ema_short


# Taking the sign of the difference to determine whether the price or the EMA is greater and then multiplying by 1/3

trading_positions = trading_positions_raw.apply(np.sign) * 1/3


# Lagging our trading signals by one day.

trading_positions_final = trading_positions.shift(1)

fig, (ax1, ax2) = plt.subplots(2, 1, figsize=(16,9))

ax1.plot(df.loc[start_date:end_date, :].index, df.loc[start_date:end_date, 'Close'], label='Price')

ax1.plot(ema_short.loc[start_date:end_date, :].index, ema_short.loc[start_date:end_date, 'Close'], label = 'Span 20-days EMA')




ax2.plot(trading_positions_final.loc[start_date:end_date, :].index, trading_positions_final.loc[start_date:end_date, 'Close'],

label='Trading position')

ax2.set_ylabel('Trading position')


### Building A Trading Strategy With Python

start_date = '2020-01-01'

end_date = '2020-12-31'

df= df.loc[start_date:end_date, :]

# Initialize the short and long windows

short_window = 40

long_window = 100

# Initialize the `signals` DataFrame with the `signal` column

signals = pd.DataFrame(index=df.index)

signals['signal'] = 0.0

# Create short simple moving average over the short window

signals['short_mavg'] = df['Close'].rolling(window=short_window, min_periods=1, center=False).mean()

# Create long simple moving average over the long window

signals['long_mavg'] = df['Close'].rolling(window=long_window, min_periods=1, center=False).mean()

# Create signals

signals['signal'][short_window:] = np.where(signals['short_mavg'][short_window:]

> signals['long_mavg'][short_window:], 1.0, 0.0)

# Generate trading orders

signals['positions'] = signals['signal'].diff()

# Initialize the plot figure

fig = plt.figure()

# Add a subplot and label for y-axis

ax1 = fig.add_subplot(111, ylabel='Price in $')

# Plot the closing price

df['Close'].plot(ax=ax1, color='r', lw=2.)

# Plot the short and long moving averages

signals[['short_mavg', 'long_mavg']].plot(ax=ax1, lw=2.)

# Plot the buy signals

ax1.plot(signals.loc[signals.positions == 1.0].index,

signals.short_mavg[signals.positions == 1.0],

'^', markersize=10, color='m')

# Plot the sell signals

ax1.plot(signals.loc[signals.positions == -1.0].index,

signals.short_mavg[signals.positions == -1.0],

'v', markersize=10, color='k')

# Show the plot


### References

- 1- https://tradeciety.com/how-to-use-moving-averages/

- 2- https://tradingsim.com/blog/simple-moving-average/

- 3- https://www.learndatasci.com/tutorials/python-finance-part-3-moving-average-trading-strategy/

- 4- https://www.kaggle.com/faressayah/stock-market-analysis-prediction-using-lstm/notebook#2.-What-was-the-moving-average-of-the-various-stocks?

- 5- https://www.kaggle.com/mmmarchetti/tutorial-python-for-finance