Instructions
Requirements and Specifications
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
![EMA_SMA.png](EMA_SMA.png)
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')
try:
import yfinance as yf # import Yahoo! Finance
except:
!pip install yfinance # install Yahoo! Finance
import yfinance as yf # import Yahoo! Finance
### importing data
df = yf.download("TSLA")
df.head()
# Plot the closing prices
df['Close'].plot(grid=True)
# Show the plot
plt.show()
# Calculating the short-window simple moving average
short_rolling = df.rolling(window=20).mean()
short_rolling.head()
# Calculating the long-window simple moving average
long_rolling = df.rolling(window=100).mean()
long_rolling.tail()
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.legend(loc='best')
ax.set_ylabel('Price in $')
ax.xaxis.set_major_formatter(my_year_month_fmt)
- 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.legend(loc='best')
ax.set_ylabel('Price in $')
ax.xaxis.set_major_formatter(my_year_month_fmt)
# Taking the difference between the prices and the EMA timeseries
trading_positions_raw = df - ema_short
trading_positions_raw.tail()
# 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
trading_positions.tail()
# 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')
ax1.set_ylabel('$')
ax1.legend(loc='best')
ax1.xaxis.set_major_formatter(my_year_month_fmt)
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')
ax2.xaxis.set_major_formatter(my_year_month_fmt)
### 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
plt.show()
### 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
Related Samples
Explore our Python Assignment Samples for comprehensive solutions to coding challenges. These examples cover topics from basic syntax to advanced data structures and algorithms, offering clear explanations and step-by-step implementations. Ideal for students seeking practical insights to excel in Python programming assignments and deepen their coding proficiency effectively.
Python
Python
Python
Python
Python
Python
Python
Python
Python
Python
Python
Python
Python
Python
Python
Python
Python
Python
Python
Python