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
from System.Collections.Generic import List
from QuantConnect.Algorithm import QCAlgorithm
from QuantConnect.Data.UniverseSelection import *
import decimal as d
import numpy as np
import math
import json
import time

### <summary>
### Demonstration of the Scheduled Events features available in QuantConnect.
### </summary>
### <meta name="tag" content="scheduled events" />
### <meta name="tag" content="date rules" />
### <meta name="tag" content="time rules" />
class ScheduledEventsAlgorithm(QCAlgorithm):

    def Initialize(self):
        '''Initialise the data and resolution required, as well as the cash and start-end dates for your algorithm. All algorithms must initialized.'''

        self.SetStartDate(2017,1,1)   #Set Start Date
        self.SetEndDate(2017,1,5)    #Set End Date
        self.SetCash(100000)           #Set Strategy Cash
        self.UniverseSettings.Resolution = Resolution.Daily;
        
        self.AddUniverse(StockDataSource, "my-stock-data-source", self.stockDataSource)
        
    def stockDataSource(self, data):
        list = []
        for item in data:
            for symbol in item["Symbols"]:
                list.append(symbol)
        self.symbols = list
        return self.symbols

        # schedule an event to fire every trading day for a security the
        # time rule here tells it to fire 10 minutes after SPY's market open
        self.Schedule.On(self.DateRules.EveryDay("SPY"), self.TimeRules.AfterMarketOpen("SPY", 10), self.OpenPositions)

        
        # schedule an event to fire every trading day for a security the
        # time rule here tells it to fire 10 minutes before SPY's market close
        self.Schedule.On(self.DateRules.EveryDay("SPY"), self.TimeRules.BeforeMarketClose("SPY", 10), self.LiquidatePositions)
        

    def OpenPositions(self):
        if not self.Portfolio.Invested:
            self.SetHoldings(self.symbols[0], 1)
    
    def LiquidatePositions(self):
        if self.Portfolio.Invested:
            self.Liquidate()
        
        
class StockDataSource(PythonData):
    
    def GetSource(self, config, date, isLiveMode):
        url = "https://www.dropbox.com/s/2az14r5xbx4w5j6/daily-stock-picker-live.csv?dl=1" if isLiveMode else \
            "https://www.dropbox.com/s/e17vdejcjrb6hpj/stock_test.csv?dl=1"

        return SubscriptionDataSource(url, SubscriptionTransportMedium.RemoteFile)
    
    def Reader(self, config, line, date, isLiveMode):
        if not (line.strip() and line[0].isdigit()): return None
        
        stocks = StockDataSource()
        stocks.Symbol = config.Symbol
        
        csv = line.split(',')
        if isLiveMode:
            stocks.Time = date
            stocks["Symbols"] = csv
        else:
            stocks.Time = datetime.strptime(csv[0], "%Y%m%d")
            stocks["Symbols"] = csv[1]
        return stocks