我有以下代码可以正常工作:
for index, row in dfcodes.iterrows():
# for each security code identify those with 3 down candles and narrowing raneg for first 3 days of 6 day set
scode=row['Security_Code']
tdate='2016-01-15'
df=fetch_last(scode,tdate,6)
dfreverse=df.sort('TradeDate', ascending=True)
#look for 3 consecutive down candles with narrowing range and then 2 up candles
dfdownbars=dfreverse.head(5)
ncnt=1
for index,row in dfdownbars.iterrows():
otmp = row['Opening_Price']
ctmp = row['Closing_Price']
rtmp = abs(row['Opening_Price'] - row['Closing_Price'])
dtmp = row['TradeDate']
if ctmp<otmp and ncnt==1:
o1 = otmp
c1 = ctmp
r1 = rtmp
d1 = dtmp
ncnt+=1
elif ctmp<otmp and otmp<o1 and ctmp<c1 and rtmp<=r1 and ncnt==2:
o2 = otmp
c2 = ctmp
r2 = rtmp
d2 = dtmp
ncnt += 1
elif ctmp<otmp and otmp<o2 and rtmp<=r2 and ncnt==3:
o3 = otmp
c3 = ctmp
r3 = rtmp
d3 = dtmp
ncnt += 1
else:
break
但是,一旦添加第4个elif,就会出现以下错误:
elif ctmp>;otmp和ctmp>;c3和ncnt==4: 名称错误:未定义名称“c3”
也就是说,错误代码现在看起来像这样:
^{pr2}$有人能告诉我为什么在我添加最后一个'elif'之前,所有的c1-c3变量都被识别了,为什么在最后的'elif'语句中没有识别变量'c3'? 顺便说一下,我正在迭代pandas数据帧
非常感谢您的帮助
格伦
TL;DR:如果您先检查ncnt,您可能会工作:
为了得到一个更长远的答案,你必须首先承认你在做一些有点棘手和不寻常的事情。您在else子句中定义名称,并相信您的程序将运行这些cluse来定义名称,然后再在代码中检查这些名称。在
也就是说,在for循环的第一次迭代中,您点击以下行:
^{pr2}$因为运行代码来定义新变量}。如果在第一次迭代中条件为false,则下一步将单击以下行:
o1
、c1
、和{Python将开始查找变量,尝试获取
o1
的值,并立即给出NameError: name 'o1' is not defined
异常。在有两种实物期权:
在使用之前定义所有名称,可能将它们设置为0。这是首选的方法,可以避免让负责维护代码的人跟踪你。
首先仔细检查你的状态。此代码是一个小状态机,当前状态由ncnt记录。如果您的代码首先检查它是否处于正确的状态,则永远不会引用错误的变量。所以更好的代码应该重命名ncount并用
if nState == 3 and o3 > something...
开始if语句。一旦 nState错误,if语句将停止而不查看尚不存在的变量。继续编码。在
相关问题 更多 >
编程相关推荐