Using the same algorithm code that I have in live. From today the backtest is no longer run, the strange thing that 10 minutes after running the last backtest, it stopped working. After about an hour of trying, one was successful and immediately afterwards kept giving the same error in the events section.
The source code is that of this topic: Intersection of Roc,

all the algorithms contained in this topic have stopped working and have the same error.

Runtime Error: In Scheduled Event 'EveryDay: SPY: 100 min after MarketOpen', Trying to retrieve an element from a collection using a key that does not exist in that collection throws a KeyError exception. To prevent the exception, ensure that the SPY key exist in the collection and/or that collection is not empty.
  at _validate_read_indexer
    key=key in indexing.py:line 1177
 KeyError : "None of [Index([SPY], dtype='object', name='symbol')] are in the [columns]"

 

 

  1. import numpy as np
  2. # ------------------------------------------------------------------
  3. STK = ['QQQ']; BND = ['TLT']; VOLA = 126; BASE_RET = 85; LEV = 1.00;
  4. PAIRS = ['SLV', 'GLD', 'XLI', 'XLU', 'DBB', 'UUP']
  5. # ------------------------------------------------------------------
  6. class DualMomentumInOut(QCAlgorithm):
  7. def Initialize(self):
  8. self.SetStartDate(2020, 1, 1)
  9. self.SetEndDate(2021, 3, 4)
  10. self.cap = 10000
  11. self.SetCash(self.cap)
  12. self.STK = self.AddEquity('QQQ', Resolution.Minute).Symbol
  13. self.BND = self.AddEquity('TLT', Resolution.Minute).Symbol
  14. self.ASSETS = [self.STK, self.BND]
  15. self.SLV = self.AddEquity('SLV', Resolution.Daily).Symbol
  16. self.GLD = self.AddEquity('GLD', Resolution.Daily).Symbol
  17. self.XLI = self.AddEquity('XLI', Resolution.Daily).Symbol
  18. self.XLU = self.AddEquity('XLU', Resolution.Daily).Symbol
  19. self.DBB = self.AddEquity('DBB', Resolution.Daily).Symbol
  20. self.UUP = self.AddEquity('UUP', Resolution.Daily).Symbol
  21. self.MKT = self.AddEquity('SPY', Resolution.Daily).Symbol
  22. self.pairs = [self.SLV, self.GLD, self.XLI, self.XLU, self.DBB, self.UUP]
  23. self.bull = 1
  24. self.count = 0
  25. self.outday = 0
  26. self.wt = {}
  27. self.real_wt = {}
  28. self.mkt = []
  29. self.SetWarmUp(timedelta(350))
  30. self.Schedule.On(self.DateRules.EveryDay(), self.TimeRules.AfterMarketOpen('SPY', 100),
  31. self.daily_check)
  32. symbols = [self.MKT] + self.pairs
  33. for symbol in symbols:
  34. self.consolidator = TradeBarConsolidator(timedelta(days=1))
  35. self.consolidator.DataConsolidated += self.consolidation_handler
  36. self.SubscriptionManager.AddConsolidator(symbol, self.consolidator)
  37. self.history = self.History(symbols, VOLA + 1, Resolution.Daily)
  38. if self.history.empty or 'close' not in self.history.columns:
  39. return
  40. self.history = self.history['close'].unstack(level=0).dropna()
  41. def consolidation_handler(self, sender, consolidated):
  42. self.history.loc[consolidated.EndTime, consolidated.Symbol] = consolidated.Close
  43. self.history = self.history.iloc[-(VOLA + 1):]
  44. def daily_check(self):
  45. vola = self.history[[self.MKT]].pct_change().std() * np.sqrt(252)
  46. wait_days = int(vola * BASE_RET)
  47. period = int((1.0 - vola) * BASE_RET)
  48. r = self.history.pct_change(period).iloc[-1]
  49. exit = ((r[self.SLV] < r[self.GLD]) and (r[self.XLI] < r[self.XLU]) and (r[self.DBB] < r[self.UUP]))
  50. if exit:
  51. self.bull = False
  52. self.outday = self.count
  53. if self.count >= self.outday + wait_days:
  54. self.bull = True
  55. self.count += 1
  56. if not self.bull:
  57. for sec in self.ASSETS:
  58. self.wt[sec] = LEV if sec is self.BND else 0
  59. self.trade()
  60. elif self.bull:
  61. for sec in self.ASSETS:
  62. self.wt[sec] = LEV if sec is self.STK else 0
  63. self.trade()
  64. def trade(self):
  65. for sec, weight in self.wt.items():
  66. if weight == 0 and self.Portfolio[sec].IsLong:
  67. self.Liquidate(sec)
  68. cond1 = weight == 0 and self.Portfolio[sec].IsLong
  69. cond2 = weight > 0 and not self.Portfolio[sec].Invested
  70. if cond1 or cond2:
  71. self.SetHoldings(sec, weight)
  72. def OnEndOfDay(self):
  73. mkt_price = self.Securities[self.MKT].Close
  74. self.mkt.append(mkt_price)
  75. mkt_perf = self.mkt[-1] / self.mkt[0] * self.cap
  76. self.Plot('Strategy Equity', 'SPY', mkt_perf)
  77. account_leverage = self.Portfolio.TotalHoldingsValue / self.Portfolio.TotalPortfolioValue
  78. self.Plot('Holdings', 'leverage', round(account_leverage, 1))
  79. for sec, weight in self.wt.items():
  80. self.real_wt[sec] = round(self.ActiveSecurities[sec].Holdings.Quantity * self.Securities[sec].Price / self.Portfolio.TotalPortfolioValue,4)
  81. self.Plot('Holdings', self.Securities[sec].Symbol, round(self.real_wt[sec], 3))
+ Expand

Author

Strongs

July 2021