Rajandran R Creator of OpenAlgo - OpenSource Algo Trading framework for Indian Traders. Telecom Engineer turned Full-time Derivative Trader. Mostly Trading Nifty, Banknifty, 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. Building Algo Platforms, Writing about Markets, Trading System Design, Market Sentiment, Trading Softwares & Trading Nuances since 2007 onwards. Author of Marketcalls.in

Mastering VectorBT – Position Sizing – Code Snippets – Part 4 – Python Tutorial

2 min read

VectorBT (Vector BackTester) is a versatile backtesting library for Python, which includes features for position sizing in trading strategies. Position sizing determines how much capital to allocate to a particular trade, influencing both the potential return and risk. Let’s explore the different types of position sizing methods available in VectorBT and how to implement them with code snippets:

Import VectorBT Library, Download the Data, and Write the Trading Logic

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

# Fetch historical data for HDFCBANK using VectorBT
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)


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

Once the Trading Logic is Implemented it is time to implement the vectorBT backtesting with position sizing. The four types of position sizing are Amount, Value, Percent, and TargetPercent. Each of these methods impacts how the size of a position (i.e., the amount of an asset to be bought or sold) is determined. Let’s discuss each of these methods with the provided code examples.

1. Amount Sizing

In Amount sizing, the size parameter represents the fixed number of units of the asset to be bought or sold. This is the simplest form of sizing and does not vary with the price of the asset or the size of the portfolio.

portfolio = vbt.Portfolio.from_signals(
    data, entries, exits,
    direction='longonly',
    size=100,  # Fixed size of 100 units
    size_type='amount',
    fees=0.001,
    init_cash=1000000,
    min_size=1,
    size_granularity=1,
    freq='1D'
)

2. Value Sizing

In Value sizing, the size parameter represents the fixed cash value to be invested in each trade. The actual number of units bought or sold will vary depending on the asset’s price.

portfolio = vbt.Portfolio.from_signals(
    data, entries, exits,
    direction='longonly',
    size=100000,  # Fixed cash value of 100,000
    size_type='value',
    fees=0.001,
    init_cash=1000000,
    min_size=1,
    size_granularity=1,
    freq='1D'
)

3. Percent Sizing

In Percent sizing, the size parameter represents a percentage of the current portfolio value in INR that is used for each trade.

Behavior: The amount in INR invested in new trades changes in line with changes in the portfolio’s value, maintaining the specified percentage.

Example: If you set the size to 50%, and your portfolio value is ₹10,00,000, it will use ₹5,00,000 for the next trade. If the portfolio grows to ₹11,00,000, the next trade will use ₹5,50,000, and so forth.

Usage: This method is useful for maintaining consistent risk relative to your portfolio’s size.

portfolio = vbt.Portfolio.from_signals(
    data, entries, exits,
    direction='longonly',
    size=0.5,  # 50% of the current portfolio value
    size_type='percent',
    fees=0.001,
    init_cash=1000000,
    min_size=1,
    size_granularity=1,
    freq='1D'
)

4. TargetPercent Sizing

TargetPercent sizing is a bit different. It specifies the desired percentage of the portfolio to be allocated to a particular asset. This method is often used in portfolio rebalancing strategies. Note that it uses from_orders instead of from_signals.

TargetPercent position sizing aims to achieve a target portfolio allocation in INR for a specific asset.

Behavior: It adjusts the position size to match a desired percentage allocation of the portfolio’s total value. Trades are executed to reach the specified target allocation.

Example: If the target is set to 15% for an asset, and the asset currently makes up 10% of the portfolio, VectorBT will buy enough of the asset to increase its proportion to 15%. Conversely, if the asset’s proportion exceeds 15% due to price appreciation, it will sell to reduce it back to 15%.

Usage: Commonly used in rebalancing strategies to maintain a certain balance among different assets.

portfolio = vbt.Portfolio.from_orders(
    close=price,
    size=0.15,  # The target percent allocation for each asset
    size_type='targetpercent',
    group_by=true,
    cash_sharing=True,
    fees=0.001,
    init_cash=1000000,
    freq='1D',
    min_size=1,
    size_granularity=1
)

In this method, the size parameter represents the target percentage of the portfolio to be allocated to each asset. The portfolio will buy or sell enough shares to reach the specified allocation.

Rajandran R Creator of OpenAlgo - OpenSource Algo Trading framework for Indian Traders. Telecom Engineer turned Full-time Derivative Trader. Mostly Trading Nifty, Banknifty, 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. Building Algo Platforms, Writing about Markets, Trading System Design, Market Sentiment, Trading Softwares & Trading Nuances since 2007 onwards. Author of Marketcalls.in

[Course] Designing a Stock Market Trading Dashboard App using…

Designing a Stock Market App using Python is a hands-on course that guides you through the development of a functional stock market application. Over...
Rajandran R
1 min read

Exploring the Essential Python Libraries for Data Analytics

Python has emerged as a powerhouse due to its versatility, ease of use, and extensive library support. Whether you're manipulating data, visualizing trends, performing...
Rajandran R
3 min read

Integrating Tradingview Lightweight Charts with Yahoo Finance Data –…

Hey traders! If you’re looking for a way to visualize your stock data dynamically and interactively, you’re in for a treat. Today, we’ll explore...
Rajandran R
2 min read

Leave a Reply

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