Hello everyone,
I am fairly new to QC so I hope that this question isn't too obvious! I will put my code at the bottom but I am having a problem with my algorithm. I am getting no errors or exceptions, however when it runs it doesn't place any trades. I have the same code running on PyCharm and it works just fine. I am thinking it is something wrong I am doing with the QC API. Essentially, the self.history['Position'] is the buy signal but it doesn't place any trades when it should. Thank you for the help!!
from datetime import date
import numpy as np
import datetime
import pandas
class SimpleBreakoutExample(QCAlgorithm):
def Initialize(self):
self.SetCash(100000)
self.SetStartDate(2021,10,1)
self.SetEndDate(date.today())
ticker = "MSFT"
self.ticker = str(ticker)
equity = self.AddEquity(ticker, Resolution.Minute)
self.symbol = self.AddEquity(ticker, Resolution.Minute).Symbol
equity.SetDataNormalizationMode(DataNormalizationMode.Raw)
self.equity = equity.Symbol
self.SetBenchmark(self.equity)
option = self.AddOption(ticker, Resolution.Minute)
option.SetFilter(-1,1,timedelta(5),timedelta(11))
self.Schedule.On(self.DateRules.EveryDay(self.symbol), \
self.TimeRules.AfterMarketOpen(self.symbol, 20), \
Action(self.EveryMarketOpen))
# def OnData(self, data):
# option_invested = [x.Key for x in self.Portfolio if x.Value.Invested and x.Value.Type==SecurityType.Option]
def EveryMarketOpen(self):
ticker = str(self.ticker)
start = datetime.datetime(2021, 2, 1)
option_invested = [x.Key for x in self.Portfolio if x.Value.Invested and x.Value.Type==SecurityType.Option]
end = date.today()
qb = QuantBook()
spy = qb.AddEquity(ticker)
self.history = qb.History(spy.Symbol, start, end, Resolution.Daily)
self.history['Close'] = self.history['close']
self.history['20_SMA'] = self.history['Close'].rolling(window=5, min_periods=1).mean()
self.history['50_SMA'] = self.history['Close'].rolling(window=12, min_periods=1).mean()
self.history['Signal'] = 0.0
self.history['Signal'] = np.where(self.history['20_SMA'] > self.history['50_SMA'], 1.0, 0.0)
self.history['Position'] = self.history['Signal'].diff()
self.history['Buy Signal'] = self.history['Position'] == 1
self.Signal = int(self.history.tail(1)['Position'])
if option_invested:
if self.Time + timedelta(2) > option_invested[0].ID.Date:
self.Liquidate(option_invested[0], "Too close to expiration")
return
if self.Signal == 1:
for i in data.OptionChains:
chains = i.Value
self.BuyCall(chains)
def BuyCall(self,chains):
expiry = sorted(chains,key = lambda x: x.Expiry, reverse=True)[0].Expiry
calls = [i for i in chains if i.Expiry == expiry and i.Right == OptionRight.Call]
call_contracts = sorted(calls,key = lambda x: abs(x.Strike - x.UnderlyingLastPrice))
if len(call_contracts) == 0:
return
self.call = call_contracts[0]
quantity = self.Portfolio.TotalPortfolioValue / self.call.AskPrice
quantity = int( 0.05 * quantity / 100 )
self.Buy(self.call.Symbol, quantity)
def OnOrderEvent(self, orderEvent):
order = self.Transactions.GetOrderById(orderEvent.OrderId)
if order.Type == OrderType.OptionExercise:
self.Liquidate()
Fred Painchaud
Hey Cameron,
Just adding a line to your algo to get some logs. Your signal is always -1. Why? I don't know yet but maybe it rings a bell to you much faster than it would for me…
Of course, as you know, if your signal is never “1”, your algo does not buy.
Fred
Fred Painchaud
Hi again,
Looks like .diff() always returns 0.0 - 1.0 = -1.0.
Position is always 0.0 except at the end it is -1.0.
Fred
Cameron Dunn
The material on this website is provided for informational purposes only and does not constitute an offer to sell, a solicitation to buy, or a recommendation or endorsement for any security or strategy, nor does it constitute an offer to provide investment advisory services by QuantConnect. In addition, the material offers no opinion with respect to the suitability of any security or specific investment. QuantConnect makes no guarantees as to the accuracy or completeness of the views expressed in the website. The views are subject to change, and may have become unreliable for various reasons, including changes in market conditions or economic circumstances. All investments involve risk, including loss of principal. You should consult with an investment professional before making any investment decisions.
To unlock posting to the community forums please complete at least 30% of Boot Camp.
You can continue your Boot Camp training progress from the terminal. We hope to see you in the community soon!