As i was attempting to inherit data from a class in another .py file, i got an error message saying. 

‘’ Algorithm.Initialize() Error: During the algorithm initialization, the following exception has occurred: Loader.TryCreatePythonAlgorithm(): Unable to import python module ./cache/algorithm/main.pyc. AlgorithmPythonWrapper(): NameError : name 'ReversalAlpha' is not defined
at <module>
class SupportResistance(ReversalAlpha):
File "main.py" in dailyhours.py: line 8"

How do i do it successfully, given that this is the class below i'm trying to inherit:

  1. """ Block of code whose output gives us daily support levels as well as resistance
  2. levels """
  3. from datetime import datetime,timedelta
  4. import numpy as np
  5. class ReversalAlpha(QCAlgorithm):
  6. def Initialize(self):
  7. self.ticker = "USDCAD"
  8. # Rolling Windows to hold bar close data keyed by symbol
  9. self.closingData = {}
  10. #for ticker in tickers:
  11. symbol = self.AddForex(self.ticker, Resolution.Daily, Market.Oanda).Symbol
  12. self.closingData[symbol] = RollingWindow[float](50)
  13. # Warm up our rolling windows
  14. self.SetWarmUp(50)
  15. def OnData(self, data):
  16. for symbol, window in self.closingData.items():
  17. if data.ContainsKey(symbol) and data[symbol] is not None:
  18. window.Add(data[symbol].Close)
  19. if self.IsWarmingUp or not all([window.IsReady for window in self.closingData.values()]):
  20. return
  21. for symbol, window in self.closingData.items(): #references the key-value pairs in the dictionary
  22. supports_D, resistances_D = self.GetPriceLevels(window) # Daily Supports and Daily Resistances
  23. self.Log(f"Symbol: {symbol.Value} , Supports: {supports_D} , Resistances: {resistances_D}")
  24. def GetPriceLevels(self, series, variation = 0.005, h = 3):
  25. supports_D = [] # List that will hold daily Supports points
  26. resistances_D = [] # List that will hold daily Resistances points
  27. maxima = []
  28. minima = []
  29. # finding maxima and minima by looking for hills/troughs locally
  30. for i in range(h, series.Size-h):
  31. if series[i] > series[i-h] and series[i] > series[i+h]:
  32. maxima.append(series[i])
  33. elif series[i] < series[i-h] and series[i] < series[i+h]:
  34. minima.append(series[i])
  35. # identifying maximas which are resistances
  36. for m in maxima:
  37. r = m * variation
  38. # maxima which are near each other
  39. commonLevel = [x for x in maxima if x > m - r and x < m + r]
  40. # if 2 or more maxima are clustered near an area, it is a resistance
  41. if len(commonLevel) > 1:
  42. # we pick the highest maxima if the cluster as our resistance
  43. level = max(commonLevel)
  44. if level not in resistances_D:
  45. resistances_D.append(level)
  46. # identify minima which are supports
  47. for l in minima:
  48. r = l * variation
  49. # minima which are near each other
  50. commonLevel = [x for x in minima if x > l - r and x < l + r]
  51. # if 2 or more minima are clustered near an area, it is a support
  52. if len(commonLevel) > 1:
  53. # We pick the lowest minima of the cluster as our support
  54. level = min(commonLevel)
  55. if level not in supports_D:
  56. supports_D.append(level)
  57. return supports_D, resistances_D
  58. # Your New Python File
  59. #if nextSupportZone > current_price:
  60. #return
+ Expand

to this other class:

  1. """ Block of code whose two methods output gives us next support and next resistance """
  2. from datetime import datetime,timedelta
  3. SupportD = None
  4. ResistanceD = None
  5. class SupportResistance(ReversalAlpha):
  6. def __init__(self, algorithm):
  7. self.ticker = "USDCAD"
  8. self.Algorithm = algorithm
  9. self.SupportResistance = GetPriceLevels(self, series, variation = 0.005, h = 3)
  10. #find out how to consolidate hourly data into 4hr bars
  11. self.FourHourWindow = RollingWindow[float](21)
  12. algorithm.Consolidate(self.Ticker, timedelta(hours=4), self.SaveFourHourBars)
  13. def NextSupport(self):
  14. price = self.Algorithm.Securities[self.Ticker].Price
  15. SupportD, ResistanceD = self.SupportResistance
  16. less_than_price = [x for x in SupportD if x < price ]
  17. return less_than_price[min4(range(len(less_than_price)), key=lambda i: abs(less_than_price[i] - price))]
  18. def NextResistance(self):
  19. price = self.Algorithm.Securities[self.Ticker].Price
  20. SupportD, ResistanceD = self.SupportResistance
  21. greater_than_price = [y for y in ResistanceD if y > price ]
  22. return greater_than_price[min(range(len(greater_than_price)), key=lambda i: abs(greater_than_price[i] - price))]
  23. def SaveFourHourBars(self, bar):
  24. self.FourHourWindow.Add(bar)
  25. # Your New Python File
  26. #How do you conduct an inheritance of methods of a class from another .py file and create a new method using data from
  27. # the inherited class. .
  28. #Here's a rough idea of what i wanted to create:
  29. # Your New Python File
+ Expand

which will be used in this main .py algorithm class

  1. from datetime import datetime,timedelta
  2. import numpy as np
  3. from dailyhours import *
  4. #from fourhr_support_resistance import *
  5. Macdlong = None
  6. class MeasuredApricot(QCAlgorithm):
  7. def Initialize(self):
  8. self.SetStartDate(2019, 1, 30) # Set Start Date
  9. self.SetEndDate(2020, 12, 30)
  10. self.SetCash(100000) # Set Strategy Cash
  11. self.ticker = "USDCAD"
  12. # Rolling Windows to hold bar close data keyed by symbol
  13. self.Data = {}
  14. #for ticker in tickers:
  15. symbol = self.AddForex(self.ticker, Resolution.Hour, Market.Oanda).Symbol
  16. self.Data[symbol] = SymbolData(self, symbol)
  17. self.tolerance = 0.0025
  18. self.stopLossLevel = -0.05 # stop loss percentage
  19. self.stopProfitLevel = 0.01# stop profit percentage
  20. #self.SupportResistance = SupportResistance(self, self.ticker)
  21. self.SetWarmUp(50, Resolution.Hour)
  22. #def MarketClose(self):
  23. #self.SupportResistance.Reset()
  24. def OnData(self, data):
  25. if self.IsWarmingUp: #Data to warm up the algo is being collected.
  26. return
  27. for symbol, symbolData in self.Data.items(): #Return the dictionary's key-value pairs:
  28. if not (data.ContainsKey(symbol) and data[symbol] is not None and symbolData.IsReady):
  29. continue
  30. MACD = symbolData.macd.Current.Value
  31. MACDfast = symbolData.macd.Fast.Current.Value
  32. RSI = symbolData.rsi.Current.Value
  33. current_price = data[symbol].Close
  34. signalDeltaPercent = (MACD - MACD)/MACDfast
  35. #nextSupportZone =
  36. #nextResistanceZone =
  37. #support = self.SupportResistance.NextSupport()
  38. #resistance = self.SupportResistance.NextResistance()
  39. if self.Portfolio[symbol].Invested:
  40. if self.isLong:
  41. condStopProfit = (current_price - self.buyInPrice)/self.buyInPrice > self.stopProfitLevel
  42. condStopLoss = (current_price - self.buyInPrice)/self.buyInPrice < self.stopLossLevel
  43. if condStopProfit:
  44. self.Liquidate(symbol)
  45. self.Log(f"{self.Time} Long Position Stop Profit at {current_price}")
  46. if condStopLoss:
  47. self.Liquidate(symbol)
  48. self.Log(f"{self.Time} Long Position Stop Loss at {current_price}")
  49. else:
  50. condStopProfit = (self.sellInPrice - current_price)/self.sellInPrice > self.stopProfitLevel
  51. condStopLoss = (self.sellInPrice - current_price)/self.sellInPrice < self.stopLossLevel
  52. if condStopProfit:
  53. self.Liquidate(symbol)
  54. self.Log(f"{self.Time} Short Position Stop Profit at {current_price}")
  55. if condStopLoss:
  56. self.Liquidate(symbol)
  57. self.Log(f"{self.Time} Short Position Stop Loss at {current_price}")
  58. if not self.Portfolio[symbol].Invested:
  59. MacdLong = signalDeltaPercent > self.tolerance
  60. #Above Support = current_price > closestSupportZone * tolerance1(1.004)
  61. #Below Resistance = current_price < closestResistanceZone * tolerance2(0.987)
  62. # tolerance = will be dependent on the minimum number of pips before a r/s level
  63. if RSI > 50 and Macdlong: #Below Resistance:
  64. self.SetHoldings(symbol, 1)
  65. # get buy-in price for trailing stop loss/profit
  66. self.buyInPrice = current_price
  67. # entered long position
  68. self.isLong = True
  69. self.Log(f"{self.Time} Entered Long Position at {current_price}")
  70. if RSI < 50 and not Macdlong: #Above Support:
  71. self.SetHoldings(symbol, -1)
  72. # get sell-in price for trailing stop loss/profit
  73. self.sellInPrice = current_price
  74. # entered short position
  75. self.isLong = False
  76. self.Log(f"{self.Time} Entered Short Position at {current_price}")
  77. class SymbolData:
  78. def __init__(self, algorithm, symbol):
  79. self.macd = MovingAverageConvergenceDivergence(12,26,9)
  80. self.rsi = RelativeStrengthIndex(14)
  81. self.macdWindow = RollingWindow[IndicatorDataPoint](2) #setting the Rolling Window for the fast MACD indicator, takes two values
  82. algorithm.RegisterIndicator(symbol, self.macd, timedelta(hours=4))
  83. self.macd.Updated += self.MacdUpdated #Updating those two values
  84. self.rsiWindow = RollingWindow[IndicatorDataPoint](2) #setting the Rolling Window for the slow SMA indicator, takes two values
  85. algorithm.RegisterIndicator(symbol, self.rsi, timedelta(hours=4))
  86. self.rsi.Updated += self.RsiUpdated #Updating those two values
  87. self.closeWindow = RollingWindow[float](21)
  88. # Add consolidator to track rolling close prices
  89. self.consolidator = QuoteBarConsolidator(4)
  90. self.consolidator.DataConsolidated += self.CloseUpdated
  91. algorithm.SubscriptionManager.AddConsolidator(symbol, self.consolidator)
  92. def MacdUpdated(self, sender, updated):
  93. '''Event holder to update the MACD Rolling Window values'''
  94. if self.macd.IsReady:
  95. self.macdWindow.Add(updated)
  96. def RsiUpdated(self, sender, updated):
  97. '''Event holder to update the RSI Rolling Window values'''
  98. if self.rsi.IsReady:
  99. self.rsiWindow.Add(updated)
  100. def CloseUpdated(self, sender, bar):
  101. '''Event holder to update the close Rolling Window values'''
  102. self.closeWindow.Add(bar.Close)
  103. @property
  104. def IsReady(self):
  105. return self.macd.IsReady and self.rsi.IsReady and self.closeWindow.IsReady
+ Expand

Any help and all the help i can get will be appreciated.

Author

Samwel Kibet

August 2021