Member-only story

Start Backtesting Stock Market Trading Strategies using Python and Backtesting.py — Part 1

The Scraper Guy
3 min readSep 17, 2024

--

Get started backtesting strategies to see if they are profitable!

Introduction

Today I show you an easy way to setup a backtest using a library called Backtesting.py with data coming from yfinance. The hope is that I will continue this series to create more complex strategies over time.

The strategy is a a simple moving average strategy based on volume. If the volume currently is 2x that of the average of the last 14 periods, buy. If the stock hits a 10% gain sell and if it hits a 2% loss sell.

Code Walkthrough

To begin install Backtesting.py using pip install backtesting

Import the necessary libraries

import yfinance as yf
from backtesting import Backtest, Strategy
from backtesting.lib import crossover
import pandas as pd
from datetime import datetime, time
import numpy as np

Now create a function to download all of our needed stock data using yfinance. We download all stock data for the S&P 500 companies. You can find these tickers here —

https://docs.google.com/spreadsheets/d/1537b2LeQG5LJmxdYJBycVG59tpmLNny8nqpERdY4Qx0/edit?usp=sharing

--

--

The Scraper Guy
The Scraper Guy

Written by The Scraper Guy

Teaching You How to Scrape Using Python LinkTree - https://linktr.ee/scrapingguy

No responses yet