Overall Statistics
from NodaTime import DateTimeZone
from QuantConnect.Python import PythonQuandl
from datetime import timedelta
import decimal as d
import numpy as np


# https://github.com/QuantConnect/Lean/blob/master/Algorithm.Python/QuandlImporterAlgorithm.py


class GoldMarketTimingAlgorithm(QCAlgorithm):

    def Initialize(self):
        self.quandlGold = "WGC/GOLD_DAILY_USD"
        Quandl.SetAuthCode("iFYucqu5RRUzRyhKXRFu")


        self.SetStartDate(2006, 1, 1) 
        self.SetEndDate(2012, 12, 31)  
        self.SetCash(100000)
        
        self.AddData(QuandlCustomColumns, self.quandlGold, Resolution.Daily, TimeZones.NewYork)
        
        maPeriod = 200
        
        self.moving_average = self.EMA(self.quandlGold, maPeriod, Resolution.Daily)
        
        
        self._tolerance = d.Decimal(1 + 0.001)
        self.IsUpTrend = False
        self.IsDownTrend = False
        
        self.SetWarmUp(200)
        
        # Adds SPY
        self.AddEquity("SPY", Resolution.Daily)
        



    def OnData(self, data):
        if self.moving_average.IsReady:
            self.IsUpTrend = self.Securities[self.quandlGold].Price > self.moving_average.Current.Value * self._tolerance
            self.IsDownTrend = self.Securities[self.quandlGold].Price < self.moving_average.Current.Value * self._tolerance
            if (not self.Portfolio.Invested) and self.IsUpTrend:
                self.SetHoldings(self.quandlGold, 1)

            if self.Portfolio.Invested and self.IsDownTrend:
                self.Liquidate()

    def OnEndOfDay(self):
        if self.IsUpTrend:
            self.Plot("Indicator Signal", "EOD",1)
        elif self.IsDownTrend:
            self.Plot("Indicator Signal", "EOD",-1)
        elif self.moving_average.IsReady:
            self.Plot("Indicator Signal", "EOD",0)


    def OnOrderEvent(self, orderEvent):
        self.Log(str(orderEvent))

        
        
# Quandl often doesn't use close columns so need to tell LEAN which is the "value" column.
class QuandlCustomColumns(PythonQuandl):
    '''Custom quandl data type for setting customized value column name. Value column is used for the primary trading calculations and charting.'''
    def __init__(self):
        # Define ValueColumnName: cannot be None, Empty or non-existant column name
        self.ValueColumnName = "Value"