stock market

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

  • pandas is imported for data manipulation.
  • numpy is for numerical computations.
  • matplotlib.pyplot is for plotting charts.

2. Reading and Displaying 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

  • 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 and 200.

4. Plotting the Data with SMAs

  • 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

  • Removes any rows with NaN values (which occur because moving averages require at least n data points).

6. Focusing on 2016 Data

  • Filters data from 2016.
  • Plots price and SMAs for that year.

7.Generating Trade Signal Positions

  • Tries to generate a signal where:
  • If short SMA > long SMA, signal is 0 (since 1-1 = 0).
  • Probably meant to be 1 or -1 for long/short positions.

8 .Plotting With Mistakes

  • 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 :

Leave a Reply

Your email address will not be published. Required fields are marked *

RkdigitalSchool