Overall Statistics
from clr import AddReference
AddReference("System")
AddReference("QuantConnect.Algorithm")
AddReference("QuantConnect.Algorithm.Framework")
AddReference("QuantConnect.Common")

from System import *
from QuantConnect import *
from QuantConnect.Orders import *
from QuantConnect.Algorithm import *
from QuantConnect.Algorithm.Framework import *
from QuantConnect.Algorithm.Framework.Alphas import *
from QuantConnect.Algorithm.Framework.Portfolio import *
from QuantConnect.Algorithm.Framework.Selection import *
from Alphas.ConstantAlphaModel import ConstantAlphaModel
from Selection.OptionUniverseSelectionModel import OptionUniverseSelectionModel
from Execution.ImmediateExecutionModel import ImmediateExecutionModel
from Risk.NullRiskManagementModel import NullRiskManagementModel
from datetime import date, timedelta

class BasicTemplateOptionsFrameworkAlgorithm(QCAlgorithmFramework):

    def Initialize(self):

        self.UniverseSettings.Resolution = Resolution.Minute

        self.SetStartDate(2018, 1, 1)
        self.SetEndDate(2018, 6, 1)
        self.SetCash(100000)

        self.SetUniverseSelection(CoarseFundamentalUniverseSelectionModel(self.CoarseSelectionFunction))
        self.SetAlpha(ConstantOptionContractAlphaModel(InsightType.Price, InsightDirection.Up, timedelta(hours = 0.5)))
        self.SetPortfolioConstruction(SingleSharePortfolioConstructionModel())
        self.SetExecution(ImmediateExecutionModel())
        self.SetRiskManagement(NullRiskManagementModel())


    def CoarseSelectionFunction(self, coarse):
        sortedByDollarVolume = sorted(coarse, key=lambda x: x.DollarVolume, reverse=True)

        self.symbols = [ x.Symbol for x in sortedByDollarVolume[:3] ]
        
        for symbol in self.symbols:
            option = self.AddOption(symbol.Value)
            option.SetFilter(-2, 2, timedelta(0), timedelta(182))
        return self.symbols

class ConstantOptionContractAlphaModel(ConstantAlphaModel):
    '''Implementation of a constant alpha model that only emits insights for option symbols'''
    def __init__(self, type, direction, period):
        super().__init__(type, direction, period)

    def ShouldEmitInsight(self, utcTime, symbol):
        # only emit alpha for option symbols and not underlying equity symbols
        if symbol.SecurityType != SecurityType.Option:
            return False

        return super().ShouldEmitInsight(utcTime, symbol)

class SingleSharePortfolioConstructionModel(PortfolioConstructionModel):
    '''Portoflio construction model that sets target quantities to 1 for up insights and -1 for down insights'''
    def CreateTargets(self, algorithm, insights):
        targets = []
        for insight in insights:
            targets.append(PortfolioTarget(insight.Symbol, insight.Direction))
        return targets