Back

"Self is not defined" Error

I am trying to add a rolling window of data to connect my custom indicator to but I keep receiving the following error on the first line of my own code and cannot figure out where I've gone wrong initializing self.

Algorithm.Initialize() Error: During the algorithm initialization, the following exception has occurred: Loader.TryCreatePythonAlgorithm(): Unable to import python module ./cache/algorithm/main.pyc. AlgorithmPythonWrapper(): NameError : name 'self' is not defined
at in main.py:line 54
:: low = self.quoteBarWindow(\'Low\')
NameError : name 'self' is not defined Stack Trace: QuantConnect.Lean.Engine.Setup.AlgorithmSetupException: During the algorithm initialization, the following exception has occurred: Loader.TryCreatePythonAlgorithm(): Unable to import python module ./cache/algorithm/main.pyc. AlgorithmPythonWrapper(): NameError : name 'self' is not defined
at in main.py:line 54
:: low = self.quoteBarWindow(\'Low\')
NameError : name 'self' is not defined
at QuantConnect.Lean.Engine.Setup.BacktestingSetupHandler.CreateAlgorithmInstance (QuantConnect.Packets.AlgorithmNodePacket algorithmNodePacket, System.String assemblyPath) [0x0009c] in :0
at QuantConnect.Lean.Engine.Engine.Run (QuantConnect.Packets.AlgorithmNodePacket job, QuantConnect.Lean.Engine.AlgorithmManager manager, System.String assemblyPath, QuantConnect.Util.WorkerThread workerThread) [0x000f8] in :0 

Here is my code up to that point:

from Execution.ImmediateExecutionModel import ImmediateExecutionModel
from statistics import stdev, mean
import matplotlib
# ___library_import_statements___
import pandas as pd
# for pandas_datareader, otherwise it might have issues, sometimes there is some version mismatch
pd.core.common.is_list_like = pd.api.types.is_list_like
import numpy as np
import matplotlib.pyplot as plt
import datetime
import time
from clr import AddReference
AddReference("System")
AddReference("QuantConnect.Common")
AddReference("QuantConnect.Jupyter")
AddReference("QuantConnect.Indicators")
from System import *
from QuantConnect import *
from QuantConnect.Data.Custom import *
from QuantConnect.Data.Market import TradeBar, QuoteBar
from QuantConnect.Jupyter import *
from QuantConnect.Indicators import *
from datetime import datetime, timedelta
import matplotlib.pyplot as plt
import pandas as pd
matplotlib


class RollingWindowAlgorithm(QCAlgorithm):

def Initialize(self):


self.SetStartDate(2000, 10, 1) # Set Start Date
self.SetCash(100000) # Set Strategy Cash
self.AddEquity("CENX", Resolution.Daily)
self.SetExecution(ImmediateExecutionModel())
self.quoteBarWindow = RollingWindow[QuoteBar](270)


def OnData(self, data):
'''OnData event is the primary entry point for your algorithm. Each new data point will be pumped in here.'''

# Add SPY TradeBar in rollling window
self.window.Add(data["SPY"])

# Wait for windows to be ready.
if not (self.window.IsReady and self.smaWin.IsReady): return

currBar = self.window[0] # Current bar had index zero.
pastBar = self.window[1] # Past bar has index one.
self.Log("Price: {0} -> {1} ... {2} -> {3}".format(pastBar.Time, pastBar.Close, currBar.Time, currBar.Close))

low = self.quoteBarWindow('Low')
# use numerical integer index instead of date
df = self.quoteBarWindow('Time')

Any ideas? Thanks!

Update Backtest







0

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.


The reason I was getting this error was because of the indentation of my code below self initializition. If the code in not indented equally or more than a self rule than it will act like the self rule does not exist. I guess this platform reads python as a converted version of c#? Hopefully this helps someone learning this platform that comes across the same issue!

Note: The code snippets don't show indentation so I hope my explaination of how I corrected it will suffice.

2

Update Backtest





0

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.


Loading...

This discussion is closed