こんにちは!エンジニアの絹田です。今回はPythonでAphaVantage APIを扱う方法について紹介します。
AlphaVantageとは
AlphaVantageはAlpha Vantageは2017年に創立された米国ボストンの会社で、エンタープライズグレードの金融市場データを提供しています。従来の資産クラス(株式やETFなど)から経済シグナル、外国為替レートから暗号通貨、基本データから技術指標まで幅広く提供していることに加えて、JSONフォーマットでの提供など開発者にわかりやすいことに定評があります。ExcelやGoogleスプレッドシートとの連携がしやすいです。
以前はOandaやGoogle Finance、Yahoo Financeなどが有力候補でしたが、サービスの終了や超大幅値上げなどにより、今後はAlpha Vantageへの移行がいいと思います。
ドキュメント
公式ドキュメント
https://www.alphavantage.co/documentation/
非公式ドキュメント
APIキーの取得
下記のページからメールアドレスを入力するとAPIキーが発行できます。
https://www.alphavantage.co/support/#api-key
ソースコード
USD/JPYのリアルタイムデータを取得
import json
import requests
import pandas as pd
'''
read API key from secret.json
secret.json
{
"API_KEY": "NXXXXXXXXXXXXXX"
}
'''
with open('secret.json') as f:
secret = json.load(f)
API_KEY = secret['API_KEY']
def main():
'''
最新のデータを取得
{
"Realtime Currency Exchange Rate": {
"1. From_Currency Code": "EUR",
"2. From_Currency Name": "Euro",
"3. To_Currency Code": "USD",
"4. To_Currency Name": "United States Dollar",
"5. Exchange Rate": "1.09805640",
"6. Last Refreshed": "2022-03-16 02:33:01",
"7. Time Zone": "UTC",
"8. Bid Price": "1.09805640",
"9. Ask Price": "1.09805640"
}
}
'''
url = f'https://www.alphavantage.co/query?function=CURRENCY_EXCHANGE_RATE&from_currency=USD&to_currency=JPY&apikey={API_KEY}'
r = requests.get(url)
data = r.json()
print(json.dumps(data, indent=2))
if __name__ == '__main__':
main()
main関数の最後にprint(json.dumps(data, indent=2))していますが、そちらにはこのようなデータが格納されます。
{
"Realtime Currency Exchange Rate": {
"1. From_Currency Code": "USD",
"2. From_Currency Name": "United States Dollar",
"3. To_Currency Code": "JPY",
"4. To_Currency Name": "Japanese Yen",
"5. Exchange Rate": "118.23600000",
"6. Last Refreshed": "2022-03-16 02:19:22",
"7. Time Zone": "UTC",
"8. Bid Price": "118.23600000",
"9. Ask Price": "118.23600000"
}
}
タイムゾーンはUTCですので、9時間プラスすると日本時間になります。
ヒストリカルデータを取得する
import json
import requests
import pandas as pd
'''
read API key from secret.json
secret.json
{
"API_KEY": "NXXXXXXXXXXXXXX"
}
'''
with open('secret.json') as f:
secret = json.load(f)
API_KEY = secret['API_KEY']
def main():
'''
# ヒストリカルデータを取得
{
"Meta Data": {
"1. Information": "Intraday (5min) open, high, low, close prices and volume",
"2. Symbol": "USDJPY",
"3. Last Refreshed": "2022-03-15 22:30:00",
"4. Interval": "5min",
"5. Output Size": "Compact",
"6. Time Zone": "US/Eastern"
},
"Time Series (5min)": {
"2022-03-15 22:30:00": {
"1. open": "118.2500",
"2. high": "118.2570",
"3. low": "118.2100",
"4. close": "118.2470",
"5. volume": "0"
},
"2022-03-15 22:25:00": {
"1. open": "118.2330",
"2. high": "118.2620",
"3. low": "118.2100",
"4. close": "118.2500",
"5. volume": "0"
},
}
'''
url = f'https://www.alphavantage.co/query?function=TIME_SERIES_INTRADAY&symbol=USDJPY&interval=5min&apikey={API_KEY}'
r = requests.get(url)
data = r.json()
print(json.dumps(data, indent=2))
if __name__ == '__main__':
main()
main関数の最後にprint(json.dumps(data, indent=2))していますが、そちらにはこのようなデータが格納されます。
{
"Meta Data": {
"1. Information": "Intraday (5min) open, high, low, close prices and volume",
"2. Symbol": "USDJPY",
"3. Last Refreshed": "2022-03-15 22:45:00",
"4. Interval": "5min",
"5. Output Size": "Compact",
"6. Time Zone": "US/Eastern"
},
"Time Series (5min)": {
"2022-03-15 22:45:00": {
"1. open": "118.2460",
"2. high": "118.2550",
"3. low": "118.2200",
"4. close": "118.2530",
"5. volume": "0"
},
"2022-03-15 22:40:00": {
"1. open": "118.2310",
"2. high": "118.2540",
"3. low": "118.1900",
"4. close": "118.2500",
"5. volume": "0"
},
こちらはタイムゾーンが東部標準時ですので、夏時間では13時間プラスすると日本時間になります。
東部標準時は、アラスカ州・ハワイ州を除いた)アメリカ合衆国本土にある4つの時間帯のうち一番先行する時間帯で、首都ワシントンD.C.やニューヨーク市のほか、東海岸の諸都市がこの時間帯に属する。カナダでは首都オタワ、モントリオール、トロントなど主要都市部がこの時間帯に属する。
夏時間は日本の方が13時間進んでいて、それ以外だと日本の方が14時間進んでいます。
Required: function
The time series of your choice. In this case, function=TIME_SERIES_INTRADAY
❚ Required: symbol
The name of the equity of your choice. For example: symbol=IBM
❚ Required: interval
Time interval between two consecutive data points in the time series. The following values are supported: 1min
, 5min
, 15min
, 30min
, 60min
❚ Optional: adjusted
By default, adjusted=true
and the output time series is adjusted by historical split and dividend events. Set adjusted=false
to query raw (as-traded) intraday values.
❚ Optional: outputsize
By default, outputsize=compact
. Strings compact
and full
are accepted with the following specifications: compact
returns only the latest 100 data points in the intraday time series; full
returns the full-length intraday time series. The “compact” option is recommended if you would like to reduce the data size of each API call.
❚ Optional: datatype
By default, datatype=json
. Strings json
and csv
are accepted with the following specifications: json
returns the intraday time series in JSON format; csv
returns the time series as a CSV (comma separated value) file.
❚ Required: apikey
Your API key. Claim your free API key here.
ソースコードまとめ
import json
import requests
import pandas as pd
'''
read API key from secret.json
secret.json
{
"API_KEY": "NXXXXXXXXXXXXXX"
}
'''
with open('secret.json') as f:
secret = json.load(f)
API_KEY = secret['API_KEY']
def main():
'''
最新のデータを取得
{
"Realtime Currency Exchange Rate": {
"1. From_Currency Code": "EUR",
"2. From_Currency Name": "Euro",
"3. To_Currency Code": "USD",
"4. To_Currency Name": "United States Dollar",
"5. Exchange Rate": "1.09805640",
"6. Last Refreshed": "2022-03-16 02:33:01",
"7. Time Zone": "UTC",
"8. Bid Price": "1.09805640",
"9. Ask Price": "1.09805640"
}
}
'''
url = f'https://www.alphavantage.co/query?function=CURRENCY_EXCHANGE_RATE&from_currency=USD&to_currency=JPY&apikey={API_KEY}'
'''
# ヒストリカルデータを取得
{
"Meta Data": {
"1. Information": "Intraday (5min) open, high, low, close prices and volume",
"2. Symbol": "USDJPY",
"3. Last Refreshed": "2022-03-15 22:30:00",
"4. Interval": "5min",
"5. Output Size": "Compact",
"6. Time Zone": "US/Eastern"
},
"Time Series (5min)": {
"2022-03-15 22:30:00": {
"1. open": "118.2500",
"2. high": "118.2570",
"3. low": "118.2100",
"4. close": "118.2470",
"5. volume": "0"
},
"2022-03-15 22:25:00": {
"1. open": "118.2330",
"2. high": "118.2620",
"3. low": "118.2100",
"4. close": "118.2500",
"5. volume": "0"
},
}
'''
#url = f'https://www.alphavantage.co/query?function=TIME_SERIES_INTRADAY&symbol=USDJPY&interval=5min&apikey={API_KEY}'
r = requests.get(url)
data = r.json()
print(json.dumps(data, indent=2))
if __name__ == '__main__':
main()