Overall Statistics
import numpy as np
from datetime import timedelta

from Alphas.EmaCrossAlphaModel import EmaCrossAlphaModel
from NodaTime import DateTimeZone

from Risk.NullRiskManagementModel import NullRiskManagementModel


class BasicTemplateFrameworkAlgorithm(QCAlgorithmFramework):

    def Initialize(self):
        self.SetStartDate(2014, 1, 18)   #Set Start Date
        self.SetEndDate(2014, 2, 1)    #Set End Date
        self.SetCash(1000)           #Set Strategy Cash
        self.SetBrokerageModel(BrokerageName.OandaBrokerage,AccountType.Margin)


        self.UniverseSettings.Resolution = Resolution.Daily
        symbols = [Symbol.Create("EURUSD", SecurityType.Forex, Market.Oanda),
                  Symbol.Create("GBPUSD", SecurityType.Forex, Market.Oanda)]
        self.SetUniverseSelection( ManualUniverseSelectionModel(symbols) )


        self.SetAlpha(customAlpha())

        self.SetPortfolioConstruction(NullPortfolioConstructionModel())
        self.SetExecution(NullExecutionModel())
        self.SetRiskManagement(NullRiskManagementModel())


    def OnOrderEvent(self, orderEvent):
        if orderEvent.Status == OrderStatus.Filled:
            # self.Debug("Purchased Stock: {0}".format(orderEvent.Symbol))
            pass

class customAlpha(AlphaModel):
    def __init__(self):
        self.resolution = Resolution.Daily
        self.symbolDataBySymbol = {}
    
    def Update(self, algorithm, data):
        insights = []
        
        for symbol, symbolData in self.symbolDataBySymbol.items():
            algorithm.Log("Upper:"+ str(symbolData.donchian.UpperBand)+"Lower:"+ str(symbolData.donchian.LowerBand))
            
        return insights
    
    def OnSecuritiesChanged(self, algorithm, changes):
        addedSymbols = [ x.Symbol for x in changes.AddedSecurities if x.Symbol not in self.symbolDataBySymbol]
        if len(addedSymbols) == 0: return

        history = algorithm.History(addedSymbols, 10, self.resolution)
        for symbol in addedSymbols:
            symbolData = SymbolData(algorithm, symbol, self.resolution)
            self.symbolDataBySymbol[symbol] = symbolData
            ticker = SymbolCache.GetTicker(symbol)
            
            for tuple in history.loc[ticker].itertuples():
                bar = QuoteBar(tuple.Index-timedelta(days=1), symbolData.Symbol
                                , Bar(tuple.bidopen,tuple.bidhigh,tuple.bidlow, tuple.bidclose)
                                , 0
                                , Bar(tuple.askopen,tuple.askhigh,tuple.asklow, tuple.askclose)
                                , 0
                                ,timedelta(days=1)
                              )
                symbolData.donchian.Update( bar)


class SymbolData:
    '''Contains data specific to a symbol required by this model'''
    def __init__(self, algorithm, symbol, resolution):
        self.Symbol = symbol
        self.resolution = resolution
        self.donch_period = 7
        self.ticker = SymbolCache.GetTicker(symbol)
        self.donchian = DonchianChannel(self.ticker, self.donch_period, self.donch_period)
        algorithm.RegisterIndicator(self.Symbol, self.donchian, self.resolution)