So, you want to create your first algorithmic trading system. It might seem overwhelming at first, but there’s a Python library called VectorBT that simplifies the process and makes it incredibly approachable. I’m a huge fan of VectorBT — it’s free, intuitive, and enables us to design trading systems and perform backtests with remarkably few lines of code. In this guide, we’ll develop a straightforward strategy using moving averages as our main tool. In the follow-up, we’ll delve into other types of strategies.
Before we begin, I extend an invitation for you to join my dividend investing community. By joining, you won’t miss any crucial articles and can enhance your skills as an investor. As a bonus, you’ll receive a complimentary welcome gift: A 2024 Model Book With The Newest Trading Strategies (both Options and Dividends)
Here are a few steps to prepare before diving into the actual code:
- Run these commands in your terminal to install the required libraries:
pip install datetime
(Note: The datetime module usually comes pre-installed with Python.)
2. Spend a few minutes skimming the VectorBT documentation. While you don’t need to master every detail, familiarize yourself with some of its handy functions and classes.
3. Visit Yahoo Finance to explore various indicators. At the very least, take a look at the Moving Average indicator — it’s simple yet powerful and an excellent choice for our starting strategy.
We’ll design a strategy that isn’t particularly advanced or reliable in real-world markets but serves as an excellent introductory exercise for backtesting. Here’s how it works:
- Track two moving averages: a shorter period (“fast”) and a longer period (“slow”).
- When the fast moving average crosses above the slow one, it signals bullish momentum — this is your buy signal (the “Golden Cross”).
- Conversely, if the fast moving average drops below the slow one, it indicates bearish momentum — this is your sell signal (the “Death Cross”).
While this strategy can produce false positives due to its reliance on a single indicator, it provides a great foundation for building and refining trading algorithms.
- Import Libraries
We need two libraries for this project — VectorBT and datetime.
import vectorbt as vbtimport datetime as dt
2. Set the Backtesting Window
Use the datetime library to define a testing period starting two years before today.
start_date = current_date - dt.timedelta(days=730)
3. Fetch Market Data
Utilize VectorBT’s download method to retrieve historical price data. Here’s how to get daily closing prices for the SPY ETF starting two years ago:
4. Calculate Moving Averages
VectorBT makes it easy to calculate technical indicators like moving averages. Use the .run() method to generate a 50-day (fast) and 100-day (slow) moving average.
slow_ma = vbt.MA.run(data, 100)
5. Define Entry and Exit Conditions
Create entry signals when the fast moving average crosses above the slow one, and exit signals when it crosses below.
sell_signals = fast_ma.ma_crossed_below(slow_ma)
6. Set Up the Backtest
Use the Portfolio class to integrate signals and simulate performance.
data,
buy_signals,
sell_signals,
init_cash=100,
freq='1d',
sl_stop=0.05,
tp_stop=0.2
)
7. Display Results
Finally, print key metrics and visualize the portfolio’s performance with a detailed chart:
print(portfolio.stats())
portfolio.plot().show()
import datetime as dt
current_date = dt.datetime.now()
start_date = current_date - dt.timedelta(days=730)
data = vbt.YFData.download('SPY', interval='1d', start=start_date).get('Close')
fast_ma = vbt.MA.run(data, 50)
slow_ma = vbt.MA.run(data, 100)
buy_signals = fast_ma.ma_crossed_above(slow_ma)
sell_signals = fast_ma.ma_crossed_below(slow_ma)
portfolio = vbt.Portfolio.from_signals(
data,
buy_signals,
sell_signals,
init_cash=100,
freq='1d',
sl_stop=0.05,
tp_stop=0.2
)
print(portfolio.total_profit())
print(portfolio.stats())
portfolio.plot().show()
When you run this code, the script will generate a performance graph of the strategy applied to the S&P 500 (SPY) over the past two years, including metrics like profit and summary statistics.
This exercise only scratches the surface of algorithmic trading. While I’m relatively new to the field, I wanted to provide a beginner-friendly tutorial to help others like me. VectorBT is a fantastic tool, though its resources can feel sparse at times. I encourage you to explore forums like Quantitative Finance Stack Exchange, Medium articles on trading systems, and VectorBT’s official GitHub for further learning.
Thanks for reading!