How can I download stock price data with Python?

半腔热情 提交于 2020-01-01 04:59:25

问题


I have installed pandas-daatreader but both the Google and Yahoo APIs for downloading historical stock price data have been deprecated.

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

Could you advise me how I can access historical stock prices using Python? In fact I would be interested on getting prices for as back as possible as I am doing research.

Thank you.


回答1:


Yahoo Finance is one of the free sources to get stock data. You can get the data either using pandas datareader or can get using yfinance library. The method to get data from yfinance library is shown below.

# 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 is one of the free source available on quandl to get the data for the 3000+ US equities. This is a community maintained data. Recently it is stopped being maintained but however, it is a good free source to backtest your strategies. To get the data, you need to get the free API key from quandl and replace the in the below code with your API key.

# 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()

Note: Quandl requires NumPy (v1.8 or above) and pandas (v0.14 or above) to work. To get your API key, sign up for a free Quandl account. Then, you can find your API key on Quandl account settings page.

Get data for multiple stocks

# 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()

If you are looking at a minute level or fundamental data then this page can be helpful.




回答2:


See below. Code is written in Python 2.7, but should work in 3.5 when you replace the print function. Make sure when you copy the spacing is correct in your editor: a tab is 4 spaces etc.

# 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();



回答3:


You could also use quandl, but you have to sign up and get your own API key. Not sure if any of the free financial APIs that have worked well with the pandas webreader still function reliably and well...

# 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()


来源:https://stackoverflow.com/questions/50800454/how-can-i-download-stock-price-data-with-python

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!