diff --git a/.github/release.yml b/.github/release.yml new file mode 100644 index 0000000..e863384 --- /dev/null +++ b/.github/release.yml @@ -0,0 +1,8 @@ +changelog: + exclude: + labels: + - tagpr + categories: + - title: Changes + labels: + - '*' diff --git a/.github/workflows/README.md b/.github/workflows/README.md index a41b3bd..7475915 100644 --- a/.github/workflows/README.md +++ b/.github/workflows/README.md @@ -1,56 +1,32 @@ -# GitHub Actions Workflows +# リリース手順 -このディレクトリには、J-Quants Go ClientのCI/CDワークフローが含まれています。 +[`tagpr.yml`](tagpr.yml) で [tagpr](https://github.com/Songmu/tagpr) を実行し、リリース PR と GitHub Release を作成します。設定は [`.tagpr`](../../.tagpr)、リリースノートの設定は [`.github/release.yml`](../release.yml) にあります。 -## ワークフロー一覧 +## 初回設定 -### CI (`ci.yml`) +認証には GitHub Actions が発行する `GITHUB_TOKEN` を使用します。リポジトリの Settings → Actions → General → Workflow permissions で **Allow GitHub Actions to create and approve pull requests** を有効にしてください。tagpr に必要な書き込み権限はワークフロー内の `permissions` で指定しています。 -プルリクエストやmainブランチへのプッシュ時に実行される基本的なCIワークフローです。 +## リリースの作成 -**トリガー:** -- Pull Request (mainブランチ向け) -- Push to main branch +1. 通常のプルリクエストを `main` にマージすると、未リリースの変更をまとめたリリース PR が作成・更新されます。 +2. リリース PR のバージョンと `CHANGELOG.md` を確認します。利用者への影響など、自動生成された変更履歴に不足する説明はこの PR で補足します。 +3. CI が承認待ちになったら、書き込み権限のある利用者が PR 画面の **Approve workflows to run** を選択し、CI の結果を確認します。リリース PR が更新された場合も、承認が必要になることがあります。[GitHub の実行条件](https://docs.github.com/en/actions/how-tos/write-workflows/choose-when-workflows-run/trigger-a-workflow) +4. リリース PR をマージすると、`v` 付きのバージョンタグと公開済みの GitHub Release が作成されます。 -**ジョブ:** -1. **Test**: ビルドチェックと単体テストの実行 - - Go 1.23を使用 - - カバレッジレポートをCodecovにアップロード -2. **Lint**: golangci-lintによるコード品質チェック -3. **Security**: Gosecによるセキュリティスキャン +リリース PR は、公開したいタイミングまで開いたままにできます。`main` に変更が追加されると内容が更新されます。`CHANGELOG.md` は最初のリリース PR で生成されます。 -### Release (`release.yml`) +## バージョンの選択 -新しいバージョンのリリース時に実行されるワークフローです。 +既定は patch 更新です。minor・major 更新はリリース PR のラベルで指定します。通常の変更 PR に `minor` または `major` ラベルを付けてマージすると、対応するラベルがリリース PR に反映されます。 -**トリガー:** -- タグプッシュ(`v*`パターン) +| リリース PR のラベル | 更新例 | +|---------------------|--------| +| 指定なし | `v0.8.0` → `v0.8.1` | +| `tagpr:minor` | `v0.8.0` → `v0.9.0` | +| `tagpr:major` | `v0.8.0` → `v1.0.0` | -**ジョブ:** -1. テストの実行 -2. 変更履歴の生成 -3. GitHubリリースの作成 +開いているリリース PR の `tagpr:minor`・`tagpr:major` ラベルを手動で追加・削除すると、tagpr が再実行され、PR タイトルと `CHANGELOG.md` のバージョンが更新されます。更新が完了してから内容と CI の結果を確認してください。 -## ローカルでのテスト +通常の変更 PR のラベルから反映されたバージョン指定を取り消す場合は、先に元の変更 PR の `minor`・`major` ラベルを削除してください。リリース PR 側のラベルだけを削除すると、再実行時に付け直されます。 -GitHub Actionsのワークフローをローカルでテストする場合は、[act](https://github.com/nektos/act)を使用できます: - -```bash -# CIワークフローをテスト -act pull_request - -# リリースワークフローをテスト -act push --eventpath event.json -``` - -## トラブルシューティング - -### Lintエラーが発生する場合 - -ローカルで以下を実行して修正: - -```bash -make lint -# または -golangci-lint run --fix -``` \ No newline at end of file +タグだけでバージョンを管理するため、PR タイトルを編集してもリリースバージョンは変わりません。ラベルの詳細は [tagpr のバージョン指定方法](https://github.com/Songmu/tagpr/blob/v1.20.3/docs/guides/versioning.md)を参照してください。 diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index 171d4b5..ddd932f 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -12,7 +12,7 @@ jobs: runs-on: ubuntu-latest strategy: matrix: - go-version: ['1.24', '1.25'] + go-version: ['1.25', '1.26', '1.27'] steps: - name: Checkout code @@ -64,12 +64,12 @@ jobs: - name: Set up Go uses: actions/setup-go@v5 with: - go-version: '1.24' + go-version: '1.25' - name: golangci-lint - uses: golangci/golangci-lint-action@v6 + uses: golangci/golangci-lint-action@v9 with: - version: latest + version: v2.13.2 args: --timeout=5m security: @@ -83,4 +83,4 @@ jobs: - name: Run Gosec Security Scanner uses: securego/gosec@master with: - args: ./... \ No newline at end of file + args: ./... diff --git a/.github/workflows/tagpr.yml b/.github/workflows/tagpr.yml new file mode 100644 index 0000000..35a227a --- /dev/null +++ b/.github/workflows/tagpr.yml @@ -0,0 +1,43 @@ +name: tagpr + +on: + push: + branches: [main] + pull_request_target: + branches: [main] + types: [labeled, unlabeled] + +permissions: + contents: write + pull-requests: write + issues: read + +jobs: + tagpr: + if: >- + github.event_name == 'push' || + ( + github.event.pull_request.state == 'open' && + github.event.pull_request.head.repo.full_name == github.repository && + startsWith(github.event.pull_request.head.ref, 'tagpr-from-') && + contains(github.event.pull_request.labels.*.name, 'tagpr') && + (github.event.label.name == 'tagpr:minor' || github.event.label.name == 'tagpr:major') + ) + runs-on: ubuntu-latest + concurrency: + group: tagpr + cancel-in-progress: false + queue: max + steps: + - name: Checkout code + uses: actions/checkout@v4 + with: + # An empty ref preserves the push event's commit for release detection. + ref: ${{ github.event_name == 'pull_request_target' && 'main' || '' }} + persist-credentials: false + fetch-depth: 0 + + - name: Create release pull request or release + uses: Songmu/tagpr@v1.20.3 + env: + GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }} diff --git a/.gitignore b/.gitignore index f3a2eda..6cc8a27 100644 --- a/.gitignore +++ b/.gitignore @@ -26,6 +26,7 @@ go.work.sum tmp/ # 公式APIドキュメントのローカルキャッシュ(make docs-sync で取得) docs/v2/ +docs/ai/ # IDE specific files .idea/ diff --git a/.tagpr b/.tagpr new file mode 100644 index 0000000..e53ee6b --- /dev/null +++ b/.tagpr @@ -0,0 +1,6 @@ +[tagpr] + releaseBranch = main + versionFile = - + vPrefix = true + changelog = true + release = true diff --git a/Makefile b/Makefile index bb88b72..e9dcacf 100644 --- a/Makefile +++ b/Makefile @@ -58,7 +58,7 @@ clean: # 開発ツールのインストール install-tools: @echo "golangci-lintをインストール中..." - go install github.com/golangci/golangci-lint/cmd/golangci-lint@latest + go install github.com/golangci/golangci-lint/v2/cmd/golangci-lint@v2.13.2 @echo "開発ツールのインストールが完了しました" # 全テスト実行(単体テスト + リント) @@ -83,4 +83,4 @@ mod-download: # 公式APIドキュメントを docs/v2/ に同期(ローカルキャッシュ。コミットしない) docs-sync: - ./scripts/sync-docs.sh \ No newline at end of file + ./scripts/sync-docs.sh diff --git a/README.md b/README.md index 60cbc3b..c9a38c3 100644 --- a/README.md +++ b/README.md @@ -1,18 +1,20 @@ # J-Quants Go Client -J-Quants API v2のGo言語クライアントライブラリです。株価・財務情報など日本の株式市場データを扱うAPIをGoから簡単に利用できます。 +J-Quants API v2 の Go クライアントライブラリです。株価・財務情報など、日本の株式市場データを取得できます。 利用には[J-Quants](https://jpx-jquants.com/)のAPIキーが必要です(取得できるデータは契約プランに応じます)。 ## 特徴 -- 📊 包括的な市場データアクセス(株価、財務情報、指数など) +- 📊 株価、財務情報、指数などのデータ取得 - 🔐 APIキーによるシンプルな認証 - 📄 ページネーション対応 - 🚀 セッション単位のキャッシュ機能(オプション) ## インストール +Go 1.25.0 以上が必要です。 + ```bash go get github.com/utahta/jquants ``` @@ -49,7 +51,9 @@ func main() { } for _, quote := range quotes { - fmt.Printf("%s: 終値 %.2f円\n", quote.Date, *quote.C) + if quote.C != nil { + fmt.Printf("%s: 終値 %.2f円\n", quote.Date, *quote.C) + } } } ``` @@ -74,39 +78,42 @@ httpClient := client.NewClient("your-api-key") ## キャッシュ機能 -セッション単位のキャッシュを有効にすると、同じリクエストに対するAPI呼び出しを削減できます。 +キャッシュを有効にすると、同じ HTTP クライアントで同じリクエストを行った際に、取得済みのレスポンスを再利用します。 ```go -// キャッシュを有効化 -httpClient := client.NewClient("your-api-key", client.WithCache()) - -// または環境変数から httpClient, err := client.NewClientFromEnv(client.WithCache()) +if err != nil { + log.Fatal(err) +} // キャッシュをクリア httpClient.ClearCache() // キャッシュエントリ数を取得 -size := httpClient.CacheSize() +fmt.Printf("キャッシュ件数: %d\n", httpClient.CacheSize()) ``` +API キーを直接指定する場合は、`client.NewClient("your-api-key", client.WithCache())` を使用します。 + - キャッシュはGETリクエストのみに適用されます -- キャッシュキーはリクエストパス(クエリパラメータ含む)で区別されます -- 同時リクエストの重複排除(singleflight)により効率的に動作します -- 待機中にコンテキストをキャンセルした呼び出し元は即座にエラーで戻ります(進行中のリクエストは完了してキャッシュされます) +- URL とクエリパラメータが同じリクエストでキャッシュを再利用します +- 同じリクエストを同時に実行した場合、API 呼び出しを1回にまとめます +- レスポンスの待機中にコンテキストをキャンセルすると、その呼び出しは `ctx.Err()` を返します。同じレスポンスを待つ他の呼び出しは継続します - 署名付きダウンロードURLを返すAPI(Bulk・TDnetのファイルURL取得)はURLが失効するためキャッシュを経由しません -- キャッシュはクライアントインスタンスの生存期間のみ有効です +- キャッシュは自動更新されません。最新データを再取得する場合は `ClearCache()` を呼び出すか、新しい HTTP クライアントを作成してください ## エラーハンドリング -APIがエラーステータスを返した場合は `*client.APIError` が返ります。各サービスはこれを `%w` でラップするため、`errors.As` でステータスコードとレスポンスボディを取り出せます。 +API がエラーステータスを返した場合は、`errors.As` で `*client.APIError` を取り出し、ステータスコードとレスポンスボディを確認できます。 ```go -quotes, err := jq.Quotes.GetDailyQuotesByCode(ctx, "7203") +_, err := jq.Quotes.GetDailyQuotesByCode(ctx, "7203") var apiErr *client.APIError if errors.As(err, &apiErr) { log.Printf("status=%d body=%s", apiErr.StatusCode, apiErr.Body) +} else if err != nil { + log.Printf("データ取得に失敗しました: %v", err) } ``` @@ -146,6 +153,7 @@ for { | カテゴリ | サービス | 説明 | |---------|---------|------| | **株価** | Quotes | 日次株価四本値 | +| **株価** | Valuation | 日次バリュエーション指標・時価総額 | | **株価** | PricesAM | 前場四本値 | | **株価** | MinuteQuotes | 株価分足 | | **銘柄情報** | Listed | 上場銘柄一覧 | @@ -162,25 +170,31 @@ for { | **市場統計** | TradesSpec | 投資部門別売買状況 | | **市場統計** | Breakdown | 売買内訳データ | | **市場統計** | TradingCalendar | 取引カレンダー | -| **信用取引** | WeeklyMarginInterest | 信用取引週末残高 | +| **信用取引** | WeeklyMarginInterest | 信用取引残高 | | **信用取引** | DailyMarginInterest | 日々公表信用取引残高 | | **空売り** | ShortSelling | 業種別空売り比率 | | **空売り** | ShortSellingPositions | 空売り残高報告 | | **適時開示** | TimelyDisclosure | TDnet適時開示情報 | -| **EDINET** | EdinetMajorShareholders | 大株主状況 | +| **EDINET** | EdinetMajorShareholders | 大株主状況(有価証券・半期・四半期報告書) | | **EDINET** | EdinetCrossShareholdings | 政策保有株式 | -| **EDINET** | EdinetLargeVolumeShareholders | 大量保有報告書 | +| **EDINET** | EdinetLargeVolumeShareholders | 大量保有報告書・変更報告書・訂正報告書 | | **ダウンロード** | Bulk | CSV一括ダウンロード | ※各APIの利用可能なプランについては、[J-Quants公式サイト](https://jpx-jquants.com/)で確認してください。 ## 使用例 +以下の例では、クイックスタートと同様に作成した `jq` と `ctx` を使用します。日付は契約プランで取得できる期間に合わせて指定してください。ポインタ型のフィールドは、値がない場合に `nil` になります。 + ### 日次株価を取得 ```go -// 特定銘柄の直近データ +// 特定銘柄の取得可能な全期間のデータ quotes, err := jq.Quotes.GetDailyQuotesByCode(ctx, "7203") +if err != nil { + log.Fatal(err) +} +fmt.Printf("取得件数: %d\n", len(quotes)) // 日付範囲指定 params := jquants.DailyQuotesParams{ @@ -189,28 +203,64 @@ params := jquants.DailyQuotesParams{ To: "2024-01-31", } response, err := jq.Quotes.GetDailyQuotes(ctx, params) +if err != nil { + log.Fatal(err) +} -// v2 APIでは短縮フィールド名を使用 for _, q := range response.Data { - fmt.Printf("日付: %s, 始値: %.2f, 高値: %.2f, 安値: %.2f, 終値: %.2f\n", - q.Date, *q.O, *q.H, *q.L, *q.C) + if q.O != nil && q.H != nil && q.L != nil && q.C != nil { + fmt.Printf("日付: %s, 始値: %.2f, 高値: %.2f, 安値: %.2f, 終値: %.2f\n", + q.Date, *q.O, *q.H, *q.L, *q.C) + } } ``` +### バリュエーション指標を取得 + +```go +values, err := jq.Valuation.GetValuationsByCodeAndDateRange(ctx, "7203", "2026-08-01", "2026-08-31") +if err != nil { + log.Fatal(err) +} +for _, v := range values { + if v.PER != nil && v.PBR != nil { + fmt.Printf("%s: PER %.2f倍、PBR %.2f倍\n", v.Date, *v.PER, *v.PBR) + } +} +``` + +`EPS`・`FwdEPS`・`BPS`・`ROE`・`FwdROE`・`PER`・`FwdPER`・`PBR`・`MktCap` を取得できます。数値項目はポインタで、算出できない項目は `nil` です。ROE は小数表現(`0.1` = 10%)、時価総額は百万円単位です。[指標の公式仕様](https://jpx-jquants.com/ja/spec/eq-valuation) + +取得可能な期間とデータの遅延は契約プランによって異なります。[公式のプラン別仕様](https://jpx-jquants.com/ja/spec/data-spec)を確認してください。 + +`Valuation.MktCap` は自己株式を除く株式数で算出されます。自己株式を含む `DailyQuote.MktCap` とは定義が異なります。株価四本値 API の `MktCap` は削除予定ですが、時期は未定です。[削除予告](https://jpx-jquants.com/ja/spec/release) + ### 上場銘柄一覧を取得 ```go // 全銘柄を取得 companies, err := jq.Listed.GetAllListedInfo(ctx) +if err != nil { + log.Fatal(err) +} +fmt.Printf("銘柄数: %d\n", len(companies)) // 特定銘柄の情報を取得 -companies, err := jq.Listed.GetListedInfoByCode(ctx, "7203") -fmt.Printf("企業名: %s\n", companies[0].Name) +companies, err = jq.Listed.GetListedInfoByCode(ctx, "7203") +if err != nil { + log.Fatal(err) +} +for _, company := range companies { + fmt.Printf("企業名: %s\n", company.CoName) +} // 市場区分で絞り込み(定数を使用) primeCompanies, err := jq.Listed.GetListedByMarket(ctx, jquants.MarketPrime, "") +if err != nil { + log.Fatal(err) +} for _, company := range primeCompanies { - fmt.Printf("%s (%s) - %s\n", company.Name, company.Code, company.MktName) + fmt.Printf("%s (%s) - %s\n", company.CoName, company.Code, company.MktNm) } ``` @@ -219,33 +269,66 @@ for _, company := range primeCompanies { ```go // 最新の財務情報 statement, err := jq.Statements.GetLatestStatements(ctx, "7203") -if statement.NetSales != nil { - fmt.Printf("売上高: %.0f円\n", *statement.NetSales) +if err != nil { + log.Fatal(err) +} +if statement.Sales != nil { + fmt.Printf("売上高: %.0f円\n", *statement.Sales) } // 特定日の財務情報 statements, err := jq.Statements.GetStatementsByDate(ctx, "2024-01-15") +if err != nil { + log.Fatal(err) +} // 開示書類種別での絞り込み for _, stmt := range statements { - // 連結決算のみ処理 - if stmt.TypeOfDocument.IsConsolidated() { - // IFRS採用企業のみ - if stmt.TypeOfDocument.GetAccountingStandard() == "IFRS" { - fmt.Printf("%s: IFRS採用企業\n", stmt.LocalCode) - } + if stmt.DocType.IsConsolidated() && stmt.DocType.GetAccountingStandard() == "IFRS" { + fmt.Printf("%s: IFRS採用企業\n", stmt.Code) + } +} +``` + +### 信用取引残高を公表日で取得 + +```go +data, err := jq.WeeklyMarginInterest.GetWeeklyMarginInterestByPublishedDate(ctx, "2026-09-28") +if err != nil { + log.Fatal(err) +} +for _, d := range data { + if d.PubDate != nil && d.LongVal != nil { + fmt.Printf("%s: 公表日 %s、買残高金額 %.0f\n", d.Code, *d.PubDate, *d.LongVal) } } ``` +信用取引残高は `WeeklyMarginInterest` で取得できます。`GetWeeklyMarginInterest` の `PublishedDate` は `Code` と併用できますが、`Date`・`From`・`To` とは併用できません。 + +日次データ、公表日 `PubDate`、金額6項目(`ShrtVal`・`LongVal`・`ShrtNegVal`・`LongNegVal`・`ShrtStdVal`・`LongStdVal`)の対象は2026年9月25日申込分以降です。それ以前のデータは週末残高のみで、公表日と金額は `nil` になります。公表日未収録の過去データは `PublishedDate` では検索できません。[公式仕様](https://jpx-jquants.com/ja/spec/mkt-margin-int-daily) + +### EDINET の会計期間・訂正情報 + +`EdinetMajorShareholderDoc.CurPerSt`・`CurPerEn` は当会計期間の開始日・終了日です。事業年度を表す `PerSt`・`PerEn` と区別できます。`DocTypeCode` は有価証券報告書 `120`、四半期報告書 `140`、半期報告書 `160` に対応します。[大株主状況の仕様](https://jpx-jquants.com/ja/spec/edinet-major-shareholders) + +大量保有の訂正報告書は `doc.LargeHldgTypeCode == jquants.LargeHldgTypeCodeCorrectionReport` で判定できます。`EdinetLargeVolumeShareholderDoc.ParDocId` は訂正元書類の管理番号(訂正報告書以外は `nil`)、`RptOblgDate` は報告義務発生日です。訂正報告書は訂正元を置き換えず、別レコードとして返されます。[大量保有報告書の仕様](https://jpx-jquants.com/ja/spec/edinet-large-volume-shareholders) + ### 日々公表信用取引残高を取得 ```go // 銘柄コードで取得 data, err := jq.DailyMarginInterest.GetDailyMarginInterestByCode(ctx, "1326") +if err != nil { + log.Fatal(err) +} +fmt.Printf("取得件数: %d\n", len(data)) // 公表日で取得 -data, err := jq.DailyMarginInterest.GetDailyMarginInterestByDate(ctx, "2024-02-08") +data, err = jq.DailyMarginInterest.GetDailyMarginInterestByDate(ctx, "2024-02-08") +if err != nil { + log.Fatal(err) +} // 公表理由の確認 for _, d := range data { @@ -257,30 +340,33 @@ for _, d := range data { ### ページネーション対応 -大量のデータを扱うAPIではページネーションがサポートされています。 +`GetDailyQuotesByCode` や `GetDailyQuotesByDate` は全ページを取得します。`GetDailyQuotes` で1ページずつ取得する場合は、レスポンスの `PaginationKey` を次のリクエストに指定します。 ```go params := jquants.DailyQuotesParams{ Date: "2024-01-15", } -// 最初のページ -response, err := jq.Quotes.GetDailyQuotes(ctx, params) -quotes := response.Data - -// 次のページがある場合 -if response.PaginationKey != "" { +var quotes []jquants.DailyQuote +for { + response, err := jq.Quotes.GetDailyQuotes(ctx, params) + if err != nil { + log.Fatal(err) + } + quotes = append(quotes, response.Data...) + if response.PaginationKey == "" { + break + } params.PaginationKey = response.PaginationKey - nextResponse, err := jq.Quotes.GetDailyQuotes(ctx, params) - quotes = append(quotes, nextResponse.Data...) } +fmt.Printf("取得件数: %d\n", len(quotes)) ``` ## 開発 ### 必要な環境 -- Go 1.24.0以上 +- Go 1.25.0 以上 - Make(オプション) ### ビルドとテスト @@ -350,8 +436,8 @@ quote.O, quote.H, quote.L, quote.C ## 注意事項 - J-Quants APIの利用には適切なサブスクリプションが必要です -- プランごとにレートリミットが設定されています(Free: 5/分, Light: 60/分, Standard: 120/分, Premium: 500/分) -- 営業日以外はデータが取得できない場合があります +- リクエスト数の上限はプラン・API・アドオンによって異なります。[公式のレートリミット](https://jpx-jquants.com/ja/spec/rate-limits)を確認してください +- データの更新日時や取得可能な期間は API と契約プランによって異なります - 詳細なAPI仕様は[公式ドキュメント](https://jpx-jquants.com/ja/spec/)を参照してください ## ライセンス diff --git a/edinet_large_volume_shareholders.go b/edinet_large_volume_shareholders.go index d45ccaf..13af1d1 100644 --- a/edinet_large_volume_shareholders.go +++ b/edinet_large_volume_shareholders.go @@ -10,7 +10,7 @@ import ( ) // EdinetLargeVolumeShareholdersService は大量保有報告書(EDINET)を取得するサービスです。 -// 大量保有報告書・変更報告書に記載されている発行者、提出者情報を取得します。 +// 大量保有報告書・変更報告書・訂正報告書の発行者、提出者情報を取得します。 type EdinetLargeVolumeShareholdersService struct { client client.HTTPClient } @@ -28,6 +28,7 @@ const ( LargeHldgTypeCodeChangeReportShortTermTransfer = "3" // 変更報告書(短期大量譲渡) LargeHldgTypeCodeSpecialReport = "4" // 大量保有報告書(特例対象株券等) LargeHldgTypeCodeSpecialChangeReport = "5" // 変更報告書(特例対象株券等) + LargeHldgTypeCodeCorrectionReport = "6" // 訂正報告書 ) // EdinetLargeVolumeShareholdersParams は大量保有報告書のリクエストパラメータです。 @@ -46,22 +47,23 @@ type EdinetLargeVolumeShareholdersResponse struct { PaginationKey string `json:"pagination_key"` // ページネーションキー } -// EdinetLargeVolumeShareholderDoc は大量保有報告書・変更報告書1書類分のデータを表します。 +// EdinetLargeVolumeShareholderDoc は大量保有報告書・変更報告書・訂正報告書を表します。 // J-Quants API /edinet/large-volume-shareholders エンドポイントのレスポンスデータ。 -// データは提出日2021年7月1日以降、対象書類は大量保有報告書・変更報告書等(書類種別コード350)。 -// Standardプラン以上で利用可能。 +// データは提出日2021年7月1日以降。Standardプラン以上で利用可能。 type EdinetLargeVolumeShareholderDoc struct { // 書類メタ情報 - DocId string `json:"DocId"` // EDINET書類管理番号(S + 7桁英数字) - Code string `json:"Code"` // 発行者(保有対象銘柄)の銘柄コード(5桁) - EdinetCode string `json:"EdinetCode"` // 発行者のEDINETコード - IsrName string `json:"IsrName"` // 発行者名 - DocTypeCode string `json:"DocTypeCode"` // 書類種別コード(350=大量保有報告書関連) - SubDate string `json:"SubDate"` // 提出日(YYYY-MM-DD形式) - SubTime string `json:"SubTime"` // 提出時刻(HH:MM:SS形式) - LargeHldgTypeCode string `json:"LargeHldgTypeCode"` // 大量保有書類種別コード(LargeHldgTypeCode定数を参照) - DocTitle string `json:"DocTitle"` // 書類表題(例: 大量保有報告書) - ChgRsn string `json:"ChgRsn"` // 報告義務発生日における変更事由(変更報告書のみ) + DocId string `json:"DocId"` // EDINET書類管理番号(S + 7桁英数字) + Code string `json:"Code"` // 発行者(保有対象銘柄)の銘柄コード(5桁) + EdinetCode string `json:"EdinetCode"` // 発行者のEDINETコード + IsrName string `json:"IsrName"` // 発行者名 + DocTypeCode string `json:"DocTypeCode"` // 書類種別コード(350=大量保有報告書関連、360=訂正) + SubDate string `json:"SubDate"` // 提出日(YYYY-MM-DD形式) + SubTime string `json:"SubTime"` // 提出時刻(HH:MM:SS形式) + RptOblgDate string `json:"RptOblgDate"` // 報告義務発生日(YYYY-MM-DD形式) + ParDocId *string `json:"ParDocId"` // 訂正元書類の管理番号。訂正報告書以外はnil + LargeHldgTypeCode string `json:"LargeHldgTypeCode"` // 大量保有書類種別コード(LargeHldgTypeCode定数を参照) + DocTitle string `json:"DocTitle"` // 書類表題(例: 大量保有報告書) + ChgRsn string `json:"ChgRsn"` // 報告義務発生日における変更事由(変更報告書のみ) // 保有状況の合計 TotalShsHeld *float64 `json:"TotalShsHeld"` // 保有株券等の数の合計(株)(合計欄の記載がない書類ではnull) @@ -139,16 +141,18 @@ type EdinetLargeVolumeShareholderCreditor struct { // RawEdinetLargeVolumeShareholderDoc is used for unmarshaling JSON response with mixed types type RawEdinetLargeVolumeShareholderDoc struct { // 書類メタ情報 - DocId string `json:"DocId"` - Code string `json:"Code"` - EdinetCode string `json:"EdinetCode"` - IsrName string `json:"IsrName"` - DocTypeCode string `json:"DocTypeCode"` - SubDate string `json:"SubDate"` - SubTime string `json:"SubTime"` - LargeHldgTypeCode string `json:"LargeHldgTypeCode"` - DocTitle string `json:"DocTitle"` - ChgRsn string `json:"ChgRsn"` + DocId string `json:"DocId"` + Code string `json:"Code"` + EdinetCode string `json:"EdinetCode"` + IsrName string `json:"IsrName"` + DocTypeCode string `json:"DocTypeCode"` + SubDate string `json:"SubDate"` + SubTime string `json:"SubTime"` + RptOblgDate string `json:"RptOblgDate"` + ParDocId types.NullableString `json:"ParDocId"` + LargeHldgTypeCode string `json:"LargeHldgTypeCode"` + DocTitle string `json:"DocTitle"` + ChgRsn string `json:"ChgRsn"` // 保有状況の合計 TotalShsHeld types.NullableFloat64 `json:"TotalShsHeld"` @@ -253,6 +257,8 @@ func (rd RawEdinetLargeVolumeShareholderDoc) toDoc() EdinetLargeVolumeShareholde DocTypeCode: rd.DocTypeCode, SubDate: rd.SubDate, SubTime: rd.SubTime, + RptOblgDate: rd.RptOblgDate, + ParDocId: rd.ParDocId.Ptr(), LargeHldgTypeCode: rd.LargeHldgTypeCode, DocTitle: rd.DocTitle, ChgRsn: rd.ChgRsn, diff --git a/edinet_large_volume_shareholders_test.go b/edinet_large_volume_shareholders_test.go index 8a3beaa..6b225e5 100644 --- a/edinet_large_volume_shareholders_test.go +++ b/edinet_large_volume_shareholders_test.go @@ -566,6 +566,34 @@ func TestEdinetLargeVolumeShareholdersService_GetLargeVolumeShareholdersByDate(t } } +func TestEdinetLargeVolumeShareholdersResponse_CorrectionReports(t *testing.T) { + raw := `{"data":[ + {"DocId":"S100ABCD","DocTypeCode":"350","LargeHldgTypeCode":"1","RptOblgDate":"2026-09-01","ParDocId":null}, + {"DocId":"S100ABCE","DocTypeCode":"360","LargeHldgTypeCode":"6","RptOblgDate":"2026-09-02","ParDocId":"S100ABCD"}, + {"DocId":"S100ABCF","DocTypeCode":"350","LargeHldgTypeCode":"2"} + ]}` + var resp EdinetLargeVolumeShareholdersResponse + if err := json.Unmarshal([]byte(raw), &resp); err != nil { + t.Fatal(err) + } + if len(resp.Data) != 3 { + t.Fatalf("got %d reports, want 3", len(resp.Data)) + } + original, correction, legacy := resp.Data[0], resp.Data[1], resp.Data[2] + if original.ParDocId != nil || original.RptOblgDate != "2026-09-01" { + t.Errorf("original report = %+v", original) + } + if correction.ParDocId == nil || *correction.ParDocId != original.DocId { + t.Errorf("correction parent = %v, want %s", correction.ParDocId, original.DocId) + } + if correction.DocTypeCode != "360" || correction.LargeHldgTypeCode != LargeHldgTypeCodeCorrectionReport || correction.RptOblgDate != "2026-09-02" { + t.Errorf("correction report = %+v", correction) + } + if legacy.ParDocId != nil || legacy.RptOblgDate != "" { + t.Errorf("omitted fields = %+v", legacy) + } +} + func TestEdinetLargeVolumeShareholderDoc_IsChangeReport(t *testing.T) { tests := []struct { name string @@ -577,6 +605,7 @@ func TestEdinetLargeVolumeShareholderDoc_IsChangeReport(t *testing.T) { {name: "change report with short term transfer", code: LargeHldgTypeCodeChangeReportShortTermTransfer, want: true}, {name: "special report", code: LargeHldgTypeCodeSpecialReport, want: false}, {name: "special change report", code: LargeHldgTypeCodeSpecialChangeReport, want: true}, + {name: "correction report", code: LargeHldgTypeCodeCorrectionReport, want: false}, {name: "unknown", code: LargeHldgTypeCodeUnknown, want: false}, } diff --git a/edinet_major_shareholders.go b/edinet_major_shareholders.go index 9d8bb33..dd09080 100644 --- a/edinet_major_shareholders.go +++ b/edinet_major_shareholders.go @@ -10,7 +10,7 @@ import ( ) // EdinetMajorShareholdersService は大株主状況(EDINET)を取得するサービスです。 -// 有価証券報告書に記載されている大株主の状況を取得します。 +// 有価証券報告書・半期報告書・四半期報告書が対象です。 type EdinetMajorShareholdersService struct { client client.HTTPClient } @@ -22,7 +22,7 @@ func NewEdinetMajorShareholdersService(c client.HTTPClient) *EdinetMajorSharehol // EdinetMajorShareholdersParams は大株主状況のリクエストパラメータです。 // すべて任意ですが、edinet_codeとcodeの同時指定はできません。 -// すべて省略した場合はAPI実行日に提出された全有報のデータ一覧が返ります。 +// すべて省略した場合はAPI実行日に提出された対象書類のデータ一覧が返ります。 type EdinetMajorShareholdersParams struct { EdinetCode string // EDINETコード(例: E03814)(codeとの同時指定は不可) Code string // 4桁もしくは5桁の銘柄コード(edinet_codeとの同時指定は不可) @@ -36,9 +36,9 @@ type EdinetMajorShareholdersResponse struct { PaginationKey string `json:"pagination_key"` // ページネーションキー } -// EdinetMajorShareholderDoc は有価証券報告書ごとの大株主状況データを表します。 +// EdinetMajorShareholderDoc は報告書ごとの大株主状況データを表します。 // J-Quants API /edinet/major-shareholders エンドポイントのレスポンスデータ。 -// データは2016年6月1日以降、対象書類は有価証券報告書 第三号様式。Standardプラン以上で利用可能。 +// データは2016年6月1日以降。Standardプラン以上で利用可能。 type EdinetMajorShareholderDoc struct { // 書類メタ情報 DocId string `json:"DocId"` // EDINET書類管理番号(S + 7桁英数字) @@ -46,11 +46,13 @@ type EdinetMajorShareholderDoc struct { EdinetCode string `json:"EdinetCode"` // 提出会社のEDINETコード FilerName string `json:"FilerName"` // 提出者名(会社名) FilerNameEn string `json:"FilerNameEn"` // 提出者名(英語) - DocTypeCode string `json:"DocTypeCode"` // 書類種別コード(120=有価証券報告書) + DocTypeCode string `json:"DocTypeCode"` // 書類種別コード(120=有価証券、140=四半期、160=半期) SubDate string `json:"SubDate"` // 提出日(YYYY-MM-DD形式) SubTime string `json:"SubTime"` // 提出時刻(HH:MM:SS形式) PerSt string `json:"PerSt"` // 対象事業年度の開始日(YYYY-MM-DD形式) PerEn string `json:"PerEn"` // 対象事業年度の終了日(YYYY-MM-DD形式) + CurPerSt string `json:"CurPerSt"` // 当会計期間の開始日(YYYY-MM-DD形式) + CurPerEn string `json:"CurPerEn"` // 当会計期間の終了日(YYYY-MM-DD形式) // 大株主レコード(順位順、Rank昇順) Hldrs []EdinetMajorShareholderHolder `json:"Hldrs"` @@ -79,6 +81,8 @@ type RawEdinetMajorShareholderDoc struct { SubTime string `json:"SubTime"` PerSt string `json:"PerSt"` PerEn string `json:"PerEn"` + CurPerSt string `json:"CurPerSt"` + CurPerEn string `json:"CurPerEn"` // 大株主レコード Hldrs []RawEdinetMajorShareholderHolder `json:"Hldrs"` @@ -135,6 +139,8 @@ func (r *EdinetMajorShareholdersResponse) UnmarshalJSON(data []byte) error { SubTime: rd.SubTime, PerSt: rd.PerSt, PerEn: rd.PerEn, + CurPerSt: rd.CurPerSt, + CurPerEn: rd.CurPerEn, // 大株主レコード Hldrs: holders, @@ -145,7 +151,7 @@ func (r *EdinetMajorShareholdersResponse) UnmarshalJSON(data []byte) error { } // GetMajorShareholders は大株主状況を取得します。 -// パラメータをすべて省略した場合はAPI実行日に提出された全有報のデータ一覧を取得します。 +// パラメータをすべて省略した場合はAPI実行日に提出された対象書類を取得します。 func (s *EdinetMajorShareholdersService) GetMajorShareholders(ctx context.Context, params EdinetMajorShareholdersParams) (*EdinetMajorShareholdersResponse, error) { // edinet_codeとcodeの同時指定は不可 if params.EdinetCode != "" && params.Code != "" { diff --git a/edinet_major_shareholders_test.go b/edinet_major_shareholders_test.go index 4f6752f..4d4dbec 100644 --- a/edinet_major_shareholders_test.go +++ b/edinet_major_shareholders_test.go @@ -265,6 +265,34 @@ func TestEdinetMajorShareholdersService_GetMajorShareholders_DecodesNestedHolder } } +func TestEdinetMajorShareholdersResponse_ReportingPeriods(t *testing.T) { + raw := `{"data":[ + {"DocTypeCode":"120","PerSt":"2025-04-01","PerEn":"2026-03-31","CurPerSt":"2025-04-01","CurPerEn":"2026-03-31"}, + {"DocTypeCode":"160","PerSt":"2025-04-01","PerEn":"2026-03-31","CurPerSt":"2025-04-01","CurPerEn":"2025-09-30"}, + {"DocTypeCode":"140","PerSt":"2025-04-01","PerEn":"2026-03-31","CurPerSt":"2025-07-01","CurPerEn":"2025-09-30"} + ]}` + var resp EdinetMajorShareholdersResponse + if err := json.Unmarshal([]byte(raw), &resp); err != nil { + t.Fatal(err) + } + want := []struct{ code, start, end string }{ + {"120", "2025-04-01", "2026-03-31"}, + {"160", "2025-04-01", "2025-09-30"}, + {"140", "2025-07-01", "2025-09-30"}, + } + if len(resp.Data) != len(want) { + t.Fatalf("got %d reports, want %d", len(resp.Data), len(want)) + } + for i, doc := range resp.Data { + if doc.DocTypeCode != want[i].code || doc.CurPerSt != want[i].start || doc.CurPerEn != want[i].end { + t.Errorf("report %d: got %+v, want %+v", i, doc, want[i]) + } + if doc.PerSt != "2025-04-01" || doc.PerEn != "2026-03-31" { + t.Errorf("report %d: fiscal year = %s to %s", i, doc.PerSt, doc.PerEn) + } + } +} + func TestEdinetMajorShareholdersService_GetMajorShareholdersByCode(t *testing.T) { // Setup mockClient := client.NewMockClient() diff --git a/go.mod b/go.mod index 29338a2..eb109ef 100644 --- a/go.mod +++ b/go.mod @@ -1,6 +1,6 @@ module github.com/utahta/jquants -go 1.24.0 +go 1.25.0 require ( golang.org/x/net v0.41.0 // indirect diff --git a/jquants.go b/jquants.go index a465ad2..d8ac95a 100644 --- a/jquants.go +++ b/jquants.go @@ -5,6 +5,7 @@ import "github.com/utahta/jquants/client" // JQuantsAPI はJ-Quants APIの各サービスを統合したインターフェースです。 // 各サービスの説明: // - Quotes: 株価データ(日次の始値、高値、安値、終値、出来高) +// - Valuation: バリュエーション指標(実績・予想指標、時価総額) // - PricesAM: 前場四本値データ(午前中の取引データ) // - Listed: 企業情報(企業名、業種、市場区分) // - Statements: 財務諸表(売上高、利益、ROE/ROA) @@ -12,7 +13,7 @@ import "github.com/utahta/jquants/client" // - Announcement: 翌営業日の決算発表予定(3月期・9月期決算会社のみ) // - EarningsDate: 決算発表予定日(全上場銘柄、公表・変更履歴を含む) // - TradesSpec: 投資部門別売買状況(機関投資家、個人投資家等の売買動向) -// - WeeklyMarginInterest: 信用取引週末残高(信用買い/売り残高) +// - WeeklyMarginInterest: 信用取引残高(信用買い/売り残高) // - DailyMarginInterest: 日々公表信用取引残高(日々公表銘柄の信用残高) // - ShortSelling: 業種別空売り比率(業種ごとの空売り状況) // - ShortSellingPositions: 空売り残高報告(大口の空売りポジション) @@ -26,13 +27,14 @@ import "github.com/utahta/jquants/client" // - FSDetails: 財務諸表詳細(BS/PL詳細データ) // - MinuteQuotes: 株価分足(アドオン契約が必要) // - TimelyDisclosure: TDnet適時開示情報(アドオン契約が必要) -// - EdinetMajorShareholders: 大株主状況(有価証券報告書ベース) +// - EdinetMajorShareholders: 大株主状況(有価証券・半期・四半期報告書) // - EdinetCrossShareholdings: 政策保有株式(有価証券報告書ベース) // - EdinetLargeVolumeShareholders: 大量保有報告書 // - Bulk: CSV一括ダウンロード type JQuantsAPI struct { client client.HTTPClient Quotes *QuotesService + Valuation *ValuationService PricesAM *PricesAMService MinuteQuotes *MinuteQuotesService Listed *ListedService @@ -64,6 +66,7 @@ func NewJQuantsAPI(c client.HTTPClient) *JQuantsAPI { return &JQuantsAPI{ client: c, Quotes: NewQuotesService(c), + Valuation: NewValuationService(c), PricesAM: NewPricesAMService(c), MinuteQuotes: NewMinuteQuotesService(c), Listed: NewListedService(c), diff --git a/quotes.go b/quotes.go index f42cc37..3abe1d3 100644 --- a/quotes.go +++ b/quotes.go @@ -84,9 +84,11 @@ type DailyQuote struct { AAdjC *float64 `json:"AAdjC"` // 調整済み後場終値 AAdjVo *float64 `json:"AAdjVo"` // 調整済み後場売買高 - // 時価総額・コーポレートアクション - MktCap *float64 `json:"MktCap"` // 時価総額(百万円)。ETF・ETN等および取引が存在しない日はnil - ExRT *string `json:"ExRT"` // 権利落種類(ExRightsType定数を参照)。権利落ち日以外はnil + // MktCapは自己株式を含む時価総額(百万円)です。 + // + // Deprecated: APIで削除予定(時期未定)。Valuation.MktCapを使用してください。 + MktCap *float64 `json:"MktCap"` + ExRT *string `json:"ExRT"` // 権利落種類(ExRightsType定数を参照)。権利落ち日以外はnil } // RawDailyQuote is used for unmarshaling JSON response with mixed types diff --git a/test/e2e/edinet_test.go b/test/e2e/edinet_test.go index 6ec2528..6626d86 100644 --- a/test/e2e/edinet_test.go +++ b/test/e2e/edinet_test.go @@ -7,6 +7,8 @@ import ( "context" "strings" "testing" + + "github.com/utahta/jquants" ) // TestEdinetMajorShareholdersEndpoint は/edinet/major-shareholdersエンドポイントのテスト @@ -35,6 +37,9 @@ func TestEdinetMajorShareholdersEndpoint(t *testing.T) { if doc.SubDate == "" || doc.PerSt == "" || doc.PerEn == "" { t.Errorf("Doc[%d]: SubDate/PerSt/PerEn should not be empty", i) } + if doc.CurPerSt == "" || doc.CurPerEn == "" { + t.Errorf("Doc[%d]: CurPerSt/CurPerEn should not be empty", i) + } if len(doc.Hldrs) == 0 { t.Errorf("Doc[%d]: Hldrs is empty", i) } @@ -116,11 +121,19 @@ func TestEdinetLargeVolumeShareholdersEndpoint(t *testing.T) { if doc.SubDate != date { t.Errorf("Doc[%d]: SubDate = %v, want %v", i, doc.SubDate, date) } + if doc.RptOblgDate == "" { + t.Errorf("Doc[%d]: RptOblgDate is empty", i) + } + if doc.LargeHldgTypeCode == jquants.LargeHldgTypeCodeCorrectionReport { + if doc.DocTypeCode != "360" || doc.ParDocId == nil || *doc.ParDocId == "" { + t.Errorf("Doc[%d]: correction should have DocTypeCode 360 and ParDocId", i) + } + } // 合計欄はnullの書類がある。値がある場合のみ範囲を検証する if doc.TotalShsRatio != nil { withTotals++ - if *doc.TotalShsRatio <= 0 || *doc.TotalShsRatio > 1 { - t.Errorf("Doc[%d]: TotalShsRatio = %v, want (0, 1]", i, *doc.TotalShsRatio) + if *doc.TotalShsRatio < 0 || *doc.TotalShsRatio > 1 { + t.Errorf("Doc[%d]: TotalShsRatio = %v, want [0, 1]", i, *doc.TotalShsRatio) } } if len(doc.Hldrs) == 0 { diff --git a/test/e2e/valuation_test.go b/test/e2e/valuation_test.go new file mode 100644 index 0000000..4165456 --- /dev/null +++ b/test/e2e/valuation_test.go @@ -0,0 +1,29 @@ +//go:build e2e + +package e2e + +import ( + "context" + "strings" + "testing" +) + +func TestValuationEndpoint(t *testing.T) { + data, err := jq.Valuation.GetValuationsByCodeAndDate(context.Background(), "7203", testDate) + if err != nil { + if isSubscriptionLimited(err) { + t.Skip("Skipping due to subscription limitation") + } + t.Fatal(err) + } + if len(data) != 1 { + t.Fatalf("got %d records, want 1 for 7203 on %s", len(data), testDate) + } + v := data[0] + if v.Code != "72030" || strings.ReplaceAll(v.Date, "-", "") != testDate { + t.Errorf("got %s on %s, want 72030 on %s", v.Code, v.Date, testDate) + } + if v.EPS == nil || v.BPS == nil || v.MktCap == nil { + t.Errorf("missing valuation data for 7203: %+v", v) + } +} diff --git a/valuation.go b/valuation.go new file mode 100644 index 0000000..e670337 --- /dev/null +++ b/valuation.go @@ -0,0 +1,156 @@ +package jquants + +import ( + "context" + "encoding/json" + "fmt" + "net/url" + + "github.com/utahta/jquants/client" + "github.com/utahta/jquants/types" +) + +// ValuationService は日次のバリュエーション指標を取得するサービスです。 +type ValuationService struct { + client client.HTTPClient +} + +func NewValuationService(c client.HTTPClient) *ValuationService { + return &ValuationService{client: c} +} + +// Valuation は /equities/valuation の指標を表します。 +// 実績は直近12ヶ月、予想は進行期が対象です。算出できない項目はnilです。 +type Valuation struct { + Date string `json:"Date"` + Code string `json:"Code"` + EPS *float64 `json:"EPS"` // 1株当たり利益(実績・円) + FwdEPS *float64 `json:"FwdEPS"` // 1株当たり利益(予想・円) + BPS *float64 `json:"BPS"` // 1株当たり純資産(円) + ROE *float64 `json:"ROE"` // 自己資本利益率(実績・小数。0.1 = 10%) + FwdROE *float64 `json:"FwdROE"` // 自己資本利益率(予想・小数) + PER *float64 `json:"PER"` // 株価収益率(実績・倍) + FwdPER *float64 `json:"FwdPER"` // 株価収益率(予想・倍) + PBR *float64 `json:"PBR"` // 株価純資産倍率(倍) + MktCap *float64 `json:"MktCap"` // 時価総額(百万円)。自己株式を控除した株式数で算出 +} + +// RawValuation は数値と数値文字列が混在するレスポンスの読み取りに使用します。 +type RawValuation struct { + Date string `json:"Date"` + Code string `json:"Code"` + EPS types.NullableFloat64 `json:"EPS"` + FwdEPS types.NullableFloat64 `json:"FwdEPS"` + BPS types.NullableFloat64 `json:"BPS"` + ROE types.NullableFloat64 `json:"ROE"` + FwdROE types.NullableFloat64 `json:"FwdROE"` + PER types.NullableFloat64 `json:"PER"` + FwdPER types.NullableFloat64 `json:"FwdPER"` + PBR types.NullableFloat64 `json:"PBR"` + MktCap types.NullableFloat64 `json:"MktCap"` +} + +type ValuationResponse struct { + Data []Valuation `json:"data"` + PaginationKey string `json:"pagination_key"` +} + +func (r *ValuationResponse) UnmarshalJSON(data []byte) error { + var raw struct { + Data []RawValuation `json:"data"` + PaginationKey string `json:"pagination_key"` + } + if err := json.Unmarshal(data, &raw); err != nil { + return err + } + + r.PaginationKey = raw.PaginationKey + r.Data = make([]Valuation, len(raw.Data)) + for i, v := range raw.Data { + r.Data[i] = Valuation{ + Date: v.Date, + Code: v.Code, + EPS: v.EPS.Ptr(), + FwdEPS: v.FwdEPS.Ptr(), + BPS: v.BPS.Ptr(), + ROE: v.ROE.Ptr(), + FwdROE: v.FwdROE.Ptr(), + PER: v.PER.Ptr(), + FwdPER: v.FwdPER.Ptr(), + PBR: v.PBR.Ptr(), + MktCap: v.MktCap.Ptr(), + } + } + return nil +} + +// ValuationParams はCodeまたはDateの指定が必要です。 +type ValuationParams struct { + Code string // 銘柄コード(4桁または5桁) + Date string // 日付(YYYYMMDD または YYYY-MM-DD) + From string // 開始日付(Code指定時) + To string // 終了日付(Code指定時) + PaginationKey string +} + +func (s *ValuationService) GetValuations(ctx context.Context, params ValuationParams) (*ValuationResponse, error) { + if params.Code == "" && params.Date == "" { + return nil, fmt.Errorf("either code or date parameter is required") + } + + query := url.Values{} + if params.Code != "" { + query.Set("code", params.Code) + } + if params.Date != "" { + query.Set("date", params.Date) + } + if params.From != "" { + query.Set("from", params.From) + } + if params.To != "" { + query.Set("to", params.To) + } + if params.PaginationKey != "" { + query.Set("pagination_key", params.PaginationKey) + } + + var resp ValuationResponse + if err := s.client.DoRequest(ctx, "GET", "/equities/valuation?"+query.Encode(), nil, &resp); err != nil { + return nil, fmt.Errorf("failed to get valuations: %w", err) + } + return &resp, nil +} + +// GetValuationsByCode は指定銘柄の全期間のデータを取得します。 +func (s *ValuationService) GetValuationsByCode(ctx context.Context, code string) ([]Valuation, error) { + return s.getAllValuations(ctx, ValuationParams{Code: code}) +} + +// GetValuationsByDate は指定日の全銘柄のデータを取得します。 +func (s *ValuationService) GetValuationsByDate(ctx context.Context, date string) ([]Valuation, error) { + return s.getAllValuations(ctx, ValuationParams{Date: date}) +} + +func (s *ValuationService) GetValuationsByCodeAndDate(ctx context.Context, code, date string) ([]Valuation, error) { + return s.getAllValuations(ctx, ValuationParams{Code: code, Date: date}) +} + +func (s *ValuationService) GetValuationsByCodeAndDateRange(ctx context.Context, code, from, to string) ([]Valuation, error) { + return s.getAllValuations(ctx, ValuationParams{Code: code, From: from, To: to}) +} + +func (s *ValuationService) getAllValuations(ctx context.Context, params ValuationParams) ([]Valuation, error) { + var allData []Valuation + for { + resp, err := s.GetValuations(ctx, params) + if err != nil { + return nil, err + } + allData = append(allData, resp.Data...) + if resp.PaginationKey == "" { + return allData, nil + } + params.PaginationKey = resp.PaginationKey + } +} diff --git a/valuation_test.go b/valuation_test.go new file mode 100644 index 0000000..affe0ac --- /dev/null +++ b/valuation_test.go @@ -0,0 +1,179 @@ +package jquants + +import ( + "context" + "encoding/json" + "errors" + "reflect" + "testing" + "time" + + "github.com/utahta/jquants/client" +) + +func TestValuationResponse_UnmarshalJSON(t *testing.T) { + raw := `{"data":[ + {"Date":"2023-03-24","Code":"86970","EPS":89.4,"FwdEPS":87.9, + "BPS":590.65,"ROE":0.1534,"FwdROE":0.1488,"PER":22.88, + "FwdPER":23.26,"PBR":3.46,"MktCap":1077137.0}, + {"Date":"2023-03-27","Code":"86970","EPS":"-12.3","FwdEPS":"0", + "BPS":"590.65","ROE":"-0.1","FwdROE":"0","PER":null, + "FwdPER":"","PBR":"3.46","MktCap":"1077137.0"}, + {"Date":"2023-03-24","Code":"13060","EPS":null,"FwdEPS":null, + "BPS":null,"ROE":null,"FwdROE":null,"PER":null, + "FwdPER":null,"PBR":null,"MktCap":null}, + {"Date":"2023-03-24","Code":"99990"} + ],"pagination_key":"next"}` + want := []Valuation{ + { + Date: "2023-03-24", Code: "86970", + EPS: floatPtr(89.4), FwdEPS: floatPtr(87.9), BPS: floatPtr(590.65), + ROE: floatPtr(0.1534), FwdROE: floatPtr(0.1488), PER: floatPtr(22.88), + FwdPER: floatPtr(23.26), PBR: floatPtr(3.46), MktCap: floatPtr(1077137), + }, + { + Date: "2023-03-27", Code: "86970", + EPS: floatPtr(-12.3), FwdEPS: floatPtr(0), BPS: floatPtr(590.65), + ROE: floatPtr(-0.1), FwdROE: floatPtr(0), + PBR: floatPtr(3.46), MktCap: floatPtr(1077137), + }, + {Date: "2023-03-24", Code: "13060"}, + {Date: "2023-03-24", Code: "99990"}, + } + var resp ValuationResponse + if err := json.Unmarshal([]byte(raw), &resp); err != nil { + t.Fatal(err) + } + if !reflect.DeepEqual(resp.Data, want) { + t.Errorf("data = %+v, want %+v", resp.Data, want) + } + if resp.PaginationKey != "next" { + t.Errorf("pagination key = %q, want next", resp.PaginationKey) + } +} + +func TestValuationService_GetValuations(t *testing.T) { + tests := []struct { + name string + params ValuationParams + path string + }{ + {"code", ValuationParams{Code: "8697"}, "/equities/valuation?code=8697"}, + {"date", ValuationParams{Date: "2026-09-14"}, "/equities/valuation?date=2026-09-14"}, + {"code and date", ValuationParams{Code: "86970", Date: "20260914"}, "/equities/valuation?code=86970&date=20260914"}, + {"range", ValuationParams{Code: "86970", From: "20260901", To: "20260914"}, "/equities/valuation?code=86970&from=20260901&to=20260914"}, + {"pagination", ValuationParams{Date: "20260914", PaginationKey: "next+part/=&"}, "/equities/valuation?date=20260914&pagination_key=next%2Bpart%2F%3D%26"}, + } + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + c := client.NewMockClient() + c.SetResponse("GET", tt.path, json.RawMessage(`{"data":[{"Code":"86970","EPS":"89.4"}]}`)) + jq := NewJQuantsAPI(c) + if jq.Valuation == nil { + t.Fatal("Valuation service is not registered") + } + resp, err := jq.Valuation.GetValuations(context.Background(), tt.params) + if err != nil { + t.Fatal(err) + } + if c.LastPath != tt.path || c.LastMethod != "GET" { + t.Errorf("request = %s %s, want GET %s", c.LastMethod, c.LastPath, tt.path) + } + if len(resp.Data) != 1 || !compareFloat64Ptr(resp.Data[0].EPS, floatPtr(89.4)) { + t.Errorf("data = %+v, want EPS 89.4", resp.Data) + } + }) + } +} + +func TestValuationService_GetValuationsRequiresCodeOrDate(t *testing.T) { + for _, params := range []ValuationParams{{}, {From: "20260901", To: "20260914"}} { + c := client.NewMockClient() + _, err := NewValuationService(c).GetValuations(context.Background(), params) + if err == nil || c.RequestCount != 0 { + t.Errorf("params %+v: error = %v, requests = %d; want validation error without request", params, err, c.RequestCount) + } + } +} + +func TestValuationService_Pagination(t *testing.T) { + tests := []struct { + name string + path string + next string + get func(context.Context, *ValuationService) ([]Valuation, error) + }{ + { + name: "code", path: "/equities/valuation?code=86970", + next: "/equities/valuation?code=86970&pagination_key=next", + get: func(ctx context.Context, s *ValuationService) ([]Valuation, error) { + return s.GetValuationsByCode(ctx, "86970") + }, + }, + { + name: "date", path: "/equities/valuation?date=20260914", + next: "/equities/valuation?date=20260914&pagination_key=next", + get: func(ctx context.Context, s *ValuationService) ([]Valuation, error) { + return s.GetValuationsByDate(ctx, "20260914") + }, + }, + { + name: "code and date", path: "/equities/valuation?code=86970&date=20260914", + next: "/equities/valuation?code=86970&date=20260914&pagination_key=next", + get: func(ctx context.Context, s *ValuationService) ([]Valuation, error) { + return s.GetValuationsByCodeAndDate(ctx, "86970", "20260914") + }, + }, + { + name: "range", path: "/equities/valuation?code=86970&from=20260901&to=20260914", + next: "/equities/valuation?code=86970&from=20260901&pagination_key=next&to=20260914", + get: func(ctx context.Context, s *ValuationService) ([]Valuation, error) { + return s.GetValuationsByCodeAndDateRange(ctx, "86970", "20260901", "20260914") + }, + }, + } + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + c := client.NewMockClient() + c.SetResponse("GET", tt.path, json.RawMessage(`{"data":[{"Code":"86970","EPS":89.4}],"pagination_key":"next"}`)) + c.SetResponse("GET", tt.next, json.RawMessage(`{"data":[{"Code":"72030","EPS":100}],"pagination_key":""}`)) + ctx, cancel := context.WithTimeout(context.Background(), time.Second) + defer cancel() + data, err := tt.get(ctx, NewValuationService(c)) + if err != nil { + t.Fatal(err) + } + if len(data) != 2 || data[0].Code != "86970" || data[1].Code != "72030" { + t.Errorf("data = %+v, want both pages in order", data) + } + if c.RequestCount != 2 || c.LastPath != tt.next { + t.Errorf("requests = %d, last path = %s", c.RequestCount, c.LastPath) + } + }) + } +} + +func TestValuationService_Errors(t *testing.T) { + t.Run("API error on second page", func(t *testing.T) { + c := client.NewMockClient() + c.SetResponse("GET", "/equities/valuation?code=86970", json.RawMessage(`{"data":[{"Code":"86970"}],"pagination_key":"next"}`)) + apiErr := &client.APIError{StatusCode: 429, Body: `{"message":"Too Many Requests"}`} + c.SetError("GET", "/equities/valuation?code=86970&pagination_key=next", apiErr) + ctx, cancel := context.WithTimeout(context.Background(), time.Second) + defer cancel() + data, err := NewValuationService(c).GetValuationsByCode(ctx, "86970") + var got *client.APIError + if data != nil || !errors.As(err, &got) || got != apiErr { + t.Errorf("data = %+v, error = %v; want original API error and no partial data", data, err) + } + }) + for _, raw := range []string{`{"data":[{"EPS":"not-a-number"}]}`, `{"data":[{"MktCap":{}}]}`} { + t.Run(raw, func(t *testing.T) { + c := client.NewMockClient() + c.SetResponse("GET", "/equities/valuation?code=86970", json.RawMessage(raw)) + if _, err := NewValuationService(c).GetValuations(context.Background(), ValuationParams{Code: "86970"}); err == nil { + t.Fatal("expected a decoding error") + } + }) + } +} diff --git a/weekly_margin_interest.go b/weekly_margin_interest.go index 9277092..9c425fa 100644 --- a/weekly_margin_interest.go +++ b/weekly_margin_interest.go @@ -9,7 +9,7 @@ import ( "github.com/utahta/jquants/types" ) -// WeeklyMarginInterestService は信用取引週末残高を取得するサービスです。 +// WeeklyMarginInterestService は信用取引残高を取得するサービスです。 type WeeklyMarginInterestService struct { client client.HTTPClient } @@ -19,16 +19,17 @@ func NewWeeklyMarginInterestService(c client.HTTPClient) *WeeklyMarginInterestSe return &WeeklyMarginInterestService{client: c} } -// WeeklyMarginInterestParams は信用取引週末残高のリクエストパラメータです。 +// WeeklyMarginInterestParams はCode、Date、PublishedDateのいずれかが必須です。 type WeeklyMarginInterestParams struct { - Code string // 銘柄コード(codeまたはdateのいずれかが必須) - Date string // 申込日付(YYYYMMDD または YYYY-MM-DD)(codeまたはdateのいずれかが必須) + Code string // 銘柄コード + Date string // 申込日付(YYYYMMDD または YYYY-MM-DD) + PublishedDate string // 公表日(Date/From/Toとの同時指定不可) From string // 期間の開始日(YYYYMMDD または YYYY-MM-DD) To string // 期間の終了日(YYYYMMDD または YYYY-MM-DD) PaginationKey string // ページネーションキー } -// WeeklyMarginInterestResponse は信用取引週末残高のレスポンスです。 +// WeeklyMarginInterestResponse は信用取引残高のレスポンスです。 type WeeklyMarginInterestResponse struct { Data []WeeklyMarginInterest `json:"data"` PaginationKey string `json:"pagination_key"` // ページネーションキー @@ -41,31 +42,42 @@ const ( IssueTypeOther = "3" // その他(一般信用取引のみまたは取引不可) ) -// WeeklyMarginInterest は信用取引週末残高のデータを表します。 +// WeeklyMarginInterest は信用取引残高のデータを表します。 // J-Quants API /markets/margin-interest エンドポイントのレスポンスデータ。 +// 公表日と金額は2026年9月25日申込分以降が対象で、それ以前はnilです。 type WeeklyMarginInterest struct { // 基本情報 - Date string `json:"Date"` // 申込日付(YYYY-MM-DD形式) - Code string `json:"Code"` // 銘柄コード - IssType string `json:"IssType"` // 銘柄区分(1: 信用銘柄、2: 貸借銘柄、3: その他) + PubDate *string `json:"PubDate"` // 公表日(YYYY-MM-DD形式) + Date string `json:"Date"` // 申込日付(YYYY-MM-DD形式) + Code string `json:"Code"` // 銘柄コード + IssType string `json:"IssType"` // 銘柄区分(1: 信用銘柄、2: 貸借銘柄、3: その他) // 信用取引残高(売建) - ShrtVol float64 `json:"ShrtVol"` // 売合計信用取引週末残高 - ShrtNegVol float64 `json:"ShrtNegVol"` // 売一般信用取引週末残高 - ShrtStdVol float64 `json:"ShrtStdVol"` // 売制度信用取引週末残高 + ShrtVol float64 `json:"ShrtVol"` // 売合計信用取引残高 + ShrtNegVol float64 `json:"ShrtNegVol"` // 売一般信用取引残高 + ShrtStdVol float64 `json:"ShrtStdVol"` // 売制度信用取引残高 // 信用取引残高(買建) - LongVol float64 `json:"LongVol"` // 買合計信用取引週末残高 - LongNegVol float64 `json:"LongNegVol"` // 買一般信用取引週末残高 - LongStdVol float64 `json:"LongStdVol"` // 買制度信用取引週末残高 + LongVol float64 `json:"LongVol"` // 買合計信用取引残高 + LongNegVol float64 `json:"LongNegVol"` // 買一般信用取引残高 + LongStdVol float64 `json:"LongStdVol"` // 買制度信用取引残高 + + // 信用取引残高(金額) + ShrtVal *float64 `json:"ShrtVal"` // 売合計 + LongVal *float64 `json:"LongVal"` // 買合計 + ShrtNegVal *float64 `json:"ShrtNegVal"` // 売一般信用 + LongNegVal *float64 `json:"LongNegVal"` // 買一般信用 + ShrtStdVal *float64 `json:"ShrtStdVal"` // 売制度信用 + LongStdVal *float64 `json:"LongStdVal"` // 買制度信用 } // RawWeeklyMarginInterest is used for unmarshaling JSON response with mixed types type RawWeeklyMarginInterest struct { // 基本情報 - Date string `json:"Date"` - Code string `json:"Code"` - IssType string `json:"IssType"` + PubDate types.NullableString `json:"PubDate"` + Date string `json:"Date"` + Code string `json:"Code"` + IssType string `json:"IssType"` // 信用取引残高(売建) ShrtVol types.NullableFloat64 `json:"ShrtVol"` @@ -76,6 +88,13 @@ type RawWeeklyMarginInterest struct { LongVol types.NullableFloat64 `json:"LongVol"` LongNegVol types.NullableFloat64 `json:"LongNegVol"` LongStdVol types.NullableFloat64 `json:"LongStdVol"` + + ShrtVal types.NullableFloat64 `json:"ShrtVal"` + LongVal types.NullableFloat64 `json:"LongVal"` + ShrtNegVal types.NullableFloat64 `json:"ShrtNegVal"` + LongNegVal types.NullableFloat64 `json:"LongNegVal"` + ShrtStdVal types.NullableFloat64 `json:"ShrtStdVal"` + LongStdVal types.NullableFloat64 `json:"LongStdVal"` } // UnmarshalJSON implements custom JSON unmarshaling for WeeklyMarginInterestResponse @@ -99,6 +118,7 @@ func (r *WeeklyMarginInterestResponse) UnmarshalJSON(data []byte) error { for idx, rm := range raw.Data { r.Data[idx] = WeeklyMarginInterest{ // 基本情報 + PubDate: rm.PubDate.Ptr(), Date: rm.Date, Code: rm.Code, IssType: rm.IssType, @@ -112,17 +132,25 @@ func (r *WeeklyMarginInterestResponse) UnmarshalJSON(data []byte) error { LongVol: rm.LongVol.Or(0), LongNegVol: rm.LongNegVol.Or(0), LongStdVol: rm.LongStdVol.Or(0), + ShrtVal: rm.ShrtVal.Ptr(), + LongVal: rm.LongVal.Ptr(), + ShrtNegVal: rm.ShrtNegVal.Ptr(), + LongNegVal: rm.LongNegVal.Ptr(), + ShrtStdVal: rm.ShrtStdVal.Ptr(), + LongStdVal: rm.LongStdVal.Ptr(), } } return nil } -// GetWeeklyMarginInterest は信用取引週末残高を取得します。 +// GetWeeklyMarginInterest は信用取引残高を取得します。 func (s *WeeklyMarginInterestService) GetWeeklyMarginInterest(ctx context.Context, params WeeklyMarginInterestParams) (*WeeklyMarginInterestResponse, error) { - // codeまたはdateのいずれかが必須 - if params.Code == "" && params.Date == "" { - return nil, fmt.Errorf("either code or date parameter is required") + if params.Code == "" && params.Date == "" && params.PublishedDate == "" { + return nil, fmt.Errorf("either code, date or published_date parameter is required") + } + if params.PublishedDate != "" && (params.Date != "" || params.From != "" || params.To != "") { + return nil, fmt.Errorf("published_date cannot be combined with date, from or to") } path := "/markets/margin-interest" @@ -134,6 +162,9 @@ func (s *WeeklyMarginInterestService) GetWeeklyMarginInterest(ctx context.Contex if params.Date != "" { query += fmt.Sprintf("date=%s&", params.Date) } + if params.PublishedDate != "" { + query += fmt.Sprintf("published_date=%s&", params.PublishedDate) + } if params.From != "" { query += fmt.Sprintf("from=%s&", params.From) } @@ -156,7 +187,7 @@ func (s *WeeklyMarginInterestService) GetWeeklyMarginInterest(ctx context.Contex return &resp, nil } -// GetWeeklyMarginInterestByCode は指定銘柄の信用取引週末残高を取得します。 +// GetWeeklyMarginInterestByCode は指定銘柄の信用取引残高を取得します。 // ページネーションを使用して全データを取得します。 func (s *WeeklyMarginInterestService) GetWeeklyMarginInterestByCode(ctx context.Context, code string) ([]WeeklyMarginInterest, error) { var allData []WeeklyMarginInterest @@ -185,7 +216,7 @@ func (s *WeeklyMarginInterestService) GetWeeklyMarginInterestByCode(ctx context. return allData, nil } -// GetWeeklyMarginInterestByDate は指定日の全銘柄信用取引週末残高を取得します。 +// GetWeeklyMarginInterestByDate は指定日の全銘柄信用取引残高を取得します。 // ページネーションを使用して全データを取得します。 func (s *WeeklyMarginInterestService) GetWeeklyMarginInterestByDate(ctx context.Context, date string) ([]WeeklyMarginInterest, error) { var allData []WeeklyMarginInterest @@ -214,7 +245,25 @@ func (s *WeeklyMarginInterestService) GetWeeklyMarginInterestByDate(ctx context. return allData, nil } -// GetWeeklyMarginInterestByCodeAndDateRange は指定銘柄・期間の信用取引週末残高を取得します。 +// GetWeeklyMarginInterestByPublishedDate は指定公表日の全銘柄の残高を取得します。 +// 公表日が収録されていない過去データは取得できません。 +func (s *WeeklyMarginInterestService) GetWeeklyMarginInterestByPublishedDate(ctx context.Context, publishedDate string) ([]WeeklyMarginInterest, error) { + params := WeeklyMarginInterestParams{PublishedDate: publishedDate} + var allData []WeeklyMarginInterest + for { + resp, err := s.GetWeeklyMarginInterest(ctx, params) + if err != nil { + return nil, err + } + allData = append(allData, resp.Data...) + if resp.PaginationKey == "" { + return allData, nil + } + params.PaginationKey = resp.PaginationKey + } +} + +// GetWeeklyMarginInterestByCodeAndDateRange は指定銘柄・期間の信用取引残高を取得します。 func (s *WeeklyMarginInterestService) GetWeeklyMarginInterestByCodeAndDateRange(ctx context.Context, code, from, to string) ([]WeeklyMarginInterest, error) { var allData []WeeklyMarginInterest paginationKey := "" @@ -244,7 +293,7 @@ func (s *WeeklyMarginInterestService) GetWeeklyMarginInterestByCodeAndDateRange( return allData, nil } -// GetWeeklyMarginInterestByCodeAndDate は指定銘柄の指定公表日の信用取引週末残高を取得します。 +// GetWeeklyMarginInterestByCodeAndDate は指定銘柄の指定申込日の信用取引残高を取得します。 func (s *WeeklyMarginInterestService) GetWeeklyMarginInterestByCodeAndDate(ctx context.Context, code, date string) ([]WeeklyMarginInterest, error) { resp, err := s.GetWeeklyMarginInterest(ctx, WeeklyMarginInterestParams{ Code: code, diff --git a/weekly_margin_interest_test.go b/weekly_margin_interest_test.go index fbe8f90..b30400b 100644 --- a/weekly_margin_interest_test.go +++ b/weekly_margin_interest_test.go @@ -2,8 +2,11 @@ package jquants import ( "context" + "encoding/json" "fmt" + "reflect" "testing" + "time" "github.com/utahta/jquants/client" ) @@ -45,6 +48,16 @@ func TestWeeklyMarginInterestService_GetWeeklyMarginInterest(t *testing.T) { }, wantPath: "/markets/margin-interest?date=20230217&pagination_key=key123", }, + { + name: "with published date only", + params: WeeklyMarginInterestParams{PublishedDate: "2026-09-28"}, + wantPath: "/markets/margin-interest?published_date=2026-09-28", + }, + { + name: "with code and published date and pagination", + params: WeeklyMarginInterestParams{Code: "86970", PublishedDate: "20260928", PaginationKey: "next"}, + wantPath: "/markets/margin-interest?code=86970&published_date=20260928&pagination_key=next", + }, } for _, tt := range tests { @@ -93,7 +106,7 @@ func TestWeeklyMarginInterestService_GetWeeklyMarginInterest(t *testing.T) { } } -func TestWeeklyMarginInterestService_GetWeeklyMarginInterest_RequiresCodeOrDate(t *testing.T) { +func TestWeeklyMarginInterestService_GetWeeklyMarginInterest_RequiresFilter(t *testing.T) { // Setup mockClient := client.NewMockClient() service := NewWeeklyMarginInterestService(mockClient) @@ -103,10 +116,78 @@ func TestWeeklyMarginInterestService_GetWeeklyMarginInterest_RequiresCodeOrDate( // Verify if err == nil { - t.Error("GetWeeklyMarginInterest() expected error for missing code and date but got nil") + t.Fatal("GetWeeklyMarginInterest() expected error for missing filters but got nil") + } + if err.Error() != "either code, date or published_date parameter is required" { + t.Errorf("GetWeeklyMarginInterest() error = %v", err) + } + if mockClient.RequestCount != 0 { + t.Errorf("sent %d requests for invalid parameters", mockClient.RequestCount) + } +} + +func TestWeeklyMarginInterestService_RejectsPublishedDateWithApplicationDate(t *testing.T) { + tests := []WeeklyMarginInterestParams{ + {PublishedDate: "20260928", Date: "20260925"}, + {Code: "86970", PublishedDate: "20260928", From: "20260925"}, + {Code: "86970", PublishedDate: "20260928", To: "20260925"}, + } + for _, params := range tests { + c := client.NewMockClient() + _, err := NewWeeklyMarginInterestService(c).GetWeeklyMarginInterest(context.Background(), params) + if err == nil || c.RequestCount != 0 { + t.Errorf("params %+v: error = %v, requests = %d; want validation error without request", params, err, c.RequestCount) + } + } +} + +func TestWeeklyMarginInterestResponse_DailyFields(t *testing.T) { + raw := `{"data":[ + {"PubDate":"2026-09-28","Date":"2026-09-25","Code":"86970","IssType":"2", + "ShrtVol":257400,"LongVol":"225000","ShrtNegVol":242800,"LongNegVol":81900,"ShrtStdVol":14600,"LongStdVol":143100, + "ShrtVal":514800000,"LongVal":"450000000","ShrtNegVal":"485600000","LongNegVal":163800000,"ShrtStdVal":29200000,"LongStdVal":"286200000"}, + {"Date":"2026-09-18","Code":"86970","PubDate":null,"ShrtVal":null,"LongVal":null,"ShrtNegVal":null,"LongNegVal":null,"ShrtStdVal":null,"LongStdVal":null}, + {"Date":"2026-09-11","Code":"86970"}, + {"Date":"2026-09-25","Code":"99990","PubDate":"2026-09-28","ShrtVal":0,"LongVal":"0","ShrtNegVal":0,"LongNegVal":"0","ShrtStdVal":0,"LongStdVal":"0"} + ],"pagination_key":"next"}` + want := []WeeklyMarginInterest{ + { + PubDate: stringPtr("2026-09-28"), Date: "2026-09-25", Code: "86970", IssType: "2", + ShrtVol: 257400, LongVol: 225000, ShrtNegVol: 242800, LongNegVol: 81900, ShrtStdVol: 14600, LongStdVol: 143100, + ShrtVal: floatPtr(514800000), LongVal: floatPtr(450000000), ShrtNegVal: floatPtr(485600000), + LongNegVal: floatPtr(163800000), ShrtStdVal: floatPtr(29200000), LongStdVal: floatPtr(286200000), + }, + {Date: "2026-09-18", Code: "86970"}, + {Date: "2026-09-11", Code: "86970"}, + { + PubDate: stringPtr("2026-09-28"), Date: "2026-09-25", Code: "99990", + ShrtVal: floatPtr(0), LongVal: floatPtr(0), ShrtNegVal: floatPtr(0), + LongNegVal: floatPtr(0), ShrtStdVal: floatPtr(0), LongStdVal: floatPtr(0), + }, + } + var resp WeeklyMarginInterestResponse + if err := json.Unmarshal([]byte(raw), &resp); err != nil { + t.Fatal(err) + } + if !reflect.DeepEqual(resp.Data, want) || resp.PaginationKey != "next" { + t.Errorf("response = %+v, want %+v with pagination key next", resp, want) + } +} + +func TestWeeklyMarginInterestService_GetWeeklyMarginInterestByPublishedDate(t *testing.T) { + c := client.NewMockClient() + c.SetResponse("GET", "/markets/margin-interest?published_date=20260928", json.RawMessage( + `{"data":[{"PubDate":"2026-09-28","Date":"2026-09-25","Code":"86970"}],"pagination_key":"next"}`)) + c.SetResponse("GET", "/markets/margin-interest?published_date=20260928&pagination_key=next", json.RawMessage( + `{"data":[{"PubDate":"2026-09-28","Date":"2026-09-25","Code":"72030"}],"pagination_key":""}`)) + ctx, cancel := context.WithTimeout(context.Background(), time.Second) + defer cancel() + data, err := NewWeeklyMarginInterestService(c).GetWeeklyMarginInterestByPublishedDate(ctx, "20260928") + if err != nil { + t.Fatal(err) } - if err.Error() != "either code or date parameter is required" { - t.Errorf("GetWeeklyMarginInterest() error = %v, want 'either code or date parameter is required'", err) + if len(data) != 2 || data[0].Code != "86970" || data[1].Code != "72030" || c.RequestCount != 2 { + t.Errorf("data = %+v, requests = %d; want both pages", data, c.RequestCount) } }