如果您打算投资股票,那么快速查看个别历史股票价格绝对是一个好主意。第一步是下载历史价格 - 但交易所网站不允许您有效地提取所有股票价格的数据。以下列出的是为nse(印度国家证券交易所)上市的所有股票提供日常股票价格数据的主要步骤:
导入模块 - 熊猫,numpy,日期时间,csv,pandas_datareader
# import modules
from datetime import datetime, timedelta
import pandas as pd
pd.coremon.is_list_like = pd.api.types.is_list_like #for solving import pandas_datareader issue
import numpy as np
import datetime
import csv
import requests
import pandas_datareader.data as web
import pandas_datareader as pdr
from pandas_datareader import data, wb
输入我们想要股票价格的开始和结束日期
# input start and end date
start = datetime.datetime(2018,4,20)
end = datetime.datetime(2018,5,20)
提取nse上列出的所有股票代码,例如20microns,reliance,boschltd
today = datetime.datetime.now().strftime (%y-%m-%d)
# import list of stock names from nse website
with requests.session() as s:
download = s.get('https://nseindia/products/content/sec_bhavdata_full.csv')
decoded_content = download.content.decode('utf-8')
cr = csv.reader(decoded_content.splitlines(), delimiter=',')
my_list = pd.dataframe(list(cr))
#view the top rows
my_list.head()
# clean the downloaded data
# rename the headers
new_header = my_list.iloc[0] #grab the first row for the header
my_list = my_list[1:] #take the data less the header row
my_list = my_list.rename(columns = new_header)
# get only the list of stock names - remove everything else
my_list['stock_name'] = nse/+ my_list['symbol']
stock_list = my_list['stock_name'].tolist()
stock_list = list(set(stock_list))
#view the top few stock names
stock_list[1:10]
输出:
['nse/harrmalaya',
'nse/ansalhsg',
'nse/dpl',
'nse/stan',
'nse/voltamp',
'nse/sumeetinds',
'nse/jkpaper',
'nse/kprmill',
'nse/ineosstyro']
运行for循环以下载每个股票代码的股票价格数据。
在for循环中,我们将使用web.datareader()函数从quandl(https://quandl/)下载数据
# create empty dataframe
stock_final = pd.dataframe()
# scrape the stock prices from quandl
# for i in range(len(stock_list))#use this to scrape all the stocks
for i in range(10):
print(i)
try:
stock=[]
stock = web.datareader(stock_list[i],quandl,start,end)
stock['name']=stock_list[i]
stock_final = pd.dataframe.append(stock_final,stock)
except exception: # replace exception with something more specific.
i = i+1
清理并附加数据,我们应该有以下分析数据集:
#view the top 10 rows of the downloaded data
stock_final.head()
我们可以使用这些数据来执行我们所需的所有分析和可视化
#plot trend for a particular stock
#subset for a particular stock
stock_final = stock_final[stock_final['name']=='nse/sutlejtex']
#generate a line plot
stock_final.plot(y='high')
plt.show()
“sutlejtex”股票的价格走势