用於從 Alpha Vantage API 取得股票資料/加密貨幣的 Python 模組
Alpha Vantage 以簡單的 json 或 pandas 格式提供免費的 API,用於獲取即時財務數據和最常用的財務指標。此模組實作了 Alpha Vantage 提供的免費 API 的 python 介面。它需要一個免費的 API 金鑰,可以從 http://www.alphavantage.co/support/#api-key 請求。您可以查看其 API 文件中提供的所有 API 呼叫。
若要以無程式碼方式存取金融市場數據,您還可以考慮 Wisesheets 或官方 Google Sheet 外掛程式或 Alpha Vantage 的 Microsoft Excel 外掛程式。請查看本指南,了解使用金融市場數據的一些常見技巧。
若要安裝該包,請使用:
pip install alpha_vantage
或安裝 pandas 支持,也只需安裝 pandas:
pip install alpha_vantage pandas
如果您想從來源安裝,請使用:
git clone https://github.com/RomelTorres/alpha_vantage.git
pip install -e alpha_vantage
要從 API 取得數據,只需匯入庫並使用 API 金鑰呼叫物件即可。接下來,準備好獲得一些很棒的、免費的即時財務數據。您的 API 金鑰也可能儲存在環境變數ALPHAVANTAGE_API_KEY
中。
from alpha_vantage . timeseries import TimeSeries
ts = TimeSeries ( key = 'YOUR_API_KEY' )
# Get json object with the intraday data and another with the call's metadata
data , meta_data = ts . get_intraday ( 'GOOGL' )
要查詢歷史上特定月份的數據,您可以使用「month」參數來實現各種功能。
from alpha_vantage . timeseries import TimeSeries
from alpha_vantage . techindicators import TechIndicators
ts = TimeSeries ( key = 'YOUR_API_KEY' )
ti = TechIndicators ( key = 'YOUR_API_KEY' )
# Get json object with the 30-min interval intraday data and another with the call's metadata for January, 2014.
data , meta_data = ts . get_intraday ( 'GOOGL' , month = '2014-01' , interval = '30min' )
#Get json object with the 30-min interval simple moving average (SMA) values and another with the call's metadata for January, 2014.
data , meta_data = ti . get_sma ( 'GOOGL' , month = '2014-01' , interval = '30min' )
您也可以從rapidAPI 取得金鑰。使用您的rapidAPI密鑰作為密鑰變量,並設定rapidapi=True
ts = TimeSeries ( key = 'YOUR_API_KEY' , rapidapi = True )
內部有一個重試計數器,可用於最大限度地減少連接錯誤(以防 API 無法及時回應),預設為 5,但可以根據需要增加或減少。
ts = TimeSeries ( key = 'YOUR_API_KEY' , retries = 'YOUR_RETRIES' )
該函式庫支援以 json 字典(預設)、pandas dataframe(如果安裝)或 csv 的形式給出結果,只需傳遞參數 output_format='pandas' 即可更改給定類別中所有 API 呼叫的輸出格式。請注意,某些 API 呼叫不支援 csv 格式(即ForeignExchange and TechIndicators
),因為 API 端點也不支援其呼叫的格式。
ts = TimeSeries ( key = 'YOUR_API_KEY' , output_format = 'pandas' )
呼叫給出的 pandas 資料框可以有日期字串索引或整數索引(預設索引為「日期」),根據您的需要,您可以使用兩者。
# For the default date string index behavior
ts = TimeSeries ( key = 'YOUR_API_KEY' , output_format = 'pandas' , indexing_type = 'date' )
# For the default integer index behavior
ts = TimeSeries ( key = 'YOUR_API_KEY' , output_format = 'pandas' , indexing_type = 'integer' )
資料幀結構是透過呼叫 alpha vantage Rest API 給出的。資料框的列名稱是由其資料結構給出的。例如,以下呼叫:
from alpha_vantage . timeseries import TimeSeries
from pprint import pprint
ts = TimeSeries ( key = 'YOUR_API_KEY' , output_format = 'pandas' )
data , meta_data = ts . get_intraday ( symbol = 'MSFT' , interval = '1min' , outputsize = 'full' )
pprint ( data . head ( 2 ))
將導致:
資料中的標題由 Alpha Vantage 指定(在先前的版本中,標題中的數字已被刪除,但從長遠來看,最好讓資料與 Alpha Vantage 產生的資料完全相同。)
使用 pandas 支持,我們可以輕鬆繪製「MSFT」股票的分鐘內價值:
from alpha_vantage . timeseries import TimeSeries
import matplotlib . pyplot as plt
ts = TimeSeries ( key = 'YOUR_API_KEY' , output_format = 'pandas' )
data , meta_data = ts . get_intraday ( symbol = 'MSFT' , interval = '1min' , outputsize = 'full' )
data [ '4. close' ]. plot ()
plt . title ( 'Intraday Times Series for the MSFT stock (1 min)' )
plt . show ()
給我們作為輸出:
我們可以用同樣的方式讓 pandas 繪製 Bollinger Bands® 等技術指標
from alpha_vantage . techindicators import TechIndicators
import matplotlib . pyplot as plt
ti = TechIndicators ( key = 'YOUR_API_KEY' , output_format = 'pandas' )
data , meta_data = ti . get_bbands ( symbol = 'MSFT' , interval = '60min' , time_period = 60 )
data . plot ()
plt . title ( 'BBbands indicator for MSFT stock (60 min)' )
plt . show ()
給我們作為輸出:
我們也可以繪製 BTC 等加密貨幣的價格:
from alpha_vantage . cryptocurrencies import CryptoCurrencies
import matplotlib . pyplot as plt
cc = CryptoCurrencies ( key = 'YOUR_API_KEY' , output_format = 'pandas' )
data , meta_data = cc . get_digital_currency_daily ( symbol = 'BTC' , market = 'CNY' )
data [ '4b. close (USD)' ]. plot ()
plt . tight_layout ()
plt . title ( 'Daily close value for bitcoin (BTC)' )
plt . grid ()
plt . show ()
給我們作為輸出:
外匯端點沒有元數據,因此只能以 json 格式和 pandas 形式提供(使用“csv”格式將引發錯誤)
from alpha_vantage . foreignexchange import ForeignExchange
from pprint import pprint
cc = ForeignExchange ( key = 'YOUR_API_KEY' )
# There is no metadata in this call
data , _ = cc . get_currency_exchange_rate ( from_currency = 'BTC' , to_currency = 'USD' )
pprint ( data )
給我們作為輸出:
{
'1. From_Currency Code': 'BTC',
'2. From_Currency Name': 'Bitcoin',
'3. To_Currency Code': 'USD',
'4. To_Currency Name': 'United States Dollar',
'5. Exchange Rate': '5566.80500105',
'6. Last Refreshed': '2017-10-15 15:13:08',
'7. Time Zone': 'UTC'
}
從版本 2.2.0 開始,現在將提供 asyncio 支援。這僅適用於 python 版本 3.5+。如果您沒有 3.5+,代碼將會損壞。
語法很簡單,只需使用async
關鍵字標記您的方法,然後使用await
關鍵字。
下面是一個用於非同步取得多個符號的 for 迴圈範例。這極大地提高了具有多個 API 呼叫的程式的效能。
import asyncio
from alpha_vantage . async_support . timeseries import TimeSeries
symbols = [ 'AAPL' , 'GOOG' , 'TSLA' , 'MSFT' ]
async def get_data ( symbol ):
ts = TimeSeries ( key = 'YOUR_KEY_HERE' )
data , _ = await ts . get_quote_endpoint ( symbol )
await ts . close ()
return data
loop = asyncio . get_event_loop ()
tasks = [ get_data ( symbol ) for symbol in symbols ]
group1 = asyncio . gather ( * tasks )
results = loop . run_until_complete ( group1 )
loop . close ()
print ( results )
我們寫了一篇更深入的文章來為那些從未使用過 asyncio 但想了解 asyncio、並發和多線程的人解釋它。在這裡查看:您應該使用哪一個:非同步程式設計還是多執行緒?
我在 python 筆記本中新增了一個包含範例的儲存庫,以便更好地查看該庫的用法:https://github.com/RomelTorres/av_example
為了執行測試,您必須先匯出 API 金鑰,以便測試可以使用它來運行,測試還需要 pandas、mock 和 nose。
export API_KEY=YOUR_API_KEY
cd alpha_vantage
nosetests
程式碼文件可以在 https://alpha-vantage.readthedocs.io/en/latest/ 找到
始終歡迎貢獻。只需聯絡我們,了解如何最好地做出貢獻、添加問題或製作 PR。
您可以透過以下任意平台聯繫/追蹤 Alpha Vantage 團隊:
如果您喜歡或使用此項目,請考慮透過加註星標來表示您的支持。
??-??