Advertisement
Guest User

Lumibot

a guest
Aug 26th, 2024
113
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 4.13 KB | None | 0 0
  1. from lumibot.brokers import Alpaca
  2. from lumibot.backtesting import YahooDataBacktesting
  3. from lumibot.strategies.strategy import Strategy
  4. from lumibot.traders import Trader
  5. from datetime import datetime, timedelta
  6. from alpaca_trade_api import REST
  7. from timedelta import Timedelta
  8.  
  9. API_KEY = # ALPACA API KEY
  10. API_SECRET = # ALPACA API SECRET
  11. BASE_URL = "https://paper-api.alpaca.markets"
  12.  
  13. ALPACA_CREDS = {
  14. "API_KEY" : API_KEY,
  15. "API_SECRET" : API_SECRET,
  16. "PAPER" : True
  17. }
  18.  
  19. class BuyTheDip(Strategy):
  20. def initialize(self, symbol:str="SPY", cash_at_risk:float=.5, close_distance_threshold:float=20):
  21. self.symbol = symbol
  22. self.sleeptime = "24H"
  23. self.last_trade = None
  24. self.cash_at_risk = cash_at_risk
  25. self.close_distance_threshold = close_distance_threshold
  26. self.api = REST(base_url=BASE_URL, key_id=API_KEY, secret_key=API_SECRET)
  27.  
  28. def position_sizing(self):
  29. cash = self.get_cash()
  30. last_price = self.get_last_price(self.symbol)
  31. quantity = round(cash * self.cash_at_risk / last_price, 0)
  32. return cash, last_price, quantity
  33.  
  34. def get_previous_day_data(self):
  35. today = self.get_datetime()
  36. yesterday = today - timedelta(days=1)
  37. bars = self.api.get_bars(self.symbol, '1Day', start=yesterday.strftime('%Y-%m-%d'), end=today.strftime('%Y-%m-%d'), limit=1).df
  38. if len(bars) > 0:
  39. return bars.iloc[0]
  40. return None
  41.  
  42. def calculate_close_distance_percentage(self, bar):
  43. if bar is None:
  44. return None
  45. day_range = bar['high'] - bar['low']
  46. close_distance = bar['close'] - bar['low']
  47. close_distance_percentage = (close_distance / day_range) * 100
  48. return close_distance_percentage
  49.  
  50. def on_trading_iteration(self):
  51. cash, last_price, quantity = self.position_sizing()
  52. previous_day_bar = self.get_previous_day_data()
  53. close_distance_percentage = self.calculate_close_distance_percentage(previous_day_bar)
  54.  
  55. if close_distance_percentage is None:
  56. self.log_message("Unable to calculate close distance percentage. Skipping trade.")
  57. return
  58.  
  59. if cash > last_price:
  60. if close_distance_percentage <= self.close_distance_threshold:
  61. if self.last_trade == "sell":
  62. self.sell_all()
  63. order = self.create_order(
  64. self.symbol,
  65. quantity,
  66. "buy",
  67. type="bracket",
  68. take_profit_price=last_price*1.02,
  69. stop_loss_price=last_price*.98
  70. )
  71. self.submit_order(order)
  72. self.last_trade = "buy"
  73. self.log_message(f"Bought {quantity} shares of {self.symbol} at {last_price}. Close distance: {close_distance_percentage:.2f}%")
  74. else:
  75. self.log_message(f"No trade. Close distance: {close_distance_percentage:.2f}% is above threshold of {self.close_distance_threshold}%")
  76.  
  77. def run_strategy(symbol:str="SPY", cash_at_risk:float=0.5, close_distance_threshold:float=20,
  78. start_date:datetime=None, end_date:datetime=None, live:bool=False):
  79.  
  80. broker = Alpaca(ALPACA_CREDS)
  81. strategy = BuyTheDip(name='rangestrat', broker=broker,
  82. parameters={"symbol": symbol,
  83. "cash_at_risk": cash_at_risk,
  84. "close_distance_threshold": close_distance_threshold})
  85.  
  86. if live:
  87. trader = Trader()
  88. trader.add_strategy(strategy)
  89. trader.run_all()
  90. else:
  91. strategy.backtest(
  92. YahooDataBacktesting,
  93. start_date,
  94. end_date,
  95. parameters={"symbol": symbol, "cash_at_risk": cash_at_risk, "close_distance_threshold": close_distance_threshold}
  96. )
  97.  
  98. run_strategy(
  99. symbol="SPY",
  100. cash_at_risk=0.5,
  101. close_distance_threshold=20,
  102. start_date=datetime(2024,1,1),
  103. end_date=datetime(2024,8,1),
  104. live=False
  105. )
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement