stock market

How to Create Simple SMA Strategies in Python?

A Simple Moving Average (SMA) strategy is one of the easiest and most popular techniques used in technical analysis for trading. It helps identify trends by smoothing out price fluctuations over a specific period.

What Is Pandas?

Pandas is an open-source Python library that provides high-performance, easy-to-use data structures and data analysis tools. It’s built on top of NumPy, and it’s especially useful for:

  • Cleaning messy data
  • Filtering and transforming datasets
  • Handling time series
  • Reading and writing data from various formats .
What Is NumPy?

NumPy is an open-source Python library that provides:

  • A powerful N-dimensional array object (ndarray)
  • Tools for performing mathematical operations on arrays
  • Functions for linear algebra, statistics, Fourier transforms, and more

1. Steps to Create an SMA Strategy Using Python:

  • pandas as pd : Imports the Pandas library, which is great for data manipulation and analysis.
  • numpy as np : Imports NumPy, used for numerical operations.
  • matplotlib as plt : This line is incorrect. You should import matplotlib.pyplot instead:

2. Reading the CSV File

  • pd.read_csv("sample.csv"): Reads data from a CSV file named sample.csv.
  • parse_dates=["Date"]: Converts the “Date” column into actual datetime objects.
  • index_col="Date": Sets the “Date” column as the index of the DataFrame, which is useful for time series analysis.

3. Displaying the DataFrame

This line just displays the contents of the DataFrame df. In a Jupyter Notebook or interactive environment, this would print the table.

4. Plotting the Data

  • df.plot(...): Plots the DataFrame using Pandas’ built-in plotting (which uses Matplotlib under the hood).
  • figsize=(12,8): Sets the size of the plot.
  • title="Nify Instrument": Adds a title to the plot.
  • fontsize=12: Sets the font size for axis labels.

5. Calculating Log Returns

  • df.shift(1): Shifts all data down by one row—this is used to get the previous day’s value.
  • df.div(...): Divides each row by the previous day’s row (element-wise).
  • np.log(...): Takes the natural logarithm of the result, which gives log returns—a common way to measure financial returns.
  • df["returns"] = ...: Adds a new column called "returns" to the DataFrame.

6. Final Line

  • Again, this just displays the updated DataFrame, now with the "returns" column added.

If you worried about layoffs and wants to stay ahead and earn some extra income .
✅ Is actively looking for IT/tech job opportunities
✅ Wants to learn and upgrade skills with trending technologies like Stock Market , AI, Data Science, Cloud, DevOps, Web3, and more .
✅ Needs a single space for job alerts + learning resources join my what’s up channel

Full program

Leave a Reply

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

RkdigitalSchool