How to Easily Backtest Strategies with VectorBT

May 7, 2021 | Data Science

In the world of financial trading, understanding the past can empower investors to navigate the unpredictable waters of the future. One of the tools making this possible is VectorBT, a powerful library that allows you to backtest trading strategies using just a few lines of Python code. This guide will explore how to utilize VectorBT effectively, ensuring even beginners can dive right in.

Getting Started

Before you can make the most of VectorBT, you need to install it within your Python environment. You can do this easily using pip:

pip install -U vectorbt

If you wish to include optional dependencies to enhance your experience, use:

pip install -U vectorbt[full]

Backtesting Your Strategies

Now that you’ve installed VectorBT, let’s examine a few examples of how you can backtest strategies with ease.

Example 1: Bitcoin Investment

Consider the scenario where you invested $100 into Bitcoin back in 2014. Using VectorBT, you can find out how much profit you would have made:

import vectorbt as vbt
price = vbt.YFData.download('BTC-USD').get(Close)
pf = vbt.Portfolio.from_holding(price, init_cash=100)
pf.total_profit()

This would show you a total profit of $8961.00, illustrating the potential benefits of early investments.

Example 2: Moving Average Strategy

Want to develop a trading strategy based on moving averages? Here’s how you can buy when the 10-day Simple Moving Average (SMA) crosses above the 50-day SMA, and sell when it does the opposite:

fast_ma = vbt.MA.run(price, 10)
slow_ma = vbt.MA.run(price, 50)
entries = fast_ma.ma_crossed_above(slow_ma)
exits = fast_ma.ma_crossed_below(slow_ma)
pf = vbt.Portfolio.from_signals(price, entries, exits, init_cash=100)
pf.total_profit()

With this strategy, you would see a total profit of $16423.25!

Example 3: Testing Multiple Strategies

To dive deeper, you can generate 1,000 random strategies and test them on Bitcoin (BTC) and Ethereum (ETH):

import numpy as np
symbols = ['BTC-USD', 'ETH-USD']
price = vbt.YFData.download(symbols, missing_index='drop').get(Close)
n = np.random.randint(10, 101, size=1000).tolist()
pf = vbt.Portfolio.from_random_signals(price, n=n, init_cash=100, seed=42)
mean_expectancy = pf.trades.expectancy().groupby(['rand_n', 'symbol']).mean()
fig = mean_expectancy.unstack().vbt.scatterplot(xaxis_title='rand_n', yaxis_title='mean_expectancy')
fig.show()

This step opens the door to countless explorations of how different strategies might perform over time.

Visualizing Data

VectorBT isn’t just about backtesting—it’s a visualization powerhouse. You can animate data with animations like Bollinger Bands:

symbols = ['BTC-USD', 'ETH-USD', 'ADA-USD']
price = vbt.YFData.download(symbols, period='6mo', missing_index='drop').get(Close)
bbands = vbt.BBANDS.run(price)
def plot(index, bbands):
    bbands = bbands.loc[index]
    # More plotting code here...
    return fig
vbt.save_animation(bbands.gif, bbands.wrapper.index, plot, bbands, delta=90, step=3, fps=3)

This provides a vibrant representation of market data, helping you better understand trends and behaviors.

Troubleshooting

While working with VectorBT, you might encounter some challenges. Here are troubleshooting tips to steer you back on course:

  • Make sure you have all necessary dependencies installed. If you’re unsure, rerun the installation command.
  • Check for any typos in your code; Python is sensitive to syntax errors.
  • If specific data isn’t loading, ensure your internet connection is active, as VectorBT fetches data from external sources.

For more insights, updates, or to collaborate on AI development projects, stay connected with fxis.ai.

Conclusion

With VectorBT, backtesting your trading strategies is not only straightforward but also visually engaging! Whether you’re a novice or an experienced trader, this tool allows you to explore financial data like never before.

At fxis.ai, we believe that such advancements are crucial for the future of AI, as they enable more comprehensive and effective solutions. Our team is continually exploring new methodologies to push the envelope in artificial intelligence, ensuring that our clients benefit from the latest technological innovations.

Stay Informed with the Newest F(x) Insights and Blogs

Tech News and Blog Highlights, Straight to Your Inbox