In [1]:
%matplotlib inline
# Imports
from clr import AddReference
AddReference("System")
AddReference("QuantConnect.Algorithm")
AddReference("QuantConnect.Common")
AddReference("QuantConnect.Jupyter")
AddReference("QuantConnect.Indicators")
from System import *
from QuantConnect import *
from QuantConnect.Algorithm import *
from QuantConnect.Data.Custom import *
from QuantConnect.Data.Market import TradeBar, QuoteBar
from QuantConnect.Data.Consolidators import *
from QuantConnect.Jupyter import *
from QuantConnect.Indicators import *
from datetime import datetime, timedelta
from statsmodels.tsa.seasonal import seasonal_decompose
import re
import statistics
import matplotlib.pyplot as plt
import pandas as pd
import numpy as np

# Create an instance
qb = QuantBook()

# Select asset data
spy = qb.AddEquity("SPY")
# gold = qb.AddEquity("GOLD")
In [2]:
class Timeframe:
    Higher = None
    Lower = None
    DataIndex = ['Symbol', 'Time']
    DataColumns = ['Close', 'High', 'Low', 'Open', 'Volume']
    
    def __init__(self, span, consolidator=TradeBarConsolidator):
        self.Data = pd.DataFrame(columns=self.DataIndex + self.DataColumns)
        self.Data.set_index(self.DataIndex, inplace=True)
        self.Consolidator = consolidator(span)
        self.Consolidator.DataConsolidated += self.Update
        self.Label = re.sub(r'(?:, )?0:00:00', '', str(self.Consolidator.Period))
    
    def Update(self, sender, data):
        self.Data.loc[(str(data.Symbol), data.Time), :] = [data.Close, data.High, data.Low, data.Open, data.Volume]
        # Keep dataframe truncated to 100 entries per symbol as we don't need more
        # for the purposes of analysis. Seasonal data for example only applies
        # to monthly timeframes and this algorithm consolidates on monthly bars.
        # If your algorithm only has one timeframe series (minute, daily, etc.)
        # then you should limit the dataset accordingly
        if len(timeframe.Data.groupby('Time')) > 100:
            self.Data = self.Data[len(timeframe.Data.groupby('Symbol')):]
    
    def __repr__(self):
        return self.Label


# We are only iterating over the 1D timeframe as
# it seems to take a large amount of time to process
# all timeframes (mostly by the consolidator accumulation process I believe)
class Timeframes:
    _All = {
#         "1": Timeframe(timedelta(minutes=1)),
#         "5": Timeframe(timedelta(minutes=5)),
#         "15": Timeframe(timedelta(minutes=15)),
#         "30": Timeframe(timedelta(minutes=30)), 
#         "1H": Timeframe(timedelta(hours=1)),
#         "4H": Timeframe(timedelta(hours=4)),
        "1D": Timeframe(timedelta(1))
    }
    
    
    def __init__(self, *labels):
        if len(labels) == 0:
            timeframes = self._All.values()
        else:
            selections = map(lambda x: str(x), labels)
            timeframes = [self._All[i] for i in selections if i in self._All]
        
        timeframes = list(timeframes)
        self.Highest = timeframes[-1]
        self.Lowest = timeframes[0]
        for index, timeframe in enumerate(timeframes):
            timeframe.Highest = self.Highest
            timeframe.Lowest = self.Lowest
            if index < len(timeframes) - 2:
                timeframe.Higher = timeframes[index + 1]
            if index > 0:
                timeframe.Lower = timeframes[index - 1]
        
        self.List = timeframes
    
    
    def __getitem__(self, index):
        return self.List[index]
    
    
    def __len__(self):
        return len(self.List)
    
    
    def __repr__(self):
        return "{}".format(self.List)
In [3]:
# Pump in data to consolidators. This History call
# is normally found in my algorithm's warmup phase.
# During the lifespan of the algorithm, consolidators
# are automatically updated.
history = qb.History(qb.Securities.Keys, timedelta(days=365), Resolution.Minute)
timeframes = Timeframes()

for symbol in qb.Securities.Keys:
    for index, data in history.loc[str(symbol)].iterrows():
        tradeBar = TradeBar()
        tradeBar.Close = data['close']
        tradeBar.Open = data['open']
        tradeBar.High = data['high']
        tradeBar.Low = data['low']
        tradeBar.Volume = data['volume']
        tradeBar.Time = index
        tradeBar.Symbol = symbol
        tradeBar.Period = Resolution.Minute
        for timeframe in timeframes:
            timeframe.Consolidator.Update(tradeBar)
In [4]:
for symbol in qb.Securities.Keys:
    s = str(symbol)
    for timeframe in timeframes:
        plt.plot(timeframe.Data.loc[s]['Close'])
        plt.xlabel("Timeframe: {}".format(timeframe))
        plt.ylabel("Price")
        plt.legend(loc='upper left')
        plt.show()
In [ ]: