Overall Statistics
Total Trades
40
Average Win
19.38%
Average Loss
-1.31%
Compounding Annual Return
13.827%
Drawdown
21.900%
Expectancy
4.525
Net Profit
147.837%
Sharpe Ratio
0.782
Loss Rate
65%
Win Rate
35%
Profit-Loss Ratio
14.79
Alpha
0.159
Beta
-0.92
Annual Standard Deviation
0.181
Annual Variance
0.033
Information Ratio
0.675
Tracking Error
0.181
Treynor Ratio
-0.154
Total Fees
$0.00
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"