import numpy as np
import pandas as pd
class MyAlgo(QCAlgorithm):
def Initialize(self):
self.SetCash(1000000)
# Start and end dates for the backtest.
self.SetStartDate(2017,7,1)
self.SetEndDate(2017,9,1)
self.AddEquity("SPY")
self.AddEquity("AAPL")
self.AddEquity("AMZN")
self.AddEquity("UPS")
self.AddEquity("PXD")
self.AddEquity("MA")
In my backtest, I see a red 'x' mark on the line 5 and I got two error messages:
25 | 14:49:35:
Build Error: File: main.py Line:5 Column:0 - File "../cache/main.py", line 89, in MyAlgo
26 | 14:49:35:
Build Error: File: n/a Line:0 Column:0 - NameError: name 'd' is not defined
1). There's no line 89. I have only line 67 in MyAlgo.
2). There's no name 'd'.
Can anyone tell me what is going on here? Thanks :)
HanByul P
I just put the entire code:
import numpy as np import pandas as pd class MyAlgo(QCAlgorithm): def Initialize(self): self.SetCash(1000000) # Start and end dates for the backtest. self.SetStartDate(2017,7,1) self.SetEndDate(2017,9,1) self.AddEquity("SPY") self.AddEquity("AAPL") self.AddEquity("AMZN") self.AddEquity("UPS") self.AddEquity("PXD") self.AddEquity("MA") self.security_list = ["AAPL", "AMZN", "UPS", "PXD", "MA"] # Schedule function: self.Schedule.On(self.DateRules.EveryDay("AAPL"), self.TimeRules.AfterMarketOpen("AAPL", 60), Action(self.rebalance)) def OnData(self, data): pass def rebalance(self): # History (Daily) history = self.History(self.security_list, 5, Resolution.Daily) price_history = history['close'].unstack(level=0) aapl_price = self.Securities["AAPL"].Price amzn_price = self.Securities["AMZN"].Price ups_price = self.Securities["UPS"].Price pxd_price = self.Securities["PXD"].Price ma_price = self.Securities["MA"].Price # Make a dataframe for current prices d = {'AAPL': [aapl_price],'AMZN': [amzn_price],'UPS': [ups_price],'PXD': [pxd_price],'MA': [ma_price]} df = pd.DataFrame(d) # Concat current prices df to history data final_history = pd.concat([price_history, df])
1). I still can't see line 89.
2). I see 'd' in line 47. This worked a few minutes ago and now this seems to be a problem.
Can anyone help me on this? Thanks :)
LukeI
The lines aren't accurate, don't read into them. I think it's because they are treating the code like C# in a python wrapper. The debugger is looking at the C# code that your python code generates, not your code itself.
One thing to keep in mind, whitespace REALLY counts on QC, a missing tab or some spaces instead of tabs can cause your code to be processed incorrectly. If your copy/paste is to be belived, you have two tabs on line 47 and 8x spaces on line 49. So the code might not process line 47 before line 49 and now you have a mysterious error that looks impossible.
Coming from Quantopian I had to copy my code into Notepad++ and enable "view whitespace characters" this allowed me to see the tabs and spaces and convert all spaces to tabs and make sure that there were no blank lines without the proper number of tabs.
example:
class MyAlgo(QCAlgorithm): <--You need a tab here in this blank line def Initialize(self): <--You need two tabs in this blank line self.SetCash(1000000) <--You need two tabs in this blank line if true: <--You need three tabs in this blank line #do something pass
Jared Broad
Hey HanByul P, LukeI -- We just fixed the Python error line issue. If you have an example of the lines not matching again please let us know..
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.
HanByul P
@Lukel, Thanks a lot ! I edited my code in the 'Notepad', copied, and pasted it in the 'main.py'. It works perfectly fine now.
@Jared, I will test this with other algo. Thanks a lot. :)
Karen Chaltikian
FWIW, I am having the exact same problem, on a class that is just a few lines, that I was able to run just a minute ago. I tried deleting everything and then copying it back from notepad, but to no avail. This is so frustrating....
Code follows:
import clr
clr.AddReference("System")
clr.AddReference("QuantConnect.Algorithm")
clr.AddReference("QuantConnect.Indicators")
clr.AddReference("QuantConnect.Common")
from System import *
from QuantConnect import *
from QuantConnect.Algorithm import *
from QuantConnect.Indicators import *
import numpy as np
from datetime import timedelta
from sklearn.linear_model import LinearRegression
class OptionsTest(QCAlgorithm):
def Initialize(self):
# Set the cash we'd like to use for our backtest
# This is ignored in live trading
self.SetCash(100000)
# Start and end dates for the backtest.
# These are ignored in live trading.
self.SetStartDate(2014,6,30)
self.SetEndDate(2014,7,1)
# Add assets you'd like to see
self.AddEquity("SPY", Resolution.Daily)
self.AddEquity("XIV", Resolution.Daily)
option = self.AddOption("SPY", Resolution.Daily)
option.SetFilter(-2, 2, timedelta(0), timedelta(182))
self.o_symbol=option.Symbol
## we sort the contracts to find at the money (ATM) contract with farthest expiration
def OnData(self, slice):
d1=self.History('SPY',21,Resolution.Daily)
d2=self.History('XIV',21,Resolution.Daily)
index=[]
for slice1,slice2 in zip(d1,d2):
index.append(slice1.Time.date())
data.append([np.float(slice1.Close),np.float(slice2.Close)])
df=pd.DataFrame(data,columns=['SPY','XIV'],index=pd.Series(index))
rr=df.diff().fillna(0)
lr=LinearRegression()
X=np.column_stack((rr['SPY'].values,rr['SPY'].values**2))
y=rr['XIV'].values
lr.fit(X,y)
resid=y-lr.predict(X)
resid=resid/resid.std()
for kvp in slice.OptionChains:
if kvp.Key != self.o_symbol:continue
chain = kvp.Value
contracts = sorted(sorted(chain,key = lambda x: abs(chain.Underlying.Price - x.Strike)),
key = lambda x: x.Expiry, reverse=True)
if len(contracts) == 0: continue
symbol = contracts[0].Symbol
if resid[-1]>1:
self.MarketOnCloseOrder(symbol, -1)
if resid[-1]<-1:
self.MarketOnCloseOrder(symbol, 1)
Jared Broad
Copying and pasting your code Karen Chaltikian -
Runtime Error: Python.Runtime.PythonException: NameError : global name 'data' is not defined at Python.Runtime.PyObject.Invoke (Python.Runtime.PyTuple args, Python.Runtime.PyDict kw) [0x00033] in <387056c9810b431d9b668f2df5d6c027>:0 at Python.Runtime.PyObject.InvokeMethod (System.String name, Python.Runtime.PyTuple args, Python.Runtime.PyDict kw) [0x00007] in <387056c9810b431d9b668f2df5d6c027>:0 at Python.Runtime.PyObject.TryInvokeMember (System.Dynamic.InvokeMemberBinder binder, System.Object[] args, System.Object& result) [0x0003e] in <387056c9810b431d9b668f2df5d6c027>:0 at (wrapper dynamic-method) System.Object:CallSite.Target (System.Runtime.CompilerServices.Closure,System.Runtime.CompilerServices.CallSite,object,QuantConnect.Data.Slice) at System.Dynamic.UpdateDelegates.UpdateAndExecuteVoid2[T0,T1] (System.Runtime.CompilerServices.CallSite site, T0 arg0, T1 arg1) [0x00128] in <63992662b765477a898ef49cdcc99ee2>:0 at QuantConnect.AlgorithmFactory.Python.Wrappers.AlgorithmPythonWrapper.OnData (QuantConnect.Data.Slice slice) [0x000c6] in <85518f2c19a04334b0375b8decda42fe>:0 at QuantConnect.Lean.Engine.AlgorithmManager.Run (QuantConnect.Packets.AlgorithmNodePacket job, QuantConnect.Interfaces.IAlgorithm algorithm, QuantConnect.Lean.Engine.DataFeeds.IDataFeed feed, QuantConnect.Lean.Engine.TransactionHandlers.ITransactionHandler transactions, QuantConnect.Lean.Engine.Results.IResultHandler results, QuantConnect.Lean.Engine.RealTime.IRealTimeHandler realtime, QuantConnect.Lean.Engine.Server.ILeanManager leanManager, System.Threading.CancellationToken token) [0x012d0] in <384b9ec8562547f68e89747b4b11550e>:0 (Open Stacktrace)
The second bottom line on the stack trace is OnData -- this means the error is in OnData. Looking down the code there's no definition of "data":
data.append([np.float(slice1.Close),np.float(slice2.Close)])
Perhaps by putting it into the forum post it converted it all to spaces & made it so I could just copy-paste?
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.
Karen Chaltikian
Thanks very much, Jared. This is gotta be the most creative use of forum :) It really works - I just keep a forum post window open, and any time I get any of these "Unexpected indent" or "line 0:column 0" errors, I just CtrlX into that window and back, and they're all gone.
Jared Broad
lol! We'll look into what its doing. Maybe we just save the files in the backend without tabs (convert everything to spaces client side).
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.
Jared Broad
Gustavo came up with a beautiful solution for this =) We'll merge it tomorrow...
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.
Jared Broad
We pushed a potential solution to this last night -- we actively convert all hard tabs to soft ones with spaces; and when we detect there's an indentation error we automatically turn on special symbols so you can see where the indentation lines up. Let us know if it solves it for you.
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.
HanByul P
@Jared, Thanks. You finally fixed. At QC, now we don't have to write Python codes in 'Notepad', and then copy & paste it to the main.py. We just write our algos in the main.py as we normaly do with Python. Thanks :)
HanByul P
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!