Overall Statistics |
Total Trades 12 Average Win 0% Average Loss 0% Compounding Annual Return 0.653% Drawdown 0.200% Expectancy 0 Net Profit 0.057% Sharpe Ratio 1.448 Probabilistic Sharpe Ratio 55.967% Loss Rate 0% Win Rate 0% Profit-Loss Ratio 0 Alpha -0.003 Beta 0.017 Annual Standard Deviation 0.004 Annual Variance 0 Information Ratio -6.322 Tracking Error 0.076 Treynor Ratio 0.3 Total Fees $0.00 |
class CommodityAlphaModel(AlphaModel): def __init__(self, period): self.period = period self.resolution = Resolution.Daily self.predictionInterval = Time.Multiply(Extensions.ToTimeSpan(self.resolution), self.period) self.symbolData = {} def Update(self, context, data): insights = [] for symbol, symbolData in self.symbolData.items(): if not context.Portfolio[symbol].Invested: if symbolData.CanEmit: if data.ContainsKey(symbol): close = symbolData.QuoteBar.Close highChannel = symbolData.Channel.UpperBand.Current.Value lowChannel = symbolData.Channel.LowerBand.Current.Value if close >= highChannel: direction = InsightDirection.Up insights.append(Insight.Price(symbol, self.predictionInterval, direction, None, None)) elif close <= lowChannel: direction = InsightDirection.Down insights.append(Insight.Price(symbol, self.predictionInterval, direction, None, None)) return insights def OnSecuritiesChanged(self, context, changes): for removed in changes.RemovedSecurities: symbol = removed.Symbol if removed in self.symbolData: symbolData = self.symbolData.pop(symbol, None) if symbolData is not None: symbolData.RemoveConsolidators(context) # initialize data for added securities symbols = [ x.Symbol for x in changes.AddedSecurities ] history = context.History(symbols, self.period, self.resolution) if history.empty: return tickers = history.index.levels[0] context.Debug("{} -- {} Added to Alpha Model".format(context.Time, [str(added.Symbol) for added in changes.AddedSecurities])) for added in changes.AddedSecurities: symbol = added.Symbol if symbol not in self.symbolData: context.Debug("{} -- {} Added to Alpha Model Symbol Data".format(context.Time, str(symbol))) data = SymbolData(context, added, self.period) self.symbolData[symbol] = data data.RegisterIndicators(context, self.resolution) if symbol not in tickers: continue else: data.WarmUpIndicators(history.loc[symbol]) class SymbolData: def __init__(self, context, security, lookback): self.context = context self.Security = security self.Symbol = security.Symbol self.Channel = DonchianChannel(self.Symbol, 20, Resolution.Daily) self.Consolidator = None self.QuoteBar = None self.Previous = None self.print = True def RegisterIndicators(self, context, resolution): self.Consolidator = context.ResolveConsolidator(self.Symbol, Resolution.Daily) self.Consolidator.DataConsolidated += self.OnDataConsolidated context.RegisterIndicator(self.Symbol, self.Channel, self.Consolidator) context.Debug("Indicator registered for {} @ {}".format(self.Symbol, context.Time)) def OnDataConsolidated(self, sender, bar): if self.print: self.context.Debug("{} -- Data Consol. for {}: {}, Ending: {}".format(self.context.Time, self.Symbol, bar.Close, bar.EndTime)) self.print = False self.QuoteBar = bar @property def CanEmit(self): # this will be getting checked at a higher freq. than the consolidator, check if a new Daily bar is available if self.Previous == self.QuoteBar: return False self.Previous = self.QuoteBar return self.Channel.IsReady def RemoveConsolidators(self, context): if self.Consolidator is not None: conext.SubscriptionManager.RemoveConsolidator(self.Symbol, self.Consolidator) def WarmUpIndicators(self, history): for index, tuple in history.iterrows(): tradeBar = TradeBar() tradeBar.Close = tuple['close'] self.Channel.Update(tradeBar)
class CommodityPortfolioConstructionModel(PortfolioConstructionModel): def CreateTargets(self, context, insights): targets = [] for insight in insights: targets.append(PortfolioTarget(insight.Symbol, insight.Direction)) return targets
from Universe import CommodityUniverseModel from Alpha import CommodityAlphaModel from Portfolio import CommodityPortfolioConstructionModel # from Execution import CommodityExecutionModel class CommodityTrading(QCAlgorithm): def Initialize(self): # Set Start Date so that backtest has 5+ years of data self.SetStartDate(2018, 1, 1) self.SetEndDate(2018, 2, 1) # No need to set End Date as the final submission will be tested # up until the review date # Set $100k Strategy Cash to trade significant AUM self.SetCash(100000) # Use the Alpha Streams Brokerage Model, developed in conjunction with # funds to model their actual fees, costs, etc. # Please do not add any additional reality modelling, such as Slippage, Fees, Buying Power, etc. # self.SetBrokerageModel(AlphaStreamsBrokerageModel()) self.SetExecution( ImmediateExecutionModel() ) # self.SetPortfolioConstruction( EqualWeightingPortfolioConstructionModel() ) self.SetPortfolioConstruction( CommodityPortfolioConstructionModel() ) self.AddAlpha( CommodityAlphaModel(period=20) ) self.UniverseSettings.Resolution = Resolution.Minute self.AddUniverseSelection( CommodityUniverseModel() ) def OnData(self, data): '''OnData event is the primary entry point for your algorithm. Each new data point will be pumped in here. Arguments: data: Slice object keyed by symbol containing the stock data ''' # if not self.Portfolio.Invested: # self.SetHoldings("SPY", 1)
from QuantConnect import * from Selection.ManualUniverseSelectionModel import ManualUniverseSelectionModel class CommodityUniverseModel(ManualUniverseSelectionModel): def __init__(self): metals = ["XAUUSD", "XAGUSD", "XCUUSD", "XPDUSD", "XPTUSD"] fuels = ["WTICOUSD", "BCOUSD", "NATGASUSD"] agri = ["SOYBNUSD", "CORNUSD", "WHEATUSD", "SUGARUSD"] universe = metals + fuels + agri super().__init__([Symbol.Create(x, SecurityType.Cfd, Market.Oanda) for x in universe])