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

from System import *
from QuantConnect import *
from QuantConnect.Algorithm import *
from QuantConnect.Data import SubscriptionDataSource
from QuantConnect.Python import PythonData
from datetime import date, timedelta, datetime
import numpy as np
import pandas as pd

class JbrTestHistory(QCAlgorithm):


    active = [
    "QQQ",        # VTI - Vanguard Total Stock Market ETF (Inception: 24 May 01)
    "SPY",        # VNQ - Vanguard REIT ETF (U.S. Real Estate) (Inception: 23 Sep 04)
    ]
    entrylevel = 0.75
    
    def Initialize(self):
        # Set the cash we'd like to use for our backtest
        # This is ignored in live trading 
        self.SetCash(100000)
        
        # Start and end dates for the backtest.
        # These are ignored in live trading.
        self.SetStartDate(2013,1,8)
        self.SetEndDate(2014,7,7)
        
        # Add assets to be used 
        for symbol in self.active:
            self.AddEquity(symbol, Resolution.Daily)

        # Schedule functions
        self.Schedule.On(self.DateRules.EveryDay(), self.TimeRules.BeforeMarketClose("SPY", 5), Action(self.CheckChannels))
        self.Schedule.On(self.DateRules.MonthStart("SPY"), self.TimeRules.BeforeMarketClose("SPY", 30), Action(self.Rebalance))

    def OnData(self, slice):
        # Simple buy and hold template
        #if not self.Portfolio.Invested:
        #    self.SetHoldings(self.spy, 1)
        #    self.Debug("numpy test >>> print numpy.pi: " + str(np.pi))
        pass

    def CheckChannels(self):
        h = self.History(self.active, 60,Resolution.Daily).close
        h = pd.concat([h.loc[x] for x in self.active], axis = 1)
        h.columns = self.active
        channel_prices=h[-30:]
        entry = channel_prices.quantile(self.entrylevel)
        for s in self.active:
            self.Debug("ticker {0} close price:{1} quantile:{2}".format(s,h[s][-1], entry[s]))

    
    def Rebalance(self):
        h = self.History(self.active, 60, Resolution.Daily).close
        h = pd.concat([h.loc[x] for x in self.active], axis = 1)
        h.columns = self.active