如何用 python 获取实时的股票数据?
最近,我们公司接到一项任务:需要爬取某个股票的实时数据,每隔一分钟爬取一次,并将数据保存在Excel文件中。我们使用Python来完成这项任务。在完成这任务之前,我们需要掌握两个知识点:Web爬取和Excel文件读写。
Web爬取
Web爬取是指从网站上获取特定数据的过程。我们通常使用Python的Requests库来访问网站。网站会以HTML格式返回相应数据,我们需要使用Beautiful Soup库将HTML格式的数据转换为Python对象进行操作。
Excel文件读写
Python中,我们可以使用OpenPyXL库来读写Excel文件。使用OpenPyXL,我们可以创建、打开、修改、保存Excel文件,读写单元格、行、列、工作表等。使用OpenPyXL之前,我们需要在系统中安装OpenPyXL库。
Python获取实时股票数据
在这篇文章中,我们将会介绍如何使用Python来获取实时股票数据并将数据存储在Excel文件中。我们将介绍三种案例:使用Sina Finance API、使用TuShare获取股票数据、使用爬虫库Beautiful Soup爬取Yahoo Finance网站数据。
案例一:使用Sina Finance API获取股票数据
Sina Finance是国内较为权威的股票行情数据提供商之一。它提供了全球股票、期货、外汇、基金、债券、指数等交易品种的实时行情数据。它提供API接口以方便用户获取股票数据。
本案例中,我们将使用Sina Finance提供的API接口获取股票数据。首先,我们需要安装sinafinance库:
pip install sinafinance
接着,我们可以使用如下代码来获取股票实时数据并保存到Excel文件中。
from sinafinance import SinaFinance
import openpyxl
from openpyxl.styles import Font, Alignment
from openpyxl.utils import column_index_from_string
def get_stock_data(code, save_file):
sf = SinaFinance()
data = sf.get_realtime_quotes([code])[code]
wb = openpyxl.Workbook()
ws = wb.active
# 设置表头
header = ['股票代码', '名称', '最新价', '涨跌幅', '成交量', '成交额']
for i in range(len(header)):
cell = ws.cell(row=1, column=i+1)
cell.value = header[i]
cell.font = Font(bold=True)
cell.alignment = Alignment(horizontal='center')
# 填充数据
row_num = 2
for i in range(len(data)):
cell = ws.cell(row=row_num+i, column=column_index_from_string('A'))
cell.value = data[i]['code']
cell = ws.cell(row=row_num+i, column=column_index_from_string('B'))
cell.value = data[i]['name']
cell = ws.cell(row=row_num+i, column=column_index_from_string('C'))
cell.value = float(data[i]['price'])
cell = ws.cell(row=row_num+i, column=column_index_from_string('D'))
cell.value = float(data[i]['change_pct'])
cell = ws.cell(row=row_num+i, column=column_index_from_string('E'))
cell.value = float(data[i]['volume']) / 100
cell = ws.cell(row=row_num+i, column=column_index_from_string('F'))
cell.value = float(data[i]['turnover']) / 10000
# 设置列宽
column_widths = [12, 12, 10, 10, 12, 12]
for i in range(len(column_widths)):
ws.column_dimensions[column_index_from_string('A')+i].width = column_widths[i]
# 保存Excel文件
wb.save(save_file)
if __name__ == '__main__':
get_stock_data('sh000001', 'sh000001.xlsx')
我们可以看到,上面的代码实现了获取实时股票数据的功能,并将数据以Excel格式保存。这个例子演示了如何使用Sina Finance API获取股票数据,这是一个比较快捷方便的方法。
案例二:使用TuShare获取股票数据
TuShare是一个开源的金融数据开放接口平台,它能为开发者提供比较丰富的金融数据API和数据下载。我们可以使用TuShare提供的数据接口来获取股票数据。
首先,我们需要安装tushare库:
pip install tushare
接着,我们可以使用如下代码来获取股票实时数据并保存在Excel文件中。
import tushare as ts
import openpyxl
from openpyxl.styles import Font, Alignment
from openpyxl.utils import column_index_from_string
def get_stock_data(code, save_file):
data = ts.get_realtime_quotes(code)
wb = openpyxl.Workbook()
ws = wb.active
# 设置表头
header = ['股票代码', '名称', '最新价', '涨跌幅', '成交量', '成交额']
for i in range(len(header)):
cell = ws.cell(row=1, column=i+1)
cell.value = header[i]
cell.font = Font(bold=True)
cell.alignment = Alignment(horizontal='center')
# 填充数据
row_num = 2
for i in range(len(data)):
cell = ws.cell(row=row_num+i, column=column_index_from_string('A'))
cell.value = data.iloc[i]['code']
cell = ws.cell(row=row_num+i, column=column_index_from_string('B'))
cell.value = data.iloc[i]['name']
cell = ws.cell(row=row_num+i, column=column_index_from_string('C'))
cell.value = float(data.iloc[i]['price'])
cell = ws.cell(row=row_num+i, column=column_index_from_string('D'))
cell.value = float(data.iloc[i]['changepercent'])
cell = ws.cell(row=row_num+i, column=column_index_from_string('E'))
cell.value = float(data.iloc[i]['volume']) / 100
cell = ws.cell(row=row_num+i, column=column_index_from_string('F'))
cell.value = float(data.iloc[i]['amount']) / 10000
# 设置列宽
column_widths = [12, 12, 10, 10, 12, 12]
for i in range(len(column_widths)):
ws.column_dimensions[column_index_from_string('A')+i].width = column_widths[i]
# 保存Excel文件
wb.save(save_file)
if __name__ == '__main__':
get_stock_data(['000001'], '000001.xlsx')
我们可以看到,上面的代码实现了获取实时股票数据的功能,并将数据以Excel格式保存。这个例子演示了如何使用TuShare获取股票数据,这也是一个比较方便的方法。
案例三:使用爬虫库Beautiful Soup爬取Yahoo Finance网站数据
除了使用各种API获取股票数据,我们还可以使用爬虫库获取数据。Yahoo Finance是一个提供股票行情数据的网站。我们可以使用Beautiful Soup爬虫库来获取Yahoo Finance上的股票数据。
首先,我们需要安装beautifulsoup4库:
pip install beautifulsoup4
接着,我们可以使用如下代码来获取股票实时数据并保存在Excel文件中。
from bs4 import BeautifulSoup
import requests
import openpyxl
from openpyxl.styles import Font, Alignment
from openpyxl.utils import column_index_from_string
def get_stock_data(code, save_file):
url = 'https://finance.yahoo.com/quote/{}?p={}'.format(code, code)
req = requests.get(url)
html = req.text
soup = BeautifulSoup(html, 'html.parser')
data = {}
data['name'] = soup.find('h1', {'class': 'D(ib) Fz(18px)'}).text
data['price'] = soup.find('span', {'class': 'Trsdu(0.3s) Fw(b) Fz(36px) Mb(-4px) D(ib)'}).text
data['change_pct'] = soup.find('span', {'class': 'Trsdu(0.3s) Fw(500) Pstart(10px) Fz(24px) C($positiveColor)'}).text
wb = openpyxl.Workbook()
ws = wb.active
# 设置表头
header = ['名称', '最新价', '涨跌幅']
for i in range(len(header)):
cell = ws.cell(row=1, column=i+1)
cell.value = header[i]
cell.font = Font(bold=True)
cell.alignment = Alignment(horizontal='center')
# 填充数据
row_num = 2
cell = ws.cell(row=row_num, column=column_index_from_string('A'))
cell.value = data['name']
cell = ws.cell(row=row_num, column=column_index_from_string('B'))
cell.value = float(data['price'])
cell = ws.cell(row=row_num, column=column_index_from_string('C'))
cell.value = float(data['change_pct'].strip('%'))
# 设置列宽
column_widths = [20, 10, 10]
for i in range(len(column_widths)):
ws.column_dimensions[column_index_from_string('A')+i].width = column_widths[i]
# 保存Excel文件
wb.save(save_file)
if __name__ == '__main__':
get_stock_data('AAPL', 'AAPL.xlsx')
我们可以看到,上面的代码实现了获取实时股票数据的功能,并将数据以Excel格式保存。这个例子演示了如何使用Beautiful Soup库获取股票数据,这也是一个比较灵活的方法。
通过上面几个例子,我们展示了如何使用Python获取实时股票数据,并将数据以Excel格式保存。这是一个比较常见的任务,可以帮助我们进行股票分析和决策。同时,我们也可以发现,Python尤其是各种数据处理库的应用,可以带给我们极大的便利,提高我们的工作效率。
最后,小编想提醒大家,如果您需要更高效、更专业的数据爬取服务,不妨考虑添闻数据公司提供的爬虫服务。添闻数据公司是一家专业的数据爬取公司,我们有丰富的爬虫经验和技术,可以为您提供定制化的爬虫服务,满足您的特定需求。
声明:本站所有文章,如无特殊说明或标注,均为本站原创发布。任何个人或组织,在未征得本站同意时,禁止复制、盗用、采集、发布本站内容到任何网站、书籍等各类媒体平台。如若本站内容侵犯了原著者的合法权益,可联系我们进行处理。