Member-only story
Start Backtesting Stock Market Trading Strategies using Python and Backtesting.py — Part 1
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