Backtest

The vectorized trading backtest takes a set of prices and a set of portfolio weights in a data frame, and calculates the net asset value of the resulting portfolio calculated from a backtest.

Use

A script which contains a function named "backtest" is given below which implements the backtest. The functoin takes two arguments

  • A DataFrame which contains the prices and asset weights
  • A dictionary containing the names of the strategies that generated the portfolio weights, and a number, which indicates what percentage of the portfolio to invest in that strategy. This allows you to mix and match strategies to see how they pair together.

#calculate the NAV of the hypothetical strategy nav = bt.backtest(df,{"trend1:1"})

The nav that is returned is a list of values

Full Code

def unit_columns(df): results = [] for name in df.columns: split = name.split(':') if(split[0] == 'Units'): results.append(name) return results pass def backtest(df, weights= {}, init=1): for name in df.columns: split = name.split(':') if split[0] == 'Asset_Weight': trader = split[1] ticker = split[2] df['Units:'+trader+':'+ticker]= df[name]/df[ticker+':Close'] pass pass records = df.to_dict(orient='records') nav = init navs = [1] units = None cols = unit_columns(df) for index,record in enumerate(records): if index>0: for name in cols: split = name.split(':') trader = split[1] ticker = split[2] units = records[index-1][name] weight = 1 if trader+':Weight' in record: weight = record[trader+':Weight'] elif trader in weights: weight = weights[trader] pnl = weight * units * nav *(record[ticker+':Close'] - records[index-1][ticker+':Close']) nav += pnl pass navs.append(nav) pass pass return navs