I have been having problems using multiple Alphas with Black Litterman in python. I have tried to create a small python minimal example to showcase the issues. 

 

  1. ValueError : shapes (1, 4) and (1, 1) not aligned: 4 (dim 1) != 1 (dim 0)

 

Is the current error with the attached code, with the imports fixed.

Attached a backtest just to share code. Note the main.py does not properly import the Alphas with magnitudes modified, so the backtest mistakenly runs (it actually should error out immediately in the Cloud IDE).

 

I also receive a different error in another Black Litterman project that goes like this:

  1. Runtime Error: It is not possible to cast a non-finite floating-point value (NaN) as decimal. Please review math operations and verify the result is valid. (Parameter 'input') in PortfolioTarget.cs:line 61 (Open Stacktrace)

 

Running similar code, but without an additional QC500 universe, gives this:

  1. Runtime Error: An item with the same key has already been added. Key: 1/18/2018 2:52:00 PM in ReturnsSymbolData.cs:line 49 (Open Stacktrace)

 

The main of that other project is set up something like this:

 

  1. from Execution.ImmediateExecutionModel import ImmediateExecutionModel
  2. from Risk.MaximumDrawdownPercentPerSecurity import MaximumDrawdownPercentPerSecurity
  3. from Selection.QC500UniverseSelectionModel import QC500UniverseSelectionModel
  4. from WIPExecution import WIPExecution
  5. from StochasticRSI import StochasticRSI
  6. from Portfolio.EqualWeightingPortfolioConstructionModel import EqualWeightingPortfolioConstructionModel
  7. from CustomUniverse import QC10UniverseSelectionModel
  8. from StochasticRSIAlphaModel import StochasticRSIAlphaModel
  9. from NeuralNetworkAlpha import NeuralNetworkAlpha
  10. from EmaCrossAlphaModelMagnitude import EmaCrossAlphaModelMagnitude
  11. from MacdAlphaModelMagnitude import MacdAlphaModelMagnitude
  12. class ExecutionModelRefactor(QCAlgorithm):
  13. def Initialize(self):
  14. self.RISK_FREE_RATE = float(self.GetParameter("RISK_FREE_RATE"))
  15. self.DELTA = float(self.GetParameter("DELTA"))
  16. self.TAU = float(self.GetParameter("TAU"))
  17. self.SetStartDate(2018,1,1); # Set Start Date
  18. self.SetCash(100000) # Set Strategy Cash
  19. ################# CHUNGUS ALGS #################
  20. self.AddAlpha(MacdAlphaModelMagnitude(120, 260, 90, MovingAverageType.TripleExponential, Resolution.Minute, bounceThresholdPercent = 0.025))
  21. self.AddAlpha(EmaCrossAlphaModelMagnitude(50, 200, Resolution.Minute))
  22. ################# CHUNGUS ALGS #################
  23. self.SetExecution(WIPExecution())
  24. self.SetPortfolioConstruction(BlackLittermanOptimizationPortfolioConstructionModel(delta=2.5, tau=0.05, risk_free_rate=0.00,portfolioBias=PortfolioBias.Long))
  25. self.SetRiskManagement(MaximumDrawdownPercentPerSecurity(0.05))
  26. self.UniverseSettings.Resolution = Resolution.Minute
  27. symbols = [
  28. Symbol.Create("SPY", SecurityType.Equity, Market.USA),
  29. Symbol.Create("UVXY", SecurityType.Equity, Market.USA),
  30. Symbol.Create("GLD", SecurityType.Equity, Market.USA),
  31. Symbol.Create("TLT", SecurityType.Equity, Market.USA),
  32. Symbol.Create("SOXL", SecurityType.Equity, Market.USA),
  33. Symbol.Create("QQQ", SecurityType.Equity, Market.USA),
  34. Symbol.Create("NVDA", SecurityType.Equity, Market.USA),
  35. Symbol.Create("AMD", SecurityType.Equity, Market.USA),
  36. Symbol.Create("INTC", SecurityType.Equity, Market.USA),
  37. Symbol.Create("USO", SecurityType.Equity, Market.USA),
  38. Symbol.Create("IEF", SecurityType.Equity, Market.USA),
  39. Symbol.Create("SHY", SecurityType.Equity, Market.USA),
  40. Symbol.Create("SH", SecurityType.Equity, Market.USA)
  41. ]
  42. self.AddUniverseSelection(ManualUniverseSelectionModel(symbols))
  43. #self.AddUniverseSelection(QC10UniverseSelectionModel())
  44. self.SetWarmUp(14, Resolution.Daily)
  45. def OnData(self, data):
  46. '''OnData event is the primary entry point for your algorithm. Each new data point will be pumped in here.
  47. Arguments:
  48. data: Slice object keyed by symbol containing the stock data
  49. '''
  50. if self.IsWarmingUp: #or not any([self.base_stoch_minutely, self.base_stoch_hourly, self.base_stoch_daily]):# or not self.base_stoch_minutely or not self.base_stoch_hourly or not self.base_stoch_daily:
  51. return
  52. ## Print delisting warnings and notifications
  53. for universe in self.UniverseManager.Values:
  54. for symbol in universe.Members.Keys:
  55. symbol_str = str(symbol)
  56. if data.Delistings.ContainsKey(symbol):
  57. delisting = data.Delistings[symbol]
  58. ## Log the delisting warning type
  59. self.Log(delisting.ToString())
  60. if delisting.Type == 0:
  61. self.Log(symbol_str + ' will be delisted EOD')
  62. if delisting.Type == 1:
  63. self.Log(symbol_str + ' delisted')
  64. ## Log old and new symbol, and change to new symbol upon symbol change
  65. if data.SymbolChangedEvents.ContainsKey(symbol):
  66. self.Log("Old symbol: {0}, New symbol: {1}".format(data.SymbolChangedEvents[symbol].OldSymbol,data.SymbolChangedEvents[symbol].NewSymbol))
  67. #self.base_security = str(data.SymbolChangedEvents[STOCK_BASE].NewSymbol)
  68. ## Log split information and update history
  69. if data.Splits.ContainsKey(symbol):
  70. split_stock = data.Splits[symbol]
  71. if split_stock.Type == 0:
  72. self.Log(symbol_str + ' stock will split next trading day')
  73. if split_stock.Type == 1:
  74. self.Log("Split type: {0}, Split factor: {1}, Reference price: {2}".format(split_stock.Type, split_stock.SplitFactor, split_stock.ReferencePrice))
+ Expand

 

Author

Ross Wendt

March 2022