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

from QuantConnect import *
from QuantConnect.Indicators import *
from QuantConnect.Logging import Log
from QuantConnect.Algorithm import *
from QuantConnect.Algorithm.Framework import *
from QuantConnect.Algorithm.Framework.Alphas import *
from datetime import timedelta
from enum import Enum
import pandas as pd
import datetime
import numpy as np

class template_AlphaModel(AlphaModel):

    def __init__(self,
                 period = 14,
                 resolution = Resolution.Daily):
                     
        self.period = period
        self.resolution = resolution
        self.insight_period = 5
        self.insightPeriod = Time.Multiply(Extensions.ToTimeSpan(resolution), self.insight_period)
        self.symbolDataBySymbol ={}
        self.symbols = []

        resolutionString = Extensions.GetEnumString(resolution, Resolution)
        self.Name = '{}({},{})'.format(self.__class__.__name__, period, resolutionString)

        self.magic_date = '1999-01-01'

        
    def GetData(self,algorithm,timeWindow = 10):

        history = algorithm.History(self.symbols, timeWindow, Resolution.Daily)

        return history
    
  
    
    def Update(self, algorithm, data):
            
        insights = []
        for symbol in list(self.symbols):
            prediction = np.random.choice(a=[1,-1],size=1)
            
            if prediction > 0:
                insights.append( Insight(symbol, self.insightPeriod, InsightType.Price, InsightDirection.Up, magnitude = 0.1, confidence=1.) )
            if prediction < 0:
                insights.append( Insight(symbol, self.insightPeriod, InsightType.Price, InsightDirection.Down, magnitude = -0.1, confidence=1.) )
    
            
        return insights


        
    def OnSecuritiesChanged(self, algorithm, changes):

        # clean up data for removed securities
        removedSymbols = [ x.Symbol for x in changes.RemovedSecurities ]
        if len(removedSymbols) > 0:
            for subscription in algorithm.SubscriptionManager.Subscriptions:
                if subscription.Symbol in removedSymbols:
                    try:
                        self.symbolDataBySymbol.pop(subscription.Symbol, None)
                        subscription.Consolidators.Clear()
                    except:
                        continue

        addedSymbols = [ x.Symbol for x in changes.AddedSecurities if x.Symbol not in self.symbolDataBySymbol]
        
        for i in range(len(addedSymbols)):
            try:
                self.symbols = list(set(self.symbols + [addedSymbols[i]]))
            except Exception as e:
                algorithm.Debug(str(e))
                continue
        
        for i in range(len(removedSymbols)):
            try:
                self.symbols = list(set(self.symbols) - set([removedSymbols[i]]))
            except Exception as e:
                algorithm.Debug(str(e))
                continue
            

        return
from Alphas.PearsonCorrelationPairsTradingAlphaModel import PearsonCorrelationPairsTradingAlphaModel
from Execution.ImmediateExecutionModel import ImmediateExecutionModel
from Portfolio.EqualWeightingPortfolioConstructionModel import EqualWeightingPortfolioConstructionModel
from Risk.MaximumDrawdownPercentPerSecurity import MaximumDrawdownPercentPerSecurity
from Selection.UncorrelatedUniverseSelectionModel import UncorrelatedUniverseSelectionModel
#from Portfolio.MeanVarianceOptimizationPortfolioConstructionModel import MeanVarianceOptimizationPortfolioConstructionModel
from alpha_template1 import template_AlphaModel
#from Portfolio.BlackLittermanOptimizationPortfolioConstructionModel import BlackLittermanOptimizationPortfolioConstructionModel
from Execution.StandardDeviationExecutionModel import StandardDeviationExecutionModel
#from Risk.MaximumSectorExposureRiskManagementModel import MaximumSectorExposureRiskManagementModel
from Risk.TrailingStopRiskManagementModel import TrailingStopRiskManagementModel
from Selection.QC500UniverseSelectionModel import QC500UniverseSelectionModel

class CalibratedNadionSplitter(QCAlgorithm):

    def Initialize(self):
        #self.SetStartDate(2019, 1, 5) 
        self.SetStartDate(2017, 10, 15) 
        self.SetCash(100000) 
        
        self.AddAlpha(template_AlphaModel())

        self.SetExecution(StandardDeviationExecutionModel())

        self.SetPortfolioConstruction(EqualWeightingPortfolioConstructionModel())

        self.SetRiskManagement(MaximumDrawdownPercentPerSecurity(0.01))

        self.SetUniverseSelection(UncorrelatedUniverseSelectionModel())


    def OnData(self, data):
        '''OnData event is the primary entry point for your algorithm. Each new data point will be pumped in here.
            Arguments:
                data: Slice object keyed by symbol containing the stock data
        '''