Overall Statistics
Total Orders
511
Average Win
8.80%
Average Loss
-5.84%
Compounding Annual Return
17.260%
Drawdown
65.300%
Expectancy
0.340
Start Equity
100000
End Equity
1056775.13
Net Profit
956.775%
Sharpe Ratio
0.489
Sortino Ratio
0.364
Probabilistic Sharpe Ratio
0.850%
Loss Rate
47%
Win Rate
53%
Profit-Loss Ratio
1.51
Alpha
0.184
Beta
-0.28
Annual Standard Deviation
0.325
Annual Variance
0.106
Information Ratio
0.19
Tracking Error
0.37
Treynor Ratio
-0.568
Total Fees
$33625.44
Estimated Strategy Capacity
$510000.00
Lowest Capacity Asset
VIXY UT076X30D0MD
Portfolio Turnover
9.39%
# https://quantpedia.com/strategies/trading-vix-etfs-v2/
#
# Investment universe consists of SPDR S&P500 Trust ETF (SPY) and ProShares Short S&P500 ETF (SH) for long and short exposure to the
# S&P500 and iPath S&P500 VIX ST Futures ETN (VXX) and VelocityShares Daily Inverse VIX ST ETN (XIV) for long and short exposure to 
# short-term VIX futures. First, the relative difference between the front-month VIX futures and spot VIX is calculated 
# (contango/backwardation check). If the relative basis is above (below) an upper (lower) buy threshold, BU (BL) determined by the trader, 
# it indicates that the market is in contango (backwardation) and that one should hold XIV (VXX) and hedge with SH (SPY). The position is 
# closed when the relative basis falls below an upper (lower) sell-threshold, SU (SL), which may be set equal to, or lower (higher) than
# the buy-threshold. A reason why one might want the upper (lower) sell-threshold lower (higher) than the upper (lower) buy-threshold is
# to avoid too-frequent trading. The best results are with a 0% hedge ratio (trader doesn’t use SPY/SH hedging). However, it is possible
# to use multiple different hedging levels with different results (see table 10 in a source academic paper for more options).

from QuantConnect.Python import PythonQuandl
from AlgorithmImports import *

class TradingVIXETFsv2(QCAlgorithm):

    def Initialize(self):
        self.SetStartDate(2010, 1, 1)
        self.SetCash(100000)

        self.vixy = self.AddEquity('VIXY', Resolution.Minute).Symbol
        
        # Vix futures data.
        self.vix_future = self.AddFuture(Futures.Indices.VIX, Resolution.Minute)

        # Vix spot.
        self.vix_spot = self.AddData(CBOE, 'VIX', Resolution.Daily).Symbol
        
        self.vix_future.SetFilter(timedelta(0), timedelta(30))
        
        # Vix futures active contract updated on expiration.
        self.active_contract = None
        
        self.Schedule.On(self.DateRules.EveryDay(self.vixy), self.TimeRules.AfterMarketOpen(self.vixy, 1), self.Rebalance)

    def Rebalance(self):
        # split data error prevention
        if self.Time.year == 2021 and self.Time.month == 5:
            self.Liquidate()
            return
            
        if self.active_contract:
            if self.Securities.ContainsKey(self.vix_spot):
                spot_price = self.Securities[self.vix_spot].Price
                vix_future_price = self.active_contract.LastPrice
                if spot_price == 0 or vix_future_price == 0: 
                    return
                
                relative_basis = vix_future_price / spot_price
                
                # BU 8%, SU 6%, BL -8%, SL -6% thresholds.
                # Short volatility.
                if relative_basis > 1.08:
                    if not self.Portfolio[self.vixy].IsShort and self.Securities[self.vixy].Price != 0:
                        self.SetHoldings(self.vixy, -1)
                
                if relative_basis >= 1.06 and relative_basis <= 1.08 and self.Portfolio[self.vixy].IsLong:
                    self.Liquidate(self.vixy)
                
                if relative_basis < 1.06 and relative_basis > 0.94:
                    if self.Portfolio[self.vixy].Invested:
                        self.Liquidate(self.vixy)
                
                if relative_basis <= 0.94 and relative_basis >= 0.92 and self.Portfolio[self.vixy].IsShort:
                    self.Liquidate(self.vixy)
                
                # Long volatility.
                if not self.Portfolio[self.vixy].IsLong and relative_basis < 0.92:
                    if self.Securities[self.vixy].Price != 0:
                        self.SetHoldings(self.vixy, 1)

    def OnData(self, slice):
        chains = [x for x in slice.FutureChains]

        cl_chain = None
        if len(chains) > 0:
            cl_chain = chains[0]
        else:
            return
        
        if cl_chain.Value.Contracts.Count >= 1:
            contracts = [i for i in cl_chain.Value]
            contracts = sorted(contracts, key = lambda x: x.Expiry)
            near_contract = contracts[0]
            self.active_contract = near_contract