Reg : Portfolio Rebalancing #674
Closed
marketcalls
started this conversation in
General
Replies: 1 comment
-
Found the issue and fixed it. The code uses to allocate orders on daily basis. Gone throught the notebook examples and then fixed it. |
Beta Was this translation helpful? Give feedback.
0 replies
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
-
Hi,
I have been testing VectorBT and so far had a terrific experience. Need to know who to apply monthly rebalancing if already the weights
are fixed. Here is the sample code I have with fixed weights with rebalancing every 30 days. But the trade results are confusing to me. How to validate rebalancing is happening every 30 days
`import numpy as np
import pandas as pd
import vectorbt as vbt
from vectorbt.portfolio import nb
from numba import njit
from vectorbt.portfolio.enums import SizeType, Direction
Load data
symbols = ['HDFCBANK.NS', 'RELIANCE.NS', 'TCS.NS', 'MARUTI.NS']
data = vbt.YFData.download(symbols, missing_index='drop').get('Close')
Align data
aligned_data = data.dropna()
Define weights
weights = np.array([0.25, 0.10, 0.30, 0.35])
@njit
def fill_size_nb(c):
"""Custom function to distribute weights."""
size = np.full(c.group_len, 0, dtype=np.float_)
size[:] = weights
return size
@njit
def pre_segment_func_nb(c, price):
"""Perform rebalancing at a timestamp."""
for col in range(c.from_col, c.to_col):
c.last_val_price[col] = nb.get_col_elem_nb(c, col, price)
size = fill_size_nb(c)
order_value_out = np.empty(c.group_len, dtype=np.float_)
nb.sort_call_seq_nb(c, size, SizeType.TargetPercent, Direction.LongOnly, order_value_out)
return (size,)
@njit
def order_func_nb(c, size, price, fees):
"""Create an order."""
return nb.order_nb(
size=nb.get_elem_nb(c, size),
price=nb.get_elem_nb(c, price),
size_type=SizeType.TargetPercent,
direction=Direction.LongOnly,
fees=nb.get_elem_nb(c, fees)
)
Define rebalancing dates (= active segments)
segment_mask = pd.Series(False, index=aligned_data.index)
segment_mask.iloc[::30] = True # every 30 days
Set initial capital
initial_capital = 100000
Define and run the simulation
pf = vbt.Portfolio.from_order_func(
aligned_data,
order_func_nb,
vbt.Rep('price'),
vbt.Rep('fees'),
pre_segment_func_nb=pre_segment_func_nb,
pre_segment_args=(
vbt.Rep('price'),
),
broadcast_named_args=dict(
price=aligned_data,
fees=0.001
),
segment_mask=segment_mask,
cash_sharing=True,
group_by=True,
init_cash=initial_capital,
freq='1D'
)
Analyze results
stats = pf.stats(agg_func=None)
print(stats)
Backtesting Trade Results
# Accessing trade details trades = portfolio.trades.records_readable print("\nTrade Details:") trades
Beta Was this translation helpful? Give feedback.
All reactions