Rajandran R Telecom Engineer turned Full-time Derivative Trader. Mostly Trading Nifty, Banknifty, USDINR and High Liquid Stock Derivatives. Trading the Markets Since 2006 onwards. Using Market Profile and Orderflow for more than a decade. Designed and published 100+ open source trading systems on various trading tools. Strongly believe that market understanding and robust trading frameworks are the key to the trading success. Writing about Markets, Trading System Design, Market Sentiment, Trading Softwares & Trading Nuances since 2007 onwards. Author of Marketcalls.in)

How to Install VectorBT in a Virtual Environment and Access using VS Code – Python Tutorial

4 min read

I use the Python 3.11 version on my local Windows machine and unfortunately, VectorBT supports currently only up to the 3.10 version. When I tried to Install VectorBT I got the following error.

ERROR: Could not find a version that satisfies the requirement vectorBT (from versions: none)
ERROR: No matching distribution found for vectorBT

Maybe if you are also struggling to install VectorBT then this tutorial is for you.

What is a Virtual Environment?

A Python virtual environment is a self-contained directory that contains a Python installation for a particular version of Python, plus several additional packages. Virtual environments are used to manage dependencies for different projects, ensuring that each project has access to the specific versions of libraries it needs and that these dependencies don’t interfere with each other.

Install venv library

pip install venv

Using VectorBT in a virtual environment is a practical way to manage project-specific dependencies and avoid conflicts with other Python projects on your system. Here’s a step-by-step guide on how to set up a virtual environment for VectorBT, particularly useful if your system’s default Python version is not compatible with it (e.g., Python 3.11 when VectorBT supports up to Python 3.10).

Step 1: Install a Compatible Python Version

First, ensure you have a Python version compatible with VectorBT. If your system’s default Python version is higher (like 3.11), you might need to install Python 3.10. Tools like pyenv can help manage multiple Python versions on a single machine.

Step 2: Create a Virtual Environment

You can create a virtual environment using Python’s built-in venv module or with virtual environment wrappers like virtualenv. Here’s how to do it with venv:

Navigate to Your Project Directory: Open a terminal and navigate to the directory where you want your project to reside.

Create the Virtual Environment: Run the following command to create a virtual environment. Replace python3.10 with the appropriate command for your Python 3.10 installation, and myenv with your preferred environment name.

python3.10 -m venv myenv

Activate the Virtual Environment: Before you install packages, you need to activate the virtual environment. The activation command varies by operating system:

Windows:

myenv\Scripts\activate.bat

macOS and Linux:

source myenv/bin/activate
  1. Once activated, your command prompt should indicate that you’re now working inside the virtual environment.

Step 3: Install VectorBT

With the virtual environment active, you can now install VectorBT using pip:

pip install vectorbt

This command installs VectorBT and its dependencies in the virtual environment, not affecting the rest of your system.

Step 4: Working with the Virtual Environment

  • Running Python Scripts: Any Python scripts that require VectorBT should be run from within this activated environment.
  • Deactivating the Environment: When you’re done, you can deactivate the virtual environment by typing deactivate in the terminal. This returns you to the system’s default Python environment.

Step 5: Managing the Environment

  • Saving Dependencies: It’s good practice to save your project’s dependencies for reproducibility. Use pip freeze > requirements.txt to create a requirements.txt file with all installed packages and their versions.
  • Recreating the Environment: You can recreate the environment on another machine or directory using the requirements.txt file by running pip install -r requirements.txt in a new virtual environment.

Using virtual environments is a best practice in Python development. It allows you to manage project-specific dependencies and Python versions without interfering with other projects or the system-wide Python installation. This approach is especially useful when working with libraries like VectorBT that require a specific Python version.

How to Open a Virtual Environment in VS Code

Step 1: Open Your Project in VS Code

  1. Launch VS Code.
  2. Open your project folder by going to File > Open Folder and selecting the folder where your Python project is located.

Step 2: Activate the Virtual Environment

VS Code might automatically detect and select the Python interpreter from your virtual environment. To manually select or confirm it:

Open a terminal in VS Code: You can do this by going to Terminal > New Terminal.

Activate the Virtual Environment: In the terminal, navigate to your project folder (if not already there) and activate the virtual environment. The activation command varies based on your operating system:

Windows:

.\myenv\Scripts\activate

MacOS:

source myenv/bin/activate

Here, myenv is the name of your virtual environment. Adjust the command if your environment has a different name.

Step 3: Select the Python Interpreter in VS Code

  1. Open the Command Palette by pressing Ctrl+Shift+P (or Cmd+Shift+P on macOS).
  2. Type and select: Python: Select Interpreter.
  3. Choose the Python interpreter from your virtual environment. It’s usually located inside the virtual environment folder (myenv) and named python.

Step 4: Install Required Packages (if necessary)

With your virtual environment activated and the interpreter selected, you can install any required packages using the integrated terminal: Here are some of the other supporting data packages I installed along with VectorBT for calculating technical indicators and getting feeds from free resources

pip install yfinance
pip install pandas_ta
pip install ta-lib
pip install nbformat
pip install --upgrade --no-cache-dir git+https://github.com/rongardF/tvdatafeed.git

Step 5: Write and Run Your Python Code

  • You can now write your Python code in VS Code, and it will use the Python interpreter from the virtual environment.
  • To run the code, you can either use the built-in run feature of VS Code or execute the script from the terminal.

import vectorbt as vbt
import numpy as np
import pandas as pd

# Fetch historical data for HDFCBANK using VectorBT
hdfc_data = vbt.YFData.download('HDFCBANK.NS', start='2010-01-01', end='2023-01-01').get('Close')

# Calculate 10 and 20 days exponential moving averages
short_ema = vbt.MA.run(hdfc_data, 10, short_name='fast', ewm=True)
long_ema = vbt.MA.run(hdfc_data, 20, short_name='slow', ewm=True)


# Generate crossover signals
entries = short_ema.ma_crossed_above(long_ema)
exits = short_ema.ma_crossed_below(long_ema)

# Set initial capital
initial_capital = 100000

# Create and run the portfolio with 50% of equity position sizing
portfolio = vbt.Portfolio.from_signals(
    hdfc_data, entries, exits,
    direction = 'longonly',
    size=0.5,  # 50% of current equity
    size_type='percent',  # Use percent of equity for sizing
    fees=0.001,
    init_cash=initial_capital,
    freq='1D',
    min_size =1,
    size_granularity = 1
)

# Retrieve and print the backtesting stats
stats = portfolio.stats()
print("Backtesting Stats:")
print(stats)

Step 6: Deactivating the Virtual Environment

When you’re done, you can deactivate the virtual environment by typing deactivate in the terminal. However, this is optional in VS Code, as closing VS Code or the terminal session will automatically deactivate it.

Additional Tips

  • Workspace Settings: If you work with others, consider setting the Python interpreter path in the workspace settings (settings.json) so that everyone uses the same setup.
  • Extensions: The Python extension by Microsoft is highly recommended for Python development in VS Code. It offers features like IntelliSense, linting, debugging, and more.

Using a virtual environment in VS Code helps manage dependencies and ensures that your project’s setup is consistent and reproducible.

Rajandran R Telecom Engineer turned Full-time Derivative Trader. Mostly Trading Nifty, Banknifty, USDINR and High Liquid Stock Derivatives. Trading the Markets Since 2006 onwards. Using Market Profile and Orderflow for more than a decade. Designed and published 100+ open source trading systems on various trading tools. Strongly believe that market understanding and robust trading frameworks are the key to the trading success. Writing about Markets, Trading System Design, Market Sentiment, Trading Softwares & Trading Nuances since 2007 onwards. Author of Marketcalls.in)

How to Place Orders Concurrently using ThreadPoolExecutor – Python…

Creating concurrent orders is essential for active traders, especially those handling large funds, as it allows for executing multiple trade orders simultaneously, thereby maximizing...
Rajandran R
2 min read

Host your Python Flask Web Application using pyngrok and…

Ngrok offers several significant advantages for developers, especially when it comes to testing applications or hosting machine learning models. Ngrok allows you to expose...
Rajandran R
1 min read

Building a Google Gemini Digital Assistant Slack Bot :…

In an era where efficiency is key, integrating a digital assistant into Slack using Google Gemini's AI technology offers a transformative solution. This guide...
Rajandran R
10 min read

Leave a Reply

Get Notifications, Alerts on Market Updates, Trading Tools, Automation & More