EMA Crossover Diff
3 removals
114 lines
5 additions
116 lines
## https://www.quantconnect.com/forum/discussion/12768/share-kalman-filter-crossovers-for-crypto-and-smart-rollingwindows/p1/comment-38206
from datetime import timedelta
from datetime import timedelta
from AlgorithmImports import *
from AlgorithmImports import *
import math
import math
# from Shared.IntradayMomentumIndex importIn
# from Shared.IntradayMomentumIndex importIn
from SmartRollingWindow import *
from SmartRollingWindow import *
def truncate(number, decimals=0):
def truncate(number, decimals=0):
"""
"""
Returns a value truncated to a specific number of decimal places.
Returns a value truncated to a specific number of decimal places.
"""
"""
if not isinstance(decimals, int):
if not isinstance(decimals, int):
raise TypeError("decimal places must be an integer.")
raise TypeError("decimal places must be an integer.")
elif decimals < 0:
elif decimals < 0:
raise ValueError("decimal places has to be 0 or more.")
raise ValueError("decimal places has to be 0 or more.")
elif decimals == 0:
elif decimals == 0:
return math.trunc(number)
return math.trunc(number)
factor = 10.0 ** decimals
factor = 10.0 ** decimals
return math.trunc(number * factor) / factor
return math.trunc(number * factor) / factor
class Asset():
class Asset():
def __init__(self, algorithm, symbol):
def __init__(self, algorithm, symbol):
self.symbol = symbol
self.symbol = symbol
self.algorithm = algorithm
self.algorithm = algorithm
def InitIndicators(self, slowPeriod, fastPeriod, resolution):
def InitIndicators(self, slowPeriod, fastPeriod, resolution):
self.fast = self.algorithm.EMA(self.symbol, fastPeriod, Resolution.Daily)
self.fast = self.algorithm.EMA(self.symbol, fastPeriod, Resolution.Daily)
self.slow = self.algorithm.EMA(self.symbol, slowPeriod, Resolution.Daily)
self.slow = self.algorithm.EMA(self.symbol, slowPeriod, Resolution.Daily)
self.slowWindow = SmartRollingWindow('float', 2)
self.slowWindow = SmartRollingWindow('float', 2)
self.fastWindow = SmartRollingWindow('float', 2)
self.fastWindow = SmartRollingWindow('float', 2)
self.priceWindow = SmartRollingWindow('float', 2)
self.priceWindow = SmartRollingWindow('float', 2)
def UpdateIndicators(self):
def UpdateAssetWindows(self):
self.slowWindow.Add(self.slow.Current.Value)
self.slowWindow.Add(self.slow.Current.Value)
self.fastWindow.Add(self.fast.Current.Value)
self.fastWindow.Add(self.fast.Current.Value)
self.priceWindow.Add(self.algorithm.Securities[self.symbol].Price)
self.priceWindow.Add(self.algorithm.Securities[self.symbol].Price)
def PrefixWithSymbol(self, str):
def PrefixWithSymbol(self, str):
return "{}: {}".format(self.symbol.Value, str)
return "{}: {}".format(self.symbol.Value, str)
def Plot(self, chartName):
def Plot(self, chartName):
self.algorithm.Plot(chartName, self.PrefixWithSymbol("Price"), self.algorithm.Securities[self.symbol].Price)
self.algorithm.Plot(chartName, self.PrefixWithSymbol("Price"), self.algorithm.Securities[self.symbol].Price)
self.algorithm.Plot(chartName, self.PrefixWithSymbol("Slow"), self.slow.Current.Value)
self.algorithm.Plot(chartName, self.PrefixWithSymbol("Slow"), self.slow.Current.Value)
self.algorithm.Plot(chartName, self.PrefixWithSymbol("Fast"), self.fast.Current.Value)
self.algorithm.Plot(chartName, self.PrefixWithSymbol("Fast"), self.fast.Current.Value)
class FocusedYellowGreenJellyfish(QCAlgorithm):
class FocusedYellowGreenJellyfish(QCAlgorithm):
def Initialize(self):
def Initialize(self):
self.InitAlgoParams()
self.InitAlgoParams()
self.InitBacktestParams()
self.InitBacktestParams()
self.InitAssets()
self.InitAssets()
self.InitIndicators()
self.InitIndicators()
def InitAlgoParams(self):
def InitAlgoParams(self):
self.benchmarkTicker = 'BTCUSDT';
self.benchmarkTicker = 'BTCUSDT';
self.tickers = ["SOLUSDT", "ETHUSDT", "BNBUSDT"]
self.tickers = ["SOLUSDT", "ETHUSDT", "BNBUSDT"]
self.assets = {}
self.assets = {}
self.ticker = "SOLUSDT"
self.ticker = "SOLUSDT"
self.resolution = Resolution.Minute
self.resolution = Resolution.Minute
self.slowPeriod = int(self.GetParameter('slowPeriod'))
self.slowPeriod = int(self.GetParameter('slowPeriod'))
self.fastPeriod = int(self.GetParameter('fastPeriod'))
self.fastPeriod = int(self.GetParameter('fastPeriod'))
def InitBacktestParams(self):
def InitBacktestParams(self):
self.SetAccountCurrency("USDT")
self.SetAccountCurrency("USDT")
self.SetCash(100000)
self.SetCash(100000)
self.SetStartDate(2020, 1, 1)
self.SetStartDate(2020, 1, 1)
def InitAssets(self):
def InitAssets(self):
self.SetBrokerageModel(BrokerageName.Binance, AccountType.Cash)
self.SetBrokerageModel(BrokerageName.Binance, AccountType.Cash)
self.benchmarkSymbol = self.AddCrypto(self.benchmarkTicker, self.resolution).Symbol
self.benchmarkSymbol = self.AddCrypto(self.benchmarkTicker, self.resolution).Symbol
for ticker in self.tickers:
for ticker in self.tickers:
symbol = self.AddCrypto(ticker, self.resolution).Symbol
symbol = self.AddCrypto(ticker, self.resolution).Symbol
self.assets[ticker] = Asset(self, symbol)
self.assets[ticker] = Asset(self, symbol)
self.SetBenchmark(self.benchmarkTicker)
self.SetBenchmark(self.benchmarkTicker)
def InitIndicators(self):
def InitIndicators(self):
self.SetWarmUp(self.slowPeriod * 2, self.resolution)
self.SetWarmUp(self.slowPeriod * 2, self.resolution)
for asset in self.assets.values():
for asset in self.assets.values():
asset.InitIndicators(self.slowPeriod, self.fastPeriod, self.resolution)
asset.InitIndicators(self.slowPeriod, self.fastPeriod, self.resolution)
self.Consolidate(self.benchmarkSymbol, Resolution.Daily, self.OnConsolidatedBarClose)
self.Consolidate(self.benchmarkSymbol, Resolution.Daily, self.OnConsolidatedBarClose)
def UpdateRollingWindows(self):
def UpdateRollingWindows(self):
for asset in self.assets.values():
for asset in self.assets.values():
asset.UpdateIndicators()
asset.UpdateAssetWindows()
def ShouldExit(self, asset):
def ShouldExit(self, asset):
return asset.priceWindow.isBelow(asset.slowWindow) or asset.slowWindow.isAbove(asset.fastWindow)
return asset.priceWindow.isBelow(asset.slowWindow) or asset.slowWindow.isAbove(asset.fastWindow)
def ShouldEnter(self, asset):
def ShouldEnter(self, asset):
return asset.fastWindow.isAbove(asset.slowWindow) and asset.priceWindow.isAbove(asset.fastWindow)
return asset.fastWindow.isAbove(asset.slowWindow) and asset.priceWindow.isAbove(asset.fastWindow)
def OnEndOfDay(self):
def OnEndOfDay(self):
self.PlotCharts()
self.PlotCharts()
self.UpdateRollingWindows()
def OnConsolidatedBarClose(self, bar):
def OnConsolidatedBarClose(self, bar):
self.UpdateRollingWindows()
for asset in self.assets.values():
for asset in self.assets.values():
if not asset.slowWindow.IsReady():
if not asset.slowWindow.IsReady():
return
return
if self.Portfolio[asset.symbol].Invested and self.ShouldExit(asset):
if self.Portfolio[asset.symbol].Invested and self.ShouldExit(asset):
self.Liquidate(asset.symbol)
self.Liquidate(asset.symbol)
elif not self.Portfolio[asset.symbol].Invested and self.ShouldEnter(asset):
elif not self.Portfolio[asset.symbol].Invested and self.ShouldEnter(asset):
percent = truncate(1 / len(self.assets.values()), 1)
percent = truncate(1 / len(self.assets.values()), 1)
cost = self.Portfolio.TotalPortfolioValue * percent
cost = self.Portfolio.TotalPortfolioValue * percent
cash = self.Portfolio.TotalPortfolioValue - self.Portfolio.TotalHoldingsValue
cash = self.Portfolio.TotalPortfolioValue - self.Portfolio.TotalHoldingsValue
self.Log("Cost: {}, Cash: {}".format(cost, cash))
self.Log("Cost: {}, Cash: {}".format(cost, cash))
if (cost > cash):
if (cost > cash):
percent = truncate(cash / self.Portfolio.TotalPortfolioValue, 1)
percent = truncate(cash / self.Portfolio.TotalPortfolioValue, 1)
self.SetHoldings(asset.symbol, percent);
self.SetHoldings(asset.symbol, percent);
def PlotCharts(self):
def PlotCharts(self):
chartName = "Charts"
chartName = "Charts"
# self.Plot('Benchmark', "Benchmark", self.Securities[self.benchmarkSymbol].Price)
# self.Plot('Benchmark', "Benchmark", self.Securities[self.benchmarkSymbol].Price)
for asset in self.assets.values():
for asset in self.assets.values():
asset.Plot(chartName)
asset.Plot(chartName)