VectorBT position sizing is controlled by two arguments of the portfolio functions: size and size_type. With size_type you choose whether size means a fixed number of shares (amount), a fixed rupee value (value), a share of available capital (percent) or a target weight in the portfolio (targetpercent). This part of the series shows each one with code you can copy.
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:

amount: fixed number of units every trade, regardless of price or equity.value: fixed rupee value every trade; the number of shares changes with price.percent: a fraction of available resources (cash when you are flat), so trade size compounds with the account.targetpercent: rebalances a holding to a target weight; it works withfrom_orders, notfrom_signals.- The original snippets had three small bugs (
hdfc_data,priceandtrue); a corrected, tested script is included below.
Step 1: Import VectorBT, download the data and write the trading logic
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)
Note: the snippet above downloads the data into data but then calls vbt.MA.run(hdfc_data, ...). Rename one of them (for example use data in both places) or Python will raise a NameError. The corrected script at the end of this article fixes this.
The four VectorBT position sizing types
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.
| size_type | What size means | Works with | Typical use |
|---|---|---|---|
amount | Number of units (shares, lots) | from_signals, from_orders | Fixed quantity systems, F&O lots |
value | Rupee value per trade | from_signals, from_orders | Equal capital per trade |
percent | Fraction of available resources (0.5 = 50%) | from_signals, from_orders | Compounding equity |
targetpercent | Target weight of the holding in the portfolio | from_orders (not from_signals) | Rebalancing portfolios |
targetamount and targetvalue, which work the same way as targetpercent but with units or rupees.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'
)
With size=100 every entry buys exactly 100 shares. If the account does not have enough cash, VectorBT buys as many as it can afford. This is the closest match to how most futures and options traders think: a fixed number of lots per trade.
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'
)
With size=100000 and a share price of ₹1,650, VectorBT buys 60 shares (₹99,000) because size_granularity=1 forces whole shares. When the price rises to ₹1,800, the same ₹1,00,000 buys 55 shares. Each trade has roughly the same rupee exposure, but profits are not reinvested.
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'
)
One detail worth knowing: in VectorBT, percent is a percentage of the available resources. For a long-only entry from a flat position that is your free cash, which equals the portfolio value when nothing else is held. If you already hold positions in other assets with shared cash, 50% applies to what is left, not to total equity.
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.
In the snippet above, group_by=true should be group_by=True (Python booleans are capitalised), and price must be a DataFrame with one column per stock. If you try size_type='targetpercent' with from_signals, VectorBT raises “Only SizeType.Amount, SizeType.Value, and SizeType.Percent are supported”, which is why the rebalancing example switches to from_orders.
Try it: how many shares does each size type buy?
Change the price, portfolio value and size settings to see how many shares each size_type would buy or sell on the next signal.
Simplified: ignores fees and slippage and rounds down to whole shares (like size_granularity=1). Percent uses the cash available when you are flat; TargetPercent compares the target holding with what you already own and can sell as well as buy.
Updated version (2026): corrected and tested script
This script fixes the variable names, the boolean and the missing price DataFrame, and runs all four sizing modes one after another. I tested it with vectorbt 1.2.0, pandas 3.x and numpy 2.x. The targetpercent example rebalances a five stock basket to 15% each on the first trading day of every month, which is how the mode is normally used. See Part 2 on portfolio backtesting and rebalancing for more on rebalancing.
import numpy as np
import pandas as pd
import vectorbt as vbt
# 1. Data and signals (single stock)
close = vbt.YFData.download('HDFCBANK.NS', start='2015-01-01', end='2026-01-01').get('Close')
fast = vbt.MA.run(close, 10, short_name='fast', ewm=True)
slow = vbt.MA.run(close, 20, short_name='slow', ewm=True)
entries = fast.ma_crossed_above(slow)
exits = fast.ma_crossed_below(slow)
common = dict(direction='longonly', fees=0.001, init_cash=1_000_000,
min_size=1, size_granularity=1, freq='1D')
# 2. amount, value and percent work with from_signals
for size, size_type in [(100, 'amount'), (100_000, 'value'), (0.5, 'percent')]:
pf = vbt.Portfolio.from_signals(close, entries, exits,
size=size, size_type=size_type, **common)
print(f"{size_type:>8}: return {pf.total_return():.2%}, "
f"max drawdown {pf.max_drawdown():.2%}, trades {pf.trades.count()}")
# 3. targetpercent needs from_orders: rebalance 5 stocks to 15% each, monthly
symbols = ['HDFCBANK.NS', 'ICICIBANK.NS', 'RELIANCE.NS', 'INFY.NS', 'TCS.NS']
prices = vbt.YFData.download(symbols, start='2015-01-01', end='2026-01-01').get('Close')
size = pd.DataFrame(np.nan, index=prices.index, columns=prices.columns)
month_starts = prices.groupby([prices.index.year, prices.index.month]).head(1).index
size.loc[month_starts] = 0.15 # NaN on other days means "do nothing"
pf = vbt.Portfolio.from_orders(
close=prices,
size=size,
size_type='targetpercent',
group_by=True, # one portfolio for all columns
cash_sharing=True,
call_seq='auto', # sell before buy when rebalancing
fees=0.001,
init_cash=1_000_000,
min_size=1,
size_granularity=1,
freq='1D'
)
print(f"targetpercent: return {pf.total_return():.2%}, "
f"max drawdown {pf.max_drawdown():.2%}")
Yahoo Finance sometimes rate-limits requests. If YFData.download fails, wait a few minutes or load your own data (for example from your broker API) into a pandas Series or DataFrame; everything after the download step stays the same.
Which position sizing should you use?
- Testing an entry and exit idea: start with
value. Equal rupee exposure makes the trade list easy to compare and keeps one big winner from dominating the result through compounding. - Simulating a real account: use
percentso trade size grows and shrinks with equity, and compare drawdown with the value version. - F&O systems: use
amountwith the contract lot size assize_granularity, so the backtest never buys a fraction of a lot. - Asset allocation and momentum portfolios: use
targetpercentwithfrom_orders,cash_sharing=Trueandcall_seq='auto'so sells are processed before buys.
Common mistakes with VectorBT position sizing
- Forgetting
size_granularity. Without it VectorBT happily buys 60.6 shares, which flatters results for high priced stocks. - Setting percent above 1.
size=50withpercentmeans 5000%, not 50%; use 0.5. - Comparing runs with different sizing as if they were different strategies. Sizing changes the equity curve, not the edge. Compare win rate and average trade first.
- Ignoring fees with small trades. A fixed
fees=0.001(0.1%) is a fair approximation for Indian delivery trades including STT and charges; intraday and F&O need different values.
Frequently Asked Questions
What is size_type in VectorBT?
It tells VectorBT how to read the size argument: as units (amount), as cash value (value), as a fraction of available resources (percent), or as a target holding (targetamount, targetvalue, targetpercent).
Why does targetpercent not work with from_signals?
Signals say “enter” or “exit”, while target sizing says “hold this much”. The two can contradict each other, so VectorBT only allows amount, value and percent in from_signals. Use from_orders for target sizing.
How do I backtest F&O lot sizes in VectorBT?
Use size_type=’amount’ with size equal to the number of lots multiplied by the lot size, and set size_granularity to the lot size so orders are always whole lots.
Is vectorbt still maintained?
The open-source vectorbt package is still published on PyPI and the version used here, 1.2.0, ran the script above without changes. The author also offers a paid version, VectorBT PRO, with more features.
If you have not set up VectorBT yet, start with how to install VectorBT in a virtual environment and Part 1 on backtesting and optimisation.
in the next tutorial we will be discussing about VectorBT – Broadcasting
Learn by watching: free videos every week
Market Profile, order flow, Python, AI and OpenAlgo tutorials on YouTube.

