需要爬取某個(gè)股票的實(shí)時(shí)數(shù)據(jù),每隔一分鐘爬取一次,并將數(shù)據(jù)保存在Excel文件中。我們使用Python來(lái)完成這項(xiàng)任務(wù)。在完成這任務(wù)之前,我們需要掌握兩個(gè)知識(shí)點(diǎn):Web爬取和Excel文件讀寫(xiě)。
Web爬取
Web爬取是指從網(wǎng)站上獲取特定數(shù)據(jù)的過(guò)程。我們通常使用Python的Requests庫(kù)來(lái)訪(fǎng)問(wèn)網(wǎng)站。網(wǎng)站會(huì)以HTML格式返回相應(yīng)數(shù)據(jù),我們需要使用Beautiful Soup庫(kù)將HTML格式的數(shù)據(jù)轉(zhuǎn)換為Python對(duì)象進(jìn)行操作。
#Excel文件讀寫(xiě)
Python中,我們可以使用OpenPyXL庫(kù)來(lái)讀寫(xiě)Excel文件。使用OpenPyXL,我們可以創(chuàng)建、打開(kāi)、修改、保存Excel文件,讀寫(xiě)單元格、行、列、工作表等。使用OpenPyXL之前,我們需要在系統(tǒng)中安裝OpenPyXL庫(kù)。
在這篇文章中,我們將會(huì)介紹如何使用Python來(lái)獲取實(shí)時(shí)股票數(shù)據(jù)并將數(shù)據(jù)存儲(chǔ)在Excel文件中。我們將介紹三種案例:使用Sina Finance API、使用TuShare獲取股票數(shù)據(jù)、使用爬蟲(chóng)庫(kù)Beautiful Soup爬取Yahoo Finance網(wǎng)站數(shù)據(jù)。
案例一:使用Sina Finance API獲取股票數(shù)據(jù)
Sina Finance是國(guó)內(nèi)較為權(quán)威的股票行情數(shù)據(jù)提供商之一。它提供了全球股票、期貨、外匯、基金、債券、指數(shù)等交易品種的實(shí)時(shí)行情數(shù)據(jù)。它提供API接口以方便用戶(hù)獲取股票數(shù)據(jù)。
本案例中,我們將使用Sina Finance提供的API接口獲取股票數(shù)據(jù)。首先,我們需要安裝sinafinance庫(kù):
pip install sinafinance
接著,我們可以使用如下代碼來(lái)獲取股票實(shí)時(shí)數(shù)據(jù)并保存到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
# 設(shè)置表頭
header = ['股票代碼', '名稱(chēng)', '最新價(jià)', '漲跌幅', '成交量', '成交額']
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')
# 填充數(shù)據(jù)
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
# 設(shè)置列寬
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')
我們可以看到,上面的代碼實(shí)現(xiàn)了獲取實(shí)時(shí)股票數(shù)據(jù)的功能,并將數(shù)據(jù)以Excel格式保存。這個(gè)例子演示了如何使用Sina Finance API獲取股票數(shù)據(jù),這是一個(gè)比較快捷方便的方法。
案例二:使用TuShare獲取股票數(shù)據(jù)
TuShare是一個(gè)開(kāi)源的金融數(shù)據(jù)開(kāi)放接口平臺(tái),它能為開(kāi)發(fā)者提供比較豐富的金融數(shù)據(jù)API和數(shù)據(jù)下載。我們可以使用TuShare提供的數(shù)據(jù)接口來(lái)獲取股票數(shù)據(jù)。
首先,我們需要安裝tushare庫(kù):
pip install tushare
接著,我們可以使用如下代碼來(lái)獲取股票實(shí)時(shí)數(shù)據(jù)并保存在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
# 設(shè)置表頭
header = ['股票代碼', '名稱(chēng)', '最新價(jià)', '漲跌幅', '成交量', '成交額']
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')
# 填充數(shù)據(jù)
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
# 設(shè)置列寬
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')
我們可以看到,上面的代碼實(shí)現(xiàn)了獲取實(shí)時(shí)股票數(shù)據(jù)的功能,并將數(shù)據(jù)以Excel格式保存。這個(gè)例子演示了如何使用TuShare獲取股票數(shù)據(jù),這也是一個(gè)比較方便的方法。
案例三:使用爬蟲(chóng)庫(kù)Beautiful Soup爬取Yahoo Finance網(wǎng)站數(shù)據(jù)
除了使用各種API獲取股票數(shù)據(jù),我們還可以使用爬蟲(chóng)庫(kù)獲取數(shù)據(jù)。Yahoo Finance是一個(gè)提供股票行情數(shù)據(jù)的網(wǎng)站。我們可以使用Beautiful Soup爬蟲(chóng)庫(kù)來(lái)獲取Yahoo Finance上的股票數(shù)據(jù)。
首先,我們需要安裝beautifulsoup4庫(kù):
pip install beautifulsoup4
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
# 設(shè)置表頭
header = ['名稱(chēng)', '最新價(jià)', '漲跌幅']
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')
# 填充數(shù)據(jù)
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('%'))
# 設(shè)置列寬
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')
我們可以看到,上面的代碼實(shí)現(xiàn)了獲取實(shí)時(shí)股票數(shù)據(jù)的功能,并將數(shù)據(jù)以Excel格式保存。這個(gè)例子演示了如何使用Beautiful Soup庫(kù)獲取股票數(shù)據(jù),這也是一個(gè)比較靈活的方法。
通過(guò)上面幾個(gè)例子,我們展示了如何使用Python獲取實(shí)時(shí)股票數(shù)據(jù),并將數(shù)據(jù)以Excel格式保存。這是一個(gè)比較常見(jiàn)的任務(wù),可以幫助我們進(jìn)行股票分析和決策。同時(shí),我們也可以發(fā)現(xiàn),Python尤其是各種數(shù)據(jù)處理庫(kù)的應(yīng)用,可以帶給我們極大的便利,提高我們的工作效率。文章來(lái)源:http://www.zghlxwxcb.cn/news/detail-829230.html
添聞提供的思路僅供參考。文章來(lái)源地址http://www.zghlxwxcb.cn/news/detail-829230.html
到了這里,關(guān)于如何用 python 獲取實(shí)時(shí)的股票數(shù)據(jù)?的文章就介紹完了。如果您還想了解更多內(nèi)容,請(qǐng)?jiān)谟疑辖撬阉鱐OY模板網(wǎng)以前的文章或繼續(xù)瀏覽下面的相關(guān)文章,希望大家以后多多支持TOY模板網(wǎng)!