簡體   English   中英

如何使用 Python 下載股票價格數據?

[英]How can I download stock price data with Python?

我已經安裝了pandas-datareader但我想知道是否有替代方案。

到目前為止,我正在使用這個:

import pandas_datareader.data as web
start_date = '2018-01-01'
end_date = '2018-06-08'
panel_data = web.DataReader('SPY', 'yahoo', start_date, end_date)

雅虎財經是獲取股票數據的免費來源之一。 您可以使用 pandas datareader 或使用 yfinance 庫獲取數據。 從 yfinance 庫中獲取數據的方法如下所示。

import yfinance as yf
# Get the data of the stock AAPL
data = yf.download('AAPL','2016-01-01','2019-08-01')

Wiki 是quandl上可用的免費資源之一,可獲取 3000 多種美國股票的數據。 這是一個社區維護的數據。 最近它停止維護,但是,它是一個很好的免費資源來回測您的策略。 要獲取數據,您需要從 quandl 獲取免費的 API 密鑰,並將以下代碼中的 替換為您的 API 密鑰。

# Import the quandl package
import quandl
# Get the data from quandl
data = quandl.get("WIKI/KO", start_date="2016-01-01", end_date="2018-01-01", 
    api_key=<Your_API_Key>)

注意:Quandl 需要 NumPy(v1.8 或更高版本)和 pandas(v0.14 或更高版本)才能工作。 要獲取您的 API 密鑰,請注冊一個免費的 Quandl 帳戶。 然后,您可以在 Quandl 帳戶設置頁面上找到您的 API 密鑰。

見下文。 代碼是用 Python 2.7 編寫的,但在替換打印函數時應該可以在 3.5 中運行。 確保在編輯器中復制間距時正確:制表符為 4 個空格等。

# pip install datareader
import pandas as pd
pd.core.common.is_list_like = pd.api.types.is_list_like
import pandas_datareader.data as web
import matplotlib.pyplot as plt
import numpy as np

from datetime import datetime, timedelta

#stock of interest
stock=['MSFT','SAP','V','JPM']

# period of analysis
end = datetime.now()
start = end - timedelta(days=500)

for i in range(len(stock)):
    f = web.DataReader(stock[i], 'morningstar', start, end)

    # nice looking timeseries (DataFrame to panda Series)
    f = f.reset_index()
    f = pd.Series(f.Close.values,f.Date)

    print "Start: Year, Month, Day, Time"
    print str(start)
    f.plot(label=stock[i]);
    plt.legend()
    plt.ylabel('price in [USD]')

plt.show();

您也可以使用 quandl,但您必須注冊並獲取您自己的 API 密鑰。 不確定是否有任何與 Pandas 網絡閱讀器配合良好的免費金融 API 仍然可靠且良好地運行......

# pip install datareader
import pandas as pd
pd.core.common.is_list_like = pd.api.types.is_list_like
# quandl api explore
import quandl
from datetime import datetime, timedelta
import matplotlib.pyplot as plt
# api instructions
quandl.ApiConfig.api_key = "YOUR_API_KEY"
end = datetime.now()
start = end - timedelta(days=365)
# frankfurt stock exchange
mydata2 = quandl.get('FSE/VOW3_X', start_date = start, end_date = end)
f = mydata2.reset_index()
# timeseries
plt.figure(1)
f = pd.Series(f.Close.values,f.Date)
f.plot()
plt.show()

我發現最簡單的是新的SimFin Python API ,它允許您下載股票價格和基本數據,將其保存到磁盤,然后只需幾行代碼即可將其加載到 Pandas DataFrames 中。 他們還制作了幾個關於如何將他們的數據與其他庫(例如 statsmodels、scikit-learn、TensorFlow 等)一起使用的教程。 下面的基本示例是從他們的 github 頁面復制的。

您可以通過在終端窗口中鍵入以下命令來安裝 SimFin python 包(最好在其自己的環境中,請參閱他們的完整說明):

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

我們還可以加載每日股價並繪制 Microsoft(股票代碼 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')

這會產生以下圖像:

MSFT 股價收盤

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM