diff --git a/README.md b/README.md index 678da69..dd35958 100644 --- a/README.md +++ b/README.md @@ -94,6 +94,7 @@ size := httpClient.CacheSize() - キャッシュキーはリクエストパス(クエリパラメータ含む)で区別されます - 同時リクエストの重複排除(singleflight)により効率的に動作します - 待機中にコンテキストをキャンセルした呼び出し元は即座にエラーで戻ります(進行中のリクエストは完了してキャッシュされます) +- 署名付きダウンロードURLを返すAPI(Bulk・TDnetのファイルURL取得)はURLが失効するためキャッシュを経由しません - キャッシュはクライアントインスタンスの生存期間のみ有効です ## 利用可能なAPI @@ -104,6 +105,7 @@ size := httpClient.CacheSize() |---------|---------|------| | **株価** | Quotes | 日次株価四本値 | | **株価** | PricesAM | 前場四本値 | +| **株価** | MinuteQuotes | 株価分足 | | **銘柄情報** | Listed | 上場銘柄一覧 | | **財務** | Statements | 財務情報 | | **財務** | FSDetails | 財務諸表詳細(BS/PL/CF) | @@ -121,6 +123,11 @@ size := httpClient.CacheSize() | **信用取引** | DailyMarginInterest | 日々公表信用取引残高 | | **空売り** | ShortSelling | 業種別空売り比率 | | **空売り** | ShortSellingPositions | 空売り残高報告 | +| **適時開示** | TimelyDisclosure | TDnet適時開示情報 | +| **EDINET** | EdinetMajorShareholders | 大株主状況 | +| **EDINET** | EdinetCrossShareholdings | 政策保有株式 | +| **EDINET** | EdinetLargeVolumeShareholders | 大量保有報告書 | +| **ダウンロード** | Bulk | CSV一括ダウンロード | ※各APIの利用可能なプランについては、[J-Quants公式サイト](https://jpx-jquants.com/)で確認してください。 @@ -297,18 +304,6 @@ quote.O, quote.H, quote.L, quote.C 詳細は[公式の移行ガイド](https://jpx-jquants.com/ja/spec/migration-v1-v2)を参照してください。 -## エラーハンドリング - -```go -quotes, err := jq.Quotes.GetDailyQuotesByCode(ctx, "9999") -if err != nil { - // APIエラーの詳細を取得 - if apiErr, ok := err.(*client.APIError); ok { - fmt.Printf("APIエラー: %d - %s\n", apiErr.StatusCode, apiErr.Message) - } -} -``` - ## 注意事項 - J-Quants APIの利用には適切なサブスクリプションが必要です diff --git a/bulk.go b/bulk.go new file mode 100644 index 0000000..19b7ec2 --- /dev/null +++ b/bulk.go @@ -0,0 +1,162 @@ +package jquants + +import ( + "context" + "encoding/json" + "fmt" + + "github.com/utahta/jquants/client" + "github.com/utahta/jquants/types" +) + +// BulkService はCSVファイルの一括ダウンロード(Bulk API)を提供するサービスです。 +// ご契約プランでアクセス可能なエンドポイントのファイルが対象です。 +// 株式ティックデータ(/equities/trades)はAPIでの提供がなく、このBulk API経由でのみ取得できます。 +type BulkService struct { + client client.HTTPClient +} + +// NewBulkService は新しいBulkServiceを作成します。 +func NewBulkService(c client.HTTPClient) *BulkService { + return &BulkService{client: c} +} + +// BulkListParams はダウンロード可能ファイル一覧のリクエストパラメータです。 +type BulkListParams struct { + Endpoint string // 対象データのエンドポイント名(e.g. /equities/bars/daily)(endpoint、dateのいずれかが必須) + Date string // 対象日付(YYYY-MM、YYYYMM、YYYY-MM-DD、YYYYMMDD)(endpoint、dateのいずれかが必須) + From string // 取得期間の開始日(YYYY-MM、YYYYMM、YYYY-MM-DD、YYYYMMDD)(endpoint指定時のみ使用可) + To string // 取得期間の終了日(YYYY-MM、YYYYMM、YYYY-MM-DD、YYYYMMDD)(endpoint指定時のみ使用可) +} + +// BulkListResponse はダウンロード可能ファイル一覧のレスポンスです。 +type BulkListResponse struct { + Data []BulkFile `json:"data"` +} + +// BulkFile はダウンロード可能ファイルの情報を表します。 +// J-Quants API /bulk/list エンドポイントのレスポンスデータ。 +type BulkFile struct { + Key string `json:"Key"` // ファイルのキー(/bulk/get でのダウンロード時に使用。e.g. equities/bars/daily/historical/2025/equities_bars_daily_202501.csv.gz) + LastModified string `json:"LastModified"` // 最終更新日時(ISO 8601形式) + Size int64 `json:"Size"` // ファイルサイズ(バイト) +} + +// RawBulkFile is used for unmarshaling JSON response with mixed types +type RawBulkFile struct { + Key string `json:"Key"` + LastModified string `json:"LastModified"` + Size types.NullableInt64 `json:"Size"` +} + +// UnmarshalJSON implements custom JSON unmarshaling for BulkListResponse +func (r *BulkListResponse) UnmarshalJSON(data []byte) error { + // First unmarshal into RawBulkFile + type rawResponse struct { + Data []RawBulkFile `json:"data"` + } + + var raw rawResponse + if err := json.Unmarshal(data, &raw); err != nil { + return err + } + + // Convert RawBulkFile to BulkFile + r.Data = make([]BulkFile, len(raw.Data)) + for idx, rbf := range raw.Data { + r.Data[idx] = BulkFile{ + Key: rbf.Key, + LastModified: rbf.LastModified, + Size: rbf.Size.Or(0), + } + } + + return nil +} + +// BulkGetParams はファイルダウンロード用URL取得のリクエストパラメータです。 +// key単独、またはendpointとdateの組み合わせのどちらかを指定します(keyとendpoint/dateの併用は不可)。 +type BulkGetParams struct { + Key string // ファイルのキー(/bulk/list で取得したKey) + Endpoint string // 対象データのエンドポイント名(e.g. /equities/bars/daily。dateと組み合わせて使用) + Date string // 対象日付(YYYY-MM、YYYYMM、YYYY-MM-DD、YYYYMMDD。endpointと組み合わせて使用) +} + +// GetFiles はダウンロード可能ファイル一覧を取得します。 +// endpointとして取引カレンダー(/markets/calendar)を指定した場合、from/toの期間に関わらず最新の1ファイルのみが返されます。 +func (s *BulkService) GetFiles(ctx context.Context, params BulkListParams) (*BulkListResponse, error) { + // endpoint、dateのいずれかが必須 + if params.Endpoint == "" && params.Date == "" { + return nil, fmt.Errorf("either endpoint or date parameter is required") + } + // from/toはendpoint指定時のみ使用可能 + if (params.From != "" || params.To != "") && params.Endpoint == "" { + return nil, fmt.Errorf("from/to parameters can only be used with endpoint parameter") + } + + path := "/bulk/list" + + query := "?" + if params.Endpoint != "" { + query += fmt.Sprintf("endpoint=%s&", params.Endpoint) + } + if params.Date != "" { + query += fmt.Sprintf("date=%s&", params.Date) + } + if params.From != "" { + query += fmt.Sprintf("from=%s&", params.From) + } + if params.To != "" { + query += fmt.Sprintf("to=%s&", params.To) + } + + if len(query) > 1 { + path += query[:len(query)-1] // Remove trailing & + } + + var resp BulkListResponse + if err := s.client.DoRequest(ctx, "GET", path, nil, &resp); err != nil { + return nil, fmt.Errorf("failed to get bulk file list: %w", err) + } + + return &resp, nil +} + +// GetDownloadURL はファイルダウンロード用の署名付きURLを取得します。 +// 取得したURLの有効期限は5分で、再利用はできません。ファイルはgzip形式で圧縮されたCSVです。 +func (s *BulkService) GetDownloadURL(ctx context.Context, params BulkGetParams) (string, error) { + // key単独、またはendpointとdateの組み合わせのどちらかが必須 + if params.Key != "" && (params.Endpoint != "" || params.Date != "") { + return "", fmt.Errorf("key parameter cannot be combined with endpoint or date parameter") + } + if params.Key == "" && (params.Endpoint == "" || params.Date == "") { + return "", fmt.Errorf("either key or endpoint and date parameters are required") + } + + path := "/bulk/get" + + query := "?" + if params.Key != "" { + query += fmt.Sprintf("key=%s&", params.Key) + } + if params.Endpoint != "" { + query += fmt.Sprintf("endpoint=%s&", params.Endpoint) + } + if params.Date != "" { + query += fmt.Sprintf("date=%s&", params.Date) + } + + if len(query) > 1 { + path += query[:len(query)-1] // Remove trailing & + } + + var resp struct { + URL string `json:"url"` + } + // 署名付きURLは5分で失効し1回限りのため、キャッシュを経由しない + if err := client.DoRequestNoCache(ctx, s.client, "GET", path, nil, &resp); err != nil { + return "", fmt.Errorf("failed to get bulk download URL: %w", err) + } + + return resp.URL, nil +} diff --git a/bulk_test.go b/bulk_test.go new file mode 100644 index 0000000..228a617 --- /dev/null +++ b/bulk_test.go @@ -0,0 +1,306 @@ +package jquants + +import ( + "context" + "encoding/json" + "fmt" + "testing" + + "github.com/utahta/jquants/client" +) + +func TestBulkService_GetFiles(t *testing.T) { + tests := []struct { + name string + params BulkListParams + wantPath string + wantErr bool + }{ + { + name: "with endpoint only", + params: BulkListParams{ + Endpoint: "/equities/bars/daily", + }, + wantPath: "/bulk/list?endpoint=/equities/bars/daily", + }, + { + name: "with date only", + params: BulkListParams{ + Date: "2025-01", + }, + wantPath: "/bulk/list?date=2025-01", + }, + { + name: "with endpoint and period", + params: BulkListParams{ + Endpoint: "/equities/bars/daily", + From: "202401", + To: "202412", + }, + wantPath: "/bulk/list?endpoint=/equities/bars/daily&from=202401&to=202412", + }, + { + name: "with no required parameters", + params: BulkListParams{}, + wantPath: "", + wantErr: true, + }, + { + name: "with from/to but no endpoint", + params: BulkListParams{ + Date: "20250101", + From: "202401", + To: "202412", + }, + wantPath: "", + wantErr: true, + }, + } + + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + // Setup + mockClient := client.NewMockClient() + service := NewBulkService(mockClient) + + // Mock response based on documentation sample + mockResponse := BulkListResponse{ + Data: []BulkFile{ + { + Key: "equities/bars/daily/historical/2025/equities_bars_daily_202501.csv.gz", + LastModified: "2025-11-07T20:48:51.295000+00:00", + Size: 6933528, + }, + }, + } + if !tt.wantErr { + mockClient.SetResponse("GET", tt.wantPath, mockResponse) + } + + // Execute + resp, err := service.GetFiles(context.Background(), tt.params) + + // Verify + if tt.wantErr { + if err == nil { + t.Error("GetFiles() expected error but got nil") + } + return + } + + if err != nil { + t.Fatalf("GetFiles() error = %v", err) + } + if resp == nil { + t.Fatal("GetFiles() returned nil response") + } + if len(resp.Data) == 0 { + t.Error("GetFiles() returned empty data") + } + if mockClient.LastPath != tt.wantPath { + t.Errorf("GetFiles() path = %v, want %v", mockClient.LastPath, tt.wantPath) + } + }) + } +} + +func TestBulkService_GetFiles_RequiresParameter(t *testing.T) { + // Setup + mockClient := client.NewMockClient() + service := NewBulkService(mockClient) + + // Execute with empty parameters + _, err := service.GetFiles(context.Background(), BulkListParams{}) + + // Verify + if err == nil { + t.Error("GetFiles() expected error for missing parameters but got nil") + } + if err.Error() != "either endpoint or date parameter is required" { + t.Errorf("GetFiles() error = %v, want 'either endpoint or date parameter is required'", err) + } +} + +func TestBulkService_GetFiles_FromToRequiresEndpoint(t *testing.T) { + // Setup + mockClient := client.NewMockClient() + service := NewBulkService(mockClient) + + // Execute with from/to but no endpoint + _, err := service.GetFiles(context.Background(), BulkListParams{Date: "20250101", From: "202401"}) + + // Verify + if err == nil { + t.Error("GetFiles() expected error for from/to without endpoint but got nil") + } + if err.Error() != "from/to parameters can only be used with endpoint parameter" { + t.Errorf("GetFiles() error = %v, want 'from/to parameters can only be used with endpoint parameter'", err) + } +} + +func TestBulkListResponse_UnmarshalJSON(t *testing.T) { + // ドキュメントのレスポンスサンプルに基づくJSON + // Sizeはfloat64の丸めが発生する2^53超の値で厳密なint64パースを確認する + raw := `{ + "data": [ + { + "Key": "equities/bars/daily/historical/2025/equities_bars_daily_202501.csv.gz", + "LastModified": "2025-11-07T20:48:51.295000+00:00", + "Size": 9007199254740993 + }, + { + "Key": "equities/bars/daily/historical/2024/equities_bars_daily_202412.csv.gz", + "LastModified": "2025-01-07T18:30:15.123000+00:00", + "Size": 6845123 + } + ] + }` + + var resp BulkListResponse + if err := json.Unmarshal([]byte(raw), &resp); err != nil { + t.Fatalf("UnmarshalJSON() error = %v", err) + } + + if len(resp.Data) != 2 { + t.Fatalf("UnmarshalJSON() returned %d items, want 2", len(resp.Data)) + } + + file := resp.Data[0] + if file.Key != "equities/bars/daily/historical/2025/equities_bars_daily_202501.csv.gz" { + t.Errorf("UnmarshalJSON() Key = %v", file.Key) + } + if file.LastModified != "2025-11-07T20:48:51.295000+00:00" { + t.Errorf("UnmarshalJSON() LastModified = %v", file.LastModified) + } + if file.Size != 9007199254740993 { + t.Errorf("UnmarshalJSON() Size = %v, want 9007199254740993", file.Size) + } + if resp.Data[1].Size != 6845123 { + t.Errorf("UnmarshalJSON() Size = %v, want 6845123", resp.Data[1].Size) + } +} + +func TestBulkService_GetDownloadURL(t *testing.T) { + tests := []struct { + name string + params BulkGetParams + wantPath string + wantErr bool + }{ + { + name: "with key only", + params: BulkGetParams{ + Key: "equities/bars/daily/historical/2025/equities_bars_daily_202501.csv.gz", + }, + wantPath: "/bulk/get?key=equities/bars/daily/historical/2025/equities_bars_daily_202501.csv.gz", + }, + { + name: "with endpoint and date", + params: BulkGetParams{ + Endpoint: "/equities/bars/daily", + Date: "202501", + }, + wantPath: "/bulk/get?endpoint=/equities/bars/daily&date=202501", + }, + { + name: "with key and endpoint", + params: BulkGetParams{ + Key: "equities/bars/daily/historical/2025/equities_bars_daily_202501.csv.gz", + Endpoint: "/equities/bars/daily", + }, + wantErr: true, + }, + { + name: "with key and date", + params: BulkGetParams{ + Key: "equities/bars/daily/historical/2025/equities_bars_daily_202501.csv.gz", + Date: "202501", + }, + wantErr: true, + }, + { + name: "with endpoint only", + params: BulkGetParams{ + Endpoint: "/equities/bars/daily", + }, + wantErr: true, + }, + { + name: "with date only", + params: BulkGetParams{ + Date: "202501", + }, + wantErr: true, + }, + { + name: "with no parameters", + params: BulkGetParams{}, + wantErr: true, + }, + } + + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + // Setup + mockClient := client.NewMockClient() + service := NewBulkService(mockClient) + + wantURL := "https://example.presigned-url.com/file.csv.gz" + if !tt.wantErr { + mockClient.SetResponse("GET", tt.wantPath, map[string]string{"url": wantURL}) + } + + // Execute + url, err := service.GetDownloadURL(context.Background(), tt.params) + + // Verify + if tt.wantErr { + if err == nil { + t.Error("GetDownloadURL() expected error but got nil") + } + return + } + + if err != nil { + t.Fatalf("GetDownloadURL() error = %v", err) + } + if url != wantURL { + t.Errorf("GetDownloadURL() url = %v, want %v", url, wantURL) + } + if mockClient.LastPath != tt.wantPath { + t.Errorf("GetDownloadURL() path = %v, want %v", mockClient.LastPath, tt.wantPath) + } + }) + } +} + +func TestBulkService_GetDownloadURL_Error(t *testing.T) { + // Setup + mockClient := client.NewMockClient() + service := NewBulkService(mockClient) + + // Set error response + mockClient.SetError("GET", "/bulk/get?key=some/file.csv.gz", fmt.Errorf("unauthorized")) + + // Execute + _, err := service.GetDownloadURL(context.Background(), BulkGetParams{Key: "some/file.csv.gz"}) + + // Verify + if err == nil { + t.Error("GetDownloadURL() expected error but got nil") + } +} + +func TestBulkService_GetDownloadURL_SkipsCache(t *testing.T) { + mockClient := client.NewMockClient() + service := NewBulkService(mockClient) + mockClient.SetResponse("GET", "/bulk/get?key=abc", map[string]string{"url": "https://example.com/file.csv.gz"}) + + if _, err := service.GetDownloadURL(context.Background(), BulkGetParams{Key: "abc"}); err != nil { + t.Fatalf("GetDownloadURL() error = %v", err) + } + // 署名付きURLは失効するため、キャッシュバイパスを要求していること + if !mockClient.LastSkipCache { + t.Error("GetDownloadURL() should request cache bypass for expiring signed URLs") + } +} diff --git a/client/client.go b/client/client.go index 45f63ad..f1602b6 100644 --- a/client/client.go +++ b/client/client.go @@ -32,6 +32,23 @@ type Client struct { // ClientOption is a function type for configuring Client settings. type ClientOption func(*Client) +// NoCacheRequester is implemented by clients that can bypass their session +// cache for a single request. +type NoCacheRequester interface { + DoRequestNoCache(ctx context.Context, method, path string, body interface{}, result interface{}) error +} + +// DoRequestNoCache performs a request without using the session cache when the +// client supports it, falling back to a normal DoRequest otherwise. +// Use it for responses that must not be reused: expiring signed URLs and +// cursor-based differential polling. +func DoRequestNoCache(ctx context.Context, c HTTPClient, method, path string, body interface{}, result interface{}) error { + if nc, ok := c.(NoCacheRequester); ok { + return nc.DoRequestNoCache(ctx, method, path, body, result) + } + return c.DoRequest(ctx, method, path, body, result) +} + // WithCache enables caching functionality. // Cache is only applied to GET requests. func WithCache() ClientOption { @@ -129,6 +146,17 @@ func (c *Client) DoRequest(ctx context.Context, method, path string, body interf return decodeResponse(respBody, result) } +// DoRequestNoCache performs a request bypassing the session cache and the +// singleflight deduplication, so every call reaches the server. Responses are +// not stored in the cache. See NoCacheRequester for when to use this. +func (c *Client) DoRequestNoCache(ctx context.Context, method, path string, body interface{}, result interface{}) error { + respBody, err := c.doHTTPRequest(ctx, method, path, body) + if err != nil { + return err + } + return decodeResponse(respBody, result) +} + // doHTTPRequest performs the actual HTTP request. func (c *Client) doHTTPRequest(ctx context.Context, method, path string, body interface{}) ([]byte, error) { url := c.baseURL + path diff --git a/client/client_test.go b/client/client_test.go index 9dd8daa..bf363b0 100644 --- a/client/client_test.go +++ b/client/client_test.go @@ -106,6 +106,77 @@ func TestClient_DoRequest_CacheHitMiss(t *testing.T) { } } +func TestClient_DoRequestNoCache(t *testing.T) { + var callCount int + server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + callCount++ + w.Header().Set("Content-Type", "application/json") + _ = json.NewEncoder(w).Encode(map[string]int{"count": callCount}) + })) + defer server.Close() + + c := NewClient("test-api-key", WithCache()) + c.baseURL = server.URL + + type response struct { + Count int `json:"count"` + } + + // DoRequestNoCache always hits the server and never populates the cache + var resp1, resp2 response + if err := c.DoRequestNoCache(context.Background(), http.MethodGet, "/signed", nil, &resp1); err != nil { + t.Fatalf("unexpected error: %v", err) + } + if err := c.DoRequestNoCache(context.Background(), http.MethodGet, "/signed", nil, &resp2); err != nil { + t.Fatalf("unexpected error: %v", err) + } + if callCount != 2 { + t.Errorf("expected 2 calls (cache bypassed), got %d", callCount) + } + if resp1.Count != 1 || resp2.Count != 2 { + t.Errorf("expected fresh responses 1 and 2, got %d and %d", resp1.Count, resp2.Count) + } + if c.CacheSize() != 0 { + t.Errorf("expected empty cache after DoRequestNoCache requests, got %d entries", c.CacheSize()) + } + + // An existing cache entry is not read by DoRequestNoCache + var resp3, resp4 response + if err := c.DoRequest(context.Background(), http.MethodGet, "/signed", nil, &resp3); err != nil { + t.Fatalf("unexpected error: %v", err) + } + if err := c.DoRequestNoCache(context.Background(), http.MethodGet, "/signed", nil, &resp4); err != nil { + t.Fatalf("unexpected error: %v", err) + } + if resp4.Count != 4 { + t.Errorf("expected DoRequestNoCache to bypass existing cache entry, got count %d", resp4.Count) + } +} + +// plainHTTPClient is an HTTPClient implementation without NoCacheRequester +// support, emulating a downstream custom client. +type plainHTTPClient struct { + calls int +} + +func (p *plainHTTPClient) DoRequest(ctx context.Context, method, path string, body interface{}, result interface{}) error { + p.calls++ + return nil +} + +func TestDoRequestNoCache_FallbackForPlainClient(t *testing.T) { + p := &plainHTTPClient{} + + // NoCacheRequesterを実装しないクライアントでは通常のDoRequestにフォールバックする + err := DoRequestNoCache(context.Background(), p, http.MethodGet, "/signed", nil, nil) + if err != nil { + t.Fatalf("unexpected error: %v", err) + } + if p.calls != 1 { + t.Errorf("expected fallback to DoRequest exactly once, got %d calls", p.calls) + } +} + func TestClient_DoRequest_CacheDisabled(t *testing.T) { var callCount int server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { diff --git a/client/mock.go b/client/mock.go index ea1678c..ed532ff 100644 --- a/client/mock.go +++ b/client/mock.go @@ -9,12 +9,13 @@ import ( // MockClient is a mock implementation of HTTPClient interface for testing type MockClient struct { - Responses map[string]interface{} - Errors map[string]error - RequestCount int - LastMethod string - LastPath string - LastBody interface{} + Responses map[string]interface{} + Errors map[string]error + RequestCount int + LastMethod string + LastPath string + LastBody interface{} + LastSkipCache bool } // NewMockClient creates a new mock client @@ -35,6 +36,7 @@ func (m *MockClient) DoRequest(ctx context.Context, method, path string, body in m.LastMethod = method m.LastPath = path m.LastBody = body + m.LastSkipCache = false key := fmt.Sprintf("%s:%s", method, path) @@ -67,6 +69,13 @@ func (m *MockClient) DoRequest(ctx context.Context, method, path string, body in return fmt.Errorf("no mock response set for %s", key) } +// DoRequestNoCache implements NoCacheRequester interface +func (m *MockClient) DoRequestNoCache(ctx context.Context, method, path string, body interface{}, result interface{}) error { + err := m.DoRequest(ctx, method, path, body, result) + m.LastSkipCache = true + return err +} + // SetResponse sets a mock response for a specific method and path func (m *MockClient) SetResponse(method, path string, response interface{}) { key := fmt.Sprintf("%s:%s", method, path) diff --git a/edinet_cross_shareholdings.go b/edinet_cross_shareholdings.go new file mode 100644 index 0000000..a8d864d --- /dev/null +++ b/edinet_cross_shareholdings.go @@ -0,0 +1,442 @@ +package jquants + +import ( + "context" + "encoding/json" + "fmt" + + "github.com/utahta/jquants/client" + "github.com/utahta/jquants/types" +) + +// EdinetCrossShareholdingsService は政策保有株式(EDINET)を取得するサービスです。 +// 有価証券報告書「株式の保有状況」に基づく政策保有株式データを取得します。 +type EdinetCrossShareholdingsService struct { + client client.HTTPClient +} + +// NewEdinetCrossShareholdingsService は新しいEdinetCrossShareholdingsServiceを作成します。 +func NewEdinetCrossShareholdingsService(c client.HTTPClient) *EdinetCrossShareholdingsService { + return &EdinetCrossShareholdingsService{client: c} +} + +// EdinetCrossShareholdingsParams は政策保有株式のリクエストパラメータです。 +// すべて任意ですが、edinet_codeとcodeの同時指定はできません。 +// すべて省略した場合はAPI実行日に提出された全有報のデータ一覧が返ります。 +type EdinetCrossShareholdingsParams struct { + EdinetCode string // EDINETコード(例: E03814)(codeとの同時指定は不可) + Code string // 4桁もしくは5桁の銘柄コード(edinet_codeとの同時指定は不可) + Date string // 提出日(YYYYMMDD または YYYY-MM-DD) + PaginationKey string // ページネーションキー +} + +// EdinetCrossShareholdingsResponse は政策保有株式のレスポンスです。 +type EdinetCrossShareholdingsResponse struct { + Data []EdinetCrossShareholdingDoc `json:"data"` + PaginationKey string `json:"pagination_key"` // ページネーションキー +} + +// EdinetCrossShareholdingDoc は有価証券報告書ごとの政策保有株式データを表します。 +// J-Quants API /edinet/cross-shareholdings エンドポイントのレスポンスデータ。 +// データは2020年3月31日以降、対象書類は有価証券報告書。Standardプラン以上で利用可能。 +type EdinetCrossShareholdingDoc struct { + // 書類メタ情報 + DocId string `json:"DocId"` // EDINET書類管理番号(S + 7桁英数字) + Code string `json:"Code"` // 提出会社の銘柄コード(5桁) + EdinetCode string `json:"EdinetCode"` // 提出会社のEDINETコード + FilerName string `json:"FilerName"` // 提出者名(会社名) + FilerNameEn string `json:"FilerNameEn"` // 提出者名(英語) + DocTypeCode string `json:"DocTypeCode"` // 書類種別コード(120=有価証券報告書) + 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形式) + + // 保有主体ブロック(記載がない場合はnil) + Report *EdinetCrossShareholdingBlock `json:"Report"` // 提出会社 + Largest *EdinetCrossShareholdingBlock `json:"Largest"` // 連結最大保有会社 + SecondLargest *EdinetCrossShareholdingBlock `json:"SecondLargest"` // 連結第二最大保有会社 +} + +// EdinetCrossShareholdingBlock は保有主体(提出会社/連結最大保有会社/連結第二最大保有会社)ごとの保有状況を表します。 +type EdinetCrossShareholdingBlock struct { + // 保有主体情報 + HldrName string `json:"HldrName"` // 当該保有主体の会社名 + HldrCode string `json:"HldrCode"` // 当該保有主体の証券コード(5桁) + HldrEdinetCode string `json:"HldrEdinetCode"` // 当該保有主体のEDINETコード + + // 上場株式 + ListedIss float64 `json:"ListedIss"` // 銘柄数 + ListedBookVal float64 `json:"ListedBookVal"` // 貸借対照表計上額合計(円) + ListedIncIss float64 `json:"ListedIncIss"` // 株式数が増加した銘柄数 + ListedIncAcqCost float64 `json:"ListedIncAcqCost"` // 増加に係る取得価額合計(円) + ListedDecIss float64 `json:"ListedDecIss"` // 株式数が減少した銘柄数 + ListedDecSaleAmt float64 `json:"ListedDecSaleAmt"` // 減少に係る売却価額合計(円) + ListedIncRsn string `json:"ListedIncRsn"` // 株式数が増加した理由 + + // 非上場株式 + NonListedIss float64 `json:"NonListedIss"` // 銘柄数 + NonListedBookVal float64 `json:"NonListedBookVal"` // 貸借対照表計上額合計(円) + NonListedIncIss float64 `json:"NonListedIncIss"` // 株式数が増加した銘柄数 + NonListedIncAcqCost float64 `json:"NonListedIncAcqCost"` // 増加に係る取得価額合計(円) + NonListedDecIss float64 `json:"NonListedDecIss"` // 株式数が減少した銘柄数 + NonListedDecSaleAmt float64 `json:"NonListedDecSaleAmt"` // 減少に係る売却価額合計(円) + NonListedIncRsn string `json:"NonListedIncRsn"` // 株式数が増加した理由 + + // 銘柄レコード + Spec []EdinetCrossShareholdingIssue `json:"Spec"` // 特定投資株式 + Deem []EdinetCrossShareholdingIssue `json:"Deem"` // みなし保有株式 + + // 注釈(HTML断片) + SpecFn string `json:"SpecFn"` // 特定投資株式の注釈 + DeemFn string `json:"DeemFn"` // みなし保有株式の注釈 +} + +// EdinetCrossShareholdingIssue は特定投資株式・みなし保有株式の1銘柄分のデータを表します。 +// 株式数・貸借対照表計上額が非開示の場合は数値がnilとなり、対応する*NotDiscに +// 非開示マーカー生値(* / * / ※ / (注N))が入ります。 +type EdinetCrossShareholdingIssue struct { + // 保有先銘柄情報 + IsrName string `json:"IsrName"` // 保有先銘柄名 + IsrCode string `json:"IsrCode"` // 保有先の銘柄コード(5桁、IsrNameから名寄せ) + IsrEdinetCode string `json:"IsrEdinetCode"` // 保有先のEDINETコード(IsrNameから名寄せ) + + // 株式数・貸借対照表計上額(非開示の場合はnil) + CurShs *float64 `json:"CurShs"` // 当事業年度の株式数(株) + PriShs *float64 `json:"PriShs"` // 前事業年度の株式数(株) + CurBookVal *float64 `json:"CurBookVal"` // 当事業年度の貸借対照表計上額(円) + PriBookVal *float64 `json:"PriBookVal"` // 前事業年度の貸借対照表計上額(円) + + // 非開示マーカー生値(* / * / ※ / (注N)。開示されている場合は空文字) + CurShsNotDisc string `json:"CurShsNotDisc"` // 当期株式数の非開示マーカー + PriShsNotDisc string `json:"PriShsNotDisc"` // 前期株式数の非開示マーカー + CurBookValNotDisc string `json:"CurBookValNotDisc"` // 当期貸借対照表計上額の非開示マーカー + PriBookValNotDisc string `json:"PriBookValNotDisc"` // 前期貸借対照表計上額の非開示マーカー + + // その他 + HoldRat string `json:"HoldRat"` // 保有目的・業務提携の概要・定量効果・増加理由(複合テキスト) + IsrHolds string `json:"IsrHolds"` // 当社の株式の保有の有無(生データ。例: 有 / 無 / 無(注)3) + IsrHoldsCode string `json:"IsrHoldsCode"` // 当社の株式の保有の有無の正規化値(1=有、0=無、2=判定不能) +} + +// RawEdinetCrossShareholdingDoc is used for unmarshaling JSON response with mixed types +type RawEdinetCrossShareholdingDoc struct { + // 書類メタ情報 + DocId string `json:"DocId"` + Code string `json:"Code"` + EdinetCode string `json:"EdinetCode"` + FilerName string `json:"FilerName"` + FilerNameEn string `json:"FilerNameEn"` + DocTypeCode string `json:"DocTypeCode"` + SubDate string `json:"SubDate"` + SubTime string `json:"SubTime"` + PerSt string `json:"PerSt"` + PerEn string `json:"PerEn"` + + // 保有主体ブロック + Report *RawEdinetCrossShareholdingBlock `json:"Report"` + Largest *RawEdinetCrossShareholdingBlock `json:"Largest"` + SecondLargest *RawEdinetCrossShareholdingBlock `json:"SecondLargest"` +} + +// RawEdinetCrossShareholdingBlock is used for unmarshaling JSON response with mixed types +type RawEdinetCrossShareholdingBlock struct { + HldrName string `json:"HldrName"` + HldrCode string `json:"HldrCode"` + HldrEdinetCode string `json:"HldrEdinetCode"` + + ListedIss types.NullableFloat64 `json:"ListedIss"` + ListedBookVal types.NullableFloat64 `json:"ListedBookVal"` + ListedIncIss types.NullableFloat64 `json:"ListedIncIss"` + ListedIncAcqCost types.NullableFloat64 `json:"ListedIncAcqCost"` + ListedDecIss types.NullableFloat64 `json:"ListedDecIss"` + ListedDecSaleAmt types.NullableFloat64 `json:"ListedDecSaleAmt"` + ListedIncRsn string `json:"ListedIncRsn"` + + NonListedIss types.NullableFloat64 `json:"NonListedIss"` + NonListedBookVal types.NullableFloat64 `json:"NonListedBookVal"` + NonListedIncIss types.NullableFloat64 `json:"NonListedIncIss"` + NonListedIncAcqCost types.NullableFloat64 `json:"NonListedIncAcqCost"` + NonListedDecIss types.NullableFloat64 `json:"NonListedDecIss"` + NonListedDecSaleAmt types.NullableFloat64 `json:"NonListedDecSaleAmt"` + NonListedIncRsn string `json:"NonListedIncRsn"` + + Spec []RawEdinetCrossShareholdingIssue `json:"Spec"` + Deem []RawEdinetCrossShareholdingIssue `json:"Deem"` + + SpecFn string `json:"SpecFn"` + DeemFn string `json:"DeemFn"` +} + +// RawEdinetCrossShareholdingIssue is used for unmarshaling JSON response with mixed types +type RawEdinetCrossShareholdingIssue struct { + IsrName string `json:"IsrName"` + IsrCode string `json:"IsrCode"` + IsrEdinetCode string `json:"IsrEdinetCode"` + + CurShs types.NullableFloat64 `json:"CurShs"` + PriShs types.NullableFloat64 `json:"PriShs"` + CurBookVal types.NullableFloat64 `json:"CurBookVal"` + PriBookVal types.NullableFloat64 `json:"PriBookVal"` + + CurShsNotDisc string `json:"CurShsNotDisc"` + PriShsNotDisc string `json:"PriShsNotDisc"` + CurBookValNotDisc string `json:"CurBookValNotDisc"` + PriBookValNotDisc string `json:"PriBookValNotDisc"` + + HoldRat string `json:"HoldRat"` + IsrHolds string `json:"IsrHolds"` + IsrHoldsCode string `json:"IsrHoldsCode"` +} + +// UnmarshalJSON implements custom JSON unmarshaling for EdinetCrossShareholdingsResponse +func (r *EdinetCrossShareholdingsResponse) UnmarshalJSON(data []byte) error { + // First unmarshal into RawEdinetCrossShareholdingDoc + type rawResponse struct { + Data []RawEdinetCrossShareholdingDoc `json:"data"` + PaginationKey string `json:"pagination_key"` + } + + var raw rawResponse + if err := json.Unmarshal(data, &raw); err != nil { + return err + } + + // Set pagination key + r.PaginationKey = raw.PaginationKey + + // Convert RawEdinetCrossShareholdingDoc to EdinetCrossShareholdingDoc + r.Data = make([]EdinetCrossShareholdingDoc, len(raw.Data)) + for idx, rd := range raw.Data { + r.Data[idx] = EdinetCrossShareholdingDoc{ + // 書類メタ情報 + DocId: rd.DocId, + Code: rd.Code, + EdinetCode: rd.EdinetCode, + FilerName: rd.FilerName, + FilerNameEn: rd.FilerNameEn, + DocTypeCode: rd.DocTypeCode, + SubDate: rd.SubDate, + SubTime: rd.SubTime, + PerSt: rd.PerSt, + PerEn: rd.PerEn, + + // 保有主体ブロック + Report: convertEdinetCrossShareholdingBlock(rd.Report), + Largest: convertEdinetCrossShareholdingBlock(rd.Largest), + SecondLargest: convertEdinetCrossShareholdingBlock(rd.SecondLargest), + } + } + + return nil +} + +// convertEdinetCrossShareholdingBlock converts RawEdinetCrossShareholdingBlock to EdinetCrossShareholdingBlock +func convertEdinetCrossShareholdingBlock(raw *RawEdinetCrossShareholdingBlock) *EdinetCrossShareholdingBlock { + if raw == nil { + return nil + } + + return &EdinetCrossShareholdingBlock{ + HldrName: raw.HldrName, + HldrCode: raw.HldrCode, + HldrEdinetCode: raw.HldrEdinetCode, + + ListedIss: raw.ListedIss.Or(0), + ListedBookVal: raw.ListedBookVal.Or(0), + ListedIncIss: raw.ListedIncIss.Or(0), + ListedIncAcqCost: raw.ListedIncAcqCost.Or(0), + ListedDecIss: raw.ListedDecIss.Or(0), + ListedDecSaleAmt: raw.ListedDecSaleAmt.Or(0), + ListedIncRsn: raw.ListedIncRsn, + + NonListedIss: raw.NonListedIss.Or(0), + NonListedBookVal: raw.NonListedBookVal.Or(0), + NonListedIncIss: raw.NonListedIncIss.Or(0), + NonListedIncAcqCost: raw.NonListedIncAcqCost.Or(0), + NonListedDecIss: raw.NonListedDecIss.Or(0), + NonListedDecSaleAmt: raw.NonListedDecSaleAmt.Or(0), + NonListedIncRsn: raw.NonListedIncRsn, + + Spec: convertEdinetCrossShareholdingIssues(raw.Spec), + Deem: convertEdinetCrossShareholdingIssues(raw.Deem), + + SpecFn: raw.SpecFn, + DeemFn: raw.DeemFn, + } +} + +// convertEdinetCrossShareholdingIssues converts RawEdinetCrossShareholdingIssue slice to EdinetCrossShareholdingIssue slice +func convertEdinetCrossShareholdingIssues(raws []RawEdinetCrossShareholdingIssue) []EdinetCrossShareholdingIssue { + if raws == nil { + return nil + } + + issues := make([]EdinetCrossShareholdingIssue, len(raws)) + for idx, ri := range raws { + issues[idx] = EdinetCrossShareholdingIssue{ + IsrName: ri.IsrName, + IsrCode: ri.IsrCode, + IsrEdinetCode: ri.IsrEdinetCode, + + CurShs: ri.CurShs.Ptr(), + PriShs: ri.PriShs.Ptr(), + CurBookVal: ri.CurBookVal.Ptr(), + PriBookVal: ri.PriBookVal.Ptr(), + + CurShsNotDisc: ri.CurShsNotDisc, + PriShsNotDisc: ri.PriShsNotDisc, + CurBookValNotDisc: ri.CurBookValNotDisc, + PriBookValNotDisc: ri.PriBookValNotDisc, + + HoldRat: ri.HoldRat, + IsrHolds: ri.IsrHolds, + IsrHoldsCode: ri.IsrHoldsCode, + } + } + + return issues +} + +// GetCrossShareholdings は政策保有株式を取得します。 +// パラメータをすべて省略した場合はAPI実行日に提出された全有報のデータ一覧を取得します。 +func (s *EdinetCrossShareholdingsService) GetCrossShareholdings(ctx context.Context, params EdinetCrossShareholdingsParams) (*EdinetCrossShareholdingsResponse, error) { + // edinet_codeとcodeの同時指定は不可 + if params.EdinetCode != "" && params.Code != "" { + return nil, fmt.Errorf("edinet_code and code cannot be specified together") + } + + path := "/edinet/cross-shareholdings" + + query := "?" + if params.EdinetCode != "" { + query += fmt.Sprintf("edinet_code=%s&", params.EdinetCode) + } + if params.Code != "" { + query += fmt.Sprintf("code=%s&", params.Code) + } + if params.Date != "" { + query += fmt.Sprintf("date=%s&", params.Date) + } + if params.PaginationKey != "" { + query += fmt.Sprintf("pagination_key=%s&", params.PaginationKey) + } + + if len(query) > 1 { + path += query[:len(query)-1] // Remove trailing & + } + + var resp EdinetCrossShareholdingsResponse + if err := s.client.DoRequest(ctx, "GET", path, nil, &resp); err != nil { + return nil, fmt.Errorf("failed to get cross shareholdings: %w", err) + } + + return &resp, nil +} + +// GetCrossShareholdingsByCode は指定銘柄の政策保有株式を取得します。 +// ページネーションを使用して全データを取得します。 +func (s *EdinetCrossShareholdingsService) GetCrossShareholdingsByCode(ctx context.Context, code string) ([]EdinetCrossShareholdingDoc, error) { + var allData []EdinetCrossShareholdingDoc + paginationKey := "" + + for { + params := EdinetCrossShareholdingsParams{ + Code: code, + PaginationKey: paginationKey, + } + + resp, err := s.GetCrossShareholdings(ctx, params) + if err != nil { + return nil, err + } + + allData = append(allData, resp.Data...) + + // ページネーションキーがなければ終了 + if resp.PaginationKey == "" { + break + } + paginationKey = resp.PaginationKey + } + + return allData, nil +} + +// GetCrossShareholdingsByEdinetCode は指定EDINETコードの政策保有株式を取得します。 +// ページネーションを使用して全データを取得します。 +func (s *EdinetCrossShareholdingsService) GetCrossShareholdingsByEdinetCode(ctx context.Context, edinetCode string) ([]EdinetCrossShareholdingDoc, error) { + var allData []EdinetCrossShareholdingDoc + paginationKey := "" + + for { + params := EdinetCrossShareholdingsParams{ + EdinetCode: edinetCode, + PaginationKey: paginationKey, + } + + resp, err := s.GetCrossShareholdings(ctx, params) + if err != nil { + return nil, err + } + + allData = append(allData, resp.Data...) + + // ページネーションキーがなければ終了 + if resp.PaginationKey == "" { + break + } + paginationKey = resp.PaginationKey + } + + return allData, nil +} + +// GetCrossShareholdingsByDate は指定提出日の全有報の政策保有株式を取得します。 +// ページネーションを使用して全データを取得します。 +func (s *EdinetCrossShareholdingsService) GetCrossShareholdingsByDate(ctx context.Context, date string) ([]EdinetCrossShareholdingDoc, error) { + var allData []EdinetCrossShareholdingDoc + paginationKey := "" + + for { + params := EdinetCrossShareholdingsParams{ + Date: date, + PaginationKey: paginationKey, + } + + resp, err := s.GetCrossShareholdings(ctx, params) + if err != nil { + return nil, err + } + + allData = append(allData, resp.Data...) + + // ページネーションキーがなければ終了 + if resp.PaginationKey == "" { + break + } + paginationKey = resp.PaginationKey + } + + return allData, nil +} + +// HasReport は提出会社の保有ブロックが存在するかを判定します。 +func (d *EdinetCrossShareholdingDoc) HasReport() bool { + return d.Report != nil +} + +// HasLargest は連結最大保有会社の保有ブロックが存在するかを判定します。 +func (d *EdinetCrossShareholdingDoc) HasLargest() bool { + return d.Largest != nil +} + +// HasSecondLargest は連結第二最大保有会社の保有ブロックが存在するかを判定します。 +func (d *EdinetCrossShareholdingDoc) HasSecondLargest() bool { + return d.SecondLargest != nil +} + +// IsDisclosed は当事業年度の株式数が開示されているかを判定します。 +func (i *EdinetCrossShareholdingIssue) IsDisclosed() bool { + return i.CurShs != nil +} diff --git a/edinet_cross_shareholdings_test.go b/edinet_cross_shareholdings_test.go new file mode 100644 index 0000000..aa34c00 --- /dev/null +++ b/edinet_cross_shareholdings_test.go @@ -0,0 +1,610 @@ +package jquants + +import ( + "context" + "encoding/json" + "fmt" + "testing" + + "github.com/utahta/jquants/client" +) + +func TestEdinetCrossShareholdingsService_GetCrossShareholdings(t *testing.T) { + tests := []struct { + name string + params EdinetCrossShareholdingsParams + wantPath string + wantErr bool + }{ + { + name: "with edinet code", + params: EdinetCrossShareholdingsParams{ + EdinetCode: "E03814", + }, + wantPath: "/edinet/cross-shareholdings?edinet_code=E03814", + }, + { + name: "with code", + params: EdinetCrossShareholdingsParams{ + Code: "86970", + }, + wantPath: "/edinet/cross-shareholdings?code=86970", + }, + { + name: "with date", + params: EdinetCrossShareholdingsParams{ + Date: "20250620", + }, + wantPath: "/edinet/cross-shareholdings?date=20250620", + }, + { + name: "with date in hyphen format", + params: EdinetCrossShareholdingsParams{ + Date: "2025-06-20", + }, + wantPath: "/edinet/cross-shareholdings?date=2025-06-20", + }, + { + name: "with code and date", + params: EdinetCrossShareholdingsParams{ + Code: "86970", + Date: "20250620", + }, + wantPath: "/edinet/cross-shareholdings?code=86970&date=20250620", + }, + { + name: "with edinet code and date", + params: EdinetCrossShareholdingsParams{ + EdinetCode: "E03814", + Date: "20250620", + }, + wantPath: "/edinet/cross-shareholdings?edinet_code=E03814&date=20250620", + }, + { + name: "with pagination key", + params: EdinetCrossShareholdingsParams{ + Code: "86970", + PaginationKey: "key123", + }, + wantPath: "/edinet/cross-shareholdings?code=86970&pagination_key=key123", + }, + { + name: "with no parameters", + params: EdinetCrossShareholdingsParams{}, + wantPath: "/edinet/cross-shareholdings", + }, + { + name: "with edinet code and code", + params: EdinetCrossShareholdingsParams{ + EdinetCode: "E03814", + Code: "86970", + }, + wantPath: "", + wantErr: true, + }, + } + + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + // Setup + mockClient := client.NewMockClient() + service := NewEdinetCrossShareholdingsService(mockClient) + + // Mock response based on documentation sample + mockResponse := EdinetCrossShareholdingsResponse{ + Data: []EdinetCrossShareholdingDoc{ + { + DocId: "S100YA84", + Code: "86970", + EdinetCode: "E03814", + FilerName: "株式会社日本取引所グループ", + FilerNameEn: "Japan Exchange Group, Inc.", + DocTypeCode: "120", + SubDate: "2026-06-11", + SubTime: "15:00:00", + PerSt: "2025-04-01", + PerEn: "2026-03-31", + Report: &EdinetCrossShareholdingBlock{ + HldrName: "株式会社日本取引所グループ", + HldrCode: "86970", + HldrEdinetCode: "E03814", + NonListedIss: 6, + NonListedBookVal: 1035000000, + }, + }, + }, + PaginationKey: "", + } + if !tt.wantErr { + mockClient.SetResponse("GET", tt.wantPath, mockResponse) + } + + // Execute + resp, err := service.GetCrossShareholdings(context.Background(), tt.params) + + // Verify + if tt.wantErr { + if err == nil { + t.Error("GetCrossShareholdings() expected error but got nil") + } + return + } + + if err != nil { + t.Fatalf("GetCrossShareholdings() error = %v", err) + } + if resp == nil { + t.Fatal("GetCrossShareholdings() returned nil response") + return + } + if len(resp.Data) == 0 { + t.Error("GetCrossShareholdings() returned empty data") + } + if mockClient.LastPath != tt.wantPath { + t.Errorf("GetCrossShareholdings() path = %v, want %v", mockClient.LastPath, tt.wantPath) + } + }) + } +} + +func TestEdinetCrossShareholdingsService_GetCrossShareholdings_RejectsEdinetCodeAndCode(t *testing.T) { + // Setup + mockClient := client.NewMockClient() + service := NewEdinetCrossShareholdingsService(mockClient) + + // Execute with both edinet_code and code + _, err := service.GetCrossShareholdings(context.Background(), EdinetCrossShareholdingsParams{ + EdinetCode: "E03814", + Code: "86970", + }) + + // Verify + if err == nil { + t.Error("GetCrossShareholdings() expected error for edinet_code and code but got nil") + } + if err.Error() != "edinet_code and code cannot be specified together" { + t.Errorf("GetCrossShareholdings() error = %v, want 'edinet_code and code cannot be specified together'", err) + } + if mockClient.RequestCount != 0 { + t.Errorf("GetCrossShareholdings() request count = %v, want 0", mockClient.RequestCount) + } +} + +func TestEdinetCrossShareholdingsService_GetCrossShareholdings_DecodesNestedBlocks(t *testing.T) { + // Setup + mockClient := client.NewMockClient() + service := NewEdinetCrossShareholdingsService(mockClient) + + // JSON-shaped mock response(ブロックのnull、非開示マーカー、数値が文字列で返るケースを含む) + mockJSON := json.RawMessage(`{ + "data": [ + { + "DocId": "S100YA84", + "Code": "86970", + "EdinetCode": "E03814", + "FilerName": "株式会社日本取引所グループ", + "FilerNameEn": "Japan Exchange Group, Inc.", + "DocTypeCode": "120", + "SubDate": "2026-06-11", + "SubTime": "15:00:00", + "PerSt": "2025-04-01", + "PerEn": "2026-03-31", + "Report": { + "HldrName": "株式会社日本取引所グループ", + "HldrCode": "86970", + "HldrEdinetCode": "E03814", + "ListedIss": 0, + "ListedBookVal": 0, + "ListedIncIss": 0, + "ListedIncAcqCost": 0, + "ListedDecIss": 0, + "ListedDecSaleAmt": 0, + "ListedIncRsn": null, + "NonListedIss": 6, + "NonListedBookVal": "1035000000", + "NonListedIncIss": 0, + "NonListedIncAcqCost": 0, + "NonListedDecIss": 0, + "NonListedDecSaleAmt": 0, + "NonListedIncRsn": null, + "Spec": [ + { + "IsrName": "株式会社サンプル銀行", + "IsrCode": "56780", + "IsrEdinetCode": "E05678", + "CurShs": "1200000", + "PriShs": 1200000, + "CurBookVal": 850000000, + "PriBookVal": 820000000, + "CurShsNotDisc": null, + "PriShsNotDisc": null, + "CurBookValNotDisc": null, + "PriBookValNotDisc": null, + "HoldRat": "取引関係の維持・強化のため", + "IsrHolds": "有", + "IsrHoldsCode": "1" + }, + { + "IsrName": "株式会社サンプル電機", + "IsrCode": null, + "IsrEdinetCode": null, + "CurShs": 500000, + "PriShs": null, + "CurBookVal": 350000000, + "PriBookVal": null, + "CurShsNotDisc": null, + "PriShsNotDisc": "(注3)", + "CurBookValNotDisc": null, + "PriBookValNotDisc": "(注3)", + "HoldRat": "議決権行使指図権を持つため", + "IsrHolds": "無(注)3", + "IsrHoldsCode": "0" + } + ], + "Deem": [], + "SpecFn": "

※ 特定投資株式は、事業関係の維持・強化を目的として保有しています。

", + "DeemFn": null + }, + "Largest": null, + "SecondLargest": { + "HldrName": "株式会社東京証券取引所", + "HldrCode": null, + "HldrEdinetCode": null, + "ListedIss": 0, + "ListedBookVal": 0, + "ListedIncIss": 0, + "ListedIncAcqCost": 0, + "ListedDecIss": 0, + "ListedDecSaleAmt": 0, + "ListedIncRsn": null, + "NonListedIss": 2, + "NonListedBookVal": 953000000, + "NonListedIncIss": 0, + "NonListedIncAcqCost": 0, + "NonListedDecIss": 0, + "NonListedDecSaleAmt": 0, + "NonListedIncRsn": null, + "Spec": [], + "Deem": [], + "SpecFn": null, + "DeemFn": null + } + } + ], + "pagination_key": "" + }`) + mockClient.SetResponse("GET", "/edinet/cross-shareholdings?edinet_code=E03814", mockJSON) + + // Execute + resp, err := service.GetCrossShareholdings(context.Background(), EdinetCrossShareholdingsParams{EdinetCode: "E03814"}) + + // Verify + if err != nil { + t.Fatalf("GetCrossShareholdings() error = %v", err) + } + if len(resp.Data) != 1 { + t.Fatalf("GetCrossShareholdings() returned %d items, want 1", len(resp.Data)) + } + + doc := resp.Data[0] + if doc.DocId != "S100YA84" { + t.Errorf("GetCrossShareholdings() DocId = %v, want S100YA84", doc.DocId) + } + if doc.DocTypeCode != "120" { + t.Errorf("GetCrossShareholdings() DocTypeCode = %v, want 120", doc.DocTypeCode) + } + + // ブロックの有無 + if !doc.HasReport() { + t.Fatal("GetCrossShareholdings() HasReport() = false, want true") + } + if doc.HasLargest() { + t.Error("GetCrossShareholdings() HasLargest() = true, want false") + } + if doc.Largest != nil { + t.Error("GetCrossShareholdings() Largest should be nil") + } + if !doc.HasSecondLargest() { + t.Fatal("GetCrossShareholdings() HasSecondLargest() = false, want true") + } + + // 提出会社ブロック + report := doc.Report + if report.HldrName != "株式会社日本取引所グループ" { + t.Errorf("GetCrossShareholdings() Report.HldrName = %v, want 株式会社日本取引所グループ", report.HldrName) + } + if report.NonListedIss != 6 { + t.Errorf("GetCrossShareholdings() Report.NonListedIss = %v, want 6", report.NonListedIss) + } + // 数値が文字列で返るケース + if report.NonListedBookVal != 1035000000 { + t.Errorf("GetCrossShareholdings() Report.NonListedBookVal = %v, want 1035000000", report.NonListedBookVal) + } + // nullの文字列は空文字になる + if report.ListedIncRsn != "" { + t.Errorf("GetCrossShareholdings() Report.ListedIncRsn = %v, want empty", report.ListedIncRsn) + } + if report.DeemFn != "" { + t.Errorf("GetCrossShareholdings() Report.DeemFn = %v, want empty", report.DeemFn) + } + if report.SpecFn == "" { + t.Error("GetCrossShareholdings() Report.SpecFn should not be empty") + } + if len(report.Deem) != 0 { + t.Errorf("GetCrossShareholdings() Report.Deem returned %d items, want 0", len(report.Deem)) + } + if len(report.Spec) != 2 { + t.Fatalf("GetCrossShareholdings() Report.Spec returned %d items, want 2", len(report.Spec)) + } + + // 開示されている銘柄(数値が文字列で返るケースを含む) + issue1 := report.Spec[0] + if issue1.IsrName != "株式会社サンプル銀行" { + t.Errorf("GetCrossShareholdings() Spec[0].IsrName = %v, want 株式会社サンプル銀行", issue1.IsrName) + } + if issue1.IsrCode != "56780" { + t.Errorf("GetCrossShareholdings() Spec[0].IsrCode = %v, want 56780", issue1.IsrCode) + } + if issue1.CurShs == nil || *issue1.CurShs != 1200000 { + t.Errorf("GetCrossShareholdings() Spec[0].CurShs = %v, want 1200000", ptrToStr(issue1.CurShs)) + } + if issue1.PriShs == nil || *issue1.PriShs != 1200000 { + t.Errorf("GetCrossShareholdings() Spec[0].PriShs = %v, want 1200000", ptrToStr(issue1.PriShs)) + } + if issue1.CurBookVal == nil || *issue1.CurBookVal != 850000000 { + t.Errorf("GetCrossShareholdings() Spec[0].CurBookVal = %v, want 850000000", ptrToStr(issue1.CurBookVal)) + } + if issue1.PriShsNotDisc != "" { + t.Errorf("GetCrossShareholdings() Spec[0].PriShsNotDisc = %v, want empty", issue1.PriShsNotDisc) + } + if !issue1.IsDisclosed() { + t.Error("GetCrossShareholdings() Spec[0].IsDisclosed() = false, want true") + } + if issue1.IsrHoldsCode != "1" { + t.Errorf("GetCrossShareholdings() Spec[0].IsrHoldsCode = %v, want 1", issue1.IsrHoldsCode) + } + + // 前期が非開示の銘柄(数値はnil、NotDiscにマーカー生値) + issue2 := report.Spec[1] + if issue2.IsrCode != "" { + t.Errorf("GetCrossShareholdings() Spec[1].IsrCode = %v, want empty", issue2.IsrCode) + } + if issue2.CurShs == nil || *issue2.CurShs != 500000 { + t.Errorf("GetCrossShareholdings() Spec[1].CurShs = %v, want 500000", ptrToStr(issue2.CurShs)) + } + if issue2.PriShs != nil { + t.Errorf("GetCrossShareholdings() Spec[1].PriShs = %v, want nil", ptrToStr(issue2.PriShs)) + } + if issue2.PriBookVal != nil { + t.Errorf("GetCrossShareholdings() Spec[1].PriBookVal = %v, want nil", ptrToStr(issue2.PriBookVal)) + } + if issue2.PriShsNotDisc != "(注3)" { + t.Errorf("GetCrossShareholdings() Spec[1].PriShsNotDisc = %v, want (注3)", issue2.PriShsNotDisc) + } + if issue2.PriBookValNotDisc != "(注3)" { + t.Errorf("GetCrossShareholdings() Spec[1].PriBookValNotDisc = %v, want (注3)", issue2.PriBookValNotDisc) + } + if issue2.IsrHolds != "無(注)3" { + t.Errorf("GetCrossShareholdings() Spec[1].IsrHolds = %v, want 無(注)3", issue2.IsrHolds) + } + + // 連結第二最大保有会社ブロック(nullの文字列は空文字になる) + secondLargest := doc.SecondLargest + if secondLargest.HldrName != "株式会社東京証券取引所" { + t.Errorf("GetCrossShareholdings() SecondLargest.HldrName = %v, want 株式会社東京証券取引所", secondLargest.HldrName) + } + if secondLargest.HldrCode != "" { + t.Errorf("GetCrossShareholdings() SecondLargest.HldrCode = %v, want empty", secondLargest.HldrCode) + } + if secondLargest.NonListedBookVal != 953000000 { + t.Errorf("GetCrossShareholdings() SecondLargest.NonListedBookVal = %v, want 953000000", secondLargest.NonListedBookVal) + } +} + +func TestEdinetCrossShareholdingsService_GetCrossShareholdingsByCode(t *testing.T) { + // Setup + mockClient := client.NewMockClient() + service := NewEdinetCrossShareholdingsService(mockClient) + + // Mock response - 最初のページ + mockResponse1 := EdinetCrossShareholdingsResponse{ + Data: []EdinetCrossShareholdingDoc{ + { + DocId: "S100YA84", + Code: "86970", + SubDate: "2026-06-11", + Report: &EdinetCrossShareholdingBlock{ + HldrName: "株式会社日本取引所グループ", + NonListedIss: 6, + }, + }, + { + DocId: "S100XB12", + Code: "86970", + SubDate: "2025-06-12", + Report: &EdinetCrossShareholdingBlock{ + HldrName: "株式会社日本取引所グループ", + NonListedIss: 5, + }, + }, + }, + PaginationKey: "next_page_key", + } + + // Mock response - 2ページ目 + mockResponse2 := EdinetCrossShareholdingsResponse{ + Data: []EdinetCrossShareholdingDoc{ + { + DocId: "S100WC34", + Code: "86970", + SubDate: "2024-06-13", + Report: &EdinetCrossShareholdingBlock{ + HldrName: "株式会社日本取引所グループ", + NonListedIss: 5, + }, + }, + }, + PaginationKey: "", // 最後のページ + } + + mockClient.SetResponse("GET", "/edinet/cross-shareholdings?code=86970", mockResponse1) + mockClient.SetResponse("GET", "/edinet/cross-shareholdings?code=86970&pagination_key=next_page_key", mockResponse2) + + // Execute + data, err := service.GetCrossShareholdingsByCode(context.Background(), "86970") + + // Verify + if err != nil { + t.Fatalf("GetCrossShareholdingsByCode() error = %v", err) + } + if len(data) != 3 { + t.Errorf("GetCrossShareholdingsByCode() returned %d items, want 3", len(data)) + } + for _, item := range data { + if item.Code != "86970" { + t.Errorf("GetCrossShareholdingsByCode() returned code %v, want 86970", item.Code) + } + } +} + +func TestEdinetCrossShareholdingsService_GetCrossShareholdingsByEdinetCode(t *testing.T) { + // Setup + mockClient := client.NewMockClient() + service := NewEdinetCrossShareholdingsService(mockClient) + + // Mock response + mockResponse := EdinetCrossShareholdingsResponse{ + Data: []EdinetCrossShareholdingDoc{ + { + DocId: "S100YA84", + Code: "86970", + EdinetCode: "E03814", + SubDate: "2026-06-11", + Report: &EdinetCrossShareholdingBlock{ + HldrName: "株式会社日本取引所グループ", + NonListedIss: 6, + }, + }, + }, + PaginationKey: "", + } + mockClient.SetResponse("GET", "/edinet/cross-shareholdings?edinet_code=E03814", mockResponse) + + // Execute + data, err := service.GetCrossShareholdingsByEdinetCode(context.Background(), "E03814") + + // Verify + if err != nil { + t.Fatalf("GetCrossShareholdingsByEdinetCode() error = %v", err) + } + if len(data) != 1 { + t.Errorf("GetCrossShareholdingsByEdinetCode() returned %d items, want 1", len(data)) + } + if data[0].EdinetCode != "E03814" { + t.Errorf("GetCrossShareholdingsByEdinetCode() returned edinet code %v, want E03814", data[0].EdinetCode) + } +} + +func TestEdinetCrossShareholdingsService_GetCrossShareholdingsByDate(t *testing.T) { + // Setup + mockClient := client.NewMockClient() + service := NewEdinetCrossShareholdingsService(mockClient) + + // Mock response + mockResponse := EdinetCrossShareholdingsResponse{ + Data: []EdinetCrossShareholdingDoc{ + { + DocId: "S100YA84", + Code: "86970", + SubDate: "2025-06-20", + Report: &EdinetCrossShareholdingBlock{ + HldrName: "株式会社日本取引所グループ", + NonListedIss: 6, + }, + }, + { + DocId: "S100YB56", + Code: "13660", + SubDate: "2025-06-20", + Report: &EdinetCrossShareholdingBlock{ + HldrName: "株式会社サンプル", + ListedIss: 3, + Spec: []EdinetCrossShareholdingIssue{ + { + IsrName: "株式会社サンプル銀行", + IsrCode: "56780", + CurShs: floatPtr(1200000), + }, + }, + }, + }, + }, + PaginationKey: "", + } + mockClient.SetResponse("GET", "/edinet/cross-shareholdings?date=20250620", mockResponse) + + // Execute + data, err := service.GetCrossShareholdingsByDate(context.Background(), "20250620") + + // Verify + if err != nil { + t.Fatalf("GetCrossShareholdingsByDate() error = %v", err) + } + if len(data) != 2 { + t.Errorf("GetCrossShareholdingsByDate() returned %d items, want 2", len(data)) + } + for _, item := range data { + if item.SubDate != "2025-06-20" { + t.Errorf("GetCrossShareholdingsByDate() returned sub date %v, want 2025-06-20", item.SubDate) + } + } +} + +func TestEdinetCrossShareholdingIssue_IsDisclosed(t *testing.T) { + tests := []struct { + name string + issue EdinetCrossShareholdingIssue + want bool + }{ + { + name: "disclosed", + issue: EdinetCrossShareholdingIssue{ + CurShs: floatPtr(1200000), + }, + want: true, + }, + { + name: "not disclosed", + issue: EdinetCrossShareholdingIssue{ + CurShs: nil, + CurShsNotDisc: "※", + }, + want: false, + }, + } + + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + if got := tt.issue.IsDisclosed(); got != tt.want { + t.Errorf("EdinetCrossShareholdingIssue.IsDisclosed() = %v, want %v", got, tt.want) + } + }) + } +} + +func TestEdinetCrossShareholdingsService_GetCrossShareholdings_Error(t *testing.T) { + // Setup + mockClient := client.NewMockClient() + service := NewEdinetCrossShareholdingsService(mockClient) + + // Set error response + mockClient.SetError("GET", "/edinet/cross-shareholdings?code=86970", fmt.Errorf("unauthorized")) + + // Execute + _, err := service.GetCrossShareholdings(context.Background(), EdinetCrossShareholdingsParams{Code: "86970"}) + + // Verify + if err == nil { + t.Error("GetCrossShareholdings() expected error but got nil") + } +} diff --git a/edinet_large_volume_shareholders.go b/edinet_large_volume_shareholders.go new file mode 100644 index 0000000..d45ccaf --- /dev/null +++ b/edinet_large_volume_shareholders.go @@ -0,0 +1,477 @@ +package jquants + +import ( + "context" + "encoding/json" + "fmt" + + "github.com/utahta/jquants/client" + "github.com/utahta/jquants/types" +) + +// EdinetLargeVolumeShareholdersService は大量保有報告書(EDINET)を取得するサービスです。 +// 大量保有報告書・変更報告書に記載されている発行者、提出者情報を取得します。 +type EdinetLargeVolumeShareholdersService struct { + client client.HTTPClient +} + +// NewEdinetLargeVolumeShareholdersService は新しいEdinetLargeVolumeShareholdersServiceを作成します。 +func NewEdinetLargeVolumeShareholdersService(c client.HTTPClient) *EdinetLargeVolumeShareholdersService { + return &EdinetLargeVolumeShareholdersService{client: c} +} + +// 大量保有書類種別コード(LargeHldgTypeCode)の定義 +const ( + LargeHldgTypeCodeUnknown = "0" // 不明 + LargeHldgTypeCodeReport = "1" // 大量保有報告書 + LargeHldgTypeCodeChangeReport = "2" // 変更報告書 + LargeHldgTypeCodeChangeReportShortTermTransfer = "3" // 変更報告書(短期大量譲渡) + LargeHldgTypeCodeSpecialReport = "4" // 大量保有報告書(特例対象株券等) + LargeHldgTypeCodeSpecialChangeReport = "5" // 変更報告書(特例対象株券等) +) + +// EdinetLargeVolumeShareholdersParams は大量保有報告書のリクエストパラメータです。 +// すべて任意ですが、edinet_codeとcodeの同時指定はできません。 +// すべて省略した場合はAPI実行日に提出された全書類のデータ一覧が返ります。 +type EdinetLargeVolumeShareholdersParams struct { + EdinetCode string // 発行者のEDINETコード(例: E03814)(codeとの同時指定は不可) + Code string // 発行者の4桁もしくは5桁の銘柄コード(edinet_codeとの同時指定は不可) + Date string // 提出日(YYYYMMDD または YYYY-MM-DD) + PaginationKey string // ページネーションキー +} + +// EdinetLargeVolumeShareholdersResponse は大量保有報告書のレスポンスです。 +type EdinetLargeVolumeShareholdersResponse struct { + Data []EdinetLargeVolumeShareholderDoc `json:"data"` + PaginationKey string `json:"pagination_key"` // ページネーションキー +} + +// EdinetLargeVolumeShareholderDoc は大量保有報告書・変更報告書1書類分のデータを表します。 +// J-Quants API /edinet/large-volume-shareholders エンドポイントのレスポンスデータ。 +// データは提出日2021年7月1日以降、対象書類は大量保有報告書・変更報告書等(書類種別コード350)。 +// 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"` // 報告義務発生日における変更事由(変更報告書のみ) + + // 保有状況の合計 + TotalShsHeld *float64 `json:"TotalShsHeld"` // 保有株券等の数の合計(株)(合計欄の記載がない書類ではnull) + TotalShsRatio *float64 `json:"TotalShsRatio"` // 株券等保有割合の合計(小数表現。0.1343=13.43%)(合計欄の記載がない書類ではnull) + TotalShsRatioLast *float64 `json:"TotalShsRatioLast"` // 直前の報告書に係る株券等保有割合の合計(変更報告書のみ) + TotalOutStks float64 `json:"TotalOutStks"` // 発行済株式等総数(株) + + // 提出者及び共同保有者のレコード + Hldrs []EdinetLargeVolumeShareholderHolder `json:"Hldrs"` +} + +// EdinetLargeVolumeShareholderHolder は提出者・共同保有者1名分のデータを表します。 +type EdinetLargeVolumeShareholderHolder struct { + // 保有者情報 + HldrName string `json:"HldrName"` // 保有者の氏名又は名称 + HldrNameEn string `json:"HldrNameEn"` // 保有者の名称(英語) + HldrEdinetCode string `json:"HldrEdinetCode"` // 保有者のEDINETコード + HldrCode string `json:"HldrCode"` // 保有者の銘柄コード(保有者が上場会社の場合等) + LargeHldrTypeCode string `json:"LargeHldrTypeCode"` // 保有者区分コード(1=個人、2=法人、0=不明) + LargeHldrTypeRaw string `json:"LargeHldrTypeRaw"` // 保有者区分(個人法人の別)の書類記載生値 + + // 保有状況 + HldgPurp string `json:"HldgPurp"` // 保有目的 + ImpProp string `json:"ImpProp"` // 重要提案行為等 + ColAgr string `json:"ColAgr"` // 担保契約等重要な契約 + ShsHeld float64 `json:"ShsHeld"` // 保有株券等の数(株) + ShsRatio float64 `json:"ShsRatio"` // 株券等保有割合(小数表現。0.0572=5.72%) + ShsRatioLast *float64 `json:"ShsRatioLast"` // 直前の報告書に係る株券等保有割合(変更報告書のみ) + + // 取得資金 + OwnFund *float64 `json:"OwnFund"` // 取得資金のうち自己資金額(円) + TotalBrw *float64 `json:"TotalBrw"` // 取得資金のうち借入金額計(円) + TotalOther *float64 `json:"TotalOther"` // 取得資金のうちその他金額計(円) + OtherBrk string `json:"OtherBrk"` // その他金額計の内訳(株式分割による取得等、記載がある場合) + TotalFund *float64 `json:"TotalFund"` // 取得資金合計(円) + + // 明細 + AcqDisp []EdinetLargeVolumeShareholderAcqDisp `json:"AcqDisp"` // 最近60日間の取得又は処分の状況 + BrwList []EdinetLargeVolumeShareholderBorrowing `json:"BrwList"` // 借入金の内訳 + CredList []EdinetLargeVolumeShareholderCreditor `json:"CredList"` // 借入先の名称等 +} + +// EdinetLargeVolumeShareholderAcqDisp は最近60日間の取得又は処分の状況1件分を表します。 +type EdinetLargeVolumeShareholderAcqDisp struct { + Date string `json:"Date"` // 年月日(YYYY-MM-DD形式) + SecType string `json:"SecType"` // 株券等の種類(例: 普通株式) + Shs float64 `json:"Shs"` // 数量(株) + Ratio *float64 `json:"Ratio"` // 割合(%表記。他の保有割合と異なり小数表現ではない) + Mkt string `json:"Mkt"` // 市場内外取引の別(書類記載の生値) + MktCode string `json:"MktCode"` // 市場内外取引コード(1=市場内、2=市場外) + TxnType string `json:"TxnType"` // 取得又は処分の別(書類記載の生値) + TxnTypeCode string `json:"TxnTypeCode"` // 取得又は処分コード(1=取得、2=処分) + Cptty string `json:"Cptty"` // 譲渡の相手方(短期大量譲渡変更の書類でのみ記載) + Price *float64 `json:"Price"` // 単価(円) + PriceRaw string `json:"PriceRaw"` // 単価を数値化できない場合の生値 +} + +// EdinetLargeVolumeShareholderBorrowing は借入金の内訳1件分を表します。 +type EdinetLargeVolumeShareholderBorrowing struct { + Name string `json:"Name"` // 名称(支店名を含む) + Ind string `json:"Ind"` // 業種 + Rep string `json:"Rep"` // 代表者氏名 + Addr string `json:"Addr"` // 所在地 + DiscBrwPurp string `json:"DiscBrwPurp"` // 借入目的の開示区分(1=銀行等に開示せず、2=銀行等に開示及び銀行等以外の借入) + Amt *float64 `json:"Amt"` // 金額(円) +} + +// EdinetLargeVolumeShareholderCreditor は借入先の名称等1件分を表します。 +type EdinetLargeVolumeShareholderCreditor struct { + Name string `json:"Name"` // 名称(支店名を含む) + Rep string `json:"Rep"` // 代表者氏名 + Addr string `json:"Addr"` // 所在地 +} + +// 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"` + + // 保有状況の合計 + TotalShsHeld types.NullableFloat64 `json:"TotalShsHeld"` + TotalShsRatio types.NullableFloat64 `json:"TotalShsRatio"` + TotalShsRatioLast types.NullableFloat64 `json:"TotalShsRatioLast"` + TotalOutStks types.NullableFloat64 `json:"TotalOutStks"` + + // 提出者及び共同保有者のレコード + Hldrs []RawEdinetLargeVolumeShareholderHolder `json:"Hldrs"` +} + +// RawEdinetLargeVolumeShareholderHolder is used for unmarshaling JSON response with mixed types +type RawEdinetLargeVolumeShareholderHolder struct { + HldrName string `json:"HldrName"` + HldrNameEn string `json:"HldrNameEn"` + HldrEdinetCode string `json:"HldrEdinetCode"` + HldrCode string `json:"HldrCode"` + LargeHldrTypeCode string `json:"LargeHldrTypeCode"` + LargeHldrTypeRaw string `json:"LargeHldrTypeRaw"` + + HldgPurp string `json:"HldgPurp"` + ImpProp string `json:"ImpProp"` + ColAgr string `json:"ColAgr"` + ShsHeld types.NullableFloat64 `json:"ShsHeld"` + ShsRatio types.NullableFloat64 `json:"ShsRatio"` + ShsRatioLast types.NullableFloat64 `json:"ShsRatioLast"` + + OwnFund types.NullableFloat64 `json:"OwnFund"` + TotalBrw types.NullableFloat64 `json:"TotalBrw"` + TotalOther types.NullableFloat64 `json:"TotalOther"` + OtherBrk string `json:"OtherBrk"` + TotalFund types.NullableFloat64 `json:"TotalFund"` + + AcqDisp []RawEdinetLargeVolumeShareholderAcqDisp `json:"AcqDisp"` + BrwList []RawEdinetLargeVolumeShareholderBorrowing `json:"BrwList"` + CredList []EdinetLargeVolumeShareholderCreditor `json:"CredList"` +} + +// RawEdinetLargeVolumeShareholderAcqDisp is used for unmarshaling JSON response with mixed types +type RawEdinetLargeVolumeShareholderAcqDisp struct { + Date string `json:"Date"` + SecType string `json:"SecType"` + Shs types.NullableFloat64 `json:"Shs"` + Ratio types.NullableFloat64 `json:"Ratio"` + Mkt string `json:"Mkt"` + MktCode string `json:"MktCode"` + TxnType string `json:"TxnType"` + TxnTypeCode string `json:"TxnTypeCode"` + Cptty string `json:"Cptty"` + Price types.NullableFloat64 `json:"Price"` + PriceRaw string `json:"PriceRaw"` +} + +// RawEdinetLargeVolumeShareholderBorrowing is used for unmarshaling JSON response with mixed types +type RawEdinetLargeVolumeShareholderBorrowing struct { + Name string `json:"Name"` + Ind string `json:"Ind"` + Rep string `json:"Rep"` + Addr string `json:"Addr"` + DiscBrwPurp string `json:"DiscBrwPurp"` + Amt types.NullableFloat64 `json:"Amt"` +} + +// UnmarshalJSON implements custom JSON unmarshaling for EdinetLargeVolumeShareholdersResponse +func (r *EdinetLargeVolumeShareholdersResponse) UnmarshalJSON(data []byte) error { + // First unmarshal into RawEdinetLargeVolumeShareholderDoc + type rawResponse struct { + Data []RawEdinetLargeVolumeShareholderDoc `json:"data"` + PaginationKey string `json:"pagination_key"` + } + + var raw rawResponse + if err := json.Unmarshal(data, &raw); err != nil { + return err + } + + // Set pagination key + r.PaginationKey = raw.PaginationKey + + // Convert RawEdinetLargeVolumeShareholderDoc to EdinetLargeVolumeShareholderDoc + r.Data = make([]EdinetLargeVolumeShareholderDoc, len(raw.Data)) + for idx, rd := range raw.Data { + r.Data[idx] = rd.toDoc() + } + + return nil +} + +// toDoc converts RawEdinetLargeVolumeShareholderDoc to EdinetLargeVolumeShareholderDoc +func (rd RawEdinetLargeVolumeShareholderDoc) toDoc() EdinetLargeVolumeShareholderDoc { + holders := make([]EdinetLargeVolumeShareholderHolder, len(rd.Hldrs)) + for idx, rh := range rd.Hldrs { + holders[idx] = rh.toHolder() + } + + return EdinetLargeVolumeShareholderDoc{ + // 書類メタ情報 + DocId: rd.DocId, + Code: rd.Code, + EdinetCode: rd.EdinetCode, + IsrName: rd.IsrName, + DocTypeCode: rd.DocTypeCode, + SubDate: rd.SubDate, + SubTime: rd.SubTime, + LargeHldgTypeCode: rd.LargeHldgTypeCode, + DocTitle: rd.DocTitle, + ChgRsn: rd.ChgRsn, + + // 保有状況の合計 + TotalShsHeld: rd.TotalShsHeld.Ptr(), + TotalShsRatio: rd.TotalShsRatio.Ptr(), + TotalShsRatioLast: rd.TotalShsRatioLast.Ptr(), + TotalOutStks: rd.TotalOutStks.Or(0), + + // 提出者及び共同保有者のレコード + Hldrs: holders, + } +} + +// toHolder converts RawEdinetLargeVolumeShareholderHolder to EdinetLargeVolumeShareholderHolder +func (rh RawEdinetLargeVolumeShareholderHolder) toHolder() EdinetLargeVolumeShareholderHolder { + acqDisps := make([]EdinetLargeVolumeShareholderAcqDisp, len(rh.AcqDisp)) + for idx, ra := range rh.AcqDisp { + acqDisps[idx] = EdinetLargeVolumeShareholderAcqDisp{ + Date: ra.Date, + SecType: ra.SecType, + Shs: ra.Shs.Or(0), + Ratio: ra.Ratio.Ptr(), + Mkt: ra.Mkt, + MktCode: ra.MktCode, + TxnType: ra.TxnType, + TxnTypeCode: ra.TxnTypeCode, + Cptty: ra.Cptty, + Price: ra.Price.Ptr(), + PriceRaw: ra.PriceRaw, + } + } + + borrowings := make([]EdinetLargeVolumeShareholderBorrowing, len(rh.BrwList)) + for idx, rb := range rh.BrwList { + borrowings[idx] = EdinetLargeVolumeShareholderBorrowing{ + Name: rb.Name, + Ind: rb.Ind, + Rep: rb.Rep, + Addr: rb.Addr, + DiscBrwPurp: rb.DiscBrwPurp, + Amt: rb.Amt.Ptr(), + } + } + + return EdinetLargeVolumeShareholderHolder{ + // 保有者情報 + HldrName: rh.HldrName, + HldrNameEn: rh.HldrNameEn, + HldrEdinetCode: rh.HldrEdinetCode, + HldrCode: rh.HldrCode, + LargeHldrTypeCode: rh.LargeHldrTypeCode, + LargeHldrTypeRaw: rh.LargeHldrTypeRaw, + + // 保有状況 + HldgPurp: rh.HldgPurp, + ImpProp: rh.ImpProp, + ColAgr: rh.ColAgr, + ShsHeld: rh.ShsHeld.Or(0), + ShsRatio: rh.ShsRatio.Or(0), + ShsRatioLast: rh.ShsRatioLast.Ptr(), + + // 取得資金 + OwnFund: rh.OwnFund.Ptr(), + TotalBrw: rh.TotalBrw.Ptr(), + TotalOther: rh.TotalOther.Ptr(), + OtherBrk: rh.OtherBrk, + TotalFund: rh.TotalFund.Ptr(), + + // 明細 + AcqDisp: acqDisps, + BrwList: borrowings, + CredList: rh.CredList, + } +} + +// GetLargeVolumeShareholders は大量保有報告書を取得します。 +// パラメータをすべて省略した場合はAPI実行日に提出された全書類のデータ一覧を取得します。 +func (s *EdinetLargeVolumeShareholdersService) GetLargeVolumeShareholders(ctx context.Context, params EdinetLargeVolumeShareholdersParams) (*EdinetLargeVolumeShareholdersResponse, error) { + // edinet_codeとcodeの同時指定は不可 + if params.EdinetCode != "" && params.Code != "" { + return nil, fmt.Errorf("edinet_code and code cannot be specified together") + } + + path := "/edinet/large-volume-shareholders" + + query := "?" + if params.EdinetCode != "" { + query += fmt.Sprintf("edinet_code=%s&", params.EdinetCode) + } + if params.Code != "" { + query += fmt.Sprintf("code=%s&", params.Code) + } + if params.Date != "" { + query += fmt.Sprintf("date=%s&", params.Date) + } + if params.PaginationKey != "" { + query += fmt.Sprintf("pagination_key=%s&", params.PaginationKey) + } + + if len(query) > 1 { + path += query[:len(query)-1] // Remove trailing & + } + + var resp EdinetLargeVolumeShareholdersResponse + if err := s.client.DoRequest(ctx, "GET", path, nil, &resp); err != nil { + return nil, fmt.Errorf("failed to get large volume shareholders: %w", err) + } + + return &resp, nil +} + +// GetLargeVolumeShareholdersByCode は指定銘柄の大量保有報告書を取得します。 +// ページネーションを使用して全データを取得します。 +func (s *EdinetLargeVolumeShareholdersService) GetLargeVolumeShareholdersByCode(ctx context.Context, code string) ([]EdinetLargeVolumeShareholderDoc, error) { + var allData []EdinetLargeVolumeShareholderDoc + paginationKey := "" + + for { + params := EdinetLargeVolumeShareholdersParams{ + Code: code, + PaginationKey: paginationKey, + } + + resp, err := s.GetLargeVolumeShareholders(ctx, params) + if err != nil { + return nil, err + } + + allData = append(allData, resp.Data...) + + // ページネーションキーがなければ終了 + if resp.PaginationKey == "" { + break + } + paginationKey = resp.PaginationKey + } + + return allData, nil +} + +// GetLargeVolumeShareholdersByEdinetCode は指定EDINETコードの発行者に係る大量保有報告書を取得します。 +// ページネーションを使用して全データを取得します。 +func (s *EdinetLargeVolumeShareholdersService) GetLargeVolumeShareholdersByEdinetCode(ctx context.Context, edinetCode string) ([]EdinetLargeVolumeShareholderDoc, error) { + var allData []EdinetLargeVolumeShareholderDoc + paginationKey := "" + + for { + params := EdinetLargeVolumeShareholdersParams{ + EdinetCode: edinetCode, + PaginationKey: paginationKey, + } + + resp, err := s.GetLargeVolumeShareholders(ctx, params) + if err != nil { + return nil, err + } + + allData = append(allData, resp.Data...) + + // ページネーションキーがなければ終了 + if resp.PaginationKey == "" { + break + } + paginationKey = resp.PaginationKey + } + + return allData, nil +} + +// GetLargeVolumeShareholdersByDate は指定提出日の全書類の大量保有報告書を取得します。 +// ページネーションを使用して全データを取得します。 +func (s *EdinetLargeVolumeShareholdersService) GetLargeVolumeShareholdersByDate(ctx context.Context, date string) ([]EdinetLargeVolumeShareholderDoc, error) { + var allData []EdinetLargeVolumeShareholderDoc + paginationKey := "" + + for { + params := EdinetLargeVolumeShareholdersParams{ + Date: date, + PaginationKey: paginationKey, + } + + resp, err := s.GetLargeVolumeShareholders(ctx, params) + if err != nil { + return nil, err + } + + allData = append(allData, resp.Data...) + + // ページネーションキーがなければ終了 + if resp.PaginationKey == "" { + break + } + paginationKey = resp.PaginationKey + } + + return allData, nil +} + +// IsChangeReport は変更報告書(変更報告書、短期大量譲渡、特例対象株券等の変更報告書)かを判定します。 +func (d *EdinetLargeVolumeShareholderDoc) IsChangeReport() bool { + switch d.LargeHldgTypeCode { + case LargeHldgTypeCodeChangeReport, LargeHldgTypeCodeChangeReportShortTermTransfer, LargeHldgTypeCodeSpecialChangeReport: + return true + } + return false +} + +// GetTotalShareholdingPercentage は株券等保有割合の合計をパーセント表記で取得します。 +// 合計欄の記載がない書類(TotalShsRatioがnull)の場合は0を返します。 +func (d *EdinetLargeVolumeShareholderDoc) GetTotalShareholdingPercentage() float64 { + if d.TotalShsRatio == nil { + return 0 + } + return *d.TotalShsRatio * 100 +} + +// GetShareholdingPercentage は株券等保有割合をパーセント表記で取得します。 +func (h *EdinetLargeVolumeShareholderHolder) GetShareholdingPercentage() float64 { + return h.ShsRatio * 100 +} diff --git a/edinet_large_volume_shareholders_test.go b/edinet_large_volume_shareholders_test.go new file mode 100644 index 0000000..8a3beaa --- /dev/null +++ b/edinet_large_volume_shareholders_test.go @@ -0,0 +1,640 @@ +package jquants + +import ( + "context" + "encoding/json" + "fmt" + "testing" + + "github.com/utahta/jquants/client" +) + +func TestEdinetLargeVolumeShareholdersService_GetLargeVolumeShareholders(t *testing.T) { + tests := []struct { + name string + params EdinetLargeVolumeShareholdersParams + wantPath string + wantErr bool + }{ + { + name: "with edinet code", + params: EdinetLargeVolumeShareholdersParams{ + EdinetCode: "E03814", + }, + wantPath: "/edinet/large-volume-shareholders?edinet_code=E03814", + }, + { + name: "with code", + params: EdinetLargeVolumeShareholdersParams{ + Code: "86970", + }, + wantPath: "/edinet/large-volume-shareholders?code=86970", + }, + { + name: "with date", + params: EdinetLargeVolumeShareholdersParams{ + Date: "20250707", + }, + wantPath: "/edinet/large-volume-shareholders?date=20250707", + }, + { + name: "with date in hyphen format", + params: EdinetLargeVolumeShareholdersParams{ + Date: "2025-07-07", + }, + wantPath: "/edinet/large-volume-shareholders?date=2025-07-07", + }, + { + name: "with code and date", + params: EdinetLargeVolumeShareholdersParams{ + Code: "86970", + Date: "20250707", + }, + wantPath: "/edinet/large-volume-shareholders?code=86970&date=20250707", + }, + { + name: "with edinet code and date", + params: EdinetLargeVolumeShareholdersParams{ + EdinetCode: "E03814", + Date: "20250707", + }, + wantPath: "/edinet/large-volume-shareholders?edinet_code=E03814&date=20250707", + }, + { + name: "with pagination key", + params: EdinetLargeVolumeShareholdersParams{ + Code: "86970", + PaginationKey: "key123", + }, + wantPath: "/edinet/large-volume-shareholders?code=86970&pagination_key=key123", + }, + { + name: "with no parameters", + params: EdinetLargeVolumeShareholdersParams{}, + wantPath: "/edinet/large-volume-shareholders", + }, + { + name: "with edinet code and code", + params: EdinetLargeVolumeShareholdersParams{ + EdinetCode: "E03814", + Code: "86970", + }, + wantPath: "", + wantErr: true, + }, + } + + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + // Setup + mockClient := client.NewMockClient() + service := NewEdinetLargeVolumeShareholdersService(mockClient) + + // Mock response based on documentation sample + ratioLast := 0.0614 + mockResponse := EdinetLargeVolumeShareholdersResponse{ + Data: []EdinetLargeVolumeShareholderDoc{ + { + DocId: "S100WBIV", + Code: "86970", + EdinetCode: "E03814", + IsrName: "株式会社日本取引所グループ", + DocTypeCode: "350", + SubDate: "2025-07-07", + SubTime: "12:09:00", + LargeHldgTypeCode: "5", + DocTitle: "変更報告書NO.9", + ChgRsn: "・株券等保有割合の1%以上の増加", + TotalShsHeld: floatPtr(76018630), + TotalShsRatio: floatPtr(0.0728), + TotalShsRatioLast: &ratioLast, + TotalOutStks: 1044578366, + Hldrs: []EdinetLargeVolumeShareholderHolder{ + { + HldrName: "サンプル・アセットマネジメント株式会社", + HldrEdinetCode: "E99990", + LargeHldrTypeCode: "2", + ShsHeld: 59555500, + ShsRatio: 0.057, + }, + }, + }, + }, + PaginationKey: "", + } + if !tt.wantErr { + mockClient.SetResponse("GET", tt.wantPath, mockResponse) + } + + // Execute + resp, err := service.GetLargeVolumeShareholders(context.Background(), tt.params) + + // Verify + if tt.wantErr { + if err == nil { + t.Error("GetLargeVolumeShareholders() expected error but got nil") + } + return + } + + if err != nil { + t.Fatalf("GetLargeVolumeShareholders() error = %v", err) + } + if resp == nil { + t.Fatal("GetLargeVolumeShareholders() returned nil response") + return + } + if len(resp.Data) == 0 { + t.Error("GetLargeVolumeShareholders() returned empty data") + } + if mockClient.LastPath != tt.wantPath { + t.Errorf("GetLargeVolumeShareholders() path = %v, want %v", mockClient.LastPath, tt.wantPath) + } + }) + } +} + +func TestEdinetLargeVolumeShareholdersService_GetLargeVolumeShareholders_RejectsEdinetCodeAndCode(t *testing.T) { + // Setup + mockClient := client.NewMockClient() + service := NewEdinetLargeVolumeShareholdersService(mockClient) + + // Execute with both edinet_code and code + _, err := service.GetLargeVolumeShareholders(context.Background(), EdinetLargeVolumeShareholdersParams{ + EdinetCode: "E03814", + Code: "86970", + }) + + // Verify + if err == nil { + t.Error("GetLargeVolumeShareholders() expected error for edinet_code and code but got nil") + } + if err.Error() != "edinet_code and code cannot be specified together" { + t.Errorf("GetLargeVolumeShareholders() error = %v, want 'edinet_code and code cannot be specified together'", err) + } + if mockClient.RequestCount != 0 { + t.Errorf("GetLargeVolumeShareholders() request count = %v, want 0", mockClient.RequestCount) + } +} + +func TestEdinetLargeVolumeShareholdersService_GetLargeVolumeShareholders_DecodesNestedHolders(t *testing.T) { + // Setup + mockClient := client.NewMockClient() + service := NewEdinetLargeVolumeShareholdersService(mockClient) + + // JSON-shaped mock response(null値・数値が文字列で返るケースを含む) + mockJSON := json.RawMessage(`{ + "data": [ + { + "DocId": "S100WBIV", + "Code": "86970", + "EdinetCode": "E03814", + "IsrName": "株式会社日本取引所グループ", + "DocTypeCode": "350", + "SubDate": "2025-07-07", + "SubTime": "12:09:00", + "LargeHldgTypeCode": "5", + "DocTitle": "変更報告書NO.9", + "ChgRsn": "・株券等保有割合の1%以上の増加", + "TotalShsHeld": "76018630", + "TotalShsRatio": 0.0728, + "TotalShsRatioLast": 0.0614, + "TotalOutStks": 1044578366, + "Hldrs": [ + { + "HldrName": "サンプル・アセットマネジメント株式会社", + "HldrNameEn": "Sample Asset Management Co., Ltd.", + "HldrEdinetCode": "E99990", + "HldrCode": null, + "LargeHldrTypeCode": "2", + "LargeHldrTypeRaw": "法人(株式会社)", + "HldgPurp": "信託財産の運用として保有している。", + "ImpProp": null, + "ColAgr": null, + "ShsHeld": 59555500, + "ShsRatio": 0.057, + "ShsRatioLast": 0.0506, + "OwnFund": null, + "TotalBrw": null, + "TotalOther": null, + "OtherBrk": null, + "TotalFund": null, + "AcqDisp": [], + "BrwList": [], + "CredList": [] + }, + { + "HldrName": "サンプル証券株式会社", + "HldrNameEn": "Sample Securities Co., Ltd.", + "HldrEdinetCode": "E99991", + "HldrCode": null, + "LargeHldrTypeCode": "2", + "LargeHldrTypeRaw": "法人(株式会社)", + "HldgPurp": "証券業務に係る商品在庫として保有している。", + "ImpProp": null, + "ColAgr": "消費貸借契約により、サンプル信託銀行株式会社から1,000,000株借入れている。", + "ShsHeld": 8893542, + "ShsRatio": 0.0085, + "ShsRatioLast": 0.0095, + "OwnFund": 300000000, + "TotalBrw": 500000000, + "TotalOther": null, + "OtherBrk": null, + "TotalFund": 800000000, + "AcqDisp": [ + { + "Date": "2025-06-20", + "SecType": "普通株式", + "Shs": 100000, + "Ratio": 0.01, + "Mkt": "市場内", + "MktCode": "1", + "TxnType": "取得", + "TxnTypeCode": "1", + "Cptty": null, + "Price": 3800, + "PriceRaw": null + }, + { + "Date": "2025-06-23", + "SecType": "普通株式", + "Shs": "50000", + "Ratio": null, + "Mkt": "市場外", + "MktCode": "2", + "TxnType": "処分", + "TxnTypeCode": "2", + "Cptty": null, + "Price": null, + "PriceRaw": "3,800円" + } + ], + "BrwList": [ + { + "Name": "サンプル銀行株式会社", + "Ind": "銀行", + "Rep": "代表取締役 見本 太郎", + "Addr": "東京都千代田区丸の内一丁目1番1号", + "DiscBrwPurp": "2", + "Amt": 500000000 + } + ], + "CredList": [ + { + "Name": "サンプル信託銀行株式会社", + "Rep": "代表取締役 例示 花子", + "Addr": "東京都千代田区大手町一丁目1番1号" + } + ] + } + ] + } + ], + "pagination_key": "" + }`) + mockClient.SetResponse("GET", "/edinet/large-volume-shareholders?edinet_code=E03814", mockJSON) + + // Execute + resp, err := service.GetLargeVolumeShareholders(context.Background(), EdinetLargeVolumeShareholdersParams{EdinetCode: "E03814"}) + + // Verify + if err != nil { + t.Fatalf("GetLargeVolumeShareholders() error = %v", err) + } + if len(resp.Data) != 1 { + t.Fatalf("GetLargeVolumeShareholders() returned %d items, want 1", len(resp.Data)) + } + + doc := resp.Data[0] + if doc.DocId != "S100WBIV" { + t.Errorf("GetLargeVolumeShareholders() DocId = %v, want S100WBIV", doc.DocId) + } + if doc.LargeHldgTypeCode != LargeHldgTypeCodeSpecialChangeReport { + t.Errorf("GetLargeVolumeShareholders() LargeHldgTypeCode = %v, want 5", doc.LargeHldgTypeCode) + } + if !doc.IsChangeReport() { + t.Error("GetLargeVolumeShareholders() IsChangeReport() = false, want true") + } + // 数値が文字列で返るケース + if doc.TotalShsHeld == nil || *doc.TotalShsHeld != 76018630 { + t.Errorf("GetLargeVolumeShareholders() TotalShsHeld = %v, want 76018630", ptrToStr(doc.TotalShsHeld)) + } + if doc.TotalShsRatio == nil || *doc.TotalShsRatio != 0.0728 { + t.Errorf("GetLargeVolumeShareholders() TotalShsRatio = %v, want 0.0728", ptrToStr(doc.TotalShsRatio)) + } + if doc.TotalShsRatioLast == nil || *doc.TotalShsRatioLast != 0.0614 { + t.Errorf("GetLargeVolumeShareholders() TotalShsRatioLast = %v, want 0.0614", doc.TotalShsRatioLast) + } + if doc.TotalOutStks != 1044578366 { + t.Errorf("GetLargeVolumeShareholders() TotalOutStks = %v, want 1044578366", doc.TotalOutStks) + } + if len(doc.Hldrs) != 2 { + t.Fatalf("GetLargeVolumeShareholders() returned %d holders, want 2", len(doc.Hldrs)) + } + + // null資金の保有者(nilポインタになること) + holder1 := doc.Hldrs[0] + if holder1.HldrName != "サンプル・アセットマネジメント株式会社" { + t.Errorf("GetLargeVolumeShareholders() Hldrs[0].HldrName = %v, want サンプル・アセットマネジメント株式会社", holder1.HldrName) + } + if holder1.HldrCode != "" { + t.Errorf("GetLargeVolumeShareholders() Hldrs[0].HldrCode = %v, want empty", holder1.HldrCode) + } + if holder1.ShsHeld != 59555500 { + t.Errorf("GetLargeVolumeShareholders() Hldrs[0].ShsHeld = %v, want 59555500", holder1.ShsHeld) + } + if holder1.ShsRatioLast == nil || *holder1.ShsRatioLast != 0.0506 { + t.Errorf("GetLargeVolumeShareholders() Hldrs[0].ShsRatioLast = %v, want 0.0506", holder1.ShsRatioLast) + } + if holder1.OwnFund != nil { + t.Errorf("GetLargeVolumeShareholders() Hldrs[0].OwnFund = %v, want nil", holder1.OwnFund) + } + if holder1.TotalBrw != nil { + t.Errorf("GetLargeVolumeShareholders() Hldrs[0].TotalBrw = %v, want nil", holder1.TotalBrw) + } + if holder1.TotalOther != nil { + t.Errorf("GetLargeVolumeShareholders() Hldrs[0].TotalOther = %v, want nil", holder1.TotalOther) + } + if holder1.TotalFund != nil { + t.Errorf("GetLargeVolumeShareholders() Hldrs[0].TotalFund = %v, want nil", holder1.TotalFund) + } + if len(holder1.AcqDisp) != 0 { + t.Errorf("GetLargeVolumeShareholders() Hldrs[0].AcqDisp has %d items, want 0", len(holder1.AcqDisp)) + } + + // 資金・明細ありの保有者 + holder2 := doc.Hldrs[1] + if holder2.OwnFund == nil || *holder2.OwnFund != 300000000 { + t.Errorf("GetLargeVolumeShareholders() Hldrs[1].OwnFund = %v, want 300000000", holder2.OwnFund) + } + if holder2.TotalBrw == nil || *holder2.TotalBrw != 500000000 { + t.Errorf("GetLargeVolumeShareholders() Hldrs[1].TotalBrw = %v, want 500000000", holder2.TotalBrw) + } + if holder2.TotalOther != nil { + t.Errorf("GetLargeVolumeShareholders() Hldrs[1].TotalOther = %v, want nil", holder2.TotalOther) + } + if holder2.TotalFund == nil || *holder2.TotalFund != 800000000 { + t.Errorf("GetLargeVolumeShareholders() Hldrs[1].TotalFund = %v, want 800000000", holder2.TotalFund) + } + if len(holder2.AcqDisp) != 2 { + t.Fatalf("GetLargeVolumeShareholders() Hldrs[1].AcqDisp has %d items, want 2", len(holder2.AcqDisp)) + } + + // 単価が数値で返るケース + acqDisp1 := holder2.AcqDisp[0] + if acqDisp1.Shs != 100000 { + t.Errorf("GetLargeVolumeShareholders() AcqDisp[0].Shs = %v, want 100000", acqDisp1.Shs) + } + if acqDisp1.Ratio == nil || *acqDisp1.Ratio != 0.01 { + t.Errorf("GetLargeVolumeShareholders() AcqDisp[0].Ratio = %v, want 0.01", acqDisp1.Ratio) + } + if acqDisp1.Price == nil || *acqDisp1.Price != 3800 { + t.Errorf("GetLargeVolumeShareholders() AcqDisp[0].Price = %v, want 3800", acqDisp1.Price) + } + if acqDisp1.PriceRaw != "" { + t.Errorf("GetLargeVolumeShareholders() AcqDisp[0].PriceRaw = %v, want empty", acqDisp1.PriceRaw) + } + + // 単価を数値化できず生値のみ返るケース(数量が文字列で返るケースを含む) + acqDisp2 := holder2.AcqDisp[1] + if acqDisp2.Shs != 50000 { + t.Errorf("GetLargeVolumeShareholders() AcqDisp[1].Shs = %v, want 50000", acqDisp2.Shs) + } + if acqDisp2.Ratio != nil { + t.Errorf("GetLargeVolumeShareholders() AcqDisp[1].Ratio = %v, want nil", acqDisp2.Ratio) + } + if acqDisp2.Price != nil { + t.Errorf("GetLargeVolumeShareholders() AcqDisp[1].Price = %v, want nil", acqDisp2.Price) + } + if acqDisp2.PriceRaw != "3,800円" { + t.Errorf("GetLargeVolumeShareholders() AcqDisp[1].PriceRaw = %v, want 3,800円", acqDisp2.PriceRaw) + } + + // 借入金の内訳・借入先 + if len(holder2.BrwList) != 1 { + t.Fatalf("GetLargeVolumeShareholders() Hldrs[1].BrwList has %d items, want 1", len(holder2.BrwList)) + } + borrowing := holder2.BrwList[0] + if borrowing.Name != "サンプル銀行株式会社" { + t.Errorf("GetLargeVolumeShareholders() BrwList[0].Name = %v, want サンプル銀行株式会社", borrowing.Name) + } + if borrowing.Amt == nil || *borrowing.Amt != 500000000 { + t.Errorf("GetLargeVolumeShareholders() BrwList[0].Amt = %v, want 500000000", borrowing.Amt) + } + if len(holder2.CredList) != 1 { + t.Fatalf("GetLargeVolumeShareholders() Hldrs[1].CredList has %d items, want 1", len(holder2.CredList)) + } + if holder2.CredList[0].Name != "サンプル信託銀行株式会社" { + t.Errorf("GetLargeVolumeShareholders() CredList[0].Name = %v, want サンプル信託銀行株式会社", holder2.CredList[0].Name) + } +} + +func TestEdinetLargeVolumeShareholdersService_GetLargeVolumeShareholdersByCode(t *testing.T) { + // Setup + mockClient := client.NewMockClient() + service := NewEdinetLargeVolumeShareholdersService(mockClient) + + // Mock response - 最初のページ + mockResponse1 := EdinetLargeVolumeShareholdersResponse{ + Data: []EdinetLargeVolumeShareholderDoc{ + { + DocId: "S100WBIV", + Code: "86970", + SubDate: "2025-07-07", + LargeHldgTypeCode: "5", + TotalShsRatio: floatPtr(0.0728), + }, + { + DocId: "S100WA01", + Code: "86970", + SubDate: "2025-06-20", + LargeHldgTypeCode: "2", + TotalShsRatio: floatPtr(0.0614), + }, + }, + PaginationKey: "next_page_key", + } + + // Mock response - 2ページ目 + mockResponse2 := EdinetLargeVolumeShareholdersResponse{ + Data: []EdinetLargeVolumeShareholderDoc{ + { + DocId: "S100W901", + Code: "86970", + SubDate: "2025-05-15", + LargeHldgTypeCode: "1", + TotalShsRatio: floatPtr(0.0512), + }, + }, + PaginationKey: "", // 最後のページ + } + + mockClient.SetResponse("GET", "/edinet/large-volume-shareholders?code=86970", mockResponse1) + mockClient.SetResponse("GET", "/edinet/large-volume-shareholders?code=86970&pagination_key=next_page_key", mockResponse2) + + // Execute + data, err := service.GetLargeVolumeShareholdersByCode(context.Background(), "86970") + + // Verify + if err != nil { + t.Fatalf("GetLargeVolumeShareholdersByCode() error = %v", err) + } + if len(data) != 3 { + t.Errorf("GetLargeVolumeShareholdersByCode() returned %d items, want 3", len(data)) + } + for _, item := range data { + if item.Code != "86970" { + t.Errorf("GetLargeVolumeShareholdersByCode() returned code %v, want 86970", item.Code) + } + } +} + +func TestEdinetLargeVolumeShareholdersService_GetLargeVolumeShareholdersByEdinetCode(t *testing.T) { + // Setup + mockClient := client.NewMockClient() + service := NewEdinetLargeVolumeShareholdersService(mockClient) + + // Mock response + mockResponse := EdinetLargeVolumeShareholdersResponse{ + Data: []EdinetLargeVolumeShareholderDoc{ + { + DocId: "S100WBIV", + Code: "86970", + EdinetCode: "E03814", + SubDate: "2025-07-07", + LargeHldgTypeCode: "5", + }, + }, + PaginationKey: "", + } + mockClient.SetResponse("GET", "/edinet/large-volume-shareholders?edinet_code=E03814", mockResponse) + + // Execute + data, err := service.GetLargeVolumeShareholdersByEdinetCode(context.Background(), "E03814") + + // Verify + if err != nil { + t.Fatalf("GetLargeVolumeShareholdersByEdinetCode() error = %v", err) + } + if len(data) != 1 { + t.Errorf("GetLargeVolumeShareholdersByEdinetCode() returned %d items, want 1", len(data)) + } + if data[0].EdinetCode != "E03814" { + t.Errorf("GetLargeVolumeShareholdersByEdinetCode() returned edinet code %v, want E03814", data[0].EdinetCode) + } +} + +func TestEdinetLargeVolumeShareholdersService_GetLargeVolumeShareholdersByDate(t *testing.T) { + // Setup + mockClient := client.NewMockClient() + service := NewEdinetLargeVolumeShareholdersService(mockClient) + + // Mock response + mockResponse := EdinetLargeVolumeShareholdersResponse{ + Data: []EdinetLargeVolumeShareholderDoc{ + { + DocId: "S100WBIV", + Code: "86970", + SubDate: "2025-07-07", + LargeHldgTypeCode: "5", + }, + { + DocId: "S100WBJZ", + Code: "13660", + SubDate: "2025-07-07", + LargeHldgTypeCode: "1", + }, + }, + PaginationKey: "", + } + mockClient.SetResponse("GET", "/edinet/large-volume-shareholders?date=20250707", mockResponse) + + // Execute + data, err := service.GetLargeVolumeShareholdersByDate(context.Background(), "20250707") + + // Verify + if err != nil { + t.Fatalf("GetLargeVolumeShareholdersByDate() error = %v", err) + } + if len(data) != 2 { + t.Errorf("GetLargeVolumeShareholdersByDate() returned %d items, want 2", len(data)) + } + for _, item := range data { + if item.SubDate != "2025-07-07" { + t.Errorf("GetLargeVolumeShareholdersByDate() returned sub date %v, want 2025-07-07", item.SubDate) + } + } +} + +func TestEdinetLargeVolumeShareholderDoc_IsChangeReport(t *testing.T) { + tests := []struct { + name string + code string + want bool + }{ + {name: "large volume report", code: LargeHldgTypeCodeReport, want: false}, + {name: "change report", code: LargeHldgTypeCodeChangeReport, want: true}, + {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: "unknown", code: LargeHldgTypeCodeUnknown, want: false}, + } + + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + doc := EdinetLargeVolumeShareholderDoc{LargeHldgTypeCode: tt.code} + if got := doc.IsChangeReport(); got != tt.want { + t.Errorf("EdinetLargeVolumeShareholderDoc.IsChangeReport() = %v, want %v", got, tt.want) + } + }) + } +} + +func TestEdinetLargeVolumeShareholderDoc_GetTotalShareholdingPercentage(t *testing.T) { + doc := EdinetLargeVolumeShareholderDoc{ + TotalShsRatio: floatPtr(0.1343), + } + + expected := 13.43 + got := doc.GetTotalShareholdingPercentage() + + if got != expected { + t.Errorf("EdinetLargeVolumeShareholderDoc.GetTotalShareholdingPercentage() = %v, want %v", got, expected) + } + + // 合計欄の記載がない書類(null)の場合は0 + empty := EdinetLargeVolumeShareholderDoc{} + if got := empty.GetTotalShareholdingPercentage(); got != 0 { + t.Errorf("GetTotalShareholdingPercentage() with nil TotalShsRatio = %v, want 0", got) + } +} + +func TestEdinetLargeVolumeShareholderHolder_GetShareholdingPercentage(t *testing.T) { + holder := EdinetLargeVolumeShareholderHolder{ + ShsRatio: 0.0572, + } + + expected := 5.72 + got := holder.GetShareholdingPercentage() + + if got != expected { + t.Errorf("EdinetLargeVolumeShareholderHolder.GetShareholdingPercentage() = %v, want %v", got, expected) + } +} + +func TestEdinetLargeVolumeShareholdersService_GetLargeVolumeShareholders_Error(t *testing.T) { + // Setup + mockClient := client.NewMockClient() + service := NewEdinetLargeVolumeShareholdersService(mockClient) + + // Set error response + mockClient.SetError("GET", "/edinet/large-volume-shareholders?code=86970", fmt.Errorf("unauthorized")) + + // Execute + _, err := service.GetLargeVolumeShareholders(context.Background(), EdinetLargeVolumeShareholdersParams{Code: "86970"}) + + // Verify + if err == nil { + t.Error("GetLargeVolumeShareholders() expected error but got nil") + } +} diff --git a/edinet_major_shareholders.go b/edinet_major_shareholders.go new file mode 100644 index 0000000..9d8bb33 --- /dev/null +++ b/edinet_major_shareholders.go @@ -0,0 +1,273 @@ +package jquants + +import ( + "context" + "encoding/json" + "fmt" + + "github.com/utahta/jquants/client" + "github.com/utahta/jquants/types" +) + +// EdinetMajorShareholdersService は大株主状況(EDINET)を取得するサービスです。 +// 有価証券報告書に記載されている大株主の状況を取得します。 +type EdinetMajorShareholdersService struct { + client client.HTTPClient +} + +// NewEdinetMajorShareholdersService は新しいEdinetMajorShareholdersServiceを作成します。 +func NewEdinetMajorShareholdersService(c client.HTTPClient) *EdinetMajorShareholdersService { + return &EdinetMajorShareholdersService{client: c} +} + +// EdinetMajorShareholdersParams は大株主状況のリクエストパラメータです。 +// すべて任意ですが、edinet_codeとcodeの同時指定はできません。 +// すべて省略した場合はAPI実行日に提出された全有報のデータ一覧が返ります。 +type EdinetMajorShareholdersParams struct { + EdinetCode string // EDINETコード(例: E03814)(codeとの同時指定は不可) + Code string // 4桁もしくは5桁の銘柄コード(edinet_codeとの同時指定は不可) + Date string // 提出日(YYYYMMDD または YYYY-MM-DD) + PaginationKey string // ページネーションキー +} + +// EdinetMajorShareholdersResponse は大株主状況のレスポンスです。 +type EdinetMajorShareholdersResponse struct { + Data []EdinetMajorShareholderDoc `json:"data"` + PaginationKey string `json:"pagination_key"` // ページネーションキー +} + +// EdinetMajorShareholderDoc は有価証券報告書ごとの大株主状況データを表します。 +// J-Quants API /edinet/major-shareholders エンドポイントのレスポンスデータ。 +// データは2016年6月1日以降、対象書類は有価証券報告書 第三号様式。Standardプラン以上で利用可能。 +type EdinetMajorShareholderDoc struct { + // 書類メタ情報 + DocId string `json:"DocId"` // EDINET書類管理番号(S + 7桁英数字) + Code string `json:"Code"` // 提出会社の銘柄コード(5桁) + EdinetCode string `json:"EdinetCode"` // 提出会社のEDINETコード + FilerName string `json:"FilerName"` // 提出者名(会社名) + FilerNameEn string `json:"FilerNameEn"` // 提出者名(英語) + DocTypeCode string `json:"DocTypeCode"` // 書類種別コード(120=有価証券報告書) + 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形式) + + // 大株主レコード(順位順、Rank昇順) + Hldrs []EdinetMajorShareholderHolder `json:"Hldrs"` +} + +// EdinetMajorShareholderHolder は大株主1名分のデータを表します。 +// 通常は上位10名ですが、同順位タイで11位以降が記載される場合や1名のみの場合もあります。 +type EdinetMajorShareholderHolder struct { + Rank int `json:"Rank"` // 順位(1〜10、同順位タイで11以降あり) + HldrName string `json:"HldrName"` // 株主氏名又は名称 + HldrAddr string `json:"HldrAddr"` // 株主住所 + ShsHeld float64 `json:"ShsHeld"` // 所有株式数(株) + ShsRatio float64 `json:"ShsRatio"` // 発行済株式(自己株式を除く)に対する所有割合(小数表現。0.1881=18.81%) +} + +// RawEdinetMajorShareholderDoc is used for unmarshaling JSON response with mixed types +type RawEdinetMajorShareholderDoc struct { + // 書類メタ情報 + DocId string `json:"DocId"` + Code string `json:"Code"` + EdinetCode string `json:"EdinetCode"` + FilerName string `json:"FilerName"` + FilerNameEn string `json:"FilerNameEn"` + DocTypeCode string `json:"DocTypeCode"` + SubDate string `json:"SubDate"` + SubTime string `json:"SubTime"` + PerSt string `json:"PerSt"` + PerEn string `json:"PerEn"` + + // 大株主レコード + Hldrs []RawEdinetMajorShareholderHolder `json:"Hldrs"` +} + +// RawEdinetMajorShareholderHolder is used for unmarshaling JSON response with mixed types +type RawEdinetMajorShareholderHolder struct { + Rank types.NullableInt64 `json:"Rank"` + HldrName string `json:"HldrName"` + HldrAddr string `json:"HldrAddr"` + ShsHeld types.NullableFloat64 `json:"ShsHeld"` + ShsRatio types.NullableFloat64 `json:"ShsRatio"` +} + +// UnmarshalJSON implements custom JSON unmarshaling for EdinetMajorShareholdersResponse +func (r *EdinetMajorShareholdersResponse) UnmarshalJSON(data []byte) error { + // First unmarshal into RawEdinetMajorShareholderDoc + type rawResponse struct { + Data []RawEdinetMajorShareholderDoc `json:"data"` + PaginationKey string `json:"pagination_key"` + } + + var raw rawResponse + if err := json.Unmarshal(data, &raw); err != nil { + return err + } + + // Set pagination key + r.PaginationKey = raw.PaginationKey + + // Convert RawEdinetMajorShareholderDoc to EdinetMajorShareholderDoc + r.Data = make([]EdinetMajorShareholderDoc, len(raw.Data)) + for idx, rd := range raw.Data { + holders := make([]EdinetMajorShareholderHolder, len(rd.Hldrs)) + for hIdx, rh := range rd.Hldrs { + holders[hIdx] = EdinetMajorShareholderHolder{ + Rank: int(rh.Rank.Or(0)), + HldrName: rh.HldrName, + HldrAddr: rh.HldrAddr, + ShsHeld: rh.ShsHeld.Or(0), + ShsRatio: rh.ShsRatio.Or(0), + } + } + + r.Data[idx] = EdinetMajorShareholderDoc{ + // 書類メタ情報 + DocId: rd.DocId, + Code: rd.Code, + EdinetCode: rd.EdinetCode, + FilerName: rd.FilerName, + FilerNameEn: rd.FilerNameEn, + DocTypeCode: rd.DocTypeCode, + SubDate: rd.SubDate, + SubTime: rd.SubTime, + PerSt: rd.PerSt, + PerEn: rd.PerEn, + + // 大株主レコード + Hldrs: holders, + } + } + + return nil +} + +// GetMajorShareholders は大株主状況を取得します。 +// パラメータをすべて省略した場合はAPI実行日に提出された全有報のデータ一覧を取得します。 +func (s *EdinetMajorShareholdersService) GetMajorShareholders(ctx context.Context, params EdinetMajorShareholdersParams) (*EdinetMajorShareholdersResponse, error) { + // edinet_codeとcodeの同時指定は不可 + if params.EdinetCode != "" && params.Code != "" { + return nil, fmt.Errorf("edinet_code and code cannot be specified together") + } + + path := "/edinet/major-shareholders" + + query := "?" + if params.EdinetCode != "" { + query += fmt.Sprintf("edinet_code=%s&", params.EdinetCode) + } + if params.Code != "" { + query += fmt.Sprintf("code=%s&", params.Code) + } + if params.Date != "" { + query += fmt.Sprintf("date=%s&", params.Date) + } + if params.PaginationKey != "" { + query += fmt.Sprintf("pagination_key=%s&", params.PaginationKey) + } + + if len(query) > 1 { + path += query[:len(query)-1] // Remove trailing & + } + + var resp EdinetMajorShareholdersResponse + if err := s.client.DoRequest(ctx, "GET", path, nil, &resp); err != nil { + return nil, fmt.Errorf("failed to get major shareholders: %w", err) + } + + return &resp, nil +} + +// GetMajorShareholdersByCode は指定銘柄の大株主状況を取得します。 +// ページネーションを使用して全データを取得します。 +func (s *EdinetMajorShareholdersService) GetMajorShareholdersByCode(ctx context.Context, code string) ([]EdinetMajorShareholderDoc, error) { + var allData []EdinetMajorShareholderDoc + paginationKey := "" + + for { + params := EdinetMajorShareholdersParams{ + Code: code, + PaginationKey: paginationKey, + } + + resp, err := s.GetMajorShareholders(ctx, params) + if err != nil { + return nil, err + } + + allData = append(allData, resp.Data...) + + // ページネーションキーがなければ終了 + if resp.PaginationKey == "" { + break + } + paginationKey = resp.PaginationKey + } + + return allData, nil +} + +// GetMajorShareholdersByEdinetCode は指定EDINETコードの大株主状況を取得します。 +// ページネーションを使用して全データを取得します。 +func (s *EdinetMajorShareholdersService) GetMajorShareholdersByEdinetCode(ctx context.Context, edinetCode string) ([]EdinetMajorShareholderDoc, error) { + var allData []EdinetMajorShareholderDoc + paginationKey := "" + + for { + params := EdinetMajorShareholdersParams{ + EdinetCode: edinetCode, + PaginationKey: paginationKey, + } + + resp, err := s.GetMajorShareholders(ctx, params) + if err != nil { + return nil, err + } + + allData = append(allData, resp.Data...) + + // ページネーションキーがなければ終了 + if resp.PaginationKey == "" { + break + } + paginationKey = resp.PaginationKey + } + + return allData, nil +} + +// GetMajorShareholdersByDate は指定提出日の全有報の大株主状況を取得します。 +// ページネーションを使用して全データを取得します。 +func (s *EdinetMajorShareholdersService) GetMajorShareholdersByDate(ctx context.Context, date string) ([]EdinetMajorShareholderDoc, error) { + var allData []EdinetMajorShareholderDoc + paginationKey := "" + + for { + params := EdinetMajorShareholdersParams{ + Date: date, + PaginationKey: paginationKey, + } + + resp, err := s.GetMajorShareholders(ctx, params) + if err != nil { + return nil, err + } + + allData = append(allData, resp.Data...) + + // ページネーションキーがなければ終了 + if resp.PaginationKey == "" { + break + } + paginationKey = resp.PaginationKey + } + + return allData, nil +} + +// GetShareholdingPercentage は所有割合をパーセント表記で取得します。 +func (h *EdinetMajorShareholderHolder) GetShareholdingPercentage() float64 { + return h.ShsRatio * 100 +} diff --git a/edinet_major_shareholders_test.go b/edinet_major_shareholders_test.go new file mode 100644 index 0000000..4f6752f --- /dev/null +++ b/edinet_major_shareholders_test.go @@ -0,0 +1,442 @@ +package jquants + +import ( + "context" + "encoding/json" + "fmt" + "testing" + + "github.com/utahta/jquants/client" +) + +func TestEdinetMajorShareholdersService_GetMajorShareholders(t *testing.T) { + tests := []struct { + name string + params EdinetMajorShareholdersParams + wantPath string + wantErr bool + }{ + { + name: "with edinet code", + params: EdinetMajorShareholdersParams{ + EdinetCode: "E03814", + }, + wantPath: "/edinet/major-shareholders?edinet_code=E03814", + }, + { + name: "with code", + params: EdinetMajorShareholdersParams{ + Code: "86970", + }, + wantPath: "/edinet/major-shareholders?code=86970", + }, + { + name: "with date", + params: EdinetMajorShareholdersParams{ + Date: "20250620", + }, + wantPath: "/edinet/major-shareholders?date=20250620", + }, + { + name: "with date in hyphen format", + params: EdinetMajorShareholdersParams{ + Date: "2025-06-20", + }, + wantPath: "/edinet/major-shareholders?date=2025-06-20", + }, + { + name: "with code and date", + params: EdinetMajorShareholdersParams{ + Code: "86970", + Date: "20250620", + }, + wantPath: "/edinet/major-shareholders?code=86970&date=20250620", + }, + { + name: "with edinet code and date", + params: EdinetMajorShareholdersParams{ + EdinetCode: "E03814", + Date: "20250620", + }, + wantPath: "/edinet/major-shareholders?edinet_code=E03814&date=20250620", + }, + { + name: "with pagination key", + params: EdinetMajorShareholdersParams{ + Code: "86970", + PaginationKey: "key123", + }, + wantPath: "/edinet/major-shareholders?code=86970&pagination_key=key123", + }, + { + name: "with no parameters", + params: EdinetMajorShareholdersParams{}, + wantPath: "/edinet/major-shareholders", + }, + { + name: "with edinet code and code", + params: EdinetMajorShareholdersParams{ + EdinetCode: "E03814", + Code: "86970", + }, + wantPath: "", + wantErr: true, + }, + } + + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + // Setup + mockClient := client.NewMockClient() + service := NewEdinetMajorShareholdersService(mockClient) + + // Mock response based on documentation sample + mockResponse := EdinetMajorShareholdersResponse{ + Data: []EdinetMajorShareholderDoc{ + { + DocId: "S100YA84", + Code: "86970", + EdinetCode: "E03814", + FilerName: "株式会社日本取引所グループ", + FilerNameEn: "Japan Exchange Group, Inc.", + DocTypeCode: "120", + SubDate: "2026-06-11", + SubTime: "15:00:00", + PerSt: "2025-04-01", + PerEn: "2026-03-31", + Hldrs: []EdinetMajorShareholderHolder{ + { + Rank: 1, + HldrName: "日本マスタートラスト信託銀行株式会社(信託口)", + HldrAddr: "東京都港区赤坂1丁目8番1号 赤坂インターシティAIR", + ShsHeld: 175830000, + ShsRatio: 0.1704, + }, + }, + }, + }, + PaginationKey: "", + } + if !tt.wantErr { + mockClient.SetResponse("GET", tt.wantPath, mockResponse) + } + + // Execute + resp, err := service.GetMajorShareholders(context.Background(), tt.params) + + // Verify + if tt.wantErr { + if err == nil { + t.Error("GetMajorShareholders() expected error but got nil") + } + return + } + + if err != nil { + t.Fatalf("GetMajorShareholders() error = %v", err) + } + if resp == nil { + t.Fatal("GetMajorShareholders() returned nil response") + return + } + if len(resp.Data) == 0 { + t.Error("GetMajorShareholders() returned empty data") + } + if mockClient.LastPath != tt.wantPath { + t.Errorf("GetMajorShareholders() path = %v, want %v", mockClient.LastPath, tt.wantPath) + } + }) + } +} + +func TestEdinetMajorShareholdersService_GetMajorShareholders_RejectsEdinetCodeAndCode(t *testing.T) { + // Setup + mockClient := client.NewMockClient() + service := NewEdinetMajorShareholdersService(mockClient) + + // Execute with both edinet_code and code + _, err := service.GetMajorShareholders(context.Background(), EdinetMajorShareholdersParams{ + EdinetCode: "E03814", + Code: "86970", + }) + + // Verify + if err == nil { + t.Error("GetMajorShareholders() expected error for edinet_code and code but got nil") + } + if err.Error() != "edinet_code and code cannot be specified together" { + t.Errorf("GetMajorShareholders() error = %v, want 'edinet_code and code cannot be specified together'", err) + } + if mockClient.RequestCount != 0 { + t.Errorf("GetMajorShareholders() request count = %v, want 0", mockClient.RequestCount) + } +} + +func TestEdinetMajorShareholdersService_GetMajorShareholders_DecodesNestedHolders(t *testing.T) { + // Setup + mockClient := client.NewMockClient() + service := NewEdinetMajorShareholdersService(mockClient) + + // JSON-shaped mock response(数値が文字列で返るケースを含む) + mockJSON := json.RawMessage(`{ + "data": [ + { + "DocId": "S100YA84", + "Code": "86970", + "EdinetCode": "E03814", + "FilerName": "株式会社日本取引所グループ", + "FilerNameEn": "Japan Exchange Group, Inc.", + "DocTypeCode": "120", + "SubDate": "2026-06-11", + "SubTime": "15:00:00", + "PerSt": "2025-04-01", + "PerEn": "2026-03-31", + "Hldrs": [ + { + "Rank": 1, + "HldrName": "日本マスタートラスト信託銀行株式会社(信託口)", + "HldrAddr": "東京都港区赤坂1丁目8番1号 赤坂インターシティAIR", + "ShsHeld": 175830000, + "ShsRatio": 0.1704 + }, + { + "Rank": 2, + "HldrName": "株式会社日本カストディ銀行(信託口)", + "HldrAddr": "東京都中央区晴海1丁目8-12", + "ShsHeld": "56970000", + "ShsRatio": "0.0552" + } + ] + } + ], + "pagination_key": "" + }`) + mockClient.SetResponse("GET", "/edinet/major-shareholders?edinet_code=E03814", mockJSON) + + // Execute + resp, err := service.GetMajorShareholders(context.Background(), EdinetMajorShareholdersParams{EdinetCode: "E03814"}) + + // Verify + if err != nil { + t.Fatalf("GetMajorShareholders() error = %v", err) + } + if len(resp.Data) != 1 { + t.Fatalf("GetMajorShareholders() returned %d items, want 1", len(resp.Data)) + } + + doc := resp.Data[0] + if doc.DocId != "S100YA84" { + t.Errorf("GetMajorShareholders() DocId = %v, want S100YA84", doc.DocId) + } + if doc.Code != "86970" { + t.Errorf("GetMajorShareholders() Code = %v, want 86970", doc.Code) + } + if doc.DocTypeCode != "120" { + t.Errorf("GetMajorShareholders() DocTypeCode = %v, want 120", doc.DocTypeCode) + } + if len(doc.Hldrs) != 2 { + t.Fatalf("GetMajorShareholders() returned %d holders, want 2", len(doc.Hldrs)) + } + + holder1 := doc.Hldrs[0] + if holder1.Rank != 1 { + t.Errorf("GetMajorShareholders() Hldrs[0].Rank = %v, want 1", holder1.Rank) + } + if holder1.HldrName != "日本マスタートラスト信託銀行株式会社(信託口)" { + t.Errorf("GetMajorShareholders() Hldrs[0].HldrName = %v, want 日本マスタートラスト信託銀行株式会社(信託口)", holder1.HldrName) + } + if holder1.ShsHeld != 175830000 { + t.Errorf("GetMajorShareholders() Hldrs[0].ShsHeld = %v, want 175830000", holder1.ShsHeld) + } + if holder1.ShsRatio != 0.1704 { + t.Errorf("GetMajorShareholders() Hldrs[0].ShsRatio = %v, want 0.1704", holder1.ShsRatio) + } + + // 数値が文字列で返るケース + holder2 := doc.Hldrs[1] + if holder2.Rank != 2 { + t.Errorf("GetMajorShareholders() Hldrs[1].Rank = %v, want 2", holder2.Rank) + } + if holder2.ShsHeld != 56970000 { + t.Errorf("GetMajorShareholders() Hldrs[1].ShsHeld = %v, want 56970000", holder2.ShsHeld) + } + if holder2.ShsRatio != 0.0552 { + t.Errorf("GetMajorShareholders() Hldrs[1].ShsRatio = %v, want 0.0552", holder2.ShsRatio) + } +} + +func TestEdinetMajorShareholdersService_GetMajorShareholdersByCode(t *testing.T) { + // Setup + mockClient := client.NewMockClient() + service := NewEdinetMajorShareholdersService(mockClient) + + // Mock response - 最初のページ + mockResponse1 := EdinetMajorShareholdersResponse{ + Data: []EdinetMajorShareholderDoc{ + { + DocId: "S100YA84", + Code: "86970", + SubDate: "2026-06-11", + Hldrs: []EdinetMajorShareholderHolder{ + {Rank: 1, HldrName: "日本マスタートラスト信託銀行株式会社(信託口)", ShsHeld: 175830000, ShsRatio: 0.1704}, + }, + }, + { + DocId: "S100XB12", + Code: "86970", + SubDate: "2025-06-12", + Hldrs: []EdinetMajorShareholderHolder{ + {Rank: 1, HldrName: "日本マスタートラスト信託銀行株式会社(信託口)", ShsHeld: 170000000, ShsRatio: 0.1650}, + }, + }, + }, + PaginationKey: "next_page_key", + } + + // Mock response - 2ページ目 + mockResponse2 := EdinetMajorShareholdersResponse{ + Data: []EdinetMajorShareholderDoc{ + { + DocId: "S100WC34", + Code: "86970", + SubDate: "2024-06-13", + Hldrs: []EdinetMajorShareholderHolder{ + {Rank: 1, HldrName: "日本マスタートラスト信託銀行株式会社(信託口)", ShsHeld: 165000000, ShsRatio: 0.1600}, + }, + }, + }, + PaginationKey: "", // 最後のページ + } + + mockClient.SetResponse("GET", "/edinet/major-shareholders?code=86970", mockResponse1) + mockClient.SetResponse("GET", "/edinet/major-shareholders?code=86970&pagination_key=next_page_key", mockResponse2) + + // Execute + data, err := service.GetMajorShareholdersByCode(context.Background(), "86970") + + // Verify + if err != nil { + t.Fatalf("GetMajorShareholdersByCode() error = %v", err) + } + if len(data) != 3 { + t.Errorf("GetMajorShareholdersByCode() returned %d items, want 3", len(data)) + } + for _, item := range data { + if item.Code != "86970" { + t.Errorf("GetMajorShareholdersByCode() returned code %v, want 86970", item.Code) + } + } +} + +func TestEdinetMajorShareholdersService_GetMajorShareholdersByEdinetCode(t *testing.T) { + // Setup + mockClient := client.NewMockClient() + service := NewEdinetMajorShareholdersService(mockClient) + + // Mock response + mockResponse := EdinetMajorShareholdersResponse{ + Data: []EdinetMajorShareholderDoc{ + { + DocId: "S100YA84", + Code: "86970", + EdinetCode: "E03814", + SubDate: "2026-06-11", + Hldrs: []EdinetMajorShareholderHolder{ + {Rank: 1, HldrName: "日本マスタートラスト信託銀行株式会社(信託口)", ShsHeld: 175830000, ShsRatio: 0.1704}, + }, + }, + }, + PaginationKey: "", + } + mockClient.SetResponse("GET", "/edinet/major-shareholders?edinet_code=E03814", mockResponse) + + // Execute + data, err := service.GetMajorShareholdersByEdinetCode(context.Background(), "E03814") + + // Verify + if err != nil { + t.Fatalf("GetMajorShareholdersByEdinetCode() error = %v", err) + } + if len(data) != 1 { + t.Errorf("GetMajorShareholdersByEdinetCode() returned %d items, want 1", len(data)) + } + if data[0].EdinetCode != "E03814" { + t.Errorf("GetMajorShareholdersByEdinetCode() returned edinet code %v, want E03814", data[0].EdinetCode) + } +} + +func TestEdinetMajorShareholdersService_GetMajorShareholdersByDate(t *testing.T) { + // Setup + mockClient := client.NewMockClient() + service := NewEdinetMajorShareholdersService(mockClient) + + // Mock response + mockResponse := EdinetMajorShareholdersResponse{ + Data: []EdinetMajorShareholderDoc{ + { + DocId: "S100YA84", + Code: "86970", + SubDate: "2025-06-20", + Hldrs: []EdinetMajorShareholderHolder{ + {Rank: 1, HldrName: "日本マスタートラスト信託銀行株式会社(信託口)", ShsHeld: 175830000, ShsRatio: 0.1704}, + }, + }, + { + DocId: "S100YB56", + Code: "13660", + SubDate: "2025-06-20", + Hldrs: []EdinetMajorShareholderHolder{ + {Rank: 1, HldrName: "株式会社日本カストディ銀行(信託口)", ShsHeld: 56970000, ShsRatio: 0.0552}, + }, + }, + }, + PaginationKey: "", + } + mockClient.SetResponse("GET", "/edinet/major-shareholders?date=20250620", mockResponse) + + // Execute + data, err := service.GetMajorShareholdersByDate(context.Background(), "20250620") + + // Verify + if err != nil { + t.Fatalf("GetMajorShareholdersByDate() error = %v", err) + } + if len(data) != 2 { + t.Errorf("GetMajorShareholdersByDate() returned %d items, want 2", len(data)) + } + for _, item := range data { + if item.SubDate != "2025-06-20" { + t.Errorf("GetMajorShareholdersByDate() returned sub date %v, want 2025-06-20", item.SubDate) + } + } +} + +func TestEdinetMajorShareholderHolder_GetShareholdingPercentage(t *testing.T) { + holder := EdinetMajorShareholderHolder{ + ShsRatio: 0.1704, + } + + expected := 17.04 + got := holder.GetShareholdingPercentage() + + if got != expected { + t.Errorf("EdinetMajorShareholderHolder.GetShareholdingPercentage() = %v, want %v", got, expected) + } +} + +func TestEdinetMajorShareholdersService_GetMajorShareholders_Error(t *testing.T) { + // Setup + mockClient := client.NewMockClient() + service := NewEdinetMajorShareholdersService(mockClient) + + // Set error response + mockClient.SetError("GET", "/edinet/major-shareholders?code=86970", fmt.Errorf("unauthorized")) + + // Execute + _, err := service.GetMajorShareholders(context.Background(), EdinetMajorShareholdersParams{Code: "86970"}) + + // Verify + if err == nil { + t.Error("GetMajorShareholders() expected error but got nil") + } +} diff --git a/fs_details.go b/fs_details.go index ba5a378..1f41193 100644 --- a/fs_details.go +++ b/fs_details.go @@ -25,6 +25,7 @@ func NewFSDetailsService(c client.HTTPClient) *FSDetailsService { type FSDetailsParams struct { Code string // 銘柄コード(codeまたはdateのいずれかが必須) Date string // 開示日(YYYYMMDD または YYYY-MM-DD)(codeまたはdateのいずれかが必須) + Cursor string // 差分取得用カーソル。前回レスポンスのcursorを指定すると前回リクエスト以降のデータを取得(pagination_keyと同時指定不可) PaginationKey string // ページネーションキー } @@ -32,6 +33,7 @@ type FSDetailsParams struct { type FSDetailsResponse struct { Data []FSDetail `json:"data"` PaginationKey string `json:"pagination_key"` // ページネーションキー + Cursor string `json:"cursor"` // 差分取得用カーソル } // FSDetail は財務諸表詳細情報を表します。 @@ -60,6 +62,9 @@ func (s *FSDetailsService) GetFSDetails(ctx context.Context, params FSDetailsPar if params.Code == "" && params.Date == "" { return nil, fmt.Errorf("either code or date parameter is required") } + if params.Cursor != "" && params.PaginationKey != "" { + return nil, fmt.Errorf("cursor and pagination_key cannot be specified at the same time") + } path := "/fins/details" @@ -70,6 +75,9 @@ func (s *FSDetailsService) GetFSDetails(ctx context.Context, params FSDetailsPar if params.Date != "" { query += fmt.Sprintf("date=%s&", params.Date) } + if params.Cursor != "" { + query += fmt.Sprintf("cursor=%s&", params.Cursor) + } if params.PaginationKey != "" { query += fmt.Sprintf("pagination_key=%s&", params.PaginationKey) } @@ -79,7 +87,14 @@ func (s *FSDetailsService) GetFSDetails(ctx context.Context, params FSDetailsPar } var resp FSDetailsResponse - if err := s.client.DoRequest(ctx, "GET", path, nil, &resp); err != nil { + var err error + if params.Cursor != "" { + // cursorによる差分取得はポーリング用途のため、キャッシュを経由しない + err = client.DoRequestNoCache(ctx, s.client, "GET", path, nil, &resp) + } else { + err = s.client.DoRequest(ctx, "GET", path, nil, &resp) + } + if err != nil { return nil, fmt.Errorf("failed to get fs details: %w", err) } diff --git a/fs_details_test.go b/fs_details_test.go index e590b36..7eb1ecd 100644 --- a/fs_details_test.go +++ b/fs_details_test.go @@ -45,12 +45,30 @@ func TestFSDetailsService_GetFSDetails(t *testing.T) { }, wantPath: "/fins/details?code=86970&pagination_key=key123", }, + { + name: "with date and cursor", + params: FSDetailsParams{ + Date: "2023-01-30", + Cursor: "cur123", + }, + wantPath: "/fins/details?date=2023-01-30&cursor=cur123", + }, { name: "with no required parameters", params: FSDetailsParams{}, wantPath: "", wantErr: true, }, + { + name: "with cursor and pagination key", + params: FSDetailsParams{ + Date: "2023-01-30", + Cursor: "cur123", + PaginationKey: "key123", + }, + wantPath: "", + wantErr: true, + }, } for _, tt := range tests { @@ -622,3 +640,26 @@ func TestFSDetailsService_GetFSDetails_Error(t *testing.T) { t.Error("GetFSDetails() expected error but got nil") } } + +func TestFSDetailsService_GetFSDetails_CursorSkipsCache(t *testing.T) { + mockClient := client.NewMockClient() + service := NewFSDetailsService(mockClient) + mockClient.SetResponse("GET", "/fins/details?date=20230130&cursor=cur123", FSDetailsResponse{}) + mockClient.SetResponse("GET", "/fins/details?date=20230130", FSDetailsResponse{}) + + // cursorによるポーリングはキャッシュをバイパスすること + if _, err := service.GetFSDetails(context.Background(), FSDetailsParams{Date: "20230130", Cursor: "cur123"}); err != nil { + t.Fatalf("GetFSDetails() error = %v", err) + } + if !mockClient.LastSkipCache { + t.Error("GetFSDetails() with cursor should bypass the session cache") + } + + // cursorなしは通常どおりキャッシュ対象 + if _, err := service.GetFSDetails(context.Background(), FSDetailsParams{Date: "20230130"}); err != nil { + t.Fatalf("GetFSDetails() error = %v", err) + } + if mockClient.LastSkipCache { + t.Error("GetFSDetails() without cursor should use the session cache") + } +} diff --git a/jquants.go b/jquants.go index 3e3c226..4fabb33 100644 --- a/jquants.go +++ b/jquants.go @@ -23,50 +23,68 @@ import "github.com/utahta/jquants/client" // - Futures: 先物取引データ // - Options: 個別株オプション // - FSDetails: 財務諸表詳細(BS/PL詳細データ) +// - MinuteQuotes: 株価分足(アドオン契約が必要) +// - TimelyDisclosure: TDnet適時開示情報(アドオン契約が必要) +// - EdinetMajorShareholders: 大株主状況(有価証券報告書ベース) +// - EdinetCrossShareholdings: 政策保有株式(有価証券報告書ベース) +// - EdinetLargeVolumeShareholders: 大量保有報告書 +// - Bulk: CSV一括ダウンロード type JQuantsAPI struct { - client client.HTTPClient - Quotes *QuotesService - PricesAM *PricesAMService - Listed *ListedService - Statements *StatementsService - Dividend *DividendService - Announcement *AnnouncementService - TradesSpec *TradesSpecService - WeeklyMarginInterest *WeeklyMarginInterestService - DailyMarginInterest *DailyMarginInterestService - ShortSelling *ShortSellingService - ShortSellingPositions *ShortSellingPositionsService - Breakdown *BreakdownService - TradingCalendar *TradingCalendarService - Indices *IndicesService - TOPIX *TOPIXService - IndexOption *IndexOptionService - Futures *FuturesService - Options *OptionsService - FSDetails *FSDetailsService + client client.HTTPClient + Quotes *QuotesService + PricesAM *PricesAMService + MinuteQuotes *MinuteQuotesService + Listed *ListedService + Statements *StatementsService + Dividend *DividendService + Announcement *AnnouncementService + TradesSpec *TradesSpecService + WeeklyMarginInterest *WeeklyMarginInterestService + DailyMarginInterest *DailyMarginInterestService + ShortSelling *ShortSellingService + ShortSellingPositions *ShortSellingPositionsService + Breakdown *BreakdownService + TradingCalendar *TradingCalendarService + Indices *IndicesService + TOPIX *TOPIXService + IndexOption *IndexOptionService + Futures *FuturesService + Options *OptionsService + FSDetails *FSDetailsService + TimelyDisclosure *TimelyDisclosureService + EdinetMajorShareholders *EdinetMajorShareholdersService + EdinetCrossShareholdings *EdinetCrossShareholdingsService + EdinetLargeVolumeShareholders *EdinetLargeVolumeShareholdersService + Bulk *BulkService } func NewJQuantsAPI(c client.HTTPClient) *JQuantsAPI { return &JQuantsAPI{ - client: c, - Quotes: NewQuotesService(c), - PricesAM: NewPricesAMService(c), - Listed: NewListedService(c), - Statements: NewStatementsService(c), - Dividend: NewDividendService(c), - Announcement: NewAnnouncementService(c), - TradesSpec: NewTradesSpecService(c), - WeeklyMarginInterest: NewWeeklyMarginInterestService(c), - DailyMarginInterest: NewDailyMarginInterestService(c), - ShortSelling: NewShortSellingService(c), - ShortSellingPositions: NewShortSellingPositionsService(c), - Breakdown: NewBreakdownService(c), - TradingCalendar: NewTradingCalendarService(c), - Indices: NewIndicesService(c), - TOPIX: NewTOPIXService(c), - IndexOption: NewIndexOptionService(c), - Futures: NewFuturesService(c), - Options: NewOptionsService(c), - FSDetails: NewFSDetailsService(c), + client: c, + Quotes: NewQuotesService(c), + PricesAM: NewPricesAMService(c), + MinuteQuotes: NewMinuteQuotesService(c), + Listed: NewListedService(c), + Statements: NewStatementsService(c), + Dividend: NewDividendService(c), + Announcement: NewAnnouncementService(c), + TradesSpec: NewTradesSpecService(c), + WeeklyMarginInterest: NewWeeklyMarginInterestService(c), + DailyMarginInterest: NewDailyMarginInterestService(c), + ShortSelling: NewShortSellingService(c), + ShortSellingPositions: NewShortSellingPositionsService(c), + Breakdown: NewBreakdownService(c), + TradingCalendar: NewTradingCalendarService(c), + Indices: NewIndicesService(c), + TOPIX: NewTOPIXService(c), + IndexOption: NewIndexOptionService(c), + Futures: NewFuturesService(c), + Options: NewOptionsService(c), + FSDetails: NewFSDetailsService(c), + TimelyDisclosure: NewTimelyDisclosureService(c), + EdinetMajorShareholders: NewEdinetMajorShareholdersService(c), + EdinetCrossShareholdings: NewEdinetCrossShareholdingsService(c), + EdinetLargeVolumeShareholders: NewEdinetLargeVolumeShareholdersService(c), + Bulk: NewBulkService(c), } } diff --git a/listed.go b/listed.go index a91cfed..2525e2b 100644 --- a/listed.go +++ b/listed.go @@ -81,6 +81,18 @@ const ( Sector33Other = "9999" // その他 ) +// 商品区分コード定義 +const ( + ProductCategoryDomesticStock = "011" // 内国株券 + ProductCategoryPreferredEquity = "012" // 優先出資証券 + ProductCategoryREIT = "013" // REIT + ProductCategoryETF = "014" // ETF + ProductCategoryForeignStock = "021" // 外国株券 + ProductCategoryForeignREIT = "022" // 外国REIT + ProductCategoryForeignETF = "023" // 外国ETF + ProductCategoryForeignDR = "024" // 外国株預託証券 +) + // ListedService は上場企業情報を取得するサービスです。 // 企業名、業種分類、市場区分などの基本情報を提供します。 type ListedService struct { @@ -110,6 +122,17 @@ type ListedInfo struct { MktNm string `json:"MktNm"` // 市場区分名(プライム、スタンダード、グロース等) Mrgn string `json:"Mrgn"` // 貸借信用区分(1: 信用 / 2: 貸借 / 3: その他)(Standard/Premiumのみ) MrgnNm string `json:"MrgnNm"` // 貸借信用区分名(Standard/Premiumのみ) + ProdCat string `json:"ProdCat"` // 商品区分コード(ProductCategory定数を参照) +} + +// IsETF はETF(外国ETF含む)かを判定します。 +func (l *ListedInfo) IsETF() bool { + return l.ProdCat == ProductCategoryETF || l.ProdCat == ProductCategoryForeignETF +} + +// IsREIT はREIT(外国REIT含む)かを判定します。 +func (l *ListedInfo) IsREIT() bool { + return l.ProdCat == ProductCategoryREIT || l.ProdCat == ProductCategoryForeignREIT } type ListedInfoResponse struct { diff --git a/listed_test.go b/listed_test.go index ebfe0f8..f3fcf1d 100644 --- a/listed_test.go +++ b/listed_test.go @@ -391,3 +391,31 @@ func TestListedService_GetListedByMarket(t *testing.T) { } } } + +func TestListedInfo_ProductCategoryHelpers(t *testing.T) { + tests := []struct { + name string + prodCat string + wantETF bool + wantREIT bool + }{ + {name: "domestic stock", prodCat: ProductCategoryDomesticStock, wantETF: false, wantREIT: false}, + {name: "ETF", prodCat: ProductCategoryETF, wantETF: true, wantREIT: false}, + {name: "foreign ETF", prodCat: ProductCategoryForeignETF, wantETF: true, wantREIT: false}, + {name: "REIT", prodCat: ProductCategoryREIT, wantETF: false, wantREIT: true}, + {name: "foreign REIT", prodCat: ProductCategoryForeignREIT, wantETF: false, wantREIT: true}, + {name: "empty", prodCat: "", wantETF: false, wantREIT: false}, + } + + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + info := ListedInfo{ProdCat: tt.prodCat} + if got := info.IsETF(); got != tt.wantETF { + t.Errorf("IsETF() = %v, want %v", got, tt.wantETF) + } + if got := info.IsREIT(); got != tt.wantREIT { + t.Errorf("IsREIT() = %v, want %v", got, tt.wantREIT) + } + }) + } +} diff --git a/minute_quotes.go b/minute_quotes.go new file mode 100644 index 0000000..7c48acd --- /dev/null +++ b/minute_quotes.go @@ -0,0 +1,242 @@ +package jquants + +import ( + "context" + "encoding/json" + "fmt" + + "github.com/utahta/jquants/client" + "github.com/utahta/jquants/types" +) + +// MinuteQuotesService は株価分足データを取得するサービスです。 +// 歩み値を1分単位に集計した四本値(始値・高値・安値・終値)、出来高、売買代金を提供します。 +// 利用にはアドオン契約が必要です。データ取得可能期間は過去2年間です。 +// 約定のない時間帯の分足は返却されません。地方取引所単独上場銘柄は収録対象外です。 +type MinuteQuotesService struct { + client client.HTTPClient +} + +// NewMinuteQuotesService は新しいMinuteQuotesServiceを作成します。 +func NewMinuteQuotesService(c client.HTTPClient) *MinuteQuotesService { + return &MinuteQuotesService{client: c} +} + +// MinuteQuotesParams は株価分足のリクエストパラメータです。 +type MinuteQuotesParams struct { + Code string // 銘柄コード(4桁または5桁)(code、dateのいずれかが必須) + Date string // 日付(YYYYMMDD または YYYY-MM-DD)(code、dateのいずれかが必須) + From string // fromの指定(YYYYMMDD または YYYY-MM-DD) + To string // toの指定(YYYYMMDD または YYYY-MM-DD) + PaginationKey string // ページネーションキー +} + +// MinuteQuotesResponse は株価分足のレスポンスです。 +type MinuteQuotesResponse struct { + Data []MinuteQuote `json:"data"` + PaginationKey string `json:"pagination_key"` // ページネーションキー +} + +// MinuteQuote は株価分足データを表します。 +// J-Quants API /equities/bars/minute エンドポイントのレスポンスデータ。 +// 約定のない時間帯の分足は返却されないため、四本値・出来高・売買代金は常に値を持ちます。 +type MinuteQuote struct { + // 基本情報 + Date string `json:"Date"` // 日付(YYYY-MM-DD形式) + Time string `json:"Time"` // 時刻(HH:mm形式) + Code string `json:"Code"` // 銘柄コード + + // 四本値 + O float64 `json:"O"` // 始値 + H float64 `json:"H"` // 高値 + L float64 `json:"L"` // 安値 + C float64 `json:"C"` // 終値 + + // 出来高・売買代金 + Vo float64 `json:"Vo"` // 出来高 + Va float64 `json:"Va"` // 売買代金 +} + +// RawMinuteQuote is used for unmarshaling JSON response with mixed types +type RawMinuteQuote struct { + // 基本情報 + Date string `json:"Date"` + Time string `json:"Time"` + Code string `json:"Code"` + + // 四本値 + O types.NullableFloat64 `json:"O"` + H types.NullableFloat64 `json:"H"` + L types.NullableFloat64 `json:"L"` + C types.NullableFloat64 `json:"C"` + + // 出来高・売買代金 + Vo types.NullableFloat64 `json:"Vo"` + Va types.NullableFloat64 `json:"Va"` +} + +// UnmarshalJSON implements custom JSON unmarshaling for MinuteQuotesResponse +func (r *MinuteQuotesResponse) UnmarshalJSON(data []byte) error { + // First unmarshal into RawMinuteQuote + type rawResponse struct { + Data []RawMinuteQuote `json:"data"` + PaginationKey string `json:"pagination_key"` + } + + var raw rawResponse + if err := json.Unmarshal(data, &raw); err != nil { + return err + } + + // Set pagination key + r.PaginationKey = raw.PaginationKey + + // Convert RawMinuteQuote to MinuteQuote + r.Data = make([]MinuteQuote, len(raw.Data)) + for idx, rmq := range raw.Data { + r.Data[idx] = MinuteQuote{ + // 基本情報 + Date: rmq.Date, + Time: rmq.Time, + Code: rmq.Code, + + // 四本値 + O: rmq.O.Or(0), + H: rmq.H.Or(0), + L: rmq.L.Or(0), + C: rmq.C.Or(0), + + // 出来高・売買代金 + Vo: rmq.Vo.Or(0), + Va: rmq.Va.Or(0), + } + } + + return nil +} + +// GetMinuteQuotes は株価分足データを取得します。 +func (s *MinuteQuotesService) GetMinuteQuotes(ctx context.Context, params MinuteQuotesParams) (*MinuteQuotesResponse, error) { + // code、dateのいずれかが必須 + if params.Code == "" && params.Date == "" { + return nil, fmt.Errorf("either code or date parameter is required") + } + + path := "/equities/bars/minute" + + query := "?" + if params.Code != "" { + query += fmt.Sprintf("code=%s&", params.Code) + } + if params.Date != "" { + query += fmt.Sprintf("date=%s&", params.Date) + } + if params.From != "" { + query += fmt.Sprintf("from=%s&", params.From) + } + if params.To != "" { + query += fmt.Sprintf("to=%s&", params.To) + } + if params.PaginationKey != "" { + query += fmt.Sprintf("pagination_key=%s&", params.PaginationKey) + } + + if len(query) > 1 { + path += query[:len(query)-1] // Remove trailing & + } + + var resp MinuteQuotesResponse + if err := s.client.DoRequest(ctx, "GET", path, nil, &resp); err != nil { + return nil, fmt.Errorf("failed to get minute quotes: %w", err) + } + + return &resp, nil +} + +// GetMinuteQuotesByCode は指定銘柄の株価分足データを取得します。 +// ページネーションを使用して全データを取得します。 +func (s *MinuteQuotesService) GetMinuteQuotesByCode(ctx context.Context, code string) ([]MinuteQuote, error) { + var allData []MinuteQuote + paginationKey := "" + + for { + params := MinuteQuotesParams{ + Code: code, + PaginationKey: paginationKey, + } + + resp, err := s.GetMinuteQuotes(ctx, params) + if err != nil { + return nil, err + } + + allData = append(allData, resp.Data...) + + // ページネーションキーがなければ終了 + if resp.PaginationKey == "" { + break + } + paginationKey = resp.PaginationKey + } + + return allData, nil +} + +// GetMinuteQuotesByCodeAndDate は指定銘柄の指定日の株価分足データを取得します。 +// ページネーションを使用して全データを取得します。 +func (s *MinuteQuotesService) GetMinuteQuotesByCodeAndDate(ctx context.Context, code, date string) ([]MinuteQuote, error) { + var allData []MinuteQuote + paginationKey := "" + + for { + params := MinuteQuotesParams{ + Code: code, + Date: date, + PaginationKey: paginationKey, + } + + resp, err := s.GetMinuteQuotes(ctx, params) + if err != nil { + return nil, err + } + + allData = append(allData, resp.Data...) + + // ページネーションキーがなければ終了 + if resp.PaginationKey == "" { + break + } + paginationKey = resp.PaginationKey + } + + return allData, nil +} + +// GetMinuteQuotesByDate は指定日の全上場銘柄の株価分足データを取得します。 +// ページネーションを使用して全データを取得します。 +func (s *MinuteQuotesService) GetMinuteQuotesByDate(ctx context.Context, date string) ([]MinuteQuote, error) { + var allData []MinuteQuote + paginationKey := "" + + for { + params := MinuteQuotesParams{ + Date: date, + PaginationKey: paginationKey, + } + + resp, err := s.GetMinuteQuotes(ctx, params) + if err != nil { + return nil, err + } + + allData = append(allData, resp.Data...) + + // ページネーションキーがなければ終了 + if resp.PaginationKey == "" { + break + } + paginationKey = resp.PaginationKey + } + + return allData, nil +} diff --git a/minute_quotes_test.go b/minute_quotes_test.go new file mode 100644 index 0000000..f3f63d6 --- /dev/null +++ b/minute_quotes_test.go @@ -0,0 +1,386 @@ +package jquants + +import ( + "context" + "encoding/json" + "fmt" + "testing" + + "github.com/utahta/jquants/client" +) + +func TestMinuteQuotesService_GetMinuteQuotes(t *testing.T) { + tests := []struct { + name string + params MinuteQuotesParams + wantPath string + wantErr bool + }{ + { + name: "with code only", + params: MinuteQuotesParams{ + Code: "86970", + }, + wantPath: "/equities/bars/minute?code=86970", + }, + { + name: "with code and date", + params: MinuteQuotesParams{ + Code: "86970", + Date: "20230324", + }, + wantPath: "/equities/bars/minute?code=86970&date=20230324", + }, + { + name: "with date only", + params: MinuteQuotesParams{ + Date: "2023-03-24", + }, + wantPath: "/equities/bars/minute?date=2023-03-24", + }, + { + name: "with code and date range", + params: MinuteQuotesParams{ + Code: "86970", + From: "20230301", + To: "20230331", + }, + wantPath: "/equities/bars/minute?code=86970&from=20230301&to=20230331", + }, + { + name: "with pagination key", + params: MinuteQuotesParams{ + Code: "86970", + PaginationKey: "key123", + }, + wantPath: "/equities/bars/minute?code=86970&pagination_key=key123", + }, + { + name: "with no required parameters", + params: MinuteQuotesParams{}, + wantPath: "", + wantErr: true, + }, + } + + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + // Setup + mockClient := client.NewMockClient() + service := NewMinuteQuotesService(mockClient) + + // Mock response based on documentation sample + mockResponse := MinuteQuotesResponse{ + Data: []MinuteQuote{ + { + Date: "2023-03-24", + Time: "09:00", + Code: "86970", + O: 2047.0, + H: 2055.0, + L: 2045.0, + C: 2050.0, + Vo: 12500.0, + Va: 25625000.0, + }, + }, + PaginationKey: "", + } + if !tt.wantErr { + mockClient.SetResponse("GET", tt.wantPath, mockResponse) + } + + // Execute + resp, err := service.GetMinuteQuotes(context.Background(), tt.params) + + // Verify + if tt.wantErr { + if err == nil { + t.Error("GetMinuteQuotes() expected error but got nil") + } + return + } + + if err != nil { + t.Fatalf("GetMinuteQuotes() error = %v", err) + } + if resp == nil { + t.Fatal("GetMinuteQuotes() returned nil response") + } + if len(resp.Data) == 0 { + t.Error("GetMinuteQuotes() returned empty data") + } + if mockClient.LastPath != tt.wantPath { + t.Errorf("GetMinuteQuotes() path = %v, want %v", mockClient.LastPath, tt.wantPath) + } + }) + } +} + +func TestMinuteQuotesService_GetMinuteQuotes_RequiresParameter(t *testing.T) { + // Setup + mockClient := client.NewMockClient() + service := NewMinuteQuotesService(mockClient) + + // Execute with empty parameters + _, err := service.GetMinuteQuotes(context.Background(), MinuteQuotesParams{}) + + // Verify + if err == nil { + t.Error("GetMinuteQuotes() expected error for missing parameters but got nil") + } + if err.Error() != "either code or date parameter is required" { + t.Errorf("GetMinuteQuotes() error = %v, want 'either code or date parameter is required'", err) + } +} + +func TestMinuteQuotesResponse_UnmarshalJSON(t *testing.T) { + // ドキュメントのレスポンスサンプルに基づくJSON + // 2件目は数値の文字列・nullが混在するケース(防御的なデコードの確認) + raw := `{ + "data": [ + { + "Date": "2023-03-24", + "Time": "09:00", + "Code": "86970", + "O": 2047.0, + "H": 2055.0, + "L": 2045.0, + "C": 2050.0, + "Vo": 12500.0, + "Va": 25625000.0 + }, + { + "Date": "2023-03-24", + "Time": "09:01", + "Code": "86970", + "O": "2050.5", + "H": 2052.0, + "L": 2049.0, + "C": 2051.0, + "Vo": 3200.0, + "Va": null + } + ], + "pagination_key": "value1.value2." + }` + + var resp MinuteQuotesResponse + if err := json.Unmarshal([]byte(raw), &resp); err != nil { + t.Fatalf("UnmarshalJSON() error = %v", err) + } + + if len(resp.Data) != 2 { + t.Fatalf("UnmarshalJSON() returned %d items, want 2", len(resp.Data)) + } + if resp.PaginationKey != "value1.value2." { + t.Errorf("UnmarshalJSON() PaginationKey = %v, want value1.value2.", resp.PaginationKey) + } + + q := resp.Data[0] + if q.Date != "2023-03-24" { + t.Errorf("UnmarshalJSON() Date = %v, want 2023-03-24", q.Date) + } + if q.Time != "09:00" { + t.Errorf("UnmarshalJSON() Time = %v, want 09:00", q.Time) + } + if q.Code != "86970" { + t.Errorf("UnmarshalJSON() Code = %v, want 86970", q.Code) + } + if q.O != 2047.0 { + t.Errorf("UnmarshalJSON() O = %v, want 2047.0", q.O) + } + if q.H != 2055.0 { + t.Errorf("UnmarshalJSON() H = %v, want 2055.0", q.H) + } + if q.L != 2045.0 { + t.Errorf("UnmarshalJSON() L = %v, want 2045.0", q.L) + } + if q.C != 2050.0 { + t.Errorf("UnmarshalJSON() C = %v, want 2050.0", q.C) + } + if q.Vo != 12500.0 { + t.Errorf("UnmarshalJSON() Vo = %v, want 12500.0", q.Vo) + } + if q.Va != 25625000.0 { + t.Errorf("UnmarshalJSON() Va = %v, want 25625000.0", q.Va) + } + + // 数値文字列は数値としてパースされ、nullはゼロ値になる + if resp.Data[1].O != 2050.5 { + t.Errorf("UnmarshalJSON() O = %v, want 2050.5", resp.Data[1].O) + } + if resp.Data[1].Va != 0 { + t.Errorf("UnmarshalJSON() Va = %v, want 0", resp.Data[1].Va) + } +} + +func TestMinuteQuotesService_GetMinuteQuotesByCode(t *testing.T) { + // Setup + mockClient := client.NewMockClient() + service := NewMinuteQuotesService(mockClient) + + // Mock response - 最初のページ + mockResponse1 := MinuteQuotesResponse{ + Data: []MinuteQuote{ + { + Date: "2023-03-24", + Time: "09:00", + Code: "86970", + O: 2047.0, + H: 2055.0, + L: 2045.0, + C: 2050.0, + Vo: 12500.0, + Va: 25625000.0, + }, + { + Date: "2023-03-24", + Time: "09:01", + Code: "86970", + O: 2050.0, + H: 2052.0, + L: 2049.0, + C: 2051.0, + Vo: 3200.0, + Va: 6563200.0, + }, + }, + PaginationKey: "next_page_key", + } + + // Mock response - 2ページ目 + mockResponse2 := MinuteQuotesResponse{ + Data: []MinuteQuote{ + { + Date: "2023-03-24", + Time: "09:02", + Code: "86970", + O: 2051.0, + H: 2053.0, + L: 2050.0, + C: 2052.0, + Vo: 1800.0, + Va: 3693600.0, + }, + }, + PaginationKey: "", // 最後のページ + } + + mockClient.SetResponse("GET", "/equities/bars/minute?code=86970", mockResponse1) + mockClient.SetResponse("GET", "/equities/bars/minute?code=86970&pagination_key=next_page_key", mockResponse2) + + // Execute + data, err := service.GetMinuteQuotesByCode(context.Background(), "86970") + + // Verify + if err != nil { + t.Fatalf("GetMinuteQuotesByCode() error = %v", err) + } + if len(data) != 3 { + t.Errorf("GetMinuteQuotesByCode() returned %d items, want 3", len(data)) + } + for _, item := range data { + if item.Code != "86970" { + t.Errorf("GetMinuteQuotesByCode() returned code %v, want 86970", item.Code) + } + } +} + +func TestMinuteQuotesService_GetMinuteQuotesByCodeAndDate(t *testing.T) { + // Setup + mockClient := client.NewMockClient() + service := NewMinuteQuotesService(mockClient) + + // Mock response + mockResponse := MinuteQuotesResponse{ + Data: []MinuteQuote{ + { + Date: "2023-03-24", + Time: "09:00", + Code: "86970", + O: 2047.0, + C: 2050.0, + Vo: 12500.0, + }, + }, + PaginationKey: "", + } + mockClient.SetResponse("GET", "/equities/bars/minute?code=86970&date=20230324", mockResponse) + + // Execute + data, err := service.GetMinuteQuotesByCodeAndDate(context.Background(), "86970", "20230324") + + // Verify + if err != nil { + t.Fatalf("GetMinuteQuotesByCodeAndDate() error = %v", err) + } + if len(data) != 1 { + t.Errorf("GetMinuteQuotesByCodeAndDate() returned %d items, want 1", len(data)) + } + if data[0].Code != "86970" { + t.Errorf("GetMinuteQuotesByCodeAndDate() returned code %v, want 86970", data[0].Code) + } + if data[0].Date != "2023-03-24" { + t.Errorf("GetMinuteQuotesByCodeAndDate() returned date %v, want 2023-03-24", data[0].Date) + } +} + +func TestMinuteQuotesService_GetMinuteQuotesByDate(t *testing.T) { + // Setup + mockClient := client.NewMockClient() + service := NewMinuteQuotesService(mockClient) + + // Mock response + mockResponse := MinuteQuotesResponse{ + Data: []MinuteQuote{ + { + Date: "2023-03-24", + Time: "09:00", + Code: "86970", + O: 2047.0, + }, + { + Date: "2023-03-24", + Time: "09:00", + Code: "13660", + O: 1500.0, + }, + }, + PaginationKey: "", + } + mockClient.SetResponse("GET", "/equities/bars/minute?date=20230324", mockResponse) + + // Execute + data, err := service.GetMinuteQuotesByDate(context.Background(), "20230324") + + // Verify + if err != nil { + t.Fatalf("GetMinuteQuotesByDate() error = %v", err) + } + if len(data) != 2 { + t.Errorf("GetMinuteQuotesByDate() returned %d items, want 2", len(data)) + } + for _, item := range data { + if item.Date != "2023-03-24" { + t.Errorf("GetMinuteQuotesByDate() returned date %v, want 2023-03-24", item.Date) + } + } +} + +func TestMinuteQuotesService_GetMinuteQuotes_Error(t *testing.T) { + // Setup + mockClient := client.NewMockClient() + service := NewMinuteQuotesService(mockClient) + + // Set error response + mockClient.SetError("GET", "/equities/bars/minute?code=86970", fmt.Errorf("unauthorized")) + + // Execute + _, err := service.GetMinuteQuotes(context.Background(), MinuteQuotesParams{Code: "86970"}) + + // Verify + if err == nil { + t.Error("GetMinuteQuotes() expected error but got nil") + } +} diff --git a/statements.go b/statements.go index 8ca0b62..69e3c65 100644 --- a/statements.go +++ b/statements.go @@ -311,6 +311,7 @@ type RawStatement struct { type StatementsResponse struct { Data []Statement `json:"data"` PaginationKey string `json:"pagination_key"` + Cursor string `json:"cursor"` // 差分取得用カーソル(Premiumプランのみ) } // UnmarshalJSON implements custom JSON unmarshaling @@ -319,6 +320,7 @@ func (s *StatementsResponse) UnmarshalJSON(data []byte) error { type rawResponse struct { Data []RawStatement `json:"data"` PaginationKey string `json:"pagination_key"` + Cursor string `json:"cursor"` } var raw rawResponse @@ -327,6 +329,7 @@ func (s *StatementsResponse) UnmarshalJSON(data []byte) error { } s.PaginationKey = raw.PaginationKey + s.Cursor = raw.Cursor // Convert RawStatement to Statement s.Data = make([]Statement, len(raw.Data)) @@ -479,6 +482,7 @@ func (s *StatementsResponse) UnmarshalJSON(data []byte) error { type StatementsParams struct { Code string // 銘柄コード(4桁または5桁) Date string // 開示日付(YYYYMMDD または YYYY-MM-DD) + Cursor string // 差分取得用カーソル。前回レスポンスのcursorを指定すると前回リクエスト以降のデータを取得(Premiumプランのみ。pagination_keyと同時指定不可) PaginationKey string // ページネーションキー } @@ -487,8 +491,13 @@ type StatementsParams struct { // パラメータ: // - Code: 銘柄コード(例: "7203" または "72030") // - Date: 開示日付(例: "20240101" または "2024-01-01") +// - Cursor: 差分取得用カーソル(Premiumプランのみ) // - PaginationKey: ページネーション用キー func (s *StatementsService) GetStatements(ctx context.Context, params StatementsParams) (*StatementsResponse, error) { + if params.Cursor != "" && params.PaginationKey != "" { + return nil, fmt.Errorf("cursor and pagination_key cannot be specified at the same time") + } + path := "/fins/summary" query := "?" @@ -498,6 +507,9 @@ func (s *StatementsService) GetStatements(ctx context.Context, params Statements if params.Date != "" { query += fmt.Sprintf("date=%s&", params.Date) } + if params.Cursor != "" { + query += fmt.Sprintf("cursor=%s&", params.Cursor) + } if params.PaginationKey != "" { query += fmt.Sprintf("pagination_key=%s&", params.PaginationKey) } @@ -507,7 +519,14 @@ func (s *StatementsService) GetStatements(ctx context.Context, params Statements } var resp StatementsResponse - if err := s.client.DoRequest(ctx, "GET", path, nil, &resp); err != nil { + var err error + if params.Cursor != "" { + // cursorによる差分取得はポーリング用途のため、キャッシュを経由しない + err = client.DoRequestNoCache(ctx, s.client, "GET", path, nil, &resp) + } else { + err = s.client.DoRequest(ctx, "GET", path, nil, &resp) + } + if err != nil { return nil, fmt.Errorf("failed to get statements: %w", err) } diff --git a/statements_test.go b/statements_test.go index 3b4c631..83eb78d 100644 --- a/statements_test.go +++ b/statements_test.go @@ -35,6 +35,11 @@ func TestStatementsService_GetStatements(t *testing.T) { params: StatementsParams{Date: "20240101", PaginationKey: "key123"}, wantPath: "/fins/summary?date=20240101&pagination_key=key123", }, + { + name: "with date and cursor", + params: StatementsParams{Date: "20240101", Cursor: "cur123"}, + wantPath: "/fins/summary?date=20240101&cursor=cur123", + }, { name: "with no parameters", params: StatementsParams{}, @@ -119,6 +124,20 @@ func TestStatementsService_GetStatements(t *testing.T) { } } +func TestStatementsService_GetStatements_CursorConflict(t *testing.T) { + mockClient := client.NewMockClient() + service := NewStatementsService(mockClient) + + _, err := service.GetStatements(context.Background(), StatementsParams{ + Date: "20240101", + Cursor: "cur123", + PaginationKey: "key123", + }) + if err == nil { + t.Error("GetStatements() expected error for cursor and pagination_key specified together") + } +} + func TestStatementsService_GetLatestStatements(t *testing.T) { // Setup mockClient := client.NewMockClient() @@ -608,3 +627,26 @@ func TestStatementsResponse_UnmarshalJSON_MissingValueVariants(t *testing.T) { t.Errorf("TA = %v, want nil for null", *s.TA) } } + +func TestStatementsService_GetStatements_CursorSkipsCache(t *testing.T) { + mockClient := client.NewMockClient() + service := NewStatementsService(mockClient) + mockClient.SetResponse("GET", "/fins/summary?date=20240101&cursor=cur123", StatementsResponse{}) + mockClient.SetResponse("GET", "/fins/summary?date=20240101", StatementsResponse{}) + + // cursorによるポーリングはキャッシュをバイパスすること + if _, err := service.GetStatements(context.Background(), StatementsParams{Date: "20240101", Cursor: "cur123"}); err != nil { + t.Fatalf("GetStatements() error = %v", err) + } + if !mockClient.LastSkipCache { + t.Error("GetStatements() with cursor should bypass the session cache") + } + + // cursorなしは通常どおりキャッシュ対象 + if _, err := service.GetStatements(context.Background(), StatementsParams{Date: "20240101"}); err != nil { + t.Fatalf("GetStatements() error = %v", err) + } + if mockClient.LastSkipCache { + t.Error("GetStatements() without cursor should use the session cache") + } +} diff --git a/test/e2e/bulk_test.go b/test/e2e/bulk_test.go new file mode 100644 index 0000000..95e8b88 --- /dev/null +++ b/test/e2e/bulk_test.go @@ -0,0 +1,56 @@ +//go:build e2e +// +build e2e + +package e2e + +import ( + "context" + "testing" + + "github.com/utahta/jquants" +) + +// TestBulkEndpoint は/bulk/list, /bulk/getエンドポイントのテスト +func TestBulkEndpoint(t *testing.T) { + t.Run("GetFiles_And_GetDownloadURL", func(t *testing.T) { + resp, err := jq.Bulk.GetFiles(context.Background(), jquants.BulkListParams{ + Endpoint: "/equities/bars/daily", + }) + if err != nil { + if isSubscriptionLimited(err) { + t.Skip("Skipping due to subscription limitation") + } + t.Fatalf("Failed to get bulk file list: %v", err) + } + if len(resp.Data) == 0 { + t.Skip("No bulk files available for /equities/bars/daily") + } + + for i, f := range resp.Data { + if f.Key == "" { + t.Errorf("File[%d]: Key is empty", i) + } + if f.Size <= 0 { + t.Errorf("File[%d]: Size = %v, want > 0", i, f.Size) + } + if f.LastModified == "" { + t.Errorf("File[%d]: LastModified is empty", i) + } + if i >= 10 { + break + } + } + t.Logf("Retrieved %d bulk files for /equities/bars/daily", len(resp.Data)) + + // 先頭ファイルのダウンロードURL取得(URLは5分有効・1回限りのためダウンロードはしない) + url, err := jq.Bulk.GetDownloadURL(context.Background(), jquants.BulkGetParams{ + Key: resp.Data[0].Key, + }) + if err != nil { + t.Fatalf("Failed to get download URL for %s: %v", resp.Data[0].Key, err) + } + if url == "" { + t.Errorf("GetDownloadURL(%s): URL is empty", resp.Data[0].Key) + } + }) +} diff --git a/test/e2e/edinet_test.go b/test/e2e/edinet_test.go new file mode 100644 index 0000000..6ec2528 --- /dev/null +++ b/test/e2e/edinet_test.go @@ -0,0 +1,141 @@ +//go:build e2e +// +build e2e + +package e2e + +import ( + "context" + "strings" + "testing" +) + +// TestEdinetMajorShareholdersEndpoint は/edinet/major-shareholdersエンドポイントのテスト +// Standardプラン以上で利用可能。 +// 有価証券報告書の提出は6月に集中し単日指定では空になりやすいため、銘柄指定で取得する。 +func TestEdinetMajorShareholdersEndpoint(t *testing.T) { + t.Run("GetMajorShareholders_ByCode", func(t *testing.T) { + docs, err := jq.EdinetMajorShareholders.GetMajorShareholdersByCode(context.Background(), "7203") + if err != nil { + if isSubscriptionLimited(err) { + t.Skip("Skipping due to subscription limitation") + } + t.Fatalf("Failed to get major shareholders: %v", err) + } + if len(docs) == 0 { + t.Fatal("No major shareholders filings for 7203 (data since 2016-06 should exist)") + } + + for i, doc := range docs { + if !strings.HasPrefix(doc.DocId, "S") { + t.Errorf("Doc[%d]: DocId = %v, want S-prefixed", i, doc.DocId) + } + if doc.Code != "72030" { + t.Errorf("Doc[%d]: Code = %v, want 72030", i, doc.Code) + } + if doc.SubDate == "" || doc.PerSt == "" || doc.PerEn == "" { + t.Errorf("Doc[%d]: SubDate/PerSt/PerEn should not be empty", i) + } + if len(doc.Hldrs) == 0 { + t.Errorf("Doc[%d]: Hldrs is empty", i) + } + for j, h := range doc.Hldrs { + if h.HldrName == "" { + t.Errorf("Doc[%d].Hldrs[%d]: HldrName is empty", i, j) + } + if h.ShsRatio <= 0 || h.ShsRatio > 1 { + t.Errorf("Doc[%d].Hldrs[%d]: ShsRatio = %v, want (0, 1]", i, j, h.ShsRatio) + } + } + } + t.Logf("Retrieved %d major shareholders filings for 7203", len(docs)) + }) +} + +// TestEdinetCrossShareholdingsEndpoint は/edinet/cross-shareholdingsエンドポイントのテスト +// Standardプラン以上で利用可能。 +func TestEdinetCrossShareholdingsEndpoint(t *testing.T) { + t.Run("GetCrossShareholdings_ByCode", func(t *testing.T) { + docs, err := jq.EdinetCrossShareholdings.GetCrossShareholdingsByCode(context.Background(), "7203") + if err != nil { + if isSubscriptionLimited(err) { + t.Skip("Skipping due to subscription limitation") + } + t.Fatalf("Failed to get cross shareholdings: %v", err) + } + if len(docs) == 0 { + t.Fatal("No cross shareholdings filings for 7203 (data since 2020-03 should exist)") + } + + reports := 0 + issues := 0 + for i, doc := range docs { + if !strings.HasPrefix(doc.DocId, "S") { + t.Errorf("Doc[%d]: DocId = %v, want S-prefixed", i, doc.DocId) + } + if doc.Code != "72030" { + t.Errorf("Doc[%d]: Code = %v, want 72030", i, doc.Code) + } + if doc.HasReport() { + reports++ + issues += len(doc.Report.Spec) + len(doc.Report.Deem) + if doc.Report.HldrName == "" { + t.Errorf("Doc[%d]: Report.HldrName is empty", i) + } + } + } + if reports == 0 { + t.Error("No document has a Report block for 7203") + } + t.Logf("Retrieved %d filings (%d with Report block, %d issues) for 7203", + len(docs), reports, issues) + }) +} + +// TestEdinetLargeVolumeShareholdersEndpoint は/edinet/large-volume-shareholdersエンドポイントのテスト +// Standardプラン以上で利用可能。 +func TestEdinetLargeVolumeShareholdersEndpoint(t *testing.T) { + t.Run("GetLargeVolumeShareholders_ByDate", func(t *testing.T) { + date := getTestDateFormatted() + docs, err := jq.EdinetLargeVolumeShareholders.GetLargeVolumeShareholdersByDate(context.Background(), date) + if err != nil { + if isSubscriptionLimited(err) { + t.Skip("Skipping due to subscription limitation") + } + t.Fatalf("Failed to get large volume shareholders: %v", err) + } + if len(docs) == 0 { + t.Skipf("No large volume filings on %s", date) + } + + changeReports := 0 + withTotals := 0 + for i, doc := range docs { + if !strings.HasPrefix(doc.DocId, "S") { + t.Errorf("Doc[%d]: DocId = %v, want S-prefixed", i, doc.DocId) + } + if doc.SubDate != date { + t.Errorf("Doc[%d]: SubDate = %v, want %v", i, doc.SubDate, date) + } + // 合計欄は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 len(doc.Hldrs) == 0 { + t.Errorf("Doc[%d]: Hldrs is empty", i) + } + for j, h := range doc.Hldrs { + if h.ShsRatio < 0 || h.ShsRatio > 1 { + t.Errorf("Doc[%d].Hldrs[%d]: ShsRatio = %v, want [0, 1]", i, j, h.ShsRatio) + } + } + if doc.IsChangeReport() { + changeReports++ + } + } + t.Logf("Retrieved %d large volume filings (%d change reports, %d with totals) for %s", + len(docs), changeReports, withTotals, date) + }) +} diff --git a/test/e2e/minute_quotes_test.go b/test/e2e/minute_quotes_test.go new file mode 100644 index 0000000..f6cab53 --- /dev/null +++ b/test/e2e/minute_quotes_test.go @@ -0,0 +1,46 @@ +//go:build e2e +// +build e2e + +package e2e + +import ( + "context" + "testing" +) + +// TestMinuteQuotesEndpoint は/equities/bars/minuteエンドポイントのテスト +// 株価分足アドオン契約が必要。 +func TestMinuteQuotesEndpoint(t *testing.T) { + t.Run("GetMinuteQuotes_ByCodeAndDate", func(t *testing.T) { + date := getTestDate() + quotes, err := jq.MinuteQuotes.GetMinuteQuotesByCodeAndDate(context.Background(), "7203", date) + if err != nil { + if isSubscriptionLimited(err) { + t.Skip("Skipping due to subscription limitation (minute bars add-on required)") + } + t.Fatalf("Failed to get minute quotes: %v", err) + } + if len(quotes) == 0 { + t.Skipf("No minute quotes for 7203 on %s", date) + } + + for i, q := range quotes { + if q.Time == "" { + t.Errorf("Quote[%d]: Time is empty", i) + } + if q.O <= 0 || q.H <= 0 || q.L <= 0 || q.C <= 0 { + t.Errorf("Quote[%d] %s: OHLC = %v/%v/%v/%v, want > 0", i, q.Time, q.O, q.H, q.L, q.C) + } + if q.H < q.L { + t.Errorf("Quote[%d] %s: H (%v) < L (%v)", i, q.Time, q.H, q.L) + } + if q.Vo <= 0 { + t.Errorf("Quote[%d] %s: Vo = %v, want > 0 (約定のない分足は返らない仕様)", i, q.Time, q.Vo) + } + if i >= 30 { + break + } + } + t.Logf("Retrieved %d minute bars for 7203 on %s", len(quotes), date) + }) +} diff --git a/test/e2e/timely_disclosure_test.go b/test/e2e/timely_disclosure_test.go new file mode 100644 index 0000000..ede2e9b --- /dev/null +++ b/test/e2e/timely_disclosure_test.go @@ -0,0 +1,75 @@ +//go:build e2e +// +build e2e + +package e2e + +import ( + "context" + "testing" + + "github.com/utahta/jquants" +) + +// TestTimelyDisclosureEndpoint は/td/list, /td/files, /td/bulkエンドポイントのテスト +// TDnet/適時開示情報アドオン契約が必要。 +func TestTimelyDisclosureEndpoint(t *testing.T) { + t.Run("GetDisclosures_ByDate", func(t *testing.T) { + date := getTestDateFormatted() + disclosures, err := jq.TimelyDisclosure.GetDisclosuresByDate(context.Background(), date) + if err != nil { + if isSubscriptionLimited(err) { + t.Skip("Skipping due to subscription limitation (TDnet add-on required)") + } + t.Fatalf("Failed to get disclosures: %v", err) + } + if len(disclosures) == 0 { + t.Skipf("No disclosures on %s", date) + } + + for i, d := range disclosures { + if len(d.DiscNo) != 14 { + t.Errorf("Disclosure[%d]: DiscNo = %v, want 14 digits", i, d.DiscNo) + } + if d.DiscDate != date { + t.Errorf("Disclosure[%d]: DiscDate = %v, want %v", i, d.DiscDate, date) + } + if d.Title == "" { + t.Errorf("Disclosure[%d]: Title is empty", i) + } + if len(d.DiscItems) == 0 { + t.Errorf("Disclosure[%d]: DiscItems is empty", i) + } + if i >= 20 { + break + } + } + t.Logf("Retrieved %d disclosures for %s", len(disclosures), date) + + // 先頭の開示についてファイルURLの取得も検証 + files, err := jq.TimelyDisclosure.GetDisclosureFiles(context.Background(), + jquants.TimelyDisclosureFilesParams{DiscNo: disclosures[0].DiscNo}) + if err != nil { + t.Fatalf("Failed to get disclosure files for %s: %v", disclosures[0].DiscNo, err) + } + if files.Files.PDF == "" && files.Files.SummaryPDF == "" && files.Files.XBRL == "" { + t.Errorf("GetDisclosureFiles(%s): all file URLs are empty", disclosures[0].DiscNo) + } + }) + + t.Run("GetBulkFile", func(t *testing.T) { + bulk, err := jq.TimelyDisclosure.GetBulkFile(context.Background()) + if err != nil { + if isSubscriptionLimited(err) { + t.Skip("Skipping due to subscription limitation (TDnet add-on required)") + } + t.Fatalf("Failed to get bulk file: %v", err) + } + if bulk.URL == "" { + t.Error("GetBulkFile(): URL is empty") + } + if bulk.LastUpdated == "" { + t.Error("GetBulkFile(): LastUpdated is empty") + } + t.Logf("Bulk CSV last updated: %s", bulk.LastUpdated) + }) +} diff --git a/timely_disclosure.go b/timely_disclosure.go new file mode 100644 index 0000000..9e7fb5d --- /dev/null +++ b/timely_disclosure.go @@ -0,0 +1,309 @@ +package jquants + +import ( + "context" + "encoding/json" + "fmt" + "slices" + + "github.com/utahta/jquants/client" + "github.com/utahta/jquants/types" +) + +// 適時開示書類タイプ(Docs・docsパラメータで使用する値) +const ( + TimelyDisclosureDocFullPDF = "g" // 全文情報PDF + TimelyDisclosureDocSummaryPDF = "s" // サマリ情報PDF + TimelyDisclosureDocXBRL = "x" // XBRL関連ファイル +) + +// TimelyDisclosureService はTDnet適時開示情報を取得するサービスです。 +// 利用にはTDnet/適時開示情報アドオン契約が必要です。データ取得可能期間は過去5年間です。 +type TimelyDisclosureService struct { + client client.HTTPClient +} + +// NewTimelyDisclosureService は新しいTimelyDisclosureServiceを作成します。 +func NewTimelyDisclosureService(c client.HTTPClient) *TimelyDisclosureService { + return &TimelyDisclosureService{client: c} +} + +// TimelyDisclosureParams は適時開示インデックス一覧のリクエストパラメータです。 +type TimelyDisclosureParams struct { + Date string // 開示日(YYYYMMDD または YYYY-MM-DD)(date、codeのいずれかが必須) + Code string // 4桁もしくは5桁の銘柄コード(date、codeのいずれかが必須) + From string // 取得開始日(YYYYMMDD または YYYY-MM-DD)。codeと組み合わせ、toと必ずペアで指定 + To string // 取得終了日(YYYYMMDD または YYYY-MM-DD)。codeと組み合わせ、fromと必ずペアで指定 + DiscItems string // 公開項目コードで絞り込む(カンマ区切りで複数指定可能、AND条件) + Cursor string // 差分取得用カーソル(前回レスポンスのcursorを指定)。pagination_keyと同時指定不可 + PaginationKey string // ページネーションキー。cursorと同時指定不可 +} + +// TimelyDisclosureResponse は適時開示インデックス一覧のレスポンスです。 +type TimelyDisclosureResponse struct { + Data []TimelyDisclosure `json:"data"` + Cursor string `json:"cursor"` // 差分取得用カーソル(dateに当日を指定し、ページネーションなしで全件取得できた場合のみ返却) + PaginationKey string `json:"pagination_key"` // ページネーションキー +} + +// TimelyDisclosure は適時開示インデックスのデータを表します。 +// J-Quants API /td/list エンドポイントのレスポンスデータ。 +type TimelyDisclosure struct { + DiscNo string `json:"DiscNo"` // 開示番号(14桁) + Code string `json:"Code"` // 銘柄コード + Name string `json:"Name"` // 会社名 + DiscDate string `json:"DiscDate"` // 開示日(YYYY-MM-DD形式) + DiscTime string `json:"DiscTime"` // 開示時刻(HH:MM形式) + Title string `json:"Title"` // 開示タイトル + DiscStatus string `json:"DiscStatus"` // 取扱属性(""=新規、"revision"=訂正、"delete"=削除。現仕様では常に新規) + RevNo int `json:"RevNo"` // 開示履歴番号(1~99。現仕様では常に1) + DiscItems []string `json:"DiscItems"` // 公開項目コードのリスト + Docs []string `json:"Docs"` // 書類タイプのリスト(g=全文情報PDF、s=サマリ情報PDF、x=XBRL関連ファイル) +} + +// RawTimelyDisclosure is used for unmarshaling JSON response with mixed types +type RawTimelyDisclosure struct { + DiscNo string `json:"DiscNo"` + Code string `json:"Code"` + Name string `json:"Name"` + DiscDate string `json:"DiscDate"` + DiscTime string `json:"DiscTime"` + Title string `json:"Title"` + DiscStatus types.NullableString `json:"DiscStatus"` + RevNo types.NullableInt64 `json:"RevNo"` + DiscItems []string `json:"DiscItems"` + Docs []string `json:"Docs"` +} + +// UnmarshalJSON implements custom JSON unmarshaling for TimelyDisclosureResponse +func (r *TimelyDisclosureResponse) UnmarshalJSON(data []byte) error { + // First unmarshal into RawTimelyDisclosure + type rawResponse struct { + Data []RawTimelyDisclosure `json:"data"` + Cursor string `json:"cursor"` + PaginationKey string `json:"pagination_key"` + } + + var raw rawResponse + if err := json.Unmarshal(data, &raw); err != nil { + return err + } + + r.Cursor = raw.Cursor + r.PaginationKey = raw.PaginationKey + + // Convert RawTimelyDisclosure to TimelyDisclosure + r.Data = make([]TimelyDisclosure, len(raw.Data)) + for idx, rtd := range raw.Data { + r.Data[idx] = TimelyDisclosure{ + DiscNo: rtd.DiscNo, + Code: rtd.Code, + Name: rtd.Name, + DiscDate: rtd.DiscDate, + DiscTime: rtd.DiscTime, + Title: rtd.Title, + DiscStatus: rtd.DiscStatus.Or(""), + RevNo: int(rtd.RevNo.Or(0)), + DiscItems: rtd.DiscItems, + Docs: rtd.Docs, + } + } + + return nil +} + +// TimelyDisclosureFilesParams は適時開示ファイル取得のリクエストパラメータです。 +type TimelyDisclosureFilesParams struct { + DiscNo string // 開示番号(14桁)(必須) + Docs string // 取得するファイル種別(カンマ区切りで複数指定可能。g=全文情報PDF、s=サマリ情報PDF、x=XBRL関連ファイル。省略時は全種別) +} + +// TimelyDisclosureFiles は適時開示ファイルのダウンロードURL情報を表します。 +// J-Quants API /td/files エンドポイントのレスポンスデータ。 +type TimelyDisclosureFiles struct { + DiscNo string `json:"discNo"` // 開示番号(14桁) + Files TimelyDisclosureFileURLs `json:"files"` // ファイルのダウンロードURL一覧 +} + +// TimelyDisclosureFileURLs は書類タイプごとの署名付きダウンロードURLです。 +// URLの有効期限は15分です。docsで絞った場合や書類が存在しない場合、該当フィールドは空文字になります。 +type TimelyDisclosureFileURLs struct { + PDF string `json:"pdf"` // 全文情報PDFのダウンロードURL + SummaryPDF string `json:"summaryPdf"` // サマリ情報PDFのダウンロードURL + XBRL string `json:"xbrl"` // XBRL関連ファイルのダウンロードURL +} + +// TimelyDisclosureBulk は適時開示インデックス一括ダウンロード情報を表します。 +// J-Quants API /td/bulk エンドポイントのレスポンスデータ。 +// URLはgzip圧縮CSVの署名付きダウンロードURLで、有効期限は15分です。 +type TimelyDisclosureBulk struct { + LastUpdated string `json:"lastUpdated"` // CSVファイルの最終更新日時(ISO 8601形式) + URL string `json:"url"` // CSVファイル(gzip圧縮)のダウンロードURL +} + +// GetDisclosures は適時開示インデックス一覧を取得します。 +func (s *TimelyDisclosureService) GetDisclosures(ctx context.Context, params TimelyDisclosureParams) (*TimelyDisclosureResponse, error) { + // date、codeのいずれかが必須 + if params.Date == "" && params.Code == "" { + return nil, fmt.Errorf("either date or code parameter is required") + } + // cursorとpagination_keyは同時指定不可 + if params.Cursor != "" && params.PaginationKey != "" { + return nil, fmt.Errorf("cursor and pagination_key parameters cannot be specified together") + } + + path := "/td/list" + + query := "?" + if params.Date != "" { + query += fmt.Sprintf("date=%s&", params.Date) + } + if params.Code != "" { + query += fmt.Sprintf("code=%s&", params.Code) + } + if params.From != "" { + query += fmt.Sprintf("from=%s&", params.From) + } + if params.To != "" { + query += fmt.Sprintf("to=%s&", params.To) + } + if params.DiscItems != "" { + query += fmt.Sprintf("discItems=%s&", params.DiscItems) + } + if params.Cursor != "" { + query += fmt.Sprintf("cursor=%s&", params.Cursor) + } + if params.PaginationKey != "" { + query += fmt.Sprintf("pagination_key=%s&", params.PaginationKey) + } + + if len(query) > 1 { + path += query[:len(query)-1] // Remove trailing & + } + + var resp TimelyDisclosureResponse + var err error + if params.Cursor != "" { + // cursorによる差分取得はポーリング用途のため、キャッシュを経由しない + err = client.DoRequestNoCache(ctx, s.client, "GET", path, nil, &resp) + } else { + err = s.client.DoRequest(ctx, "GET", path, nil, &resp) + } + if err != nil { + return nil, fmt.Errorf("failed to get timely disclosures: %w", err) + } + + return &resp, nil +} + +// GetDisclosuresByDate は指定開示日の適時開示インデックス一覧を取得します。 +// ページネーションを使用して全データを取得します。 +func (s *TimelyDisclosureService) GetDisclosuresByDate(ctx context.Context, date string) ([]TimelyDisclosure, error) { + var allData []TimelyDisclosure + paginationKey := "" + + for { + params := TimelyDisclosureParams{ + Date: date, + PaginationKey: paginationKey, + } + + resp, err := s.GetDisclosures(ctx, params) + if err != nil { + return nil, err + } + + allData = append(allData, resp.Data...) + + // ページネーションキーがなければ終了 + if resp.PaginationKey == "" { + break + } + paginationKey = resp.PaginationKey + } + + return allData, nil +} + +// GetDisclosuresByCode は指定銘柄の適時開示インデックス一覧を取得します(直近5年間)。 +// ページネーションを使用して全データを取得します。 +func (s *TimelyDisclosureService) GetDisclosuresByCode(ctx context.Context, code string) ([]TimelyDisclosure, error) { + var allData []TimelyDisclosure + paginationKey := "" + + for { + params := TimelyDisclosureParams{ + Code: code, + PaginationKey: paginationKey, + } + + resp, err := s.GetDisclosures(ctx, params) + if err != nil { + return nil, err + } + + allData = append(allData, resp.Data...) + + // ページネーションキーがなければ終了 + if resp.PaginationKey == "" { + break + } + paginationKey = resp.PaginationKey + } + + return allData, nil +} + +// GetDisclosureFiles は開示番号に対応する適時開示ファイルのダウンロードURLを取得します。 +// URLの有効期限は15分です。 +func (s *TimelyDisclosureService) GetDisclosureFiles(ctx context.Context, params TimelyDisclosureFilesParams) (*TimelyDisclosureFiles, error) { + // discNoは必須 + if params.DiscNo == "" { + return nil, fmt.Errorf("discNo parameter is required") + } + + path := "/td/files" + + query := "?" + query += fmt.Sprintf("discNo=%s&", params.DiscNo) + if params.Docs != "" { + query += fmt.Sprintf("docs=%s&", params.Docs) + } + + path += query[:len(query)-1] // Remove trailing & + + var resp TimelyDisclosureFiles + // 署名付きURLは15分で失効するため、キャッシュを経由しない + if err := client.DoRequestNoCache(ctx, s.client, "GET", path, nil, &resp); err != nil { + return nil, fmt.Errorf("failed to get timely disclosure files: %w", err) + } + + return &resp, nil +} + +// GetBulkFile は全開示インデックスCSV(gzip圧縮)のダウンロードURLを取得します。 +// URLの有効期限は15分です。 +func (s *TimelyDisclosureService) GetBulkFile(ctx context.Context) (*TimelyDisclosureBulk, error) { + var resp TimelyDisclosureBulk + // 署名付きURLは15分で失効するため、キャッシュを経由しない + if err := client.DoRequestNoCache(ctx, s.client, "GET", "/td/bulk", nil, &resp); err != nil { + return nil, fmt.Errorf("failed to get timely disclosure bulk file: %w", err) + } + + return &resp, nil +} + +// IsRevision は訂正開示情報かを判定します。 +func (td *TimelyDisclosure) IsRevision() bool { + return td.DiscStatus == "revision" +} + +// IsDeleted は削除開示情報かを判定します。 +func (td *TimelyDisclosure) IsDeleted() bool { + return td.DiscStatus == "delete" +} + +// HasXBRL はXBRL関連ファイルが存在するかを判定します。 +func (td *TimelyDisclosure) HasXBRL() bool { + return slices.Contains(td.Docs, TimelyDisclosureDocXBRL) +} diff --git a/timely_disclosure_test.go b/timely_disclosure_test.go new file mode 100644 index 0000000..f75ab64 --- /dev/null +++ b/timely_disclosure_test.go @@ -0,0 +1,741 @@ +package jquants + +import ( + "context" + "encoding/json" + "fmt" + "testing" + + "github.com/utahta/jquants/client" +) + +func TestTimelyDisclosureService_GetDisclosures(t *testing.T) { + tests := []struct { + name string + params TimelyDisclosureParams + wantPath string + wantErr bool + }{ + { + name: "with date only", + params: TimelyDisclosureParams{ + Date: "20250401", + }, + wantPath: "/td/list?date=20250401", + }, + { + name: "with hyphenated date", + params: TimelyDisclosureParams{ + Date: "2025-04-01", + }, + wantPath: "/td/list?date=2025-04-01", + }, + { + name: "with code only", + params: TimelyDisclosureParams{ + Code: "86970", + }, + wantPath: "/td/list?code=86970", + }, + { + name: "with code and date range", + params: TimelyDisclosureParams{ + Code: "86970", + From: "20250301", + To: "20250401", + }, + wantPath: "/td/list?code=86970&from=20250301&to=20250401", + }, + { + name: "with date and discItems", + params: TimelyDisclosureParams{ + Date: "20250401", + DiscItems: "11101,11102", + }, + wantPath: "/td/list?date=20250401&discItems=11101,11102", + }, + { + name: "with date and cursor", + params: TimelyDisclosureParams{ + Date: "20250401", + Cursor: "cursor123", + }, + wantPath: "/td/list?date=20250401&cursor=cursor123", + }, + { + name: "with date and pagination key", + params: TimelyDisclosureParams{ + Date: "20250401", + PaginationKey: "key123", + }, + wantPath: "/td/list?date=20250401&pagination_key=key123", + }, + { + name: "with no required parameters", + params: TimelyDisclosureParams{}, + wantPath: "", + wantErr: true, + }, + { + name: "with cursor and pagination key", + params: TimelyDisclosureParams{ + Date: "20250401", + Cursor: "cursor123", + PaginationKey: "key123", + }, + wantPath: "", + wantErr: true, + }, + } + + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + // Setup + mockClient := client.NewMockClient() + service := NewTimelyDisclosureService(mockClient) + + // Mock response based on documentation sample + mockResponse := TimelyDisclosureResponse{ + Data: []TimelyDisclosure{ + { + DiscNo: "20250401130100", + Code: "86970", + Name: "日本取引所グループ", + DiscDate: "2025-04-01", + DiscTime: "08:00", + Title: "2025年3月期 決算短信〔日本基準〕(連結)", + DiscStatus: "", + RevNo: 1, + DiscItems: []string{"11101"}, + Docs: []string{"g", "s", "x"}, + }, + }, + Cursor: "", + PaginationKey: "", + } + if !tt.wantErr { + mockClient.SetResponse("GET", tt.wantPath, mockResponse) + } + + // Execute + resp, err := service.GetDisclosures(context.Background(), tt.params) + + // Verify + if tt.wantErr { + if err == nil { + t.Error("GetDisclosures() expected error but got nil") + } + return + } + + if err != nil { + t.Fatalf("GetDisclosures() error = %v", err) + } + if resp == nil { + t.Fatal("GetDisclosures() returned nil response") + return + } + if len(resp.Data) == 0 { + t.Error("GetDisclosures() returned empty data") + } + if mockClient.LastPath != tt.wantPath { + t.Errorf("GetDisclosures() path = %v, want %v", mockClient.LastPath, tt.wantPath) + } + }) + } +} + +func TestTimelyDisclosureService_GetDisclosures_RequiresParameter(t *testing.T) { + // Setup + mockClient := client.NewMockClient() + service := NewTimelyDisclosureService(mockClient) + + // Execute with empty parameters + _, err := service.GetDisclosures(context.Background(), TimelyDisclosureParams{}) + + // Verify + if err == nil { + t.Error("GetDisclosures() expected error for missing parameters but got nil") + } + if err.Error() != "either date or code parameter is required" { + t.Errorf("GetDisclosures() error = %v, want 'either date or code parameter is required'", err) + } +} + +func TestTimelyDisclosureService_GetDisclosures_CursorConflictsWithPaginationKey(t *testing.T) { + // Setup + mockClient := client.NewMockClient() + service := NewTimelyDisclosureService(mockClient) + + // Execute with cursor and pagination_key + _, err := service.GetDisclosures(context.Background(), TimelyDisclosureParams{ + Date: "20250401", + Cursor: "cursor123", + PaginationKey: "key123", + }) + + // Verify + if err == nil { + t.Error("GetDisclosures() expected error for cursor and pagination_key but got nil") + } + if err.Error() != "cursor and pagination_key parameters cannot be specified together" { + t.Errorf("GetDisclosures() error = %v, want 'cursor and pagination_key parameters cannot be specified together'", err) + } +} + +func TestTimelyDisclosureResponse_UnmarshalJSON(t *testing.T) { + // DiscStatusのnullが空文字として、配列フィールドとcursorがそのまま取得できること + jsonData := `{ + "data": [ + { + "DiscNo": "20250401130100", + "Code": "86970", + "Name": "日本取引所グループ", + "DiscDate": "2025-04-01", + "DiscTime": "08:00", + "Title": "2025年3月期 決算短信〔日本基準〕(連結)", + "DiscStatus": null, + "RevNo": 1, + "DiscItems": ["11101", "11102"], + "Docs": ["g", "s", "x"] + }, + { + "DiscNo": "20250401130200", + "Code": "13010", + "Name": "極洋", + "DiscDate": "2025-04-01", + "DiscTime": "09:00", + "Title": "訂正開示", + "DiscStatus": "revision", + "RevNo": 2, + "DiscItems": ["11102"], + "Docs": ["g"] + } + ], + "cursor": "cursor123", + "pagination_key": "" + }` + + var resp TimelyDisclosureResponse + if err := json.Unmarshal([]byte(jsonData), &resp); err != nil { + t.Fatalf("UnmarshalJSON failed: %v", err) + } + if len(resp.Data) != 2 { + t.Fatalf("data count = %d, want 2", len(resp.Data)) + } + if resp.Cursor != "cursor123" { + t.Errorf("Cursor = %v, want cursor123", resp.Cursor) + } + if resp.PaginationKey != "" { + t.Errorf("PaginationKey = %v, want empty", resp.PaginationKey) + } + + // 1件目: DiscStatusはnull→空文字、配列フィールドあり + d := resp.Data[0] + if d.DiscNo != "20250401130100" { + t.Errorf("DiscNo = %v, want 20250401130100", d.DiscNo) + } + if d.DiscStatus != "" { + t.Errorf("DiscStatus = %v, want empty for null", d.DiscStatus) + } + if d.RevNo != 1 { + t.Errorf("RevNo = %v, want 1", d.RevNo) + } + if len(d.DiscItems) != 2 || d.DiscItems[0] != "11101" || d.DiscItems[1] != "11102" { + t.Errorf("DiscItems = %v, want [11101 11102]", d.DiscItems) + } + if len(d.Docs) != 3 || d.Docs[0] != "g" || d.Docs[1] != "s" || d.Docs[2] != "x" { + t.Errorf("Docs = %v, want [g s x]", d.Docs) + } + if d.IsRevision() || d.IsDeleted() { + t.Error("IsRevision()/IsDeleted() should be false for null DiscStatus") + } + if !d.HasXBRL() { + t.Error("HasXBRL() should be true when Docs contains x") + } + + // 2件目: 訂正開示、XBRLなし + d = resp.Data[1] + if !d.IsRevision() { + t.Error("IsRevision() should be true for revision") + } + if d.RevNo != 2 { + t.Errorf("RevNo = %v, want 2", d.RevNo) + } + if d.HasXBRL() { + t.Error("HasXBRL() should be false when Docs does not contain x") + } +} + +func TestTimelyDisclosureService_GetDisclosuresByDate(t *testing.T) { + // Setup + mockClient := client.NewMockClient() + service := NewTimelyDisclosureService(mockClient) + + // Mock response - 最初のページ + mockResponse1 := TimelyDisclosureResponse{ + Data: []TimelyDisclosure{ + { + DiscNo: "20250401130100", + Code: "86970", + DiscDate: "2025-04-01", + RevNo: 1, + }, + { + DiscNo: "20250401130200", + Code: "13010", + DiscDate: "2025-04-01", + RevNo: 1, + }, + }, + PaginationKey: "next_page_key", + } + + // Mock response - 2ページ目 + mockResponse2 := TimelyDisclosureResponse{ + Data: []TimelyDisclosure{ + { + DiscNo: "20250401130300", + Code: "72030", + DiscDate: "2025-04-01", + RevNo: 1, + }, + }, + PaginationKey: "", // 最後のページ + } + + mockClient.SetResponse("GET", "/td/list?date=20250401", mockResponse1) + mockClient.SetResponse("GET", "/td/list?date=20250401&pagination_key=next_page_key", mockResponse2) + + // Execute + data, err := service.GetDisclosuresByDate(context.Background(), "20250401") + + // Verify + if err != nil { + t.Fatalf("GetDisclosuresByDate() error = %v", err) + } + if len(data) != 3 { + t.Errorf("GetDisclosuresByDate() returned %d items, want 3", len(data)) + } + for _, item := range data { + if item.DiscDate != "2025-04-01" { + t.Errorf("GetDisclosuresByDate() returned date %v, want 2025-04-01", item.DiscDate) + } + } +} + +func TestTimelyDisclosureService_GetDisclosuresByCode(t *testing.T) { + // Setup + mockClient := client.NewMockClient() + service := NewTimelyDisclosureService(mockClient) + + // Mock response - 最初のページ + mockResponse1 := TimelyDisclosureResponse{ + Data: []TimelyDisclosure{ + { + DiscNo: "20250401130100", + Code: "86970", + DiscDate: "2025-04-01", + RevNo: 1, + }, + }, + PaginationKey: "next_page_key", + } + + // Mock response - 2ページ目 + mockResponse2 := TimelyDisclosureResponse{ + Data: []TimelyDisclosure{ + { + DiscNo: "20250301120100", + Code: "86970", + DiscDate: "2025-03-01", + RevNo: 1, + }, + }, + PaginationKey: "", // 最後のページ + } + + mockClient.SetResponse("GET", "/td/list?code=86970", mockResponse1) + mockClient.SetResponse("GET", "/td/list?code=86970&pagination_key=next_page_key", mockResponse2) + + // Execute + data, err := service.GetDisclosuresByCode(context.Background(), "86970") + + // Verify + if err != nil { + t.Fatalf("GetDisclosuresByCode() error = %v", err) + } + if len(data) != 2 { + t.Errorf("GetDisclosuresByCode() returned %d items, want 2", len(data)) + } + for _, item := range data { + if item.Code != "86970" { + t.Errorf("GetDisclosuresByCode() returned code %v, want 86970", item.Code) + } + } +} + +func TestTimelyDisclosureService_GetDisclosureFiles(t *testing.T) { + tests := []struct { + name string + params TimelyDisclosureFilesParams + wantPath string + wantErr bool + }{ + { + name: "with discNo only", + params: TimelyDisclosureFilesParams{ + DiscNo: "20250401130100", + }, + wantPath: "/td/files?discNo=20250401130100", + }, + { + name: "with discNo and docs", + params: TimelyDisclosureFilesParams{ + DiscNo: "20250401130100", + Docs: "g,s", + }, + wantPath: "/td/files?discNo=20250401130100&docs=g,s", + }, + { + name: "with docs constant", + params: TimelyDisclosureFilesParams{ + DiscNo: "20250401130100", + Docs: TimelyDisclosureDocXBRL, + }, + wantPath: "/td/files?discNo=20250401130100&docs=x", + }, + { + name: "without discNo", + params: TimelyDisclosureFilesParams{}, + wantPath: "", + wantErr: true, + }, + } + + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + // Setup + mockClient := client.NewMockClient() + service := NewTimelyDisclosureService(mockClient) + + // Mock response based on documentation sample + mockResponse := TimelyDisclosureFiles{ + DiscNo: "20250401130100", + Files: TimelyDisclosureFileURLs{ + PDF: "https://example.com/download-url-pdf", + SummaryPDF: "https://example.com/download-url-summary", + XBRL: "https://example.com/download-url-xbrl", + }, + } + if !tt.wantErr { + mockClient.SetResponse("GET", tt.wantPath, mockResponse) + } + + // Execute + resp, err := service.GetDisclosureFiles(context.Background(), tt.params) + + // Verify + if tt.wantErr { + if err == nil { + t.Error("GetDisclosureFiles() expected error but got nil") + } + return + } + + if err != nil { + t.Fatalf("GetDisclosureFiles() error = %v", err) + } + if resp == nil { + t.Fatal("GetDisclosureFiles() returned nil response") + return + } + if resp.DiscNo != "20250401130100" { + t.Errorf("GetDisclosureFiles() DiscNo = %v, want 20250401130100", resp.DiscNo) + } + if mockClient.LastPath != tt.wantPath { + t.Errorf("GetDisclosureFiles() path = %v, want %v", mockClient.LastPath, tt.wantPath) + } + }) + } +} + +func TestTimelyDisclosureService_GetDisclosureFiles_RequiresDiscNo(t *testing.T) { + // Setup + mockClient := client.NewMockClient() + service := NewTimelyDisclosureService(mockClient) + + // Execute with empty parameters + _, err := service.GetDisclosureFiles(context.Background(), TimelyDisclosureFilesParams{}) + + // Verify + if err == nil { + t.Error("GetDisclosureFiles() expected error for missing discNo but got nil") + } + if err.Error() != "discNo parameter is required" { + t.Errorf("GetDisclosureFiles() error = %v, want 'discNo parameter is required'", err) + } +} + +func TestTimelyDisclosureFiles_UnmarshalJSON_AllFiles(t *testing.T) { + // 全種別のURLが取得できること + jsonData := `{ + "discNo": "20250401130100", + "files": { + "pdf": "https://example.com/download-url-pdf", + "summaryPdf": "https://example.com/download-url-summary", + "xbrl": "https://example.com/download-url-xbrl" + } + }` + + var files TimelyDisclosureFiles + if err := json.Unmarshal([]byte(jsonData), &files); err != nil { + t.Fatalf("UnmarshalJSON failed: %v", err) + } + if files.DiscNo != "20250401130100" { + t.Errorf("DiscNo = %v, want 20250401130100", files.DiscNo) + } + if files.Files.PDF != "https://example.com/download-url-pdf" { + t.Errorf("Files.PDF = %v, want https://example.com/download-url-pdf", files.Files.PDF) + } + if files.Files.SummaryPDF != "https://example.com/download-url-summary" { + t.Errorf("Files.SummaryPDF = %v, want https://example.com/download-url-summary", files.Files.SummaryPDF) + } + if files.Files.XBRL != "https://example.com/download-url-xbrl" { + t.Errorf("Files.XBRL = %v, want https://example.com/download-url-xbrl", files.Files.XBRL) + } +} + +func TestTimelyDisclosureFiles_UnmarshalJSON_PDFOnly(t *testing.T) { + // docsで絞った場合など、存在しないキーは空文字になること + jsonData := `{ + "discNo": "20250401130100", + "files": { + "pdf": "https://example.com/download-url-pdf" + } + }` + + var files TimelyDisclosureFiles + if err := json.Unmarshal([]byte(jsonData), &files); err != nil { + t.Fatalf("UnmarshalJSON failed: %v", err) + } + if files.Files.PDF != "https://example.com/download-url-pdf" { + t.Errorf("Files.PDF = %v, want https://example.com/download-url-pdf", files.Files.PDF) + } + if files.Files.SummaryPDF != "" { + t.Errorf("Files.SummaryPDF = %v, want empty", files.Files.SummaryPDF) + } + if files.Files.XBRL != "" { + t.Errorf("Files.XBRL = %v, want empty", files.Files.XBRL) + } +} + +func TestTimelyDisclosureService_GetBulkFile(t *testing.T) { + // Setup + mockClient := client.NewMockClient() + service := NewTimelyDisclosureService(mockClient) + + // Mock response based on documentation sample + mockResponse := TimelyDisclosureBulk{ + LastUpdated: "2025-04-01T08:00:00Z", + URL: "https://example.com/download-url-bulk-csv", + } + mockClient.SetResponse("GET", "/td/bulk", mockResponse) + + // Execute + resp, err := service.GetBulkFile(context.Background()) + + // Verify + if err != nil { + t.Fatalf("GetBulkFile() error = %v", err) + } + if resp == nil { + t.Fatal("GetBulkFile() returned nil response") + return + } + if resp.LastUpdated != "2025-04-01T08:00:00Z" { + t.Errorf("GetBulkFile() LastUpdated = %v, want 2025-04-01T08:00:00Z", resp.LastUpdated) + } + if resp.URL != "https://example.com/download-url-bulk-csv" { + t.Errorf("GetBulkFile() URL = %v, want https://example.com/download-url-bulk-csv", resp.URL) + } + if mockClient.LastPath != "/td/bulk" { + t.Errorf("GetBulkFile() path = %v, want /td/bulk", mockClient.LastPath) + } +} + +func TestTimelyDisclosureBulk_UnmarshalJSON(t *testing.T) { + jsonData := `{ + "lastUpdated": "2025-04-01T08:00:00Z", + "url": "https://example.com/download-url-bulk-csv" + }` + + var bulk TimelyDisclosureBulk + if err := json.Unmarshal([]byte(jsonData), &bulk); err != nil { + t.Fatalf("UnmarshalJSON failed: %v", err) + } + if bulk.LastUpdated != "2025-04-01T08:00:00Z" { + t.Errorf("LastUpdated = %v, want 2025-04-01T08:00:00Z", bulk.LastUpdated) + } + if bulk.URL != "https://example.com/download-url-bulk-csv" { + t.Errorf("URL = %v, want https://example.com/download-url-bulk-csv", bulk.URL) + } +} + +func TestTimelyDisclosure_IsRevision(t *testing.T) { + tests := []struct { + name string + disclosure TimelyDisclosure + want bool + }{ + { + name: "revision", + disclosure: TimelyDisclosure{DiscStatus: "revision"}, + want: true, + }, + { + name: "new disclosure", + disclosure: TimelyDisclosure{DiscStatus: ""}, + want: false, + }, + { + name: "delete", + disclosure: TimelyDisclosure{DiscStatus: "delete"}, + want: false, + }, + } + + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + if got := tt.disclosure.IsRevision(); got != tt.want { + t.Errorf("TimelyDisclosure.IsRevision() = %v, want %v", got, tt.want) + } + }) + } +} + +func TestTimelyDisclosure_IsDeleted(t *testing.T) { + tests := []struct { + name string + disclosure TimelyDisclosure + want bool + }{ + { + name: "delete", + disclosure: TimelyDisclosure{DiscStatus: "delete"}, + want: true, + }, + { + name: "new disclosure", + disclosure: TimelyDisclosure{DiscStatus: ""}, + want: false, + }, + { + name: "revision", + disclosure: TimelyDisclosure{DiscStatus: "revision"}, + want: false, + }, + } + + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + if got := tt.disclosure.IsDeleted(); got != tt.want { + t.Errorf("TimelyDisclosure.IsDeleted() = %v, want %v", got, tt.want) + } + }) + } +} + +func TestTimelyDisclosure_HasXBRL(t *testing.T) { + tests := []struct { + name string + disclosure TimelyDisclosure + want bool + }{ + { + name: "has xbrl", + disclosure: TimelyDisclosure{Docs: []string{"g", "s", "x"}}, + want: true, + }, + { + name: "no xbrl", + disclosure: TimelyDisclosure{Docs: []string{"g", "s"}}, + want: false, + }, + { + name: "empty docs", + disclosure: TimelyDisclosure{Docs: nil}, + want: false, + }, + } + + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + if got := tt.disclosure.HasXBRL(); got != tt.want { + t.Errorf("TimelyDisclosure.HasXBRL() = %v, want %v", got, tt.want) + } + }) + } +} + +func TestTimelyDisclosureService_GetDisclosures_Error(t *testing.T) { + // Setup + mockClient := client.NewMockClient() + service := NewTimelyDisclosureService(mockClient) + + // Set error response + mockClient.SetError("GET", "/td/list?code=86970", fmt.Errorf("unauthorized")) + + // Execute + _, err := service.GetDisclosures(context.Background(), TimelyDisclosureParams{Code: "86970"}) + + // Verify + if err == nil { + t.Error("GetDisclosures() expected error but got nil") + } +} + +func TestTimelyDisclosureService_SignedURLMethods_SkipCache(t *testing.T) { + mockClient := client.NewMockClient() + service := NewTimelyDisclosureService(mockClient) + + mockClient.SetResponse("GET", "/td/files?discNo=20250401130100", TimelyDisclosureFiles{DiscNo: "20250401130100"}) + if _, err := service.GetDisclosureFiles(context.Background(), TimelyDisclosureFilesParams{DiscNo: "20250401130100"}); err != nil { + t.Fatalf("GetDisclosureFiles() error = %v", err) + } + // 署名付きURLは失効するため、キャッシュバイパスを要求していること + if !mockClient.LastSkipCache { + t.Error("GetDisclosureFiles() should request cache bypass for expiring signed URLs") + } + + mockClient.SetResponse("GET", "/td/bulk", TimelyDisclosureBulk{URL: "https://example.com/bulk.csv.gz"}) + if _, err := service.GetBulkFile(context.Background()); err != nil { + t.Fatalf("GetBulkFile() error = %v", err) + } + if !mockClient.LastSkipCache { + t.Error("GetBulkFile() should request cache bypass for expiring signed URLs") + } +} + +func TestTimelyDisclosureService_GetDisclosures_CursorSkipsCache(t *testing.T) { + mockClient := client.NewMockClient() + service := NewTimelyDisclosureService(mockClient) + mockClient.SetResponse("GET", "/td/list?date=2025-04-01&cursor=cur123", TimelyDisclosureResponse{}) + mockClient.SetResponse("GET", "/td/list?date=2025-04-01", TimelyDisclosureResponse{}) + + // cursorによるポーリングはキャッシュをバイパスすること + if _, err := service.GetDisclosures(context.Background(), TimelyDisclosureParams{Date: "2025-04-01", Cursor: "cur123"}); err != nil { + t.Fatalf("GetDisclosures() error = %v", err) + } + if !mockClient.LastSkipCache { + t.Error("GetDisclosures() with cursor should bypass the session cache") + } + + // cursorなしは通常どおりキャッシュ対象 + if _, err := service.GetDisclosures(context.Background(), TimelyDisclosureParams{Date: "2025-04-01"}); err != nil { + t.Fatalf("GetDisclosures() error = %v", err) + } + if mockClient.LastSkipCache { + t.Error("GetDisclosures() without cursor should use the session cache") + } +}