Overall Statistics |
Total Trades 0 Average Win 0% Average Loss 0% Compounding Annual Return 0% Drawdown 0% Expectancy 0 Net Profit 0% Sharpe Ratio 0 Loss Rate 0% Win Rate 0% Profit-Loss Ratio 0 Alpha 0 Beta 0 Annual Standard Deviation 0 Annual Variance 0 Information Ratio 0 Tracking Error 0 Treynor Ratio 0 Total Fees $0.00 |
from datetime import timedelta import fnmatch class IndicatorTest(QCAlgorithm): def Initialize(self): self.SetStartDate(2012,1,1) #Set Start Date self.SetEndDate(2017,1,5) #Set End Date self.SetCash(100000) #Set Strategy Cash self.symbols = [ Futures.Indices.SP500EMini, Futures.Metals.Gold, #"CL", #"CG", #"HG", #"XK", ] # Create Dictionaries for Indicators self.fast = {} self.slow = {} self.atr = {} # Add Data & Indicators for symbol in self.symbols: future = self.AddFuture(symbol, Resolution.Daily) future.SetFilter(timedelta(0), timedelta(182)) # Note use of future.Symbol, if we use symbol string we get error regarding unsubbed asset(so use the object instead) self.fast[symbol] = SimpleMovingAverage(10) self.slow[symbol] = SimpleMovingAverage(100) self.atr[symbol] = AverageTrueRange(20) ''' self.chart_target = 'Strategy Equity' sPlot = Chart(self.chart_target) # Lets chart the info for i,symbol in enumerate(self.symbols): sPlot.AddSeries(Series('%s'%symbol, SeriesType.Line, 2+i)) # Label only sPlot.AddSeries(Series('Fast %s'%symbol, SeriesType.Line, 2+i)) sPlot.AddSeries(Series('Slow %s'%symbol, SeriesType.Line, 2+i)) sPlot.AddSeries(Series('Current %s'%symbol, SeriesType.Line, 2+i)) self.AddChart(sPlot) ''' def OnData(self, data): # Used examples from here to access futures contracts # https://github.com/QuantConnect/Lean/blob/fb7d1994ff0b1859e7204ffedd609236a6fd4827/Algorithm.Python/BasicTemplateFuturesAlgorithm.py for chain in data.FutureChains: # Get contracts expiring no earlier than in 90 days contracts = filter(lambda x: x.Expiry > self.Time + timedelta(90), chain.Value) # if there is any contract, trade the front contract if len(contracts) == 0: continue front = sorted(contracts, key = lambda x: x.Expiry, reverse=True)[0] # get the corresponding underlying? has to be a better way to keep track... for base_symbol in self.symbols: if len(fnmatch.filter([str(front.Symbol)], str(base_symbol)+'*')) > 0: # match found, plot or log lookup_symbol = base_symbol self.fast[lookup_symbol].Update(self.Time, front.LastPrice) self.slow[lookup_symbol].Update(self.Time, front.LastPrice) if self.fast[lookup_symbol].Current.Value > self.slow[lookup_symbol].Current.Value: self.SetHoldings(lookup_symbol, 0.5) elif self.fast[lookup_symbol].Current.Value < self.slow[lookup_symbol].Current.Value: self.SetHoldings(lookup_symbol, 0) #self.Log(str(lookup_symbol) + " : " + str(self.fast[lookup_symbol].Current.Value)) #self.Log(str(lookup_symbol) + " : " + str(self.slow[lookup_symbol].Current.Value)) #self.Plot(self.chart_target,'Fast %s'%lookup_symbol, self.fast[lookup_symbol].Current.Value) #self.Plot(self.chart_target,'Slow %s'%lookup_symbol, self.slow[lookup_symbol].Current.Value) #self.Plot(self.chart_target,'Current %s'%lookup_symbol, front.LastPrice) #break #self.previous = self.Time
from datetime import timedelta import fnmatch class FollowingtheTrend(QCAlgorithm): def Initialize(self): self.SetStartDate(2017,1,1) #Set Start Date self.SetEndDate(2017,1,5) #Set End Date self.SetCash(100000) #Set Strategy Cash self.symbols = [ Futures.Indices.SP500EMini, Futures.Metals.Gold, #"CL", #"CG", #"HG", #"XK", ] self.fast = {} self.slow = {} for symbol in self.symbols: future = self.AddFuture(symbol, Resolution.Daily) future.SetFilter(timedelta(0), timedelta(182)) # Note use of future.Symbol, if we use symbol string we get error regarding unsubbed asset(so use the object instead) self.fast[symbol] = SimpleMovingAverage(10) self.slow[symbol] = SimpleMovingAverage(100) self.ATR[symbol] = AverageTrueRange(20) self.chart_target = 'Strategy Equitys' sPlot = Chart(self.chart_target) # Set Risk Factor for position sizing self.risk_factor = 0.002 ''' # Lets chart the info for i,symbol in enumerate(self.symbols): sPlot.AddSeries(Series('%s'%symbol, SeriesType.Line, 2+i)) # Label only sPlot.AddSeries(Series('Fast %s'%symbol, SeriesType.Line, 2+i)) sPlot.AddSeries(Series('Slow %s'%symbol, SeriesType.Line, 2+i)) sPlot.AddSeries(Series('Current %s'%symbol, SeriesType.Line, 2+i)) self.AddChart(sPlot) ''' def OnData(self, data): # Used examples from here to access futures contracts # https://github.com/QuantConnect/Lean/blob/fb7d1994ff0b1859e7204ffedd609236a6fd4827/Algorithm.Python/BasicTemplateFuturesAlgorithm.py for chain in data.FutureChains: # Get contracts expiring no earlier than in 90 days contracts = filter(lambda x: x.Expiry > self.Time + timedelta(90), chain.Value) # if there is any contract, trade the front contract if len(contracts) == 0: continue front = sorted(contracts, key = lambda x: x.Expiry, reverse=True)[0] # get the corresponding underlying? has to be a better way to keep track... for base_symbol in self.symbols: if len(fnmatch.filter([str(front.Symbol)], str(base_symbol)+'*')) > 0: # match found, plot or log lookup_symbol = base_symbol self.fast[lookup_symbol].Update(self.Time, front.LastPrice) self.slow[lookup_symbol].Update(self.Time, front.LastPrice) if self.fast[lookup_symbol].Current.Value > self.slow[lookup_symbol].Current.Value: # Calculate number of shares to buy #quantity = self.target_portfolio[symbol].ATR.Current.Value/(Portfolio.TotalPortfolioValue*self.risk_factor) quantity = (Portfolio.TotalPortfolioValue*self.risk_factor)/self.target_portfolio[lookup_symbol].ATR.Current.Value # Send Orders self.MarketOrder(lookup_symbol, quantity) elif self.fast[lookup_symbol] < self.slow[lookup_symbol]: self.Liquidate(lookup_symbol) else: continue #self.slow[lookup_symbol] #self.Log(str(lookup_symbol) + " : " + str(self.fast[lookup_symbol].Current.Value)) #self.Log(str(lookup_symbol) + " : " + str(self.slow[lookup_symbol].Current.Value)) #self.Plot(self.chart_target,'Fast %s'%lookup_symbol, self.fast[lookup_symbol].Current.Value) #self.Plot(self.chart_target,'Slow %s'%lookup_symbol, self.slow[lookup_symbol].Current.Value) #self.Plot(self.chart_target,'Current %s'%lookup_symbol, front.LastPrice) #break #self.previous = self.Time class SymbolData(object): def __init__(self, symbol, context): self.symbol = symbol """ I had to pass ATR from outside object to get it to work, could pass context and use any indica var atr = ATR(Symbol symbol, int period, MovingAverageType type = null, Resolution resolution = null, Func`2[Data.IBaseData,Data.Market.IBaseDataBar] selector = null) """ self.ATR = context.ATR(symbol, 20) """ Runtime Error: Python.Runtime.PythonException: NotSupportedException : AverageTrueRange does not support Update(DateTime, decimal) method overload. Use Update(IBaseDataBar) instead. """ # Use the below update method for ATR which is used for position sizing def update_value(self, time, value): self.ATR.Update(time, value)