【发布时间】:2016-05-30 06:43:10
【问题描述】:
我创建了一个程序,它获取股票代码,爬取网络以查找每个代码的历史价格的 CSV,并使用 matplotlib 绘制它们。几乎一切正常,但我在解析 CSV 以分离出每个价格时遇到了问题。
我得到的错误是:
prices = [float(row[4]) for row in csv_rows]
IndexError: 列表索引超出范围
我知道问题出在哪里,我只是不确定我应该如何解决它。
(问题出在parseCSV() 方法中)
# Loop to chart multiple stocks
def chartStocks(*tickers):
for ticker in tickers:
chartStock(ticker)
# Single chart stock method
def chartStock(ticker):
url = "http://finance.yahoo.com/q/hp?s=" + str(ticker) + "+Historical+Prices"
sourceCode = requests.get(url)
plainText = sourceCode.text
soup = BeautifulSoup(plainText, "html.parser")
csv = findCSV(soup)
parseCSV(csv)
# Find the CSV URL
def findCSV(soupPage):
CSV_URL_PREFIX = 'http://real-chart.finance.yahoo.com/table.csv?s='
links = soupPage.findAll('a')
for link in links:
href = link.get('href', '')
if href.startswith(CSV_URL_PREFIX):
return href
# Parse CSV for daily prices
def parseCSV(csv_text):
csv_rows = csv.reader(csv_text.split('\n'))
prices = [float(row[4]) for row in csv_rows]
days = list(range(len(prices)))
point = collections.namedtuple('Point', ['x', 'y'])
for price in prices:
i = 0
p = point(days[i], prices[i])
points = []
points.append(p)
print(points)
plotStock(points)
# Plot the data
def plotStock(points):
plt.plot(points)
plt.show()
【问题讨论】:
-
一旦您使用@mhawke 的答案实际下载 csv 数据并使用@Alexander 的方法来处理少于 5 个项目的行,那么您还需要将
points = []移出for在parseCSV()结尾附近循环。 -
您询问的问题(在处理 CSV 数据时处理 IndexError)似乎与 this earlier question 重复(或者可能是 this one 或 this one) .当然,正如其他几个人已经指出的那样,您认为的问题实际上是代码中最少的问题。
-
我相信这个帖子是under discussion on meta。