Overall Statistics
Total Orders
18
Average Win
2.47%
Average Loss
-9.71%
Compounding Annual Return
-3.108%
Drawdown
38.000%
Expectancy
-0.059
Start Equity
100000
End Equity
85376
Net Profit
-14.624%
Sharpe Ratio
-0.176
Sortino Ratio
-0.164
Probabilistic Sharpe Ratio
0.129%
Loss Rate
25%
Win Rate
75%
Profit-Loss Ratio
0.25
Alpha
-0.026
Beta
0.043
Annual Standard Deviation
0.123
Annual Variance
0.015
Information Ratio
-0.722
Tracking Error
0.176
Treynor Ratio
-0.5
Total Fees
$0.00
Estimated Strategy Capacity
$0
Lowest Capacity Asset
WGC/GOLD_DAILY_USD.NasdaqDataLink 2S
Portfolio Turnover
0.35%
# region imports
from AlgorithmImports import *
# endregion


class GoldMarketTimingAlgorithm(QCAlgorithm):

    def initialize(self):
        self.set_start_date(2010, 1, 1) 
        self.set_end_date(2015, 1, 1)  
        self.set_cash(100000)
        # United States Government 10-Year Bond Yield   
        self._ten_year_yield = 0
        self._bond_yield = self.add_data(USTreasuryYieldCurveRate, "USTYCR").symbol
        # S&P 500 Earnings Yield. Earnings Yield = trailing 12 month earnings divided by index price 
        self._earnings_yield = self.add_data(NasdaqDataLink, "MULTPL/SP500_EARNINGS_YIELD_MONTH", Resolution.DAILY, TimeZones.UTC, True).symbol
        # Gold Prices (Daily) - Currency USD (All values are national currency units per troy ounce)
        self._gold = self.add_data(NasdaqDataLink, "WGC/GOLD_DAILY_USD", Resolution.DAILY, TimeZones.UTC, True).symbol
        # Monthly rebalance
        self.add_equity("SPY", Resolution.DAILY)
        self.schedule.on(self.date_rules.month_start("SPY"), self.time_rules.at(0, 0), self._rebalance)
        self.set_warm_up(timedelta(30))

    def on_data(self, data):
        if data.contains_key(self._bond_yield) and data[self._bond_yield].ten_year:
            self._ten_year_yield = data[self._bond_yield].ten_year
            if data.contains_key(self._earnings_yield):
                self.plot("Yield Plot", "BondYield", self._ten_year_yield)
                self.plot("Yield Plot", "EarningsYield", data[self._earnings_yield].price)

    def _rebalance(self):
        if self.securities[self._earnings_yield].price == 0 or self._ten_year_yield == 0: 
            return
        # Buy _gold if E/P is higher than the bond yield and their ratio is at least 2
        if self.securities[self._earnings_yield].price > self._ten_year_yield * 2:
            self.set_holdings(self._gold, 0.9)
        else:
            self.liquidate()