Overall Statistics
Total Orders
0
Average Win
0%
Average Loss
0%
Compounding Annual Return
0%
Drawdown
0%
Expectancy
0
Start Equity
100000
End Equity
100000
Net Profit
0%
Sharpe Ratio
0
Sortino Ratio
0
Probabilistic Sharpe Ratio
0%
Loss Rate
0%
Win Rate
0%
Profit-Loss Ratio
0
Alpha
0
Beta
0
Annual Standard Deviation
0
Annual Variance
0
Information Ratio
-11.047
Tracking Error
0.058
Treynor Ratio
0
Total Fees
$0.00
Estimated Strategy Capacity
$0
Lowest Capacity Asset
Portfolio Turnover
0%
from AlgorithmImports import *
from datetime import datetime, timedelta

class VIXGapStrangle(QCAlgorithm):
    def Initialize(self):
        self.SetStartDate(2025, 2, 12)  # Set start date
        self.SetCash(100000)  # Set strategy cash
        self.SetWarmup(timedelta(minutes=10))
        self.set_brokerage_model(BrokerageName.CHARLES_SCHWAB, AccountType.MARGIN)
        self.default_order_properties.time_in_force = TimeInForce.GOOD_TIL_CANCELED

        # Strategy Parameters
        self.min_gap_size = 0.0  # Minimum VIX gap down size in points to trigger the strategy
        self.otm_percent = 0.10   # Percentage OTM for options

        self.vix = self.AddIndex("VIX", Resolution.Minute).Symbol
        self.spx = self.AddIndex("SPX", Resolution.Minute).Symbol
        self.vix_symbol = self.add_data(CBOE, "VIX", Resolution.DAILY).symbol

        # regular option SPX contracts
        self.spx_options = self.add_index_option("SPX")
        self.spx_options.set_filter(lambda u: (u.strikes(-3, 3).expiration(0, 0))) # 0dte only

        # weekly option SPX contracts
        spxw = self.add_index_option("SPX", "SPXW")
        spxw.set_filter(lambda u: (u.strikes(-10, 10)
                                     .expiration(0, 0)
                                     .include_weeklys())) # 0dte only
        
        self.spxw_option = spxw.symbol

        self.recorded_vix_close = None
        self.vix_gap = None
        self.position_opened = False
        self.gap_down = False


        # Schedule gap check for 9:30 AM EST each day
        self.Schedule.On(self.DateRules.EveryDay(), 
                        self.time_rules.after_market_open(self.spx, minutes_after_open=0),
                        self.CheckVIXGap)

        # Schedule order placement for 9:35 AM EST each day
        self.Schedule.On(self.DateRules.EveryDay(), 
                        self.time_rules.at(9,35), 
                        self.OpenStrangle)
        
        # Schedule recording previous day's VIX close at 4:15 PM EST
        self.Schedule.On(self.DateRules.EveryDay(), 
                        self.time_rules.after_market_close(self.spx, minutes_after_close=15),
                        self.RecordVIXClose)

    def RecordVIXClose(self):
        """Record VIX close after market close"""
        vix_price = self.Securities[self.vix].Close
        self.Debug(f"Vix 16:15: {vix_price}")
        self.recorded_vix_close = vix_price
        self.position_opened = False
        self.gap_down = False

    def CheckVIXGap(self):
        """Check for VIX gap down"""
        if self.position_opened:
            return

        current_vix = self.Securities[self.vix].Price
    
        history = self.history(self.vix_symbol, 2, Resolution.DAILY)
        if not history.empty:
            # Get yesterday's close
            self.previous_vix_close = history.iloc[-1].close
            previous_vix = history.iloc[-1]
            self.Debug(f"Previous Daily VIX: {previous_vix}")
            self.Debug(f"VIX recorded after close 4:15: {self.recorded_vix_close}")

        if self.recorded_vix_close is not None:
            self.vix_gap = self.recorded_vix_close - current_vix
        else:
            self.vix_gap = self.previous_vix_close - current_vix


        self.Log(f"VIX open 9:30: {current_vix}")

        # Check if VIX gap down meets minimum size requirement
        if self.vix_gap >= self.min_gap_size:
            self.Log(f"VIX gap down of {self.vix_gap:.2f} points meets minimum requirement of {self.min_gap_size:.2f}")
            self.Debug(f"VIX gap down of {self.vix_gap:.2f} points meets minimum requirement of {self.min_gap_size:.2f}")
            self.gap_down = True
            
        # else:
        #     self.Debug(f"VIX gap down of {vix_gap:.2f} points does not meet minimum requirement of {self.min_gap_size:.2f}")

    def OpenStrangle(self):
        """Open the 0.10% OTM strangle position"""
        if not self.gap_down:
            return

        # Get current option chain for SPX
        chain = self.current_slice.option_chains.get_value(self.spxw_option)

        if chain is None:
            self.debug("No SPXW chain data available at market open")
            return

        spx_price = self.Securities[self.spx].Price
        current_vix = self.Securities[self.vix].Price
        
        # Calculate target strikes
        call_strike_target = round(spx_price * (1 + self.otm_percent/100), 1)
        put_strike_target = round(spx_price * (1 - self.otm_percent/100), 1)
        self.Debug(f"call strike target: {spx_price} ---> {call_strike_target}")
        self.Debug(f"put strike target: {spx_price} ---> {put_strike_target}")
        self.Log(f"call strike target: {spx_price} ---> {call_strike_target}")
        self.Log(f"put strike target: {spx_price} ---> {put_strike_target}")

        calls = [x for x in chain if x.right == OptionRight.Call]
        puts = [x for x in chain if x.right == OptionRight.Put]
        
        # Sort by expiration (closest first)
        calls = sorted(calls, key=lambda x: x.expiry)
        puts = sorted(puts, key=lambda x: x.expiry)

        # Get the closest expiration
        target_expiry = calls[0].expiry
        
        # Filter for target expiration
        calls = [x for x in calls if x.expiry == target_expiry]
        puts = [x for x in puts if x.expiry == target_expiry]
        
        # Sort by strike distance from ATM
        calls = sorted(calls, key=lambda x: abs(chain.underlying.price - x.strike))
        puts = sorted(puts, key=lambda x: abs(chain.underlying.price - x.strike))

        # for c in calls:
        #     self.Debug(f"calls available: {c}")
        # for p in puts:
        #     self.Debug(f"puts available: {p}")

        selected_call = min(calls, key=lambda x: abs(x.strike - call_strike_target))
        selected_put = min(puts, key=lambda x: abs(x.strike - put_strike_target))
 
        # Place Strangle Order
        # self.market_order(selected_call.Symbol, 1)
        # self.market_order(selected_put.Symbol, 1)
        
        # Log entry details
        self.Debug("=== Entry Details ===")
        self.Debug(f"SPX Price: {spx_price}")
        self.Debug(f"VIX Gap Down: {self.vix_gap:.2f} points")
        self.Debug(f"Previous VIX Close: {self.previous_vix_close:.2f}")
        self.Debug(f"Current VIX: {current_vix:.2f}")
        self.Debug(f"Call - Target Strike: {call_strike_target}, Actual Strike: {selected_call}")
        self.Debug(f"Put - Target Strike: {put_strike_target}, Actual Strike: {selected_put}")

        # Log order details
        self.Debug("=== Order Details ===")
        self.Debug(f"Call Order - Symbol: {selected_call.Symbol}, Strike: {selected_call}")
        self.Debug(f"Put Order - Symbol: {selected_put.Symbol}, Strike: {selected_put}")

        self.position_opened = True
     
        
        

    def OnData(self, data):
        if self.Time.hour > 9 and self.Time.hour < 9 and self.Time.minutes < 10:
            self.Log(self.Securities["VIX"].Close)