Hello,
I'm currently working on an algorithm in QuantConnect using Python, and I've run into a problem. I get a runtime error saying "sell_option() missing 1 required positional argument: 'slice'". However, upon checking my code, I've ensured that the 'slice' argument is indeed included in the function. I'm not sure why this problem is occurring. Could someone please help me understand what might be going wrong?
Here is my code for reference:
from datetime import timedelta
from AlgorithmImports import *
import pandas as pd
class OptionWritingAlgorithm(QCAlgorithm):
def Initialize(self):
self.SetStartDate(2023, 5, 21) # Set Start Date
self.SetEndDate(2023, 7, 21) # Set End Date
self.SetCash(50000) # Set Strategy Cash
self.symbol = self.AddEquity("TSLA", Resolution.Minute).Symbol
option = self.AddOption(self.symbol, Resolution.Minute)
option.SetFilter(-10, 10, timedelta(1), timedelta(7))
# Create a dataframe to store trade info
self.trade_records = pd.DataFrame(columns=['Time', 'Symbol', 'Quantity', 'EndOfTradeCost'])
self.Schedule.On(self.DateRules.WeekStart("TSLA",0),self.TimeRules.AfterMarketOpen("TSLA",0),self.sell_option)
self.Schedule.On(self.DateRules.WeekEnd("TSLA",0),self.TimeRules.BeforeMarketClose("TSLA",5),self.check_profit)
def OnData(self, slice):
pass
def sell_option(self,slice):
if not slice:
return
if self.symbol not in slice.OptionChains:
return
chain = slice.OptionChains[self.symbol]
if not self.Portfolio.Invested:
self.Debug(f"week begin {self.Time}")
# Find contracts that are closest to delta 0.2
contracts = sorted(chain, key=lambda x: abs(x.Greeks.Delta - 0.2))[:5]
if len(contracts) > 0:
contract = contracts[0]
quantity = self.CalculateOrderQuantity(contract.Symbol, -0.5) # Selling options
self.Sell(contract.Symbol, int(quantity / 2)) # Sell half of the maximum order quantity
# Record trade info
self.trade_records = self.trade_records.append({
'Time': self.Time,
'Symbol': contract.Symbol,
'Quantity': int(quantity / 2),
'EndOfTradeCost': 0 # Placeholder, actual value will be filled at the end of week
}, ignore_index=True)
def check_profit(self,slice):
if not slice:
return
for i, row in self.trade_records.iterrows():
contract = self.Securities[row['Symbol']]
if contract.IsIntrinsic():
self.Liquidate(contract.Symbol)
row['EndOfTradeCost'] = self.Portfolio[row['Symbol']].LastTradeProfit
else:
row['EndOfTradeCost'] = contract.HoldingsCost
self.Debug(f"end of week {self.Time} ")
def OnEndOfAlgorithm(self):
# Print trade records at the end of algorithm
self.Debug(self.trade_records)
Thank you in advance for your help!
Axel
Hi !
Did you managed to solve it ? I have the same issue and have no idea why :(
Ashutosh
HelloThe issue here is that scheduled events do not automatically provide the “slice” parameter.You can resolve this issue in two ways of implementation:
1)
2)
QCAlgorithm class automatically provides a CurrentSlice property which can be used to access slice objects inside methods.
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.
CHUN CHE LIN
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!