使用Python 3.4从Yahoo读取库存数据,但无法删除数据

时间:2014-07-30 04:07:56

标签: python python-3.x yahoo-finance

我正在使用Python 3.4,我正试图从雅虎财务中下载数据 以下是我的代码:

import urllib.request  
url = 'http://ichart.finance.yahoo.com/table.csv?s=aapl&a=6&b=21&c=2014&d=6&e=29&f=2014'  
csv = urllib.request.urlopen(url).readlines()  
print(csv)  
ds,open_,high,low,close,volume,adjc = csv[1].strip().split('\n')

结果:

[b'Date,Open,High,Low,Close,Volume,Adj Close\n', b'2014-07-29,99.33,99.44,98.25,98.38,43031400,98.38\n', b'2014-07-28,97.82,99.24,97.55,99.02,55239000,99.02\n', b'2014-07-25,96.85,97.84,96.64,97.67,43403200,97.67\n', b'2014-07-24,97.04,97.32,96.42,97.03,45663100,97.03\n', b'2014-07-23,95.42,97.88,95.17,97.19,92844700,97.19\n', b'2014-07-22,94.68,94.89,94.12,94.72,54914800,94.72\n', b'2014-07-21,94.99,95.00,93.72,93.94,38887700,93.94\n']  

Traceback (most recent call last):  
  File "<pyshell#39>", line 1, in <module>  
    ds,open_,high,low,close,volume,adjc = csv[1].strip().split('\n')  
TypeError: Type str doesn't support the buffer API

现在我遇到的问题是当我试图拆分csv并将单独的行存储为单独的值时。 所以我想拆分并存储报价。但是我无法做到这一点,因为前面有'b'字符,最后有'\ n'。你们可以帮我拆分或建议另一种写作解决方案吗?

我非常感谢你的帮助。 谢谢

1 个答案:

答案 0 :(得分:2)

1)我发现requests库比urllib.request更容易使用。

2)如果数据是CSV格式,我建议使用csv模块而不是自己解析文件。

我将如何做到这一点:

#!/usr/bin/python3

import requests
import csv
import pprint

url='http://ichart.finance.yahoo.com/table.csv?s=aapl&a=6&b=21&c=2014&d=6&e=29&f=2014'

http_response=requests.get(url)
stock_reader=csv.reader(http_response.text.splitlines())
stock_data=list(stock_reader)
pprint.pprint(stock_data)

ds,open_,high,low,close,volume,adjc = stock_data[1]
print("The stock opened at {} on {}".format(open_,ds))
print("The average closing price was {0:.02f}".format(
    sum(float(item[4]) for item in stock_data[1:])/len(stock_data[1:])))

为方便起见,请尝试csv.DictReader

http_response=requests.get(url)
stock_reader=csv.DictReader(http_response.text.splitlines())
stock_data=list(stock_reader)

print("The stock opened at {Open} on {Date}".format(**stock_data[0]))
print("The average closing price was {0:.02f}".format(
    sum(float(item['Close']) for item in stock_data)/len(stock_data)))