How to Create SMA(Simple Moving Average) Crossover Strategy
The Simple Moving Average (SMA) strategy is a popular technical analysis tool used by traders to identify trends and potential buy or sell signals in the stock markets. It calculates the average closing price of an asset over a specific number of periods, smoothing out price fluctuations and helping traders understand the overall direction of the market.
In the SMA strategy, traders often use two different SMA lines — a short-term (like 20-day) and a long-term (like 50-day or 200-day) average. A buy signal is generated when the short-term SMA crosses above the long-term SMA , and a sell signal is generated when it crosses below .

Example :
write a Python script that calculates and visualizes short-term and long-term simple moving averages (SMAs) for a financial instrument , with the help of pandas
, numpy
, and matplotlib
.
1. Importing Libraries
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
pandas
is imported for data manipulation.numpy
is for numerical computations.matplotlib.pyplot
is for plotting charts.
2. Reading and Displaying Data
data = pd.read_csv("eurusd.csv", parse_dates=['Date'], index_col="Date")
print(data)
- Reads the CSV file
eurusd.csv
into a DataFrame. - Parses the
"Date"
column as datetime. - Sets
"Date"
as the DataFrame index. - Prints the DataFrame.
3. Setting Up Moving Averages
sma_s = 50
sma_l = 200
data.price.rolling(50)
data[sma_s] = data.price.rolling(sma_s).mean()
data[sma_l] = data.price.rolling(sma_l).mean()
data
- Defines short (
50
) and long (200
) period SMAs. - The
rolling()
function creates a moving window over the price. - Calculates the 50-day and 200-day rolling mean (SMA) and stores them in new columns labeled
50
and200
.
4. Plotting the Data with SMAs
data.plot(figsize=(12,8), title="NIFTY-SMA".format(sma_s, sma_l), fontsize=12)
plt.legend(fontsize=12)
plt.show()
- Plots price and both SMAs in one chart.
- Sets figure size and title (although
.format(sma_s, sma_l)
does nothing here—it should be in the string). - Displays the legend and shows the plot.
5. Cleaning and Focusing the Data
data.dropna(inplace=True)
- Removes any rows with NaN values (which occur because moving averages require at least
n
data points).
6. Focusing on 2016 Data
data.loc["2016"].plot(figsize=(12,8), title="NIFTY-SMA{}".format(sma_s, sma_l), fontsize=12)
plt.legend(fontsize=12)
plt.show()
- Filters data from 2016.
- Plots price and SMAs for that year.
7.Generating Trade Signal Positions
data["position"] = np.where(data[sma_s] > data[sma_l], 1, -1)
data
- Tries to generate a signal where:
- If short SMA > long SMA, signal is
0
(since1-1 = 0
). - Probably meant to be
1
or-1
for long/short positions.
8 .Plotting With Mistakes
data.loc[:,["sma_s","sma_l","positon"]].plot(figsize=12, secondary_y="position", title="Nifty Instrument")
plt.show()
- Attempts to plot SMAs and position values.
- Typo Alert:
"positon"
should be"position"
. secondary_y="position"
helps differentiate scales between price and position.
Full Exercise code :
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
##plt.style("seaborn")
data=pd.read_csv("eurusd.csv",parse_dates=['Date'],index_col="Date")
print(data)
sma_s=50
sma_l=200
data.price.rolling(50)
data[sma_s]=data.price.rolling(sma_s).mean()
data[sma_l]=data.price.rolling(sma_l).mean()
data
data.plot(figsize=(12,8) , title="NIFTY-SMA".format(sma_s,sma_l),fontsize=12)
plt.legend(fontsize=12)
plt.show()
data.dropna(inplace=True)
data.loc["2016"].plot(figsize=(12,8),title="NIFTY-SMA{}".format(sma_s,sma_l),fontsize=12)
plt.legend(fontsize=12)
plt.show()
data["position"]=np.where(data["sma_s"]>data["sma_l"],1-1)
data
data.loc[:,["sma_s","sma_l","positon"]].plot(figsize=12,secondary_y="position",title="Nifty Instrument")
plt.show()
data.loc["2016"].plot(figsize=(12,8),title="NIFTY-SMA{}".format(sma_s,sma_l),fontsize=12)
plt.legend(fontsize=12)
plt.show()