for bt in scenarios: print(bt[0]) experiment_id, backtest_id, parameters_id = bt[0] results = bt[1] experiment = db.load_experiment(experiment_id) backtest_params = db.load_backtests([backtest_id]) returns = db.load_returns(experiment) excess_returns = returns.values train, test = backtest.split_returns( excess_returns, backtest_params['update_periods'], backtest_params['trailing_periods']) portfolios = pg.decimallistseries2nparray(results.portfolio_weights) portfolio_returns = pg.decimallistseries2nparray(results.test_returns) train_mean = ps.mean(portfolios[0,:], train[0]) train_variance = ps.variance(portfolios[0,:], train[0]) eta = results.eta.iloc[0] backtest_statistics = ps.rkw_statistics( portfolios, portfolio_returns, eta=eta) test_statistics = backtest_statistics['statistics'] agg_returns = backtest_statistics['aggregate_returns'] output = test_statistics output['aggregate_returns'] = pg.array2pgarray(agg_returns) output['train_mean_return'] = train_mean output['train_variance'] = train_variance output['parameters_id'] = parameters_id output['experiment_id'] = experiment_id output['backtest_id'] = backtest_id outputs.append(output)
returns = pd.DataFrame(return_values, index=returns_index) # Subset based on experiment start and end dates. returns = returns.loc[experiment['start_date']:experiment['end_date']] # Load portfolios associated with the experiment. cur.execute( ''' SELECT * FROM mv_portfolios WHERE experiment_id = \'{0}\' '''.format(experiment['id']) ) column_names = tuple(d[0] for d in cur.description) values = cur.fetchall() # Convert records to data frame. portfolios = pd.DataFrame(values) portfolios.columns = column_names portfolio_values = np.array(portfolios['portfolio_weights'].apply(lambda x: list(map(float, x))).values.tolist()) portfolios_index = portfolios['id'] portfolios = pd.DataFrame(portfolio_values, index=portfolios_index) # Compute statistics for all portfolios. excess_returns = returns.values[:, experiment['asset_columns']] mean_returns = portfolios.apply(lambda x: ps.mean(x, excess_returns), axis=1) variances = portfolios.apply(lambda x: ps.variance(x, excess_returns), axis=1)