Overall Statistics
Total Trades
384
Average Win
13.26%
Average Loss
-3.22%
Compounding Annual Return
268.636%
Drawdown
36.200%
Expectancy
2.654
Net Profit
9015964.605%
Sharpe Ratio
4.203
Probabilistic Sharpe Ratio
100.000%
Loss Rate
29%
Win Rate
71%
Profit-Loss Ratio
4.12
Alpha
2.348
Beta
0.274
Annual Standard Deviation
0.567
Annual Variance
0.322
Information Ratio
3.913
Tracking Error
0.576
Treynor Ratio
8.71
Total Fees
$146779.98
from my_custom_data import *  # QuandlFuture, CboeVix, CboeVxV

from datetime import date, timedelta, datetime
from decimal import Decimal
import numpy as np
from math import floor
import json

class QuandlFutures(PythonQuandl):
        def __init__(self):
            self.ValueColumnName = "open"

class VentralTachyonAtmosphericScrubbers(QCAlgorithm):

    def Initialize(self):
        self.SetStartDate(2011, 10, 1)  # Set Start Date
        #self.SetEndDate(2020, 1, 1)
        self.SetCash(500)  # Set Strategy Cash
        
        self.perc_qnty = 1
        self.selectedResolution = Resolution.Daily
        
        self.uvxy = self.AddEquity("UVXY", self.selectedResolution).Symbol
        self.svxy = self.AddEquity("SVXY", self.selectedResolution).Symbol
        self.tqqq = self.AddEquity("TQQQ", self.selectedResolution).Symbol
        
        self.Defense = self.AddEquity("GLD", self.selectedResolution).Symbol 
        self.CanaryA = self.AddEquity("VWO", self.selectedResolution).Symbol
        self.CanaryB = self.AddEquity("BND", self.selectedResolution).Symbol
        
        self.spy = self.AddEquity("SPY", self.selectedResolution).Symbol
        self.spySma = self.SMA(self.spy, 25, self.selectedResolution, Field.Open)
        
        #Add 200-day Momentum Percent indicator (MomentumPercent computes the n-period percent change in the security) for BND (symbol, period, and resolution)
        self.CanaryAMomentum = self.MOMP("VWO", 35, self.selectedResolution)
        #Add 200-day Momentum Percent indicator (MomentumPercent computes the n-period percent change in the security) for BND (symbol, period, and resolution)
        self.CanaryBMomentum = self.MOMP("BND", 200, self.selectedResolution)
        
        self.vixStr = "VIX"
        self.vxvStr = "VXV"
        self.vixsmStr = "VIX9D"
        self.AddData(CboeVix, "VIX")
        self.AddData(CboeVxv, "VXV")
        self.AddData(CboeVixsm, "VIX9D")
        
        self.macd = self.MACD("SPY", 12, 26, 6, MovingAverageType.Exponential, self.selectedResolution, Field.Open)
        
        self.yvixRatio = 0
        self.yvixCrossUp = False
        self.yspy = 0
        self.yspySma = 0
        
        #1RiskManagement close anything that loses more than 5%
        self.SetRiskManagement(MaximumDrawdownPercentPortfolio(0.05))


    def OnData(self, data):
        if self.vixStr not in data or self.vxvStr not in data: return
        
        vixPrice = data[self.vixStr].Close
        vxvPrice = data[self.vxvStr].Close
        vixsmPrice = 10
        if self.vixsmStr in data:
            vixsmPrice = data[self.vixsmStr].Close
        
        uvxy_qnty = self.Portfolio["UVXY"].Quantity
        svxy_qnty = self.Portfolio["SVXY"].Quantity
        tqqq_qnty = self.Portfolio["TQQQ"].Quantity
        gld_qnty = self.Portfolio["GLD"].Quantity
        
        vixRatio = vixPrice/vxvPrice
        
        self.Plot("Vix/Vix3M", "Vix/Vix3M", vixRatio)
        self.Plot("vix9DCross", "vixPrice", vixPrice)
        self.Plot("vix9DCross", "vixsmPrice", vixsmPrice)
        self.Plot("MACD", "Source", self.macd.Current.Value)
        self.Plot("MACD", "Signal-Long Greater than Source", self.macd.Signal.Current.Value)

        self.Plot("SVXY", "SVXY", self.Securities["SVXY"].Price)
        
        self.Plot("SPY", "SPY open - Short Vol if NOT less that Sma current value", self.Securities["SPY"].Open)
        self.Plot("SPY", "Sma current value", self.spySma.Current.Value)
 
        self.Plot("SPY2", "yspy - Short Vol if greater than yspySma", self.yspy) 
        self.Plot("SPY2", "yspySma", self.yspySma)
        
        self.Plot("MOMP", "CanaryAMomentum", self.CanaryAMomentum.Current.Value)
        self.Plot("MOMP", "CanaryBMomentum", self.CanaryBMomentum.Current.Value)
        
        vixCrossUp = False
        if vixsmPrice:
            vixCrossUp = vixsmPrice > vixPrice
        
        macdLong = self.macd.Current.Value < self.macd.Signal.Current.Value
        
        inLong = uvxy_qnty != 0
        inShort = svxy_qnty != 0
        inRest = tqqq_qnty != 0 
        
        shortEntry = (vixRatio < 0.95) and not vixCrossUp and not (self.Securities["SPY"].Open <= self.spySma.Current.Value and self.yspy > self.yspySma)
        shortExit = inShort and (not shortEntry)
        
        longEntry = vixRatio > 1.05 and vixCrossUp and macdLong
        longExit = inLong and (not longEntry)
        
        if shortExit or longExit:
            self.Liquidate()
            if not inRest and longExit:
                self.SetHoldings(self.tqqq, self.perc_qnty)
            return
        
        if (shortEntry):
            if inLong:
                self.Liquidate(self.uvxy)
            if inRest:
                self.Liquidate(self.tqqq)
            if not inShort:
                self.SetHoldings(self.svxy, self.perc_qnty)
        
        if (longEntry):
            if inShort:
                self.Liquidate(self.svxy)
            if inRest:
                self.Liquidate(self.tqqq)
            if not inLong:
                self.SetHoldings(self.uvxy, self.perc_qnty)
        
        self.yvixRatio = vixRatio
        self.yvixCrossUp = vixCrossUp
        self.yspy = self.Securities["SPY"].Open
        self.yspySma = self.spySma.Current.Value
import decimal

class CboeVix(PythonData):
    '''CBOE Vix Download Custom Data Class'''
    #use GetSource(SubscriptionDataConfig, DateTime, bool)
    def GetSource(self, config, date, datafeed):
        url_vix = "http://www.cboe.com/publish/scheduledtask/mktdata/datahouse/vixcurrent.csv"
        return SubscriptionDataSource(url_vix, 
                                      SubscriptionTransportMedium.RemoteFile)
    def Reader(self, config, line, date, datafeed):
        if not (line.strip() and line[0].isdigit()): return None
        # New CboeVix object
        index = CboeVix();
        index.Symbol = config.Symbol
        try:
            # Example File Format:
            # Date          VIX Open    VIX High VIX Low    VIX Close
            # 01/02/2004    17.96    18.68     17.54        18.22
            #print line
            data = line.split(',')
            date = data[0].split('/')
            index.Time = datetime(int(date[2]), int(date[0]), int(date[1]))
            index.Value = decimal.Decimal(data[4])
            index["Open"] = float(data[1])
            index["High"] = float(data[2])
            index["Low"] = float(data[3])
            index["Close"] = float(data[4])
        except ValueError:
            # Do nothing
            return None
#       except KeyError, e:
#          print 'I got a KeyError - reason "%s"' % str(e)
        return index

class CboeVixsm(PythonData):
    '''CBOE Vix Download Custom Data Class'''
    def GetSource(self, config, date, datafeed):
        url_vix = "https://www.cboe.com/publish/scheduledtask/mktdata/datahouse/vix9ddailyprices.csv"
        return SubscriptionDataSource(url_vix, 
                                      SubscriptionTransportMedium.RemoteFile)
    def Reader(self, config, line, date, datafeed):
        if not (line.strip() and line[0].isdigit()): return None
        # New CboeVix object
        index = CboeVixsm();
        index.Symbol = config.Symbol
        try:
            # Example File Format:
            # Date          VIX Open    VIX High VIX Low    VIX Close
            # 01/02/2004    17.96    18.68     17.54        18.22
            #print line
            data = line.split(',')
            date = data[0].split('/')
            index.Time = datetime(int(date[2]), int(date[0]), int(date[1]))
            index.Value = decimal.Decimal(data[4])
            index["Open"] = float(data[1])
            index["High"] = float(data[2])
            index["Low"] = float(data[3])
            index["Close"] = float(data[4])
        except ValueError:
            # Do nothing
            return None
#       except KeyError, e:
#          print 'I got a KeyError - reason "%s"' % str(e)
        return index
        
# NB: CboeVxV class ==  CboeVix class, except for the URL
class CboeVxv(PythonData):
    '''CBOE VXV Download Custom Data Class'''
    
    def GetSource(self, config, date, datafeed):
        url_vxv = "http://www.cboe.com/publish/scheduledtask/mktdata/datahouse/vix3mdailyprices.csv"
        return SubscriptionDataSource(url_vxv, 
                                      SubscriptionTransportMedium.RemoteFile)
    def Reader(self, config, line, date, datafeed):
        if not (line.strip() and line[0].isdigit()): return None
        index = CboeVxv();
        index.Symbol = config.Symbol
        try:
        # Example File Format:
        #                 OPEN    HIGH    LOW        CLOSE
        # 12/04/2007    24.8    25.01    24.15    24.65
            data = line.split(',')
            date = data[0].split('/')
            index.Time = datetime(int(date[2]), int(date[0]), int(date[1]))
            index.Value = decimal.Decimal(data[4])
            index["Open"] = float(data[1])
            index["High"] = float(data[2])
            index["Low"] = float(data[3])
            index["Close"] = float(data[4])
        except ValueError:
                # Do nothing
                return None
        return index