繁体   English   中英

试图了解如何在我的代码中使用异常处理

[英]Trying to understand how to use Exception Handling with my code

我正在从Yahoo读取与CSV文件中提供给我的“股票代码”(股票代码)相关的股票数据。 但是,某些股票代码实际上在Yahoo上不可用,因此我想知道是否有一种方法可以在下面的代码中通过异常处理解决这一问题。

import pandas
import pandas.io.data as web
import datetime
import csv

f1=open('C:\Users\Username\Documents\Programming\Financialdata.csv') #Enter the location of the file
c1= csv.reader(f1)
tickers =[]
for row in c1:          #reading tickers from the csv file
    tickers.append(row)
    start=datetime.datetime(2012,1,1)
    end=datetime.datetime(2013,1,1)
    l=[]; m=[]; tickernew=[]
    i=0;j=0; k=0; z=[]
    for tick in tickers[0]:
        f=web.DataReader(tick,'yahoo', start,end)
        if len(f)==250:         #checking if the stock was traded for 250 days
            tickernew.append(tick)      #new ticker list to keep track of the new index number of tickers 
            k = k + 1               #k keeps track of the number of new tickers
            for i in range(0,len(f)-1):
                m.append(f['Adj Close'][i+1]/f['Adj Close'][i])    #calculating returns

绝对。 第一步应该是查看由于提到的无效输入而使程序崩溃时获得的回溯。

然后,只需使用try / except来包装要崩溃的代码行。 良好的Python风格鼓励您具体说明要处理的异常类型。 因此,例如,如果崩溃引发“ ValueException”,则需要执行以下操作:

try:
  bad_line_of_code
except ValueException:
  handle_the_issue

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM