I'm getting the error below when running the code below. I've been trying many things to try and format the ‘stop_loss’ and ‘take_profit’ variables, but I can't seem to fix it.

  1. #region imports
  2. from AlgorithmImports import *
  3. #endregion
  4. import numpy as np
  5. import pandas as pd
  6. class GapAndGoAlgorithm(QCAlgorithm):
  7. def Initialize(self):
  8. self.SetStartDate(2023, 1, 1) # Set start date
  9. self.SetEndDate(2023, 1, 31) # Set end date
  10. self.SetCash(100000) # Set strategy cash
  11. # Add SPY to the universe and request daily data for it
  12. self.AddEquity("SPY", Resolution.Daily)
  13. # Use universe selection to select a universe of stocks that are gapping up
  14. self.UniverseSettings.Resolution = Resolution.Daily
  15. self.AddUniverse(self.CoarseSelectionFunction, self.FineSelectionFunction)
  16. self.SelectionCount = 10
  17. self.SetBrokerageModel(BrokerageName.InteractiveBrokersBrokerage, AccountType.Margin) # Set brokerage model
  18. self.Schedule.On(self.DateRules.EveryDay(), self.TimeRules.AfterMarketOpen("SPY", 30), self.GapAndGo) # Schedule GapAndGo function to run after market open
  19. def CoarseSelectionFunction(self, coarse):
  20. # Select only stocks with a price above $5 and a daily dollar volume above $10,000,000
  21. selected = [x.Symbol for x in coarse if x.Price > 5 and x.DollarVolume > 10000000]
  22. return selected
  23. def FineSelectionFunction(self, fine):
  24. # Select stocks that gapped up at least 1% and have positive earnings and revenue growth
  25. fine = [x for x in fine if hasattr(x.EarningReports, 'BasicEPSGrowth') and x.EarningReports.BasicEPSGrowth.OneYear > 0 and x.FinancialStatements.RevenueGrowth.OneYear > 0]
  26. fine = [x for x in fine if (x.Open - x.Close[-2])/x.Close[-2] > 0.01]
  27. fine = sorted(fine, key=lambda x: (x.Volume, x.Price), reverse=True)[:self.SelectionCount]
  28. return [x.Symbol for x in fine]
  29. def GapAndGo(self):
  30. # Loop over all securities in the portfolio
  31. for security in self.Portfolio.Values:
  32. # Check if the security is currently tradable
  33. if not self.Securities[security.Symbol].IsTradable:
  34. continue
  35. # Get daily historical data for the last 2 days
  36. history = self.History([security.Symbol], 2, Resolution.Daily)
  37. # Get opening and closing prices for the last 2 days
  38. opens = history.loc[security.Symbol].open.values
  39. closes = history.loc[security.Symbol].close.values
  40. # Check if the open price today is greater than the close price of yesterday
  41. if opens[-1] > closes[-2]:
  42. # Calculate the percentage change between the two days
  43. pct_change = (closes[-1] - closes[-2]) / closes[-2]
  44. # If the percentage change is greater than 1% (i.e., a gap), execute a trade
  45. if pct_change > 0.01:
  46. # Calculate the stop loss and take profit levels based on the current price
  47. current_price = self.Securities[security.Symbol].Price
  48. stop_loss = np.array([current_price * 0.98]).item()
  49. take_profit = np.array([current_price * 1.02]).item()
  50. # Place the market order with stop loss and take profit levels
  51. self.MarketOrder(security.Symbol, 100, False, None, stop_loss, take_profit)
+ Expand

Runtime Error: Trying to dynamically access a method that does not exist throws a TypeError exception. To prevent the exception, ensure each parameter type matches those required by the 'float'>) method. Please checkout the API documentation.
  at GapAndGo
    self.MarketOrder(security.Symbol in main.py: line 65

Author

Michael Kvalvik

February 2023