Calculate Asset Weights
After retrieving prices and calculating indicators on a dataset, the next step in a backtest is to build a model that calculates the holding of a hypothetical portfolio that can be used to backtest the strategy.For this type of backtest, we make some simplifying assumptions. This backtest is used to just calculate a theoretical value for the trading strategy. We assume no market impact, no transaction costs, and shares can be traded in fractions of a share. That is, we are just trying to evaluate the theorectical value of the strategy, without accounting for market frictions. Any strategy that does not look viable with no market frictions is not worth further investigation.
Becauase shares can be traded in fractions, we calculate portfolio weights instead of number of shares traded. That is, if you want the entire portfolio value invested in a given asset, you assign its weight the value of 1.
The framework accomodates shorting shares (shares with a negative weight) and in theory you can borrow money and invest it by assigned weights that sum to more than 1.
Sample Portfolio Weights
The following code demonstrates calculating two different strategies.- Buy and Hold - this portfolio is set to a constant weight of 1. That is, the entire portfolio consists of holding one asset.
- Moving Average
- the moving average strategy devined below assumes that there is a moving average indcator defined on the dataset.
It takes the following inputs:
def buy_hold(df,name, ticker, ):
df['Asset_Weight:'+name+':'+ticker] = 1
pass
def moving_average(df,name, ticker, size1, size2, up=1,down=-1):
df['Asset_Weight:'+name+':'+ticker] = df[ticker+':MA'+str(size1)+'-MA'+str(size2)].apply(lambda x: up if x >= 0 else down)
pass
Use
The following shows calling the function to calculate the weights. Here, we are calculating the portfolio weights for a strategy that buys Apple when its 3 day moving average is above the 200 day moving average, and goes flat when it is below.
#calculate weights
td.moving_average(df, 'trend1', 'AAPL', 3, 200, 1, 0)
The portfolio weights will show up in a column named "Asset_Weight:trend1:AAPL". These weights will then be used to calculate the portfolio net asset value over time.