从python中的yahoo finance自动下载历史股票价格

时间:2012-09-14 23:06:16

标签: pandas finance yahoo-finance google-finance stockquotes

有没有办法从雅虎财经或谷歌财经(csv格式)自动下载股票的历史价格?最好是在Python中。

6 个答案:

答案 0 :(得分:98)

当你要在Python中使用这样的时间序列时,pandas是不可或缺的。这是个好消息:它带有雅虎的历史数据下载器:pandas.io.data.DataReader

from pandas.io.data import DataReader
from datetime import datetime

ibm = DataReader('IBM',  'yahoo', datetime(2000, 1, 1), datetime(2012, 1, 1))
print(ibm['Adj Close'])

Here's an example from the pandas documentation.

pandas更新> = 0.19:

pandas.io.data模块已从pandas>=0.19开始删除。相反,您应该使用单独的pandas-datareader package。安装时:

pip install pandas-datareader

然后你可以用Python做到这一点:

import pandas_datareader as pdr
from datetime import datetime

ibm = pdr.get_data_yahoo(symbols='IBM', start=datetime(2000, 1, 1), end=datetime(2012, 1, 1))
print(ibm['Adj Close'])

Downloading from Google Finance is also supported.

There's more in the documentation of pandas-datareader.

答案 1 :(得分:37)

简短回答:是的。使用Python的urllib来提取所需股票的历史数据页。跟雅虎一起去!金融;谷歌的可靠性较低,数据覆盖率较低,而且一旦拥有谷歌,您的使用方式就会受到更多限制。此外,我相信Google特别禁止您在其ToS中删除数据。

更长的答案:这是我用来提取特定公司的所有历史数据的脚本。它会提取特定股票代码的历史数据页面,然后将其保存到该符号命名的csv文件中。您必须提供自己想要提取的股票代码列表。

import urllib

base_url = "http://ichart.finance.yahoo.com/table.csv?s="
def make_url(ticker_symbol):
    return base_url + ticker_symbol

output_path = "C:/path/to/output/directory"
def make_filename(ticker_symbol, directory="S&P"):
    return output_path + "/" + directory + "/" + ticker_symbol + ".csv"

def pull_historical_data(ticker_symbol, directory="S&P"):
    try:
        urllib.urlretrieve(make_url(ticker_symbol), make_filename(ticker_symbol, directory))
    except urllib.ContentTooShortError as e:
        outfile = open(make_filename(ticker_symbol, directory), "w")
        outfile.write(e.content)
        outfile.close()

答案 2 :(得分:13)

使用实际演示扩展@Def_Os's答案......

正如@Def_Os已经说过 - 使用Pandas Datareader使这项任务变得非常有趣

In [12]: from pandas_datareader import data

AAPL

开始提取1980-01-01的所有可用历史数据
#In [13]: aapl = data.DataReader('AAPL', 'yahoo', '1980-01-01')

# yahoo api is inconsistent for getting historical data, please use google instead.
In [13]: aapl = data.DataReader('AAPL', 'google', '1980-01-01')

前5行

In [14]: aapl.head()
Out[14]:
                 Open       High     Low   Close     Volume  Adj Close
Date
1980-12-12  28.750000  28.875000  28.750  28.750  117258400   0.431358
1980-12-15  27.375001  27.375001  27.250  27.250   43971200   0.408852
1980-12-16  25.375000  25.375000  25.250  25.250   26432000   0.378845
1980-12-17  25.875000  25.999999  25.875  25.875   21610400   0.388222
1980-12-18  26.625000  26.750000  26.625  26.625   18362400   0.399475

最后5行

In [15]: aapl.tail()
Out[15]:
                 Open       High        Low      Close    Volume  Adj Close
Date
2016-06-07  99.250000  99.870003  98.959999  99.029999  22366400  99.029999
2016-06-08  99.019997  99.559998  98.680000  98.940002  20812700  98.940002
2016-06-09  98.500000  99.989998  98.459999  99.650002  26419600  99.650002
2016-06-10  98.529999  99.349998  98.480003  98.830002  31462100  98.830002
2016-06-13  98.690002  99.120003  97.099998  97.339996  37612900  97.339996

将所有数据保存为CSV文件

In [16]: aapl.to_csv('d:/temp/aapl_data.csv')

d:/temp/aapl_data.csv - 第5行

Date,Open,High,Low,Close,Volume,Adj Close
1980-12-12,28.75,28.875,28.75,28.75,117258400,0.431358
1980-12-15,27.375001,27.375001,27.25,27.25,43971200,0.408852
1980-12-16,25.375,25.375,25.25,25.25,26432000,0.378845
1980-12-17,25.875,25.999999,25.875,25.875,21610400,0.38822199999999996
1980-12-18,26.625,26.75,26.625,26.625,18362400,0.399475
...

答案 3 :(得分:6)

Python中已经存在一个名为yahoo_finance的库,因此您需要首先使用以下命令行下载该库:

sudo pip install yahoo_finance

然后,一旦您安装了yahoo_finance库,这里有一个示例代码,可以从Yahoo Finance下载您需要的数据:

#!/usr/bin/python
import yahoo_finance
import pandas as pd

symbol = yahoo_finance.Share("GOOG")
google_data = symbol.get_historical("1999-01-01", "2016-06-30")
google_df = pd.DataFrame(google_data)

# Output data into CSV
google_df.to_csv("/home/username/google_stock_data.csv")

这应该这样做。如果有效,请告诉我。

更新: 不再支持yahoo_finance库。

答案 4 :(得分:2)

您可以签出yahoo_fin软件包。它最初是在Yahoo Finance更改其API之后创建的(文档在这里:http://theautomatic.net/yahoo_fin-documentation)。

from yahoo_fin import stock_info as si

aapl_data = si.get_data("aapl")

nflx_data = si.get_data("nflx")

aapl_data.head()

nflx_data.head()

aapl.to_csv("aapl_data.csv")

nflx_data.to_csv("nflx_data.csv")

答案 5 :(得分:0)

当您知道如何时,这是微不足道的:

Generating Entity framework SQL Scripts...
Executing command: dotnet ef migrations script --idempotent --output "<path to app>\obj\Release\netcoreapp2.2\PubTmp\EFSQLScripts\Namespace1.Data.AppContext.sql" --context Namespace1.Data.AppContext 
No DbContext named 'Namespace1.Data.AppContext' was found.

如果要绘制它:

import yfinance as yf
df = yf.download('CVS', '2015-01-01')
df.to_csv('cvs-health-corp.csv')

enter image description here