Quantopian's community platform is shutting down. Please read this post for more information and download your code.
Back to Community
UnboundLocalError: local variable 'CFTA' referenced before assignment

I am new to coding and can't figure out why I am getting this build error. I am writing an algorithm that first filters out low liquidity and penny stocks to get my starting universe. Then I sort by market cap and take the first 3000 stocks. Next, I am trying to sort the remaining 3000 stocks by a custom factor: cash flow to total assets to get down to the 1000 with the highest cash flow to total assets. I will then sort by other factors. However, I cannot seem to make the cash flow to total assets sort work. I keep getting the error message:

UnboundLocalError: local variable 'CFTA' referenced before assignment. It is referring to this line of code:

CFTA = CFTA()  
pipe.add(CFTA, 'CFTA')

I copy & pasted the code section to a notebook, because it doesn't format properly when I paste it as text.

I'm sure its a pretty simple fix, I just can't figure it out. Thanks in advance.

2 responses

Hi Kirk

I noticed you haven't received any response to this.

In case you're still in need of any answer, I think it's before the names are the same. If you change the class name to CFTA_class and the call to CFTA = CFTA_class() I think it will work.

Cheers

Hamish

The Unboundlocalerror: local variable referenced before assignment is raised when you try to use a variable before it has been assigned in the local context. Python doesn't have variable declarations , so it has to figure out the scope of variables itself. It does so by a simple rule: If there is an assignment to a variable inside a function, that variable is considered local . To solve this problem, you can explicitly say it's a global by putting global declaration in your function. The global statement does not have to be at the beginning of the function definition, but that is where it is usually placed. Wherever it is placed, the global declaration makes a variable to global variable everywhere in the function.