以下が、信用取引週末残高を求めるため使用しているコードです。複数銘柄コードの値を一定期間入手しエクセル変換する機能がうまく働いています。

#個別株の株価データ取得
#pip 経由でライブラリをインストール
#J-Quantsのライブラリ
!pip install jquants-api-client

#gspreadはGoogleスプレッドシートを操作するためのライブラリです
!pip install gspread

# google認証
from google.colab import auth
auth.authenticate_user()

# googleドライブへの設定(出力フォルダ)
from google.colab import drive
drive.mount('/content/drive')

import jquantsapi
import pandas as pd
import requests
import gspread
from google.auth import default
creds, _ = default()
gc = gspread.authorize(creds)
import gspread_dataframe as gs_df
import json
from pandas import json_normalize
import datetime
import time

# JQuantsのAPIを使用するためのリフレッシュトークンの取得
# 一度取得すると1週間有効ですが、実行都度取得したほうが楽なので毎回取得としています。
# JQuantsに登録したメールアドレスとパスワードを記入
data={"mailaddress":"***", "password":"***"}
r_post = requests.post("https://api.jquants.com/v1/token/auth_user", data=json.dumps(data))
r_post.json()
REFRESH_TOKEN = r_post.json().get("refreshToken")

r_post = requests.post(f"https://api.jquants.com/v1/token/auth_refresh?refreshtoken={REFRESH_TOKEN}")
r_post.json()
ID_TOKEN = r_post.json().get("idToken")
idToken = ID_TOKEN

# code_listに調べたい銘柄コードを入力、複数の場合はカンマで区切りで入力
df_markets = pd.DataFrame()
code_list = [5019,3994] #ここを取得したいコードに変更、サンプルとしてメルカリとジモティを記載
list_ID = [str(s)+"0" for s in code_list]

from_day = "2023-11-16"
to_day = ""

for i in list_ID:
    URL = "https://api.jquants.com/v1/markets/weekly_margin_interest?code=" + str(i) + "&from=" + from_day + "&to=" + to_day
    headers = {'Authorization': 'Bearer {}'.format(idToken)}
    r = requests.get(URL,headers=headers)
    list_markets = r.json().get('weekly_margin_interest')
    df01 = pd.DataFrame(list_markets)
    df_markets = pd.concat([df_markets, df01], axis=0)
    time.sleep(1)#サーバーに負荷をかけないように1秒待ちます。

df_markets['Code']=df_markets['Code'].str[:-1]

#出力されるスプレッドシートのファイル名を定義
#ファイル名を「株価データ20231231」と実行した日付をつけてみる。
filename = "信用取引週末残高"
#今日の日付を取得
today=datetime.date.today()
#日付のYYYY-MM-DDの-をカット
today=str(today).replace('-','')
#ファイル名(filename)+今日の日付(today)でファイル作成
sh = gc.create(filename+today) # ‘’内の名称のスプレッドシートをマイドライブに新規作成

worksheet = sh.get_worksheet(0) # シートを取得
gs_df.set_with_dataframe(worksheet, df_markets.reset_index())

print("実行完了しました")

業種別空売り比率データを取得するため、上記コードを修正したのが以下コードとそのエラーになります。

修正点は1.markets/short_sellingに変更、2.codeをsector33codeに変更、3.str(s)+”0″のゼロ削除です

#個別株の株価データ取得
#pip 経由でライブラリをインストール
#J-Quantsのライブラリ
!pip install jquants-api-client

#gspreadはGoogleスプレッドシートを操作するためのライブラリです
!pip install gspread

# google認証
from google.colab import auth
auth.authenticate_user()

# googleドライブへの設定(出力フォルダ)
from google.colab import drive
drive.mount('/content/drive')

import jquantsapi
import pandas as pd
import requests
import gspread
from google.auth import default
creds, _ = default()
gc = gspread.authorize(creds)
import gspread_dataframe as gs_df
import json
from pandas import json_normalize
import datetime
import time

# JQuantsのAPIを使用するためのリフレッシュトークンの取得
# 一度取得すると1週間有効ですが、実行都度取得したほうが楽なので毎回取得としています。
# JQuantsに登録したメールアドレスとパスワードを記入
data={"mailaddress":"***", "password":"***"} 
r_post = requests.post("https://api.jquants.com/v1/token/auth_user", data=json.dumps(data))
r_post.json()
REFRESH_TOKEN = r_post.json().get("refreshToken")

r_post = requests.post(f"https://api.jquants.com/v1/token/auth_refresh?refreshtoken={REFRESH_TOKEN}")
r_post.json()
ID_TOKEN = r_post.json().get("idToken")
idToken = ID_TOKEN

# sector33code_listに調べたい銘柄コードを入力、複数の場合はカンマで区切りで入力
df_markets = pd.DataFrame()
sector33code_list = [1050,2050] #ここを取得したいコードに変更、サンプルとしてメルカリとジモティを記載
list_ID = [str(s) for s in sector33code_list]

from_day = "2023-08-30"
to_day = ""

for i in list_ID:
    URL = "https://api.jquants.com/v1/markets/short_selling?sector33code=" + str(i) + "&from=" + from_day + "&to=" + to_day
    headers = {'Authorization': 'Bearer {}'.format(idToken)}
    r = requests.get(URL,headers=headers) 
    list_markets = r.json().get('ode') 
    df01 = pd.DataFrame(list_markets) 
    df_markets = pd.concat([df_markets, df01], axis=0)
    time.sleep(1)#サーバーに負荷をかけないように1秒待ちます。

df_markets['sector33code']=df_markets['sector33code'].str[:-1]

#出力されるスプレッドシートのファイル名を定義
#ファイル名を「株価データ20231231」と実行した日付をつけてみる。
filename = "業種別空売り比率"
#今日の日付を取得
today=datetime.date.today()
#日付のYYYY-MM-DDの-をカット
today=str(today).replace('-','')
#ファイル名(filename)+今日の日付(today)でファイル作成
sh = gc.create(filename) # ‘’内の名称のスプレッドシートをマイドライブに新規作成

worksheet = sh.get_worksheet(0) # シートを取得
gs_df.set_with_dataframe(worksheet, df_markets.reset_index())
 
print("実行完了しました")

実行エラーが以下の通り


KeyError                                  Traceback (most recent call last)
/usr/local/lib/python3.10/dist-packages/pandas/core/indexes/base.py in get_loc(self, key, method, tolerance)
   3801             try:
-> 3802                 return self._engine.get_loc(casted_key)
   3803             except KeyError as err:

4 frames
pandas/_libs/hashtable_class_helper.pxi in pandas._libs.hashtable.PyObjectHashTable.get_item()

pandas/_libs/hashtable_class_helper.pxi in pandas._libs.hashtable.PyObjectHashTable.get_item()

KeyError: 'sector33code'

The above exception was the direct cause of the following exception:

KeyError                                  Traceback (most recent call last)
/usr/local/lib/python3.10/dist-packages/pandas/core/indexes/base.py in get_loc(self, key, method, tolerance)
   3802                 return self._engine.get_loc(casted_key)
   3803             except KeyError as err:
-> 3804                 raise KeyError(key) from err
   3805             except TypeError:
   3806                 # If we have a listlike key, _check_indexing_error will raise

KeyError: 'sector33code'