我发现最简单的方法是新的SimFin Python API,它可以让您下载股票价格和基本数据,将其保存到磁盘,然后只需几行代码就可以将其加载到 Pandas DataFrames 中。他们还提出了几个tutorials 说明如何将他们的数据与其他库(如 statsmodels、scikit-learn、TensorFlow 等)一起使用。下面的基本示例是从他们的 github 页面复制而来的。
您可以通过在终端窗口中键入此命令来安装 SimFin python 包(最好在其自己的环境中,请参阅他们的full instructions):
pip install simfin
然后将以下内容复制粘贴到 Jupyter Notebook 或 Python 源文件中:
import simfin as sf
from simfin.names import *
# Set your API-key for downloading data.
# If the API-key is 'free' then you will get the free data,
# otherwise you will get the data you have paid for.
# See www.simfin.com for what data is free and how to buy more.
sf.set_api_key('free')
# Set the local directory where data-files are stored.
# The dir will be created if it does not already exist.
sf.set_data_dir('~/simfin_data/')
# Load the annual Income Statements for all companies in USA.
# The data is automatically downloaded if you don't have it already.
df = sf.load_income(variant='annual', market='us')
# Print all Revenue and Net Income for Microsoft (ticker MSFT).
print(df.loc['MSFT', [REVENUE, NET_INCOME]])
这会产生以下输出:
Revenue Net Income
Report Date
2008-06-30 6.042000e+10 17681000000
2009-06-30 5.843700e+10 14569000000
2010-06-30 6.248400e+10 18760000000
2011-06-30 6.994300e+10 23150000000
2012-06-30 7.372300e+10 16978000000
2013-06-30 7.784900e+10 21863000000
2014-06-30 8.683300e+10 22074000000
2015-06-30 9.358000e+10 12193000000
2016-06-30 9.115400e+10 20539000000
2017-06-30 9.657100e+10 25489000000
2018-06-30 1.103600e+11 16571000000
2019-06-30 1.258430e+11 39240000000
我们还可以加载每日股价并绘制微软的收盘价(股票代码 MSFT):
# Load daily share-prices for all companies in USA.
# The data is automatically downloaded if you don't have it already.
df_prices = sf.load_shareprices(market='us', variant='daily')
# Plot the closing share-prices for ticker MSFT.
df_prices.loc['MSFT', CLOSE].plot(grid=True, figsize=(20,10), title='MSFT Close')
这会产生以下图像: