The trading API of financial products has been published by various companies in the virtual currency field such as Bitcoin for a long time, but I feel that there are not so many in stocks and ETFs. Meanwhile, kabu.com Securities released a trading API that supports REST format, so I tried using it.
To use the kabu station API, you need to have an account with kabu.com Securities and have a Fintech plan or higher. Therefore, those who do not have an account need to perform the following steps to start using it. Please refer to here for the detailed procedure.
When making various API requests, it is necessary to specify the token acquired in advance in the request header, so first acquire that token. When acquiring the token, the API password set in Preparation 5 in the previous section is required, but this time, put it in the environment variable.
import os
import json
import requests
API_URL = "http://localhost:18080/kabusapi"
API_PASSWORD = os.environ["API_PASSWORD"]
def get_token():
URL = API_URL + "/token"
headers = {"content-type": "application/json"}
payload = {"APIPassword": API_PASSWORD}
try:
response = requests.post(URL, data=json.dumps(payload).encode("utf8"), headers=headers)
except Exception as e:
print (e)
return json.loads(response.text).get("Token")
Get the market value information of any brand. The response also includes detailed board information. By the way, if you specify symbol as 101, you can get the Nikkei Stock Average.
variable | Description |
---|---|
token | Token acquired in the previous section |
symbol | Brand code you want to get |
exchange | Market code you want to get(1 is TSE) |
def get_price(token):
symbol = "9433"
exchange = "1"
URL = API_URL + "/board/" + symbol + "@" + exchange
headers = {
"content-type": "application/json",
"X-API-KEY": token
}
try:
response = requests.get(URL, headers=headers)
except Exception as e:
print (e)
return json.loads(response.text).get("CurrentPrice")
Reference describes various other request methods, so if you have an operation you want to perform, please refer to this. There are some preparations before the API becomes available, but once that's done, the API request itself doesn't seem to be particularly difficult. I feel that there are still few such resources in Japan, so it would be nice if the openness progressed as in the virtual currency field.
Recommended Posts