使用Python獲取股票資料最佳方法是什麼?


在本文中,我們將學習使用Python獲取股票資料的最佳方法。

我們將使用yfinance Python庫從雅虎財經檢索當前和歷史股票市場價格資料。

安裝雅虎財經(yfinance)

雅虎財經是獲取股票市場資料最好的平臺之一。只需從雅虎財經網站下載資料集,然後使用yfinance庫和Python程式設計訪問它。

您可以使用pip安裝yfinance,只需開啟命令提示符並輸入以下語法所示的命令。

語法

pip install yfinance

yfinance庫最好的部分是,它是免費使用的,不需要API金鑰。

如何獲取股票價格的當前資料

我們需要找到我們可以用於資料提取的股票程式碼。在下面的示例中,我們將顯示GOOGL的當前市場價格和前收盤價。

示例

以下程式使用yfinance模組返回市場價格值、前收盤價值和程式碼值:

import yfinance as yf
ticker = yf.Ticker('GOOGL').info
marketPrice = ticker['regularMarketPrice']
previousClosePrice = ticker['regularMarketPreviousClose']
print('Ticker Value: GOOGL')
print('Market Price Value:', marketPrice)
print('Previous Close Price Value:', previousClosePrice)

輸出

執行上述程式將生成以下輸出:

Ticker Value: GOOGL
Market Price Value: 92.83
Previous Close Price Value: 93.71

如何獲取股票價格的歷史資料

透過給出開始日期、結束日期和程式碼,我們可以獲得完整的歷史價格資料。

示例

以下程式返回開始日期和結束日期之間的股票價格資料:

# importing the yfinance package
import yfinance as yf

# giving the start and end dates
startDate = '2015-03-01'
endDate = '2017-03-01'

# setting the ticker value
ticker = 'GOOGL'

# downloading the data of the ticker value between
# the start and end dates
resultData = yf.download(ticker, startDate, endDate)

# printing the last 5 rows of the data
print(resultData.tail())

輸出

執行上述程式將生成以下輸出:

[*********************100%***********************] 1 of 1 completed
            Open      High     Low       Close     Adj Close Volume
Date
2017-02-22 42.400002 42.689499 42.335499 42.568001 42.568001 24488000
2017-02-23 42.554001 42.631001 42.125000 42.549999 42.549999 27734000
2017-02-24 42.382500 42.417999 42.147999 42.390499 42.390499 26924000
2017-02-27 42.247501 42.533501 42.150501 42.483501 42.483501 20206000
2017-02-28 42.367500 42.441502 42.071999 42.246498 42.246498 27662000

以上示例將檢索從**2015-03-01**到2017-03-01的股票價格資料。

如果要同時提取多個程式碼的資料,請將程式碼作為空格分隔的字串提供。

轉換資料以進行分析

在上例資料集中,**日期**是資料集的索引,而不是列。在對其進行任何資料分析之前,必須將此索引轉換為列。方法如下:

示例

以下程式將列名新增到開始日期和結束日期之間的股票資料:

import yfinance as yf

# giving the start and end dates
startDate = '2015-03-01'
endDate = '2017-03-01'

# setting the ticker value
ticker = 'GOOGL'

# downloading the data of the ticker value between
# the start and end dates
resultData = yf.download(ticker, startDate, endDate)

# Setting date as index
resultData["Date"] = resultData.index

# Giving column names
resultData = resultData[["Date", "Open", "High","Low", "Close", "Adj Close", "Volume"]]

# Resetting the index values
resultData.reset_index(drop=True, inplace=True)

# getting the first 5 rows of the data
print(resultData.head())

輸出

執行上述程式將生成以下輸出:

[*********************100%***********************] 1 of 1 completed
   Date      Open       High     Low       Close     Adj Close  Volume

0 2015-03-02 28.350000 28.799500 28.157499 28.750999 28.750999 50406000
1 2015-03-03 28.817499 29.042500 28.525000 28.939501 28.939501 50526000
2 2015-03-04 28.848499 29.081499 28.625999 28.916500 28.916500 37964000
3 2015-03-05 28.981001 29.160000 28.911501 29.071501 29.071501 35918000
4 2015-03-06 29.100000 29.139000 28.603001 28.645000 28.645000 37592000

以上轉換後的資料與我們從雅虎財經獲取的資料相同。

將獲得的資料儲存到CSV檔案中

可以使用**to_csv()**方法將DataFrame物件匯出到CSV檔案。以下程式碼將幫助您將資料匯出到CSV檔案,因為以上轉換後的資料已在pandas資料框中。

# importing yfinance module with an alias name
import yfinance as yf

# giving the start and end dates
startDate = '2015-03-01'
endDate = '2017-03-01'

# setting the ticker value
ticker = 'GOOGL'

# downloading the data of the ticker value between
# the start and end dates
resultData = yf.download(ticker, startDate, endDate)

# printing the last 5 rows of the data
print(resultData.tail())

# exporting/converting the above data to a CSV file
resultData.to_csv("outputGOOGL.csv")

輸出

執行上述程式將生成以下輸出:

[*********************100%***********************] 1 of 1 completed
            Open      High     Low       Close     Adj Close  Volume

Date
2017-02-22 42.400002 42.689499 42.335499 42.568001 42.568001 24488000
2017-02-23 42.554001 42.631001 42.125000 42.549999 42.549999 27734000
2017-02-24 42.382500 42.417999 42.147999 42.390499 42.390499 26924000
2017-02-27 42.247501 42.533501 42.150501 42.483501 42.483501 20206000
2017-02-28 42.367500 42.441502 42.071999 42.246498 42.246498 27662000

資料視覺化

Python的**yfinance**模組是最易於設定、從中收集資料和執行資料分析活動的模組之一。可以使用Matplotlib、Seaborn或Bokeh等包來視覺化結果並獲取見解。

您甚至可以使用**PyScript**直接在網頁上顯示這些視覺化效果。

結論

在本文中,我們學習瞭如何使用Python yfinance模組來獲取最佳股票資料。此外,我們還學習瞭如何獲取指定期間的所有股票資料,如何透過新增自定義索引和列來進行資料分析,以及如何將這些資料轉換為CSV檔案。

更新於:2023年1月16日

12K+ 次瀏覽

啟動您的職業生涯

完成課程獲得認證

開始學習
廣告