Skip to content

Instantly share code, notes, and snippets.

@Chloro989
Created March 28, 2024 14:55
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save Chloro989/b76418c7177221dbf92f06bfb4cf5eec to your computer and use it in GitHub Desktop.
Save Chloro989/b76418c7177221dbf92f06bfb4cf5eec to your computer and use it in GitHub Desktop.
make a pie chart of jpx stock you have separated by sector
import requests
import matplotlib.pyplot as plt
from dotenv import load_dotenv
import os
import japanize_matplotlib # 日本語表示に対応させる
# get the refresh token from https://jpx-jquants.com/ and paste on a .env file
# load .emv
load_dotenv()
# 環境変数からAPIキーなどを取得
REFRESH_TOKEN = os.getenv('REFRESH_TOKEN')
API_ENDPOINT = 'https://api.jquants.com/v1'
# idToken取得
try:
req_post = requests.post(f"{API_ENDPOINT}/token/auth_refresh?refreshtoken={REFRESH_TOKEN}")
idToken = req_post.json()["idToken"]
except Exception as e:
print("idTokenの取得に失敗しました。", e)
exit()
print("API使用の準備が完了しました。")
# 銘柄コードに対応するセクター情報と株価の始値を取得する関数
def get_stock_info_and_open_price(stock_code):
headers = {"Authorization": f"Bearer {idToken}"}
# 銘柄情報の取得
info_url = f"{API_ENDPOINT}/listed/info?code={stock_code}"
info_res = requests.get(info_url, headers=headers)
sector = info_res.json()["info"][0]["Sector33CodeName"]
# 株価情報の取得
price_url = f"{API_ENDPOINT}/prices/daily_quotes?code={stock_code}"
price_res = requests.get(price_url, headers=headers)
open_price = price_res.json()["daily_quotes"][-1]["Open"]
return sector, open_price
# ポートフォリオ作成関数(改良版)
def create_portfolio_improved(stock_list):
sector_investment = {}
total_investment = 0
for stock_code, shares in stock_list:
sector, open_price = get_stock_info_and_open_price(stock_code)
investment = open_price * shares
if sector not in sector_investment:
sector_investment[sector] = 0
sector_investment[sector] += investment
total_investment += investment
sector_percentages = {sector: (amount / total_investment) * 100 for sector, amount in sector_investment.items()}
plt.figure(figsize=(10, 7))
plt.pie(sector_percentages.values(), labels=sector_percentages.keys(), autopct='%1.1f%%')
plt.title('ポートフォリオ セクター別投資割合')
plt.show()
# 銘柄リスト(株数に変更) 例
stock_list = [
('27680', 15), # 双日
('67580', 10), # マクニカ
('31680', 104), # 黒谷
('36620', 5), # エイチーム
('49790', 10), # アグリオ
('67230', 5), # ルネサス
('16050', 100), # INPEX
('25930', 100), # 伊藤園
('46130', 300), # 関西ペイント
]
create_portfolio_improved(stock_list)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment