Of course! You are absolutely right. vectorbtpro is designed to handle this exact scenario efficiently without needing manual pandas operations like pivot.
The primary tool for this is the vbt.Data.from_data class method. It's a highly flexible constructor that can ingest data in various formats, including the "long" format you described, and convert it into the wide format vectorbtpro uses internally.
Let's walk through a complete example.
1. The Problem: Long-Format Data
First, let's create a sample long-format DataFrame, just like the one you described.
import pandas as pd
import numpy as np
import vectorbtpro as vbt
# Create sample long-format data
dates = pd.to_datetime(pd.date_range('2023-01-01', periods=10))
symbols = ['BTC-USD', 'ETH-USD', 'SOL-USD']
# Build the DataFrame row by row
records = []
for symbol in symbols:
# Generate some random price data and an indicator
price_start = np.random.randint(100, 10000)
prices = price_start + np.random.randn(len(dates)).cumsum() * 10
indicator = 50 + np.random.randn(len(dates)).cumsum() * 2
for i, date in enumerate(dates):
records.append({
'date': date,
'symbol': symbol,
'price': prices[i],
'my_indicator': indicator[i]
})
long_df = pd.DataFrame(records)
print("--- Original Long-Format DataFrame ---")
print(long_df.head())
This will output something like:
--- Original Long-Format DataFrame ---
date symbol price my_indicator
0 2023-01-01 BTC-USD 1683.000000 50.000000
1 2023-01-02 BTC-USD 1688.468233 49.124508
2 2023-01-03 BTC-USD 1680.177025 49.715797
3 2023-01-04 BTC-USD 1684.582963 49.431604
4 2023-01-05 BTC-USD 1682.029813 51.056088
2. The Solution: vbt.Data.from_data
Now, we'll use vbt.Data.from_data to reshape this into the wide format. We need to tell it three key things:
- Which column has the symbol information (
symbol_col).
- Which column has the datetime information (
dt_col).
- Which column(s) we want to reshape (
col_mapper).
# Convert the long-format DataFrame to vbt's wide format
# We specify the columns we want to be reshaped. Let's get both price and the indicator.
wide_data = vbt.Data.from_data(
long_df,
symbol_col='symbol',
dt_col='date',
col_mapper={'price': 'price', 'my_indicator': 'my_indicator'} # Map old col name to new name
)
# Now you can access the wide-format dataframes
wide_prices = wide_data['price']
wide_indicator = wide_data['my_indicator']
print("\n--- Reshaped Wide-Format Prices ---")
print(wide_prices.head())
print("\n--- Column Index ---")
print(wide_prices.vbt.columns)
print("\n--- Reshaped Wide-Format Indicator ---")
print(wide_indicator.head())
print("\n--- Column Index ---")
print(wide_indicator.vbt.columns)
Output:
--- Reshaped Wide-Format Prices ---
symbol BTC-USD ETH-USD SOL-USD
date
2023-01-01 1683.000000 504.000000 9932.000000
2023-01-02 1688.468233 499.043597 9933.275416
2023-01-03 1680.177025 509.833535 9936.431783
2023-01-04 1684.582963 511.458284 9927.876251
2023-01-05 1682.029813 513.755498 9923.673891
--- Column Index ---
Index(['BTC-USD', 'ETH-USD', 'SOL-USD'], dtype='object', name='symbol')
--- Reshaped Wide-Format Indicator ---
symbol BTC-USD ETH-USD SOL-USD
date
2023-01-01 50.000000 50.000000 50.000000
2023-01-02 49.124508 51.134281 51.849221
2023-01-03 49.715797 51.879483 50.334714
2023-01-04 49.431604 49.827139 50.030588
2023-01-05 51.056088 50.811898 49.200980
--- Column Index ---
Index(['BTC-USD', 'ETH-USD', 'SOL-USD'], dtype='object', name='symbol')
As you can see, the data is now perfectly formatted with the date as the index and symbols as the columns, ready for vectorbtpro analysis.
3. Using the Reshaped Data in vbt.Portfolio
Now that your data is in the correct format, you can easily use it to run a portfolio simulation. Let's create a simple strategy where we buy when our indicator crosses above 50 and sell when it crosses below.
# Use the reshaped data to generate signals
entries = wide_indicator.vbt.crossed_above(50)
exits = wide_indicator.vbt.crossed_below(50)
# Run the portfolio simulation
pf = vbt.Portfolio.from_signals(
close=wide_prices,
entries=entries,
exits=exits,
freq='D' # Don't forget to set the frequency
)
# Print the portfolio stats
print("\n--- Portfolio Total Return ---")
print(pf.total_return())
Output:
--- Portfolio Total Return ---
symbol
BTC-USD -0.005877
ETH-USD 0.003923
SOL-USD -0.003460
Name: total_return, dtype: float64
Alternative: vbt.IndicatorFactory.from_long_data
If your goal is to calculate an indicator from long-format OHLC data (as opposed to just reshaping a pre-calculated one), vectorbtpro has an even more powerful tool: vbt.IndicatorFactory.from_long_data.
This is useful when your source data is long-format OHLCV and you want to run something like vbt.RSI.run() on it directly.
Summary: Which to Use?
vbt.Data.from_data: Use this when you have pre-calculated data (prices, indicators, signals) in a long format and you simply need to reshape it into the wide format. This is the direct answer to your question.
vbt.IndicatorFactory.from_long_data: Use this when you have raw, long-format data (like Open, High, Low, Close) and you want to calculate a vbt-native or custom indicator across all symbols.