Dhruv Toshniwal

Stock Trading Back-test using Simple Moving Average

July 2023

Stock Trading Back-test using Simple Moving Average

Overview

This blog post discusses a Python script for backtesting a simple moving average (SMA) crossover trading strategy using historical stock data.

The Strategy

The strategy uses two Simple Moving Averages (short-term and long-term):

  • A "buy" signal occurs when the short-term SMA crosses above the long-term SMA
  • A "sell" signal occurs when the short-term SMA crosses below the long-term SMA

Implementation Details

Key Technologies

  • Used yfinance library to fetch historical stock price data
  • Utilized Alpaca API for executing trades
  • Implemented backtesting to analyze strategy performance

Trading Mechanism

  • Generates trading signals based on SMA crossovers
  • Trades 100 shares per signal (customizable)
  • Provides visual representation of strategy performance

Future Potential

The author suggests several potential improvements:

  • Adding short and long trading capabilities
  • Exploring more advanced technical analysis techniques
  • Investigating other algorithms like:
    • Bollinger Bands
    • MACD
    • RSI

Important Disclaimer

"Backtesting is not a guarantee of future performance. It's a method to assess the viability of a strategy based on historical data."

Code

The full implementation is available on GitHub