pmorissette / bt

bt - flexible backtesting for Python
http://pmorissette.github.io/bt
MIT License
2.25k stars 428 forks source link

WeighMeanVar does not work #337

Closed leoliu0 closed 2 years ago

leoliu0 commented 2 years ago

First, Thank you for this great tool. I take an example from the documentation and use bt.algos.WeighMeanVar() but does not work

data = bt.get('spy,agg', start='2010-01-01')

s = bt.Strategy('s1', [bt.algos.RunMonthly(),
                       bt.algos.SelectAll(),
                       bt.algos.WeighMeanVar(),
                       bt.algos.Rebalance()])
test = bt.Backtest(s, data)

res = bt.run(test)

Exception: ~/.local/lib/python3.9/site-packages/ffn/core.py in calc_mean_var_weights(returns, weight_bounds, rf, covar_method, options) 1608 # calc covariance matrix 1609 if covar_method == "ledoit-wolf": -> 1610 covar = sklearn.covariance.ledoit_wolf(returns)[0] 1611 elif covar_method == "standard": 1612 covar = returns.cov()

/usr/lib/python3.9/site-packages/sklearn/covariance/_shrunk_covariance.py in ledoit_wolf(X, assume_centered, block_size) 318 where mu = trace(cov) / n_features 319 """ --> 320 X = check_array(X) 321 # for only one feature, the result is the same whatever the shrinkage 322 if len(X.shape) == 2 and X.shape[1] == 1:

/usr/lib/python3.9/site-packages/sklearn/utils/validation.py in check_array(array, accept_sparse, accept_large_sparse, dtype, order, copy, force_all_finite, ensure_2d, allow_nd, ensure_min_samples, ensure_min_features, estimator) 795 n_samples = _num_samples(array) 796 if n_samples < ensure_min_samples: --> 797 raise ValueError( 798 "Found array with %d sample(s) (shape=%s) while a" 799 " minimum of %d is required%s."

ValueError: Found array with 0 sample(s) (shape=(0, 2)) while a minimum of 1 is required.

TimBstn commented 2 years ago

I got the same issue, any solution to that problem found?

dbogatic commented 2 years ago

I found the solution for this algo online. By adding the line bt.algos.RunAfterDate('Date'), it will work. You can see the discussion here

Screen Shot 2022-04-14 at 8 34 21 PM