| 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 datetime, timedelta
import numpy as np
import decimal as d
import dateutil
from QuantConnect.Brokerages import *
import pandas as pd
class fifo:
def __init__(self):
self.data = []
def append(self, data):
self.data.append(data)
def pop(self):
return self.data.pop(0)
def length(self):
return len(self.data)
def data_list(self):
return self.data
def max_in_list(list):
max_data = -999999
idx_max = 0
idx = 0
for i in list:
if i > max_data:
max_data = i
idx_max = idx
idx = idx + 1
return max_data, idx_max
def min_in_list(list):
min_data = 999999
idx_min = 0
idx = 0
for i in list:
if i < min_data:
min_data = i
idx_min = idx
idx = idx + 1
return min_data, idx_min
def invalid_negative_value():
return -999999
def ignore_date(timestamp, datelist):
currentdate = timestamp[:10]
ocurrentdate = dateutil.parser.parse(currentdate)
for date in datelist:
odate = dateutil.parser.parse(date)
if odate == ocurrentdate:
return True
return False
class BasicTemplateAlgorithm(QCAlgorithm):
def Initialize(self):
'''Initialise the data and resolution required, as well as the cash and start-end dates
for your algorithm. All algorithms must initialized.'''
self.total_cash = 20000
self.SetStartDate(2019, 2, 3) # Set Start Date
self.SetEndDate(2019, 7, 22) # Set End Date
self.SetCash(self.total_cash) # Set Strategy Cash
self.SetBrokerageModel(BrokerageName.InteractiveBrokersBrokerage)
self.capital_per_trade = 10000 # self.total_cash/2.0
self.instrument_list = []
self.instrument_list.append("GLD")
self.instrument_list.append("SPY")
for instrument in self.instrument_list:
self.AddEquity(instrument, Resolution.Minute)
# StopLoss and profit target not being used
self.stop_loss = 1.5
self.profit_target = 5.0
self.first_profit_target = 1.0
self.first_pullback_target = 0.7
self.vma_period = 8
self.position_type = 1
self.ignoredatelist = []
self.ignoredatelist.append("2018-12-31")
self.per_stop_loss = self.stop_loss / 100.0
self.per_profit_target = self.profit_target / 100.0
self.per_first_profit_target = self.first_profit_target / 100.0
self.per_first_pullback_target = self.first_pullback_target / 100.0
self.enter_price = 0.0
self.enter = False
self.exit = False
self.sl_exit_price = invalid_negative_value()
self.target_exit_price = invalid_negative_value()
self.prev_day_close = invalid_negative_value()
self.partial_exit = False
self.partial_entry = False
self.first_target_exit_price = 0.0
self.first_pullback_entry_price = 0.0
# cols = ["Date", "Time", "Instrument", "RSI", "Prev_High", "Current Price", "Qty", "Target",
# "SL"]
# self.df_out = pd.DataFrame(columns=cols)
dailyConsolidator = {}
self.rsi = {}
for instrument in self.instrument_list:
dailyConsolidator[instrument] = TradeBarConsolidator(TimeSpan.FromDays(1))
self.SubscriptionManager.AddConsolidator(instrument, dailyConsolidator[instrument])
dailyConsolidator[instrument].DataConsolidated += self.dailyBarHandler
self.rsi[instrument] = self.RSI(instrument, 20, MovingAverageType.Simple, Resolution.Daily)
# self.Schedule.On(self.DateRules.EveryDay(), self.TimeRules.At(9,45),Action(self.vmaTimeframeHandler))
def dailyBarHandler(self, sender, bar):
currentdatetime = str(self.Time)
currentdate = currentdatetime[:10]
currenttime = currentdatetime[11:20]
ocurrentdate = dateutil.parser.parse(currentdate)
printafterdate = "2018-11-18"
odate = dateutil.parser.parse(printafterdate)
self.Debug(str(self.Time) + ":CurrentTime " + str(currenttime) + ":CurrentBar " + str(bar.Symbol) +
" bar high:" + str(bar.High))
instrument = str(bar.Symbol)
if self.rsi[instrument].IsReady:
# get the current RSI value
rsi_value = self.rsi[instrument].Current.Value
self.Debug(str(rsi_value))
# cols = ["Date", "Time", "Instrument", "RSI", "Prev_High", "Current Price", "Qty", "Target",
# "SL"]
# self.df_out.loc[len(self.df_out)] = [currentdate, currenttime, instrument, 0, bar.High, 0.0,
# 0, 0.0, 0.0]
# processafterdate = "2016-10-30"
# oprocessdate = dateutil.parser.parse(processafterdate)
#
# if ocurrentdate > oprocessdate:
# if ignore_date(str(self.Time), self.ignoredatelist) == False:
# self.Debug("Aroon Prev Vidya:" + str(self.prev_vidya))
#
# if not self.Portfolio.Invested:
# low_per_diff = (self.prev_intraday_bar_low - self.prev_vidya) / self.prev_vidya
# tech_cond1 = low_per_diff > self.diff_target
# # tech_cond1 = True
# tech_cond2 = (self.aroon_up > self.aroon_threshold) and (
# self.aroon_up > self.aroon_down)
# if ocurrentdate > odate:
# if (tech_cond1):
# self.Debug(str(bar.EndTime) + ":" + "Tech1 condition met")
# if (tech_cond2):
# self.Debug(str(bar.EndTime) + ":" + "Tech2 condition met")
# if (tech_cond1 and tech_cond2):
# self.Debug(str(bar.EndTime) + ":" + "Aroon Low diff: " + str(low_per_diff))
# # self.Debug(str(bar.EndTime) + ":" + "Aroon Low diff: ")
# self.enter = True
# return
#
# if self.Portfolio.Invested:
# high_per_diff = (self.prev_vidya - float(bar.High)) / float(bar.High)
# exit_tech_cond1 = high_per_diff > self.diff_target
# exit_tech_cond2 = (self.aroon_up < self.aroon_threshold) or (
# self.aroon_up < self.aroon_down)
# exit_tech_cond4 = (float(bar.Close) > self.target_exit_price)
# exit_tech_cond3 = (float(bar.Close) < self.sl_exit_price)
# if ocurrentdate > odate:
# if (exit_tech_cond1):
# self.Debug(str(bar.EndTime) + ":" + "Exit Tech1 condition met")
# if (exit_tech_cond2):
# self.Debug(str(bar.EndTime) + ":" + "Exit Tech1 condition met")
# if (exit_tech_cond3):
# self.Debug(str(bar.EndTime) + ":" + "Exit Tech3 condition met")
# if (exit_tech_cond4):
# self.Debug(str(bar.EndTime) + ":" + "Exit Tech4 condition met")
# if (exit_tech_cond1 or exit_tech_cond2 or exit_tech_cond3 or exit_tech_cond4):
# self.Debug(str(bar.EndTime) + ":" + "Aroon High per diff: " + str(high_per_diff))
# self.exit = True
# return
# if ocurrentdate > odate:
# self.Debug("Daily:"+ str(self.Time) + "Open:" + str(bar.Open) + "High:" + str(
# bar.High) +
# "Low:" + str(bar.Low) + "Close:" + str(bar.Close))
# self.Debug("Aroon_Up:" + str(self.aroon_up) + "Aroon_Down" + str(self.aroon_down))
# def vmaTimeframeHandler(self):
# currentdatetime = str(self.Time)
# currentdate = currentdatetime[:10]
# ocurrentdate = dateutil.parser.parse(currentdate)
#
# printafterdate = "2018-11-18"
# odate = dateutil.parser.parse(printafterdate)
#
# processafterdate = "2016-10-30"
# oprocessdate = dateutil.parser.parse(processafterdate)
#
# if ocurrentdate <= oprocessdate:
# return
#
# if ignore_date(str(self.Time), self.ignoredatelist) == True:
# return
#
# close_price = self.Securities['GLD'].AskPrice
# vma = self.ovma.determine_vma(float(close_price), self)
# self.Debug(str(self.Time) + ": close_price:" + str(close_price) + " ; VMA:" + str(vma))
# if not self.Portfolio.Invested:
# self.Debug(str(self.Time) + ": Portfolio Not Invested" + "; vma:" + str(vma) + " ; prev_vma:" + str(self.prev_vma))
# if vma > self.prev_vma:
# self.enter = True
# self.ovmagld.on_event("signalvmaenter", self)
#
# if self.Portfolio.Invested:
# self.Debug(str(self.Time) + ": Portfolio Invested" + "; vma:" + str(vma) + " ; prev_vma:" + str(self.prev_vma))
# if vma < self.prev_vma:
# self.exit = True
# self.ovmagld.on_event("signalvmaexit", self)
#
# self.prev_vma = vma
# return
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
'''
# currentdatetime = str(self.Time)
# currentdate = currentdatetime[:10]
# ocurrentdate = dateutil.parser.parse(currentdate)
# printafterdate = "2018-11-18"
# odate = dateutil.parser.parse(printafterdate)
#
# processafterdate = "2016-10-30"
# oprocessdate = dateutil.parser.parse(processafterdate)
#
# if ocurrentdate <= oprocessdate:
# return
#
# if ignore_date(str(self.Time), self.ignoredatelist) == True:
# return
#
# current_price = float(data["GLD"].Close)
# if self.Portfolio.Invested:
# if (str(self.ovmagld.state) == "completelyfilled" and
# current_price > self.first_target_exit_price):
# self.qty = self.position_type * (
# int(float(self.capital_per_trade) / (2.0 * float(data["GLD"].Close))))
# orderticket = self.MarketOrder("GLD", -self.qty)
# self.first_pullback_entry_price = self.enter_price * \
# (1 + (self.position_type *
# self.per_first_pullback_target))
# self.Debug(str(data["GLD"].Time) + ":" + "Partial exit at :" + str(current_price) +
# "First Pullback: " + str(self.first_pullback_entry_price))
#
# self.ovmagld.on_event("firsttargetmet", self)
#
# if (str(self.ovmagld.state) == "partiallyfilled1" and
# current_price < self.first_pullback_entry_price):
# self.qty = self.position_type * (
# int(float(self.capital_per_trade) / (2.0 * float(data["GLD"].Close))))
# orderticket = self.MarketOrder("GLD", -self.qty)
# self.Debug(str(data["GLD"].Time) + ":" + "Partial entry at :" + str(current_price) +
# ": qty: " + str(self.qty))
# self.first_target_exit_price = self.enter_price * \
# (1 + (
# self.position_type * self.per_first_profit_target))
#
#
# self.ovmagld.on_event("temppullback", self)
#
#
#
# if self.enter == True:
# # self.SetHoldings(self.symbol, 0.5)
# self.qty = self.position_type * (int(float(self.capital_per_trade) / float(data["GLD"].Close)))
# orderticket = self.MarketOrder("GLD", self.qty)
# self.enter_price = float(data["GLD"].Close)
# self.sl_exit_price = self.enter_price * (1 - (self.position_type * self.per_stop_loss))
# self.target_exit_price = self.enter_price * (1 + (self.position_type * self.per_profit_target))
# self.first_target_exit_price = self.enter_price * \
# (1 + (self.position_type * self.per_first_profit_target))
# self.enter = False
# self.Debug(str(data["GLD"].Time) + ":" + "Entering at :" + str(self.enter_price) +
# " Target: " + str(self.target_exit_price) + " SL : " + str(self.sl_exit_price)
# + "First Target: " + str(self.first_target_exit_price))
#
#
#
# if (self.exit == True):
# self.Liquidate(self.symbol)
# self.exit_price = float(data["GLD"].Close)
# self.Debug(str(data["GLD"].Time) + ":" + " Exiting at :" + str(self.exit_price) +
# ": qty: " + str(self.qty))
# self.exit = False
# self.aroon_up, self.aroon_down = self.aroon.determine_aroon(self.aroon_period, bar.High, bar.Low)