web-dev-qa-db-ja.com

Pythonで株価データをダウンロードするにはどうすればよいですか?

Pandas-daatreaderをインストールしましたが、過去の株価データをダウンロードするためのGoogleとYahooの両方のAPIは廃止されました。

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)

ImmediateDeprecationError: 
Yahoo Daily has been immediately deprecated due to large breaks in the API without the
introduction of a stable replacement. Pull Requests to re-enable these data
connectors are welcome.

See https://github.com/pydata/pandas-datareader/issues

Pythonを使用して過去の株価にアクセスする方法を教えてください。実際、私は研究をしている限り、できるだけ価格を取り戻すことに興味があります。

ありがとうございました。

8
user8270077

Yahoo Financeは、株式データを取得する無料のソースの1つです。 pandas datareaderを使用してデータを取得するか、yfinanceライブラリを使用して取得できます。yfinanceライブラリからデータを取得する方法を以下に示します。

# Import the yfinance. If you get module not found error the run !pip install yfiannce from your Jupyter notebook
import yfinance as yf
# Get the data of the stock AAPL
data = yf.download('AAPL','2016-01-01','2019-08-01')
# Import the plotting library
import matplotlib.pyplot as plt
%matplotlib inline
# Plot the close price of the AAPL
data['Adj Close'].plot()
plt.show()

Quandl Wikiはquandlで利用可能な無料のソースの1つで、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>)
# Plot the close pr
import matplotlib.pyplot as plt
data.Close.plot()
# Show the plot
plt.show()

注:Quandlを使用するには、NumPy(v1.8以上)およびpandas(v0.14以上)が必要です。APIキーを取得するには、無料のQuandlアカウントにサインアップしてください。 Quandlアカウント設定ページでAPIキーを見つけることができます。

複数の株式のデータを取得する

# Define the ticker list
import pandas as pd
tickers_list = [‘AAPL’, ‘WMT’, ‘IBM’, ‘MU’, ‘BA’, ‘AXP’]
# Import pandas
data = pd.DataFrame(columns=tickers_list)
# Fetch the data
import yfinance as yf
for ticker in tickers_list:
 data[ticker] = yf.download(ticker, ‘2015–1–1’, ‘2019–1–1’)[‘Adj Close’]
# Print first 5 rows of the data
data.head()

# Plot all the close prices
((data.pct_change()+1).cumprod()).plot(figsize=(10, 7))
# Show the legend
plt.legend()
# Define the label for the title of the figure
plt.title(“Adjusted Close Price”, fontsize=16)
# Define the labels for x-axis and y-axis
plt.ylabel(‘Price’, fontsize=14)
plt.xlabel(‘Year’, fontsize=14)
# Plot the grid lines
plt.grid(which=”major”, color=’k’, linestyle=’-.’, linewidth=0.5)
plt.show()

ちょっとしたレベルや基本的なデータを見ている場合は、 this ページが役立ちます。

4
Ishan Shah

下記参照。コードは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();
2
Maik Holzhey

Quandlも使用できますが、サインアップして独自のAPIキーを取得する必要があります。 pandas webreaderで確実に機能する無料の金融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()
1
Maik Holzhey