diff --git a/breakdown.go b/breakdown.go index 929451f..a167e68 100644 --- a/breakdown.go +++ b/breakdown.go @@ -50,9 +50,9 @@ type Breakdown struct { Code string `json:"Code"` // 銘柄コード // 売りの約定代金内訳(単位:円) - LongSellVa float64 `json:"LongSellVa"` // 実売りの約定代金 - ShrtNoMrgnVa float64 `json:"ShrtNoMrgnVa"` // 空売り(信用新規売りを除く)の約定代金 - MrgnSellNewVa float64 `json:"MrgnSellNewVa"` // 信用新規売りの約定代金 + LongSellVa float64 `json:"LongSellVa"` // 実売りの約定代金 + ShrtNoMrgnVa float64 `json:"ShrtNoMrgnVa"` // 空売り(信用新規売りを除く)の約定代金 + MrgnSellNewVa float64 `json:"MrgnSellNewVa"` // 信用新規売りの約定代金 MrgnSellCloseVa float64 `json:"MrgnSellCloseVa"` // 信用返済売りの約定代金 // 買いの約定代金内訳(単位:円) @@ -74,22 +74,22 @@ type Breakdown struct { // RawBreakdown is used for unmarshaling JSON response with mixed types type RawBreakdown struct { - Date string `json:"Date"` - Code string `json:"Code"` - LongSellVa types.Float64String `json:"LongSellVa"` - ShrtNoMrgnVa types.Float64String `json:"ShrtNoMrgnVa"` - MrgnSellNewVa types.Float64String `json:"MrgnSellNewVa"` - MrgnSellCloseVa types.Float64String `json:"MrgnSellCloseVa"` - LongBuyVa types.Float64String `json:"LongBuyVa"` - MrgnBuyNewVa types.Float64String `json:"MrgnBuyNewVa"` - MrgnBuyCloseVa types.Float64String `json:"MrgnBuyCloseVa"` - LongSellVo types.Float64String `json:"LongSellVo"` - ShrtNoMrgnVo types.Float64String `json:"ShrtNoMrgnVo"` - MrgnSellNewVo types.Float64String `json:"MrgnSellNewVo"` - MrgnSellCloseVo types.Float64String `json:"MrgnSellCloseVo"` - LongBuyVo types.Float64String `json:"LongBuyVo"` - MrgnBuyNewVo types.Float64String `json:"MrgnBuyNewVo"` - MrgnBuyCloseVo types.Float64String `json:"MrgnBuyCloseVo"` + Date string `json:"Date"` + Code string `json:"Code"` + LongSellVa types.NullableFloat64 `json:"LongSellVa"` + ShrtNoMrgnVa types.NullableFloat64 `json:"ShrtNoMrgnVa"` + MrgnSellNewVa types.NullableFloat64 `json:"MrgnSellNewVa"` + MrgnSellCloseVa types.NullableFloat64 `json:"MrgnSellCloseVa"` + LongBuyVa types.NullableFloat64 `json:"LongBuyVa"` + MrgnBuyNewVa types.NullableFloat64 `json:"MrgnBuyNewVa"` + MrgnBuyCloseVa types.NullableFloat64 `json:"MrgnBuyCloseVa"` + LongSellVo types.NullableFloat64 `json:"LongSellVo"` + ShrtNoMrgnVo types.NullableFloat64 `json:"ShrtNoMrgnVo"` + MrgnSellNewVo types.NullableFloat64 `json:"MrgnSellNewVo"` + MrgnSellCloseVo types.NullableFloat64 `json:"MrgnSellCloseVo"` + LongBuyVo types.NullableFloat64 `json:"LongBuyVo"` + MrgnBuyNewVo types.NullableFloat64 `json:"MrgnBuyNewVo"` + MrgnBuyCloseVo types.NullableFloat64 `json:"MrgnBuyCloseVo"` } // UnmarshalJSON implements custom JSON unmarshaling @@ -114,20 +114,20 @@ func (r *BreakdownResponse) UnmarshalJSON(data []byte) error { r.Data[i] = Breakdown{ Date: rb.Date, Code: rb.Code, - LongSellVa: float64(rb.LongSellVa), - ShrtNoMrgnVa: float64(rb.ShrtNoMrgnVa), - MrgnSellNewVa: float64(rb.MrgnSellNewVa), - MrgnSellCloseVa: float64(rb.MrgnSellCloseVa), - LongBuyVa: float64(rb.LongBuyVa), - MrgnBuyNewVa: float64(rb.MrgnBuyNewVa), - MrgnBuyCloseVa: float64(rb.MrgnBuyCloseVa), - LongSellVo: float64(rb.LongSellVo), - ShrtNoMrgnVo: float64(rb.ShrtNoMrgnVo), - MrgnSellNewVo: float64(rb.MrgnSellNewVo), - MrgnSellCloseVo: float64(rb.MrgnSellCloseVo), - LongBuyVo: float64(rb.LongBuyVo), - MrgnBuyNewVo: float64(rb.MrgnBuyNewVo), - MrgnBuyCloseVo: float64(rb.MrgnBuyCloseVo), + LongSellVa: rb.LongSellVa.Or(0), + ShrtNoMrgnVa: rb.ShrtNoMrgnVa.Or(0), + MrgnSellNewVa: rb.MrgnSellNewVa.Or(0), + MrgnSellCloseVa: rb.MrgnSellCloseVa.Or(0), + LongBuyVa: rb.LongBuyVa.Or(0), + MrgnBuyNewVa: rb.MrgnBuyNewVa.Or(0), + MrgnBuyCloseVa: rb.MrgnBuyCloseVa.Or(0), + LongSellVo: rb.LongSellVo.Or(0), + ShrtNoMrgnVo: rb.ShrtNoMrgnVo.Or(0), + MrgnSellNewVo: rb.MrgnSellNewVo.Or(0), + MrgnSellCloseVo: rb.MrgnSellCloseVo.Or(0), + LongBuyVo: rb.LongBuyVo.Or(0), + MrgnBuyNewVo: rb.MrgnBuyNewVo.Or(0), + MrgnBuyCloseVo: rb.MrgnBuyCloseVo.Or(0), } } diff --git a/daily_margin_interest.go b/daily_margin_interest.go index 21d7f5c..39d1837 100644 --- a/daily_margin_interest.go +++ b/daily_margin_interest.go @@ -5,6 +5,7 @@ import ( "fmt" "github.com/utahta/jquants/client" + "github.com/utahta/jquants/types" ) // DailyMarginInterestService は日々公表信用取引残高を取得するサービスです。 @@ -35,11 +36,11 @@ type DailyMarginInterestResponse struct { // PublishReason は公表の理由を表します。 type PublishReason struct { - Restricted string `json:"Restricted"` // 規制措置(0: 対象外, 1: 対象) - DailyPublication string `json:"DailyPublication"` // 日々公表(0: 対象外, 1: 対象) - Monitoring string `json:"Monitoring"` // 監視(0: 対象外, 1: 対象) - RestrictedByJSF string `json:"RestrictedByJSF"` // 日証金の規制(0: 対象外, 1: 対象) - PrecautionByJSF string `json:"PrecautionByJSF"` // 日証金の注意喚起(0: 対象外, 1: 対象) + Restricted string `json:"Restricted"` // 規制措置(0: 対象外, 1: 対象) + DailyPublication string `json:"DailyPublication"` // 日々公表(0: 対象外, 1: 対象) + Monitoring string `json:"Monitoring"` // 監視(0: 対象外, 1: 対象) + RestrictedByJSF string `json:"RestrictedByJSF"` // 日証金の規制(0: 対象外, 1: 対象) + PrecautionByJSF string `json:"PrecautionByJSF"` // 日証金の注意喚起(0: 対象外, 1: 対象) UnclearOrSecOnAlert string `json:"UnclearOrSecOnAlert"` // 不明瞭または証券会社の注意喚起(0: 対象外, 1: 対象) } @@ -53,29 +54,29 @@ type DailyMarginInterest struct { PubReason PublishReason `json:"PubReason"` // 公表の理由 // 売合計信用残高 - ShrtOut float64 `json:"ShrtOut"` // 売合計信用残高(株) - ShrtOutChg interface{} `json:"ShrtOutChg"` // 前日比 売合計信用残高(株)。前日に公表されていない場合は「-」 - ShrtOutRatio interface{} `json:"ShrtOutRatio"` // 上場比 売合計信用残高(%)。ETFの場合は「*」 + ShrtOut float64 `json:"ShrtOut"` // 売合計信用残高(株) + ShrtOutChg types.NullableFloat64 `json:"ShrtOutChg"` // 前日比 売合計信用残高(株)。前日に公表されていない場合は「-」 + ShrtOutRatio types.NullableFloat64 `json:"ShrtOutRatio"` // 上場比 売合計信用残高(%)。ETFの場合は「*」 // 買合計信用残高 - LongOut float64 `json:"LongOut"` // 買合計信用残高(株) - LongOutChg interface{} `json:"LongOutChg"` // 前日比 買合計信用残高(株)。前日に公表されていない場合は「-」 - LongOutRatio interface{} `json:"LongOutRatio"` // 上場比 買合計信用残高(%)。ETFの場合は「*」 + LongOut float64 `json:"LongOut"` // 買合計信用残高(株) + LongOutChg types.NullableFloat64 `json:"LongOutChg"` // 前日比 買合計信用残高(株)。前日に公表されていない場合は「-」 + LongOutRatio types.NullableFloat64 `json:"LongOutRatio"` // 上場比 買合計信用残高(%)。ETFの場合は「*」 // 取組比率 SLRatio float64 `json:"SLRatio"` // 取組比率(%)= 売合計信用残高 / 買合計信用残高 × 100 // 一般信用取引残高 - ShrtNegOut float64 `json:"ShrtNegOut"` // 一般信用取引売残高(株) - ShrtNegOutChg interface{} `json:"ShrtNegOutChg"` // 前日比 一般信用取引売残高(株) - LongNegOut float64 `json:"LongNegOut"` // 一般信用取引買残高(株) - LongNegOutChg interface{} `json:"LongNegOutChg"` // 前日比 一般信用取引買残高(株) + ShrtNegOut float64 `json:"ShrtNegOut"` // 一般信用取引売残高(株) + ShrtNegOutChg types.NullableFloat64 `json:"ShrtNegOutChg"` // 前日比 一般信用取引売残高(株) + LongNegOut float64 `json:"LongNegOut"` // 一般信用取引買残高(株) + LongNegOutChg types.NullableFloat64 `json:"LongNegOutChg"` // 前日比 一般信用取引買残高(株) // 制度信用取引残高 - ShrtStdOut float64 `json:"ShrtStdOut"` // 制度信用取引売残高(株) - ShrtStdOutChg interface{} `json:"ShrtStdOutChg"` // 前日比 制度信用取引売残高(株) - LongStdOut float64 `json:"LongStdOut"` // 制度信用取引買残高(株) - LongStdOutChg interface{} `json:"LongStdOutChg"` // 前日比 制度信用取引買残高(株) + ShrtStdOut float64 `json:"ShrtStdOut"` // 制度信用取引売残高(株) + ShrtStdOutChg types.NullableFloat64 `json:"ShrtStdOutChg"` // 前日比 制度信用取引売残高(株) + LongStdOut float64 `json:"LongStdOut"` // 制度信用取引買残高(株) + LongStdOutChg types.NullableFloat64 `json:"LongStdOutChg"` // 前日比 制度信用取引買残高(株) // 規制区分 TSEMrgnRegCls string `json:"TSEMrgnRegCls"` // 東証信用貸借規制区分 @@ -218,37 +219,25 @@ func (s *DailyMarginInterestService) GetDailyMarginInterestByCodeAndDateRange(ct // GetShortOutChgValue は前日比売合計信用残高を数値で取得します。 // 前日に公表されていない場合(「-」)は0を返します。 func (d *DailyMarginInterest) GetShortOutChgValue() float64 { - if v, ok := d.ShrtOutChg.(float64); ok { - return v - } - return 0 + return d.ShrtOutChg.Or(0) } // GetLongOutChgValue は前日比買合計信用残高を数値で取得します。 // 前日に公表されていない場合(「-」)は0を返します。 func (d *DailyMarginInterest) GetLongOutChgValue() float64 { - if v, ok := d.LongOutChg.(float64); ok { - return v - } - return 0 + return d.LongOutChg.Or(0) } // GetShortOutRatioValue は上場比売合計信用残高を数値で取得します。 // ETFの場合(「*」)は0を返します。 func (d *DailyMarginInterest) GetShortOutRatioValue() float64 { - if v, ok := d.ShrtOutRatio.(float64); ok { - return v - } - return 0 + return d.ShrtOutRatio.Or(0) } // GetLongOutRatioValue は上場比買合計信用残高を数値で取得します。 // ETFの場合(「*」)は0を返します。 func (d *DailyMarginInterest) GetLongOutRatioValue() float64 { - if v, ok := d.LongOutRatio.(float64); ok { - return v - } - return 0 + return d.LongOutRatio.Or(0) } // IsRestricted は規制措置対象かどうかを判定します。 diff --git a/daily_margin_interest_test.go b/daily_margin_interest_test.go index df95921..4519d3a 100644 --- a/daily_margin_interest_test.go +++ b/daily_margin_interest_test.go @@ -2,10 +2,12 @@ package jquants import ( "context" + "encoding/json" "fmt" "testing" "github.com/utahta/jquants/client" + "github.com/utahta/jquants/types" ) func TestDailyMarginInterestService_GetDailyMarginInterest(t *testing.T) { @@ -77,20 +79,20 @@ func TestDailyMarginInterestService_GetDailyMarginInterest(t *testing.T) { UnclearOrSecOnAlert: "0", }, ShrtOut: 11.0, - ShrtOutChg: 0.0, - ShrtOutRatio: "*", + ShrtOutChg: types.NewNullable(0.0), + ShrtOutRatio: types.NullableFloat64{}, // ETFのため該当なし(*) LongOut: 676.0, - LongOutChg: -20.0, - LongOutRatio: "*", + LongOutChg: types.NewNullable(-20.0), + LongOutRatio: types.NullableFloat64{}, // ETFのため該当なし(*) SLRatio: 1.6, ShrtNegOut: 0.0, - ShrtNegOutChg: 0.0, + ShrtNegOutChg: types.NewNullable(0.0), ShrtStdOut: 11.0, - ShrtStdOutChg: 0.0, + ShrtStdOutChg: types.NewNullable(0.0), LongNegOut: 192.0, - LongNegOutChg: -20.0, + LongNegOutChg: types.NewNullable(-20.0), LongStdOut: 484.0, - LongStdOutChg: 0.0, + LongStdOutChg: types.NewNullable(0.0), TSEMrgnRegCls: "001", }, }, @@ -295,16 +297,16 @@ func TestDailyMarginInterestService_GetDailyMarginInterestByCodeAndDateRange(t * func TestDailyMarginInterest_GetOutChgValue(t *testing.T) { tests := []struct { - name string - data DailyMarginInterest - wantShortChg float64 - wantLongChg float64 + name string + data DailyMarginInterest + wantShortChg float64 + wantLongChg float64 }{ { name: "numeric values", data: DailyMarginInterest{ - ShrtOutChg: 100.0, - LongOutChg: -50.0, + ShrtOutChg: types.NewNullable(100.0), + LongOutChg: types.NewNullable(-50.0), }, wantShortChg: 100.0, wantLongChg: -50.0, @@ -312,8 +314,8 @@ func TestDailyMarginInterest_GetOutChgValue(t *testing.T) { { name: "string values (not published)", data: DailyMarginInterest{ - ShrtOutChg: "-", - LongOutChg: "-", + ShrtOutChg: types.NullableFloat64{}, // 前日非公表(-) + LongOutChg: types.NullableFloat64{}, // 前日非公表(-) }, wantShortChg: 0.0, wantLongChg: 0.0, @@ -337,16 +339,16 @@ func TestDailyMarginInterest_GetOutChgValue(t *testing.T) { func TestDailyMarginInterest_GetOutRatioValue(t *testing.T) { tests := []struct { - name string - data DailyMarginInterest - wantShortRatio float64 - wantLongRatio float64 + name string + data DailyMarginInterest + wantShortRatio float64 + wantLongRatio float64 }{ { name: "numeric values", data: DailyMarginInterest{ - ShrtOutRatio: 0.5, - LongOutRatio: 1.2, + ShrtOutRatio: types.NewNullable(0.5), + LongOutRatio: types.NewNullable(1.2), }, wantShortRatio: 0.5, wantLongRatio: 1.2, @@ -354,8 +356,8 @@ func TestDailyMarginInterest_GetOutRatioValue(t *testing.T) { { name: "string values (ETF)", data: DailyMarginInterest{ - ShrtOutRatio: "*", - LongOutRatio: "*", + ShrtOutRatio: types.NullableFloat64{}, // ETFのため該当なし(*) + LongOutRatio: types.NullableFloat64{}, // ETFのため該当なし(*) }, wantShortRatio: 0.0, wantLongRatio: 0.0, @@ -379,13 +381,13 @@ func TestDailyMarginInterest_GetOutRatioValue(t *testing.T) { func TestPublishReason_HelperMethods(t *testing.T) { tests := []struct { - name string - reason PublishReason - isRestricted bool - isDailyPublication bool - isMonitoring bool - isRestrictedByJSF bool - isPrecautionByJSF bool + name string + reason PublishReason + isRestricted bool + isDailyPublication bool + isMonitoring bool + isRestrictedByJSF bool + isPrecautionByJSF bool isUnclearOrSecOnAlert bool }{ { @@ -398,11 +400,11 @@ func TestPublishReason_HelperMethods(t *testing.T) { PrecautionByJSF: "1", UnclearOrSecOnAlert: "0", }, - isRestricted: false, - isDailyPublication: false, - isMonitoring: false, - isRestrictedByJSF: false, - isPrecautionByJSF: true, + isRestricted: false, + isDailyPublication: false, + isMonitoring: false, + isRestrictedByJSF: false, + isPrecautionByJSF: true, isUnclearOrSecOnAlert: false, }, { @@ -415,11 +417,11 @@ func TestPublishReason_HelperMethods(t *testing.T) { PrecautionByJSF: "0", UnclearOrSecOnAlert: "0", }, - isRestricted: true, - isDailyPublication: true, - isMonitoring: false, - isRestrictedByJSF: false, - isPrecautionByJSF: false, + isRestricted: true, + isDailyPublication: true, + isMonitoring: false, + isRestrictedByJSF: false, + isPrecautionByJSF: false, isUnclearOrSecOnAlert: false, }, { @@ -432,11 +434,11 @@ func TestPublishReason_HelperMethods(t *testing.T) { PrecautionByJSF: "1", UnclearOrSecOnAlert: "1", }, - isRestricted: true, - isDailyPublication: true, - isMonitoring: true, - isRestrictedByJSF: true, - isPrecautionByJSF: true, + isRestricted: true, + isDailyPublication: true, + isMonitoring: true, + isRestrictedByJSF: true, + isPrecautionByJSF: true, isUnclearOrSecOnAlert: true, }, } @@ -505,3 +507,47 @@ func TestTSEMarginRegulationConstants(t *testing.T) { }) } } + +func TestDailyMarginInterestResponse_UnmarshalJSON_SpecialValues(t *testing.T) { + // 「-」(前日非公表)と「*」(ETFのため該当なし)がエラーなく値なしとして扱われること + jsonData := `{ + "data": [ + { + "PubDate": "2024-02-08", + "Code": "13260", + "ShrtOut": 1000.0, + "ShrtOutChg": "-", + "ShrtOutRatio": "*", + "LongOut": 2000.0, + "LongOutChg": 150.5, + "LongOutRatio": "*" + } + ], + "pagination_key": "" + }` + + var resp DailyMarginInterestResponse + if err := json.Unmarshal([]byte(jsonData), &resp); err != nil { + t.Fatalf("UnmarshalJSON failed: %v", err) + } + if len(resp.Data) != 1 { + t.Fatalf("data count = %d, want 1", len(resp.Data)) + } + + d := resp.Data[0] + if _, ok := d.ShrtOutChg.Get(); ok { + t.Error("ShrtOutChg should be absent for dash") + } + if _, ok := d.ShrtOutRatio.Get(); ok { + t.Error("ShrtOutRatio should be absent for asterisk") + } + if v, ok := d.LongOutChg.Get(); !ok || v != 150.5 { + t.Errorf("LongOutChg = %v, %v; want 150.5, true", v, ok) + } + if got := d.GetShortOutChgValue(); got != 0 { + t.Errorf("GetShortOutChgValue() = %v, want 0", got) + } + if got := d.GetLongOutChgValue(); got != 150.5 { + t.Errorf("GetLongOutChgValue() = %v, want 150.5", got) + } +} diff --git a/dividend.go b/dividend.go index 2b2daf8..aff43ad 100644 --- a/dividend.go +++ b/dividend.go @@ -2,7 +2,6 @@ package jquants import ( "context" - "encoding/json" "fmt" "github.com/utahta/jquants/client" @@ -45,11 +44,11 @@ type DividendResponse struct { // 注意: このデータはプレミアムプラン専用APIで取得されます。 type Dividend struct { // 基本情報 - PubDate string `json:"PubDate"` // 通知日時(年月日)(YYYY-MM-DD形式) - PubTime string `json:"PubTime"` // 通知日時(時分)(HH:MI形式) - Code string `json:"Code"` // 銘柄コード - RefNo string `json:"RefNo"` // リファレンスナンバー(配当通知を一意に特定するための番号) - CARefNo string `json:"CARefNo"` // CAリファレンスナンバー(訂正・削除の対象となっている配当通知のリファレンスナンバー) + PubDate string `json:"PubDate"` // 通知日時(年月日)(YYYY-MM-DD形式) + PubTime string `json:"PubTime"` // 通知日時(時分)(HH:MI形式) + Code string `json:"Code"` // 銘柄コード + RefNo string `json:"RefNo"` // リファレンスナンバー(配当通知を一意に特定するための番号) + CARefNo string `json:"CARefNo"` // CAリファレンスナンバー(訂正・削除の対象となっている配当通知のリファレンスナンバー) // 更新・配当区分情報 StatCode string `json:"StatCode"` // 更新区分(コード)(1: 新規、2: 訂正、3: 削除) @@ -58,118 +57,25 @@ type Dividend struct { CommSpecCode string `json:"CommSpecCode"` // 記念配当/特別配当コード(0: 通常、1: 記念配当、2: 特別配当、3: 記念・特別配当) // 日程情報 - BoardDate string `json:"BoardDate"` // 取締役会決議日(YYYY-MM-DD形式) - IFTerm string `json:"IFTerm"` // 配当基準日年月(YYYY-MM形式) - RecDate string `json:"RecDate"` // 基準日(YYYY-MM-DD形式) - ExDate string `json:"ExDate"` // 権利落日(YYYY-MM-DD形式) - ActRecDate string `json:"ActRecDate"` // 権利確定日(YYYY-MM-DD形式) - PayDate *string `json:"PayDate"` // 支払開始予定日(YYYY-MM-DD形式、未定の場合: "-"、非設定の場合: 空文字) + // PayDate等のNullable型フィールドは、未定(-)をIsUndetermined()で判別できます。 + BoardDate string `json:"BoardDate"` // 取締役会決議日(YYYY-MM-DD形式) + IFTerm string `json:"IFTerm"` // 配当基準日年月(YYYY-MM形式) + RecDate string `json:"RecDate"` // 基準日(YYYY-MM-DD形式) + ExDate string `json:"ExDate"` // 権利落日(YYYY-MM-DD形式) + ActRecDate string `json:"ActRecDate"` // 権利確定日(YYYY-MM-DD形式) + PayDate types.NullableString `json:"PayDate"` // 支払開始予定日(YYYY-MM-DD形式) // 配当金額情報 - DivRate *float64 `json:"DivRate"` // 1株当たり配当金額(未定の場合: "-"、非設定の場合: 空文字) - CommDivRate *float64 `json:"CommDivRate"` // 1株当たり記念配当金額(2022年6月6日以降のみ、未定の場合: "-"、非設定の場合: 空文字) - SpecDivRate *float64 `json:"SpecDivRate"` // 1株当たり特別配当金額(2022年6月6日以降のみ、未定の場合: "-"、非設定の場合: 空文字) + DivRate types.NullableFloat64 `json:"DivRate"` // 1株当たり配当金額 + CommDivRate types.NullableFloat64 `json:"CommDivRate"` // 1株当たり記念配当金額(2022年6月6日以降のみ) + SpecDivRate types.NullableFloat64 `json:"SpecDivRate"` // 1株当たり特別配当金額(2022年6月6日以降のみ) // 税務関連情報(2014年2月24日以降のみ提供) - DistAmt *float64 `json:"DistAmt"` // 1株当たりの交付金銭等の額(未定の場合: "-"、非設定の場合: 空文字) - RetEarn *float64 `json:"RetEarn"` // 1株当たりの利益剰余金の額(未定の場合: "-"、非設定の場合: 空文字) - DeemDiv *float64 `json:"DeemDiv"` // 1株当たりのみなし配当の額(未定の場合: "-"、非設定の場合: 空文字) - DeemCapGains *float64 `json:"DeemCapGains"` // 1株当たりのみなし譲渡収入の額(未定の場合: "-"、非設定の場合: 空文字) - NetAssetDecRatio *float64 `json:"NetAssetDecRatio"` // 純資産減少割合(未定の場合: "-"、非設定の場合: 空文字) -} - -// RawDividend is used for unmarshaling JSON response with mixed types -type RawDividend struct { - // 基本情報 - PubDate string `json:"PubDate"` - PubTime string `json:"PubTime"` - Code string `json:"Code"` - RefNo string `json:"RefNo"` - CARefNo string `json:"CARefNo"` - - // 更新・配当区分情報 - StatCode string `json:"StatCode"` - IFCode string `json:"IFCode"` - FRCode string `json:"FRCode"` - CommSpecCode string `json:"CommSpecCode"` - - // 日程情報 - BoardDate string `json:"BoardDate"` - IFTerm string `json:"IFTerm"` - RecDate string `json:"RecDate"` - ExDate string `json:"ExDate"` - ActRecDate string `json:"ActRecDate"` - PayDate types.StringWithDash `json:"PayDate"` - - // 配当金額情報 - DivRate types.Float64StringWithDash `json:"DivRate"` - CommDivRate types.Float64StringWithDash `json:"CommDivRate"` - SpecDivRate types.Float64StringWithDash `json:"SpecDivRate"` - - // 税務関連情報 - DistAmt types.Float64StringWithDash `json:"DistAmt"` - RetEarn types.Float64StringWithDash `json:"RetEarn"` - DeemDiv types.Float64StringWithDash `json:"DeemDiv"` - DeemCapGains types.Float64StringWithDash `json:"DeemCapGains"` - NetAssetDecRatio types.Float64StringWithDash `json:"NetAssetDecRatio"` -} - -// UnmarshalJSON implements custom JSON unmarshaling for DividendResponse -func (r *DividendResponse) UnmarshalJSON(data []byte) error { - // First unmarshal into RawDividend - type rawResponse struct { - Data []RawDividend `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 RawDividend to Dividend - r.Data = make([]Dividend, len(raw.Data)) - for idx, rd := range raw.Data { - r.Data[idx] = Dividend{ - // 基本情報 - PubDate: rd.PubDate, - PubTime: rd.PubTime, - Code: rd.Code, - RefNo: rd.RefNo, - CARefNo: rd.CARefNo, - - // 更新・配当区分情報 - StatCode: rd.StatCode, - IFCode: rd.IFCode, - FRCode: rd.FRCode, - CommSpecCode: rd.CommSpecCode, - - // 日程情報 - BoardDate: rd.BoardDate, - IFTerm: rd.IFTerm, - RecDate: rd.RecDate, - ExDate: rd.ExDate, - ActRecDate: rd.ActRecDate, - PayDate: rd.PayDate.ToStringPtr(), - - // 配当金額情報 - DivRate: rd.DivRate.ToFloat64Ptr(), - CommDivRate: rd.CommDivRate.ToFloat64Ptr(), - SpecDivRate: rd.SpecDivRate.ToFloat64Ptr(), - - // 税務関連情報 - DistAmt: rd.DistAmt.ToFloat64Ptr(), - RetEarn: rd.RetEarn.ToFloat64Ptr(), - DeemDiv: rd.DeemDiv.ToFloat64Ptr(), - DeemCapGains: rd.DeemCapGains.ToFloat64Ptr(), - NetAssetDecRatio: rd.NetAssetDecRatio.ToFloat64Ptr(), - } - } - - return nil + DistAmt types.NullableFloat64 `json:"DistAmt"` // 1株当たりの交付金銭等の額 + RetEarn types.NullableFloat64 `json:"RetEarn"` // 1株当たりの利益剰余金の額 + DeemDiv types.NullableFloat64 `json:"DeemDiv"` // 1株当たりのみなし配当の額 + DeemCapGains types.NullableFloat64 `json:"DeemCapGains"` // 1株当たりのみなし譲渡収入の額 + NetAssetDecRatio types.NullableFloat64 `json:"NetAssetDecRatio"` // 純資産減少割合 } // GetDividend は配当情報を取得します。 @@ -359,53 +265,39 @@ func (d *Dividend) IsOrdinary() bool { // GetTotalDividendRate は配当金額の合計を計算します(通常+記念+特別)。 func (d *Dividend) GetTotalDividendRate() *float64 { - if d.DivRate == nil { + rate, ok := d.DivRate.Get() + if !ok { return nil } - total := *d.DivRate - - if d.CommDivRate != nil { - total += *d.CommDivRate - } - - if d.SpecDivRate != nil { - total += *d.SpecDivRate - } - + total := rate + d.CommDivRate.Or(0) + d.SpecDivRate.Or(0) return &total } // GetOrdinaryDividendRate は通常配当金額を計算します(総額から記念・特別を除く)。 func (d *Dividend) GetOrdinaryDividendRate() *float64 { - if d.DivRate == nil { + rate, ok := d.DivRate.Get() + if !ok { return nil } - ordinary := *d.DivRate - - if d.CommDivRate != nil { - ordinary -= *d.CommDivRate - } - - if d.SpecDivRate != nil { - ordinary -= *d.SpecDivRate - } - + ordinary := rate - d.CommDivRate.Or(0) - d.SpecDivRate.Or(0) return &ordinary } // HasPayableDate は支払開始予定日が設定されているかを判定します。 func (d *Dividend) HasPayableDate() bool { - return d.PayDate != nil && *d.PayDate != "-" && *d.PayDate != "" + _, ok := d.PayDate.Get() + return ok } -// IsPayableDateUndecided は支払開始予定日が未定かを判定します。 +// IsPayableDateUndecided は支払開始予定日が未定(-)かを判定します。 func (d *Dividend) IsPayableDateUndecided() bool { - return d.PayDate != nil && *d.PayDate == "-" + return d.PayDate.IsUndetermined() } -// IsDividendRateUndecided は配当金額が未定かを判定します。 +// IsDividendRateUndecided は配当金額が未定(-)かを判定します。 +// 非設定(空文字)の場合はfalseを返します。 func (d *Dividend) IsDividendRateUndecided() bool { - return d.DivRate == nil + return d.DivRate.IsUndetermined() } diff --git a/dividend_test.go b/dividend_test.go new file mode 100644 index 0000000..5fe359f --- /dev/null +++ b/dividend_test.go @@ -0,0 +1,91 @@ +package jquants + +import ( + "encoding/json" + "testing" + + "github.com/utahta/jquants/types" +) + +func TestDividendResponse_UnmarshalJSON_MissingValueVariants(t *testing.T) { + // 値あり・未定(-)・非設定(空文字)が区別して取得できること + jsonData := `{ + "data": [ + { + "Code": "72030", + "StatCode": "1", + "DivRate": "25.5", + "CommDivRate": "", + "SpecDivRate": "-", + "PayDate": "2024-03-25" + }, + { + "Code": "99840", + "StatCode": "1", + "DivRate": "-", + "CommDivRate": "", + "SpecDivRate": "", + "PayDate": "-" + } + ], + "pagination_key": "" + }` + + var resp DividendResponse + 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)) + } + + // 1件目: 配当額あり、記念配当は非設定、特別配当は未定、支払日あり + d := resp.Data[0] + if v, ok := d.DivRate.Get(); !ok || v != 25.5 { + t.Errorf("DivRate = %v, %v; want 25.5, true", v, ok) + } + if _, ok := d.CommDivRate.Get(); ok || d.CommDivRate.IsUndetermined() { + t.Error("CommDivRate should be absent and not undetermined for empty string") + } + if _, ok := d.SpecDivRate.Get(); ok || !d.SpecDivRate.IsUndetermined() { + t.Error("SpecDivRate should be absent and undetermined for dash") + } + if !d.HasPayableDate() || d.IsPayableDateUndecided() { + t.Errorf("PayDate = %v; want present and decided", d.PayDate) + } + if d.IsDividendRateUndecided() { + t.Error("IsDividendRateUndecided() should be false when DivRate has a value") + } + + // 2件目: 配当額・支払日ともに未定 + d = resp.Data[1] + if !d.IsDividendRateUndecided() { + t.Error("IsDividendRateUndecided() should be true for dash") + } + if !d.IsPayableDateUndecided() || d.HasPayableDate() { + t.Error("PayDate should be undecided for dash") + } + if got := d.GetTotalDividendRate(); got != nil { + t.Errorf("GetTotalDividendRate() = %v, want nil when DivRate is undecided", *got) + } +} + +func TestDividend_GetTotalDividendRate(t *testing.T) { + d := Dividend{ + DivRate: types.NewNullable(30.0), + CommDivRate: types.NewNullable(5.0), + SpecDivRate: types.NewNullable(10.0), + } + if got := d.GetTotalDividendRate(); got == nil || *got != 45.0 { + t.Errorf("GetTotalDividendRate() = %v, want 45.0", got) + } + if got := d.GetOrdinaryDividendRate(); got == nil || *got != 15.0 { + t.Errorf("GetOrdinaryDividendRate() = %v, want 15.0", got) + } + + // 記念・特別が非設定でも合計は計算できる + d2 := Dividend{DivRate: types.NewNullable(30.0)} + if got := d2.GetTotalDividendRate(); got == nil || *got != 30.0 { + t.Errorf("GetTotalDividendRate() = %v, want 30.0", got) + } +} diff --git a/futures.go b/futures.go index 6ed067c..e03d99c 100644 --- a/futures.go +++ b/futures.go @@ -4,9 +4,9 @@ import ( "context" "encoding/json" "fmt" - "strconv" "github.com/utahta/jquants/client" + "github.com/utahta/jquants/types" ) // FuturesService は先物四本値データを取得するサービスです。 @@ -55,11 +55,11 @@ type Futures struct { L float64 `json:"L"` // 日通し安値 C float64 `json:"C"` // 日通し終値 - // ナイト・セッション四本値(取引開始日初日は空文字) - EO interface{} `json:"EO"` // ナイト・セッション始値 - EH interface{} `json:"EH"` // ナイト・セッション高値 - EL interface{} `json:"EL"` // ナイト・セッション安値 - EC interface{} `json:"EC"` // ナイト・セッション終値 + // ナイト・セッション四本値(取引開始日初日は値なし) + EO *float64 `json:"EO"` // ナイト・セッション始値 + EH *float64 `json:"EH"` // ナイト・セッション高値 + EL *float64 `json:"EL"` // ナイト・セッション安値 + EC *float64 `json:"EC"` // ナイト・セッション終値 // 日中セッション四本値 AO float64 `json:"AO"` // 日中始値 @@ -67,11 +67,11 @@ type Futures struct { AL float64 `json:"AL"` // 日中安値 AC float64 `json:"AC"` // 日中終値 - // 前場四本値(前後場取引対象銘柄でない場合、空文字) - MO interface{} `json:"MO"` // 前場始値 - MH interface{} `json:"MH"` // 前場高値 - ML interface{} `json:"ML"` // 前場安値 - MC interface{} `json:"MC"` // 前場終値 + // 前場四本値(前後場取引対象銘柄でない場合、値なし) + MO *float64 `json:"MO"` // 前場始値 + MH *float64 `json:"MH"` // 前場高値 + ML *float64 `json:"ML"` // 前場安値 + MC *float64 `json:"MC"` // 前場終値 // 取引情報 Vo float64 `json:"Vo"` // 取引高 @@ -88,35 +88,35 @@ type Futures struct { // RawFutures is used for unmarshaling JSON response with mixed types type RawFutures struct { - Code string `json:"Code"` - ProdCat string `json:"ProdCat"` - Date string `json:"Date"` - CM string `json:"CM"` - EmMrgnTrgDiv string `json:"EmMrgnTrgDiv"` - O float64 `json:"O"` - H float64 `json:"H"` - L float64 `json:"L"` - C float64 `json:"C"` - EO interface{} `json:"EO"` - EH interface{} `json:"EH"` - EL interface{} `json:"EL"` - EC interface{} `json:"EC"` - AO float64 `json:"AO"` - AH float64 `json:"AH"` - AL float64 `json:"AL"` - AC float64 `json:"AC"` - MO interface{} `json:"MO"` - MH interface{} `json:"MH"` - ML interface{} `json:"ML"` - MC interface{} `json:"MC"` - Vo float64 `json:"Vo"` - OI float64 `json:"OI"` - Va float64 `json:"Va"` - VoOA interface{} `json:"VoOA"` - Settle interface{} `json:"Settle"` - LTD interface{} `json:"LTD"` - SQD interface{} `json:"SQD"` - CCMFlag interface{} `json:"CCMFlag"` + Code string `json:"Code"` + ProdCat string `json:"ProdCat"` + Date string `json:"Date"` + CM string `json:"CM"` + EmMrgnTrgDiv string `json:"EmMrgnTrgDiv"` + O float64 `json:"O"` + H float64 `json:"H"` + L float64 `json:"L"` + C float64 `json:"C"` + EO types.NullableFloat64 `json:"EO"` + EH types.NullableFloat64 `json:"EH"` + EL types.NullableFloat64 `json:"EL"` + EC types.NullableFloat64 `json:"EC"` + AO float64 `json:"AO"` + AH float64 `json:"AH"` + AL float64 `json:"AL"` + AC float64 `json:"AC"` + MO types.NullableFloat64 `json:"MO"` + MH types.NullableFloat64 `json:"MH"` + ML types.NullableFloat64 `json:"ML"` + MC types.NullableFloat64 `json:"MC"` + Vo float64 `json:"Vo"` + OI float64 `json:"OI"` + Va float64 `json:"Va"` + VoOA types.NullableFloat64 `json:"VoOA"` + Settle types.NullableFloat64 `json:"Settle"` + LTD types.NullableString `json:"LTD"` + SQD types.NullableString `json:"SQD"` + CCMFlag types.NullableString `json:"CCMFlag"` } // UnmarshalJSON implements custom JSON unmarshaling for FuturesResponse @@ -148,39 +148,29 @@ func (r *FuturesResponse) UnmarshalJSON(data []byte) error { H: rf.H, L: rf.L, C: rf.C, - EO: rf.EO, - EH: rf.EH, - EL: rf.EL, - EC: rf.EC, + EO: rf.EO.Ptr(), + EH: rf.EH.Ptr(), + EL: rf.EL.Ptr(), + EC: rf.EC.Ptr(), AO: rf.AO, AH: rf.AH, AL: rf.AL, AC: rf.AC, - MO: rf.MO, - MH: rf.MH, - ML: rf.ML, - MC: rf.MC, + MO: rf.MO.Ptr(), + MH: rf.MH.Ptr(), + ML: rf.ML.Ptr(), + MC: rf.MC.Ptr(), Vo: rf.Vo, OI: rf.OI, Va: rf.Va, } // Convert optional fields - if v, ok := parseOptionalFloat(rf.VoOA); ok { - f.VoOA = &v - } - if v, ok := parseOptionalFloat(rf.Settle); ok { - f.Settle = &v - } - if v, ok := parseOptionalString(rf.LTD); ok { - f.LTD = &v - } - if v, ok := parseOptionalString(rf.SQD); ok { - f.SQD = &v - } - if v, ok := parseOptionalString(rf.CCMFlag); ok { - f.CCMFlag = &v - } + f.VoOA = rf.VoOA.Ptr() + f.Settle = rf.Settle.Ptr() + f.LTD = rf.LTD.Ptr() + f.SQD = rf.SQD.Ptr() + f.CCMFlag = rf.CCMFlag.Ptr() r.Data[idx] = f } @@ -329,60 +319,52 @@ func (f *Futures) IsCentralContractMonth() bool { // HasNightSession はナイトセッションデータがあるかを判定します。 func (f *Futures) HasNightSession() bool { - // interface{}型のフィールドが空文字列でないかチェック - if str, ok := f.EO.(string); ok && str == "" { - return false - } - return true + return f.EO != nil } // HasMorningSession は前場データがあるかを判定します。 func (f *Futures) HasMorningSession() bool { - // interface{}型のフィールドが空文字列でないかチェック - if str, ok := f.MO.(string); ok && str == "" { - return false - } - return true + return f.MO != nil } // GetNightSessionOpen はナイトセッション始値を取得します。 func (f *Futures) GetNightSessionOpen() *float64 { - return parseInterfaceToFloat64(f.EO) + return f.EO } // GetNightSessionHigh はナイトセッション高値を取得します。 func (f *Futures) GetNightSessionHigh() *float64 { - return parseInterfaceToFloat64(f.EH) + return f.EH } // GetNightSessionLow はナイトセッション安値を取得します。 func (f *Futures) GetNightSessionLow() *float64 { - return parseInterfaceToFloat64(f.EL) + return f.EL } // GetNightSessionClose はナイトセッション終値を取得します。 func (f *Futures) GetNightSessionClose() *float64 { - return parseInterfaceToFloat64(f.EC) + return f.EC } // GetMorningSessionOpen は前場始値を取得します。 func (f *Futures) GetMorningSessionOpen() *float64 { - return parseInterfaceToFloat64(f.MO) + return f.MO } // GetMorningSessionHigh は前場高値を取得します。 func (f *Futures) GetMorningSessionHigh() *float64 { - return parseInterfaceToFloat64(f.MH) + return f.MH } // GetMorningSessionLow は前場安値を取得します。 func (f *Futures) GetMorningSessionLow() *float64 { - return parseInterfaceToFloat64(f.ML) + return f.ML } // GetMorningSessionClose は前場終値を取得します。 func (f *Futures) GetMorningSessionClose() *float64 { - return parseInterfaceToFloat64(f.MC) + return f.MC } // GetDayNightGap は日中始値とナイト終値のギャップを計算します。 @@ -399,47 +381,3 @@ func (f *Futures) GetDayNightGap() *float64 { func (f *Futures) GetWholeDayRange() float64 { return f.H - f.L } - -// Helper functions - -func parseInterfaceToFloat64(v interface{}) *float64 { - switch val := v.(type) { - case float64: - return &val - case int: - f := float64(val) - return &f - case string: - if val == "" { - return nil - } - if f, err := strconv.ParseFloat(val, 64); err == nil { - return &f - } - } - return nil -} - -func parseOptionalFloat(v interface{}) (float64, bool) { - switch val := v.(type) { - case float64: - return val, true - case int: - return float64(val), true - case string: - if val == "" { - return 0, false - } - if f, err := strconv.ParseFloat(val, 64); err == nil { - return f, true - } - } - return 0, false -} - -func parseOptionalString(v interface{}) (string, bool) { - if str, ok := v.(string); ok && str != "" { - return str, true - } - return "", false -} diff --git a/futures_test.go b/futures_test.go index 5f1ab54..8030f55 100644 --- a/futures_test.go +++ b/futures_test.go @@ -75,18 +75,18 @@ func TestFuturesService_GetFutures(t *testing.T) { H: 2853.0, L: 2825.5, C: 2829.0, - EO: 2825.5, - EH: 2850.0, - EL: 2825.5, - EC: 2845.0, + EO: floatPtr(2825.5), + EH: floatPtr(2850.0), + EL: floatPtr(2825.5), + EC: floatPtr(2845.0), AO: 2850.5, AH: 2853.0, AL: 2826.0, AC: 2829.0, - MO: "", - MH: "", - ML: "", - MC: "", + MO: nil, + MH: nil, + ML: nil, + MC: nil, Vo: 42910.0, OI: 479812.0, Va: 1217918971856.0, @@ -307,16 +307,17 @@ func TestFutures_HelperMethods(t *testing.T) { }, isEmergencyMarginTriggered: true, isCentralContractMonth: false, - hasNightSession: true, - hasMorningSession: true, + // セッションデータ未設定(nil)はデータなしと判定される + hasNightSession: false, + hasMorningSession: false, }, { name: "normal settlement price", futures: Futures{ EmMrgnTrgDiv: "002", CCMFlag: stringPtr("1"), - EO: 2825.5, - MO: "", + EO: floatPtr(2825.5), + MO: nil, }, isEmergencyMarginTriggered: false, isCentralContractMonth: true, @@ -328,8 +329,8 @@ func TestFutures_HelperMethods(t *testing.T) { futures: Futures{ EmMrgnTrgDiv: "002", CCMFlag: stringPtr("0"), - EO: "", - MO: 2500.0, + EO: nil, + MO: floatPtr(2500.0), }, isEmergencyMarginTriggered: false, isCentralContractMonth: false, @@ -359,14 +360,14 @@ func TestFutures_HelperMethods(t *testing.T) { func TestFutures_SessionGetters(t *testing.T) { // Setup futures := Futures{ - EO: 2825.5, - EH: 2850.0, - EL: 2825.5, - EC: 2845.0, - MO: "", - MH: "", - ML: "", - MC: "", + EO: floatPtr(2825.5), + EH: floatPtr(2850.0), + EL: floatPtr(2825.5), + EC: floatPtr(2845.0), + MO: nil, + MH: nil, + ML: nil, + MC: nil, } // Test night session getters @@ -407,7 +408,7 @@ func TestFutures_GetDayNightGap(t *testing.T) { { name: "positive gap", futures: Futures{ - EC: 2845.0, + EC: floatPtr(2845.0), AO: 2850.5, }, want: floatPtr(5.5), @@ -415,7 +416,7 @@ func TestFutures_GetDayNightGap(t *testing.T) { { name: "negative gap", futures: Futures{ - EC: 2850.0, + EC: floatPtr(2850.0), AO: 2845.0, }, want: floatPtr(-5.0), @@ -423,7 +424,7 @@ func TestFutures_GetDayNightGap(t *testing.T) { { name: "no night session", futures: Futures{ - EC: "", + EC: nil, AO: 2850.5, }, want: nil, diff --git a/index_option.go b/index_option.go index 42b2583..89362bb 100644 --- a/index_option.go +++ b/index_option.go @@ -4,7 +4,6 @@ import ( "context" "encoding/json" "fmt" - "strconv" "github.com/utahta/jquants/client" "github.com/utahta/jquants/types" @@ -69,46 +68,46 @@ type IndexOption struct { // RawIndexOption is used for unmarshaling JSON response with mixed types type RawIndexOption struct { // 基本情報 - Date string `json:"Date"` - Code string `json:"Code"` - CM string `json:"CM"` - Strike types.Float64String `json:"Strike"` - PCDiv string `json:"PCDiv"` - LTD string `json:"LTD"` - SQD string `json:"SQD"` - EmMrgnTrgDiv string `json:"EmMrgnTrgDiv"` + Date string `json:"Date"` + Code string `json:"Code"` + CM string `json:"CM"` + Strike types.NullableFloat64 `json:"Strike"` + PCDiv string `json:"PCDiv"` + LTD string `json:"LTD"` + SQD string `json:"SQD"` + EmMrgnTrgDiv string `json:"EmMrgnTrgDiv"` // 日通し四本値 - O types.Float64String `json:"O"` - H types.Float64String `json:"H"` - L types.Float64String `json:"L"` - C types.Float64String `json:"C"` + O types.NullableFloat64 `json:"O"` + H types.NullableFloat64 `json:"H"` + L types.NullableFloat64 `json:"L"` + C types.NullableFloat64 `json:"C"` // ナイトセッション四本値(空文字の可能性があるためinterface{}型として受け取る) - EO interface{} `json:"EO"` - EH interface{} `json:"EH"` - EL interface{} `json:"EL"` - EC interface{} `json:"EC"` + EO types.NullableFloat64 `json:"EO"` + EH types.NullableFloat64 `json:"EH"` + EL types.NullableFloat64 `json:"EL"` + EC types.NullableFloat64 `json:"EC"` // 日中セッション四本値 - AO types.Float64String `json:"AO"` - AH types.Float64String `json:"AH"` - AL types.Float64String `json:"AL"` - AC types.Float64String `json:"AC"` + AO types.NullableFloat64 `json:"AO"` + AH types.NullableFloat64 `json:"AH"` + AL types.NullableFloat64 `json:"AL"` + AC types.NullableFloat64 `json:"AC"` // 取引情報 - Vo types.Float64String `json:"Vo"` - VoOA interface{} `json:"VoOA"` - OI types.Float64String `json:"OI"` - Va types.Float64String `json:"Va"` + Vo types.NullableFloat64 `json:"Vo"` + VoOA types.NullableFloat64 `json:"VoOA"` + OI types.NullableFloat64 `json:"OI"` + Va types.NullableFloat64 `json:"Va"` // 価格・リスク情報 - Settle interface{} `json:"Settle"` - Theo interface{} `json:"Theo"` - BaseVol interface{} `json:"BaseVol"` - UnderPx interface{} `json:"UnderPx"` - IV interface{} `json:"IV"` - IR interface{} `json:"IR"` + Settle types.NullableFloat64 `json:"Settle"` + Theo types.NullableFloat64 `json:"Theo"` + BaseVol types.NullableFloat64 `json:"BaseVol"` + UnderPx types.NullableFloat64 `json:"UnderPx"` + IV types.NullableFloat64 `json:"IV"` + IR types.NullableFloat64 `json:"IR"` } // IndexOptionResponse は日経225オプションのレスポンスです。 @@ -159,69 +158,49 @@ func (r *IndexOptionResponse) UnmarshalJSON(data []byte) error { Date: ro.Date, Code: ro.Code, CM: ro.CM, - Strike: float64(ro.Strike), + Strike: ro.Strike.Or(0), PCDiv: ro.PCDiv, LTD: ro.LTD, SQD: ro.SQD, EmMrgnTrgDiv: ro.EmMrgnTrgDiv, // 日通し四本値 - O: float64(ro.O), - H: float64(ro.H), - L: float64(ro.L), - C: float64(ro.C), + O: ro.O.Or(0), + H: ro.H.Or(0), + L: ro.L.Or(0), + C: ro.C.Or(0), // ナイトセッション四本値(空文字の場合はnil) - EO: parseNullableFloat64(ro.EO), - EH: parseNullableFloat64(ro.EH), - EL: parseNullableFloat64(ro.EL), - EC: parseNullableFloat64(ro.EC), + EO: ro.EO.Ptr(), + EH: ro.EH.Ptr(), + EL: ro.EL.Ptr(), + EC: ro.EC.Ptr(), // 日中セッション四本値 - AO: float64(ro.AO), - AH: float64(ro.AH), - AL: float64(ro.AL), - AC: float64(ro.AC), + AO: ro.AO.Or(0), + AH: ro.AH.Or(0), + AL: ro.AL.Or(0), + AC: ro.AC.Or(0), // 取引情報 - Vo: float64(ro.Vo), - VoOA: parseNullableFloat64(ro.VoOA), - OI: float64(ro.OI), - Va: float64(ro.Va), + Vo: ro.Vo.Or(0), + VoOA: ro.VoOA.Ptr(), + OI: ro.OI.Or(0), + Va: ro.Va.Or(0), // 価格・リスク情報 - Settle: parseNullableFloat64(ro.Settle), - Theo: parseNullableFloat64(ro.Theo), - BaseVol: parseNullableFloat64(ro.BaseVol), - UnderPx: parseNullableFloat64(ro.UnderPx), - IV: parseNullableFloat64(ro.IV), - IR: parseNullableFloat64(ro.IR), + Settle: ro.Settle.Ptr(), + Theo: ro.Theo.Ptr(), + BaseVol: ro.BaseVol.Ptr(), + UnderPx: ro.UnderPx.Ptr(), + IV: ro.IV.Ptr(), + IR: ro.IR.Ptr(), } } return nil } -// parseNullableFloat64 converts interface{} to *float64, handling empty strings and nil -func parseNullableFloat64(v interface{}) *float64 { - switch val := v.(type) { - case float64: - return &val - case string: - if val == "" { - return nil - } - // Try to convert string to float64 using strconv.ParseFloat - f, err := strconv.ParseFloat(val, 64) - if err != nil { - return nil - } - return &f - default: - return nil - } -} - // GetIndexOptions は指定日の日経225オプションデータを取得します。 func (s *IndexOptionService) GetIndexOptions(ctx context.Context, params IndexOptionParams) (*IndexOptionResponse, error) { if params.Date == "" { diff --git a/indices.go b/indices.go index 88549d2..68cbfab 100644 --- a/indices.go +++ b/indices.go @@ -33,12 +33,12 @@ type Index struct { // RawIndex is used for unmarshaling JSON response with mixed types type RawIndex struct { - Date string `json:"Date"` - Code string `json:"Code"` - O *types.Float64String `json:"O"` - H *types.Float64String `json:"H"` - L *types.Float64String `json:"L"` - C types.Float64String `json:"C"` + Date string `json:"Date"` + Code string `json:"Code"` + O types.NullableFloat64 `json:"O"` + H types.NullableFloat64 `json:"H"` + L types.NullableFloat64 `json:"L"` + C types.NullableFloat64 `json:"C"` } // IndicesResponse は指数四本値のレスポンスです。 @@ -69,10 +69,10 @@ func (i *IndicesResponse) UnmarshalJSON(data []byte) error { i.Data[idx] = Index{ Date: ri.Date, Code: ri.Code, - O: types.ToFloat64Ptr(ri.O), - H: types.ToFloat64Ptr(ri.H), - L: types.ToFloat64Ptr(ri.L), - C: float64(ri.C), + O: ri.O.Ptr(), + H: ri.H.Ptr(), + L: ri.L.Ptr(), + C: ri.C.Or(0), } } diff --git a/options.go b/options.go index 106c706..4ab6198 100644 --- a/options.go +++ b/options.go @@ -4,9 +4,9 @@ import ( "context" "encoding/json" "fmt" - "strconv" "github.com/utahta/jquants/client" + "github.com/utahta/jquants/types" ) // OptionsService はオプション四本値データを取得するサービスです。 @@ -59,11 +59,11 @@ type Option struct { L float64 `json:"L"` // 日通し安値 C float64 `json:"C"` // 日通し終値 - // ナイト・セッション四本値(取引開始日初日は空文字) - EO interface{} `json:"EO"` // ナイト・セッション始値 - EH interface{} `json:"EH"` // ナイト・セッション高値 - EL interface{} `json:"EL"` // ナイト・セッション安値 - EC interface{} `json:"EC"` // ナイト・セッション終値 + // ナイト・セッション四本値(取引開始日初日は値なし) + EO *float64 `json:"EO"` // ナイト・セッション始値 + EH *float64 `json:"EH"` // ナイト・セッション高値 + EL *float64 `json:"EL"` // ナイト・セッション安値 + EC *float64 `json:"EC"` // ナイト・セッション終値 // 日中セッション四本値 AO float64 `json:"AO"` // 日中始値 @@ -72,10 +72,10 @@ type Option struct { AC float64 `json:"AC"` // 日中終値 // 前場四本値(前後場取引対象銘柄でない場合、空文字) - MO interface{} `json:"MO"` // 前場始値 - MH interface{} `json:"MH"` // 前場高値 - ML interface{} `json:"ML"` // 前場安値 - MC interface{} `json:"MC"` // 前場終値 + MO *float64 `json:"MO"` // 前場始値 + MH *float64 `json:"MH"` // 前場高値 + ML *float64 `json:"ML"` // 前場安値 + MC *float64 `json:"MC"` // 前場終値 // 取引情報 Vo float64 `json:"Vo"` // 取引高 @@ -97,43 +97,43 @@ type Option struct { // RawOption is used for unmarshaling JSON response with mixed types type RawOption struct { - Code string `json:"Code"` - ProdCat string `json:"ProdCat"` - UndSSO string `json:"UndSSO"` - Date string `json:"Date"` - CM string `json:"CM"` - Strike float64 `json:"Strike"` - PCDiv string `json:"PCDiv"` - EmMrgnTrgDiv string `json:"EmMrgnTrgDiv"` - O float64 `json:"O"` - H float64 `json:"H"` - L float64 `json:"L"` - C float64 `json:"C"` - EO interface{} `json:"EO"` - EH interface{} `json:"EH"` - EL interface{} `json:"EL"` - EC interface{} `json:"EC"` - AO float64 `json:"AO"` - AH float64 `json:"AH"` - AL float64 `json:"AL"` - AC float64 `json:"AC"` - MO interface{} `json:"MO"` - MH interface{} `json:"MH"` - ML interface{} `json:"ML"` - MC interface{} `json:"MC"` - Vo float64 `json:"Vo"` - OI float64 `json:"OI"` - Va float64 `json:"Va"` - VoOA interface{} `json:"VoOA"` - Settle interface{} `json:"Settle"` - Theo interface{} `json:"Theo"` - BaseVol interface{} `json:"BaseVol"` - UnderPx interface{} `json:"UnderPx"` - IV interface{} `json:"IV"` - IR interface{} `json:"IR"` - LTD interface{} `json:"LTD"` - SQD interface{} `json:"SQD"` - CCMFlag interface{} `json:"CCMFlag"` + Code string `json:"Code"` + ProdCat string `json:"ProdCat"` + UndSSO string `json:"UndSSO"` + Date string `json:"Date"` + CM string `json:"CM"` + Strike float64 `json:"Strike"` + PCDiv string `json:"PCDiv"` + EmMrgnTrgDiv string `json:"EmMrgnTrgDiv"` + O float64 `json:"O"` + H float64 `json:"H"` + L float64 `json:"L"` + C float64 `json:"C"` + EO types.NullableFloat64 `json:"EO"` + EH types.NullableFloat64 `json:"EH"` + EL types.NullableFloat64 `json:"EL"` + EC types.NullableFloat64 `json:"EC"` + AO float64 `json:"AO"` + AH float64 `json:"AH"` + AL float64 `json:"AL"` + AC float64 `json:"AC"` + MO types.NullableFloat64 `json:"MO"` + MH types.NullableFloat64 `json:"MH"` + ML types.NullableFloat64 `json:"ML"` + MC types.NullableFloat64 `json:"MC"` + Vo float64 `json:"Vo"` + OI float64 `json:"OI"` + Va float64 `json:"Va"` + VoOA types.NullableFloat64 `json:"VoOA"` + Settle types.NullableFloat64 `json:"Settle"` + Theo types.NullableFloat64 `json:"Theo"` + BaseVol types.NullableFloat64 `json:"BaseVol"` + UnderPx types.NullableFloat64 `json:"UnderPx"` + IV types.NullableFloat64 `json:"IV"` + IR types.NullableFloat64 `json:"IR"` + LTD types.NullableString `json:"LTD"` + SQD types.NullableString `json:"SQD"` + CCMFlag types.NullableString `json:"CCMFlag"` } // UnmarshalJSON implements custom JSON unmarshaling for OptionsResponse @@ -168,54 +168,34 @@ func (r *OptionsResponse) UnmarshalJSON(data []byte) error { H: ro.H, L: ro.L, C: ro.C, - EO: ro.EO, - EH: ro.EH, - EL: ro.EL, - EC: ro.EC, + EO: ro.EO.Ptr(), + EH: ro.EH.Ptr(), + EL: ro.EL.Ptr(), + EC: ro.EC.Ptr(), AO: ro.AO, AH: ro.AH, AL: ro.AL, AC: ro.AC, - MO: ro.MO, - MH: ro.MH, - ML: ro.ML, - MC: ro.MC, + MO: ro.MO.Ptr(), + MH: ro.MH.Ptr(), + ML: ro.ML.Ptr(), + MC: ro.MC.Ptr(), Vo: ro.Vo, OI: ro.OI, Va: ro.Va, } // Convert optional fields - if v, ok := parseOptionalFloatOpt(ro.VoOA); ok { - o.VoOA = &v - } - if v, ok := parseOptionalFloatOpt(ro.Settle); ok { - o.Settle = &v - } - if v, ok := parseOptionalFloatOpt(ro.Theo); ok { - o.Theo = &v - } - if v, ok := parseOptionalFloatOpt(ro.BaseVol); ok { - o.BaseVol = &v - } - if v, ok := parseOptionalFloatOpt(ro.UnderPx); ok { - o.UnderPx = &v - } - if v, ok := parseOptionalFloatOpt(ro.IV); ok { - o.IV = &v - } - if v, ok := parseOptionalFloatOpt(ro.IR); ok { - o.IR = &v - } - if v, ok := parseOptionalStringOpt(ro.LTD); ok { - o.LTD = &v - } - if v, ok := parseOptionalStringOpt(ro.SQD); ok { - o.SQD = &v - } - if v, ok := parseOptionalStringOpt(ro.CCMFlag); ok { - o.CCMFlag = &v - } + o.VoOA = ro.VoOA.Ptr() + o.Settle = ro.Settle.Ptr() + o.Theo = ro.Theo.Ptr() + o.BaseVol = ro.BaseVol.Ptr() + o.UnderPx = ro.UnderPx.Ptr() + o.IV = ro.IV.Ptr() + o.IR = ro.IR.Ptr() + o.LTD = ro.LTD.Ptr() + o.SQD = ro.SQD.Ptr() + o.CCMFlag = ro.CCMFlag.Ptr() r.Data[idx] = o } @@ -414,64 +394,53 @@ func (o *Option) IsSecurityOption() bool { // HasNightSession はナイトセッションデータがあるかを判定します。 func (o *Option) HasNightSession() bool { - // interface{}型のフィールドが空文字列でないかチェック - if str, ok := o.EO.(string); ok && str == "" { - return false - } - // 0の場合も取引なしと判定 - if val, ok := o.EO.(float64); ok && val == 0 { - return false - } - return true + // 値なしに加えて、0の場合も取引なしと判定 + return o.EO != nil && *o.EO != 0 } // HasMorningSession は前場データがあるかを判定します。 func (o *Option) HasMorningSession() bool { - // interface{}型のフィールドが空文字列でないかチェック - if str, ok := o.MO.(string); ok && str == "" { - return false - } - return true + return o.MO != nil } // GetNightSessionOpen はナイトセッション始値を取得します。 func (o *Option) GetNightSessionOpen() *float64 { - return parseInterfaceToFloat64Opt(o.EO) + return o.EO } // GetNightSessionHigh はナイトセッション高値を取得します。 func (o *Option) GetNightSessionHigh() *float64 { - return parseInterfaceToFloat64Opt(o.EH) + return o.EH } // GetNightSessionLow はナイトセッション安値を取得します。 func (o *Option) GetNightSessionLow() *float64 { - return parseInterfaceToFloat64Opt(o.EL) + return o.EL } // GetNightSessionClose はナイトセッション終値を取得します。 func (o *Option) GetNightSessionClose() *float64 { - return parseInterfaceToFloat64Opt(o.EC) + return o.EC } // GetMorningSessionOpen は前場始値を取得します。 func (o *Option) GetMorningSessionOpen() *float64 { - return parseInterfaceToFloat64Opt(o.MO) + return o.MO } // GetMorningSessionHigh は前場高値を取得します。 func (o *Option) GetMorningSessionHigh() *float64 { - return parseInterfaceToFloat64Opt(o.MH) + return o.MH } // GetMorningSessionLow は前場安値を取得します。 func (o *Option) GetMorningSessionLow() *float64 { - return parseInterfaceToFloat64Opt(o.ML) + return o.ML } // GetMorningSessionClose は前場終値を取得します。 func (o *Option) GetMorningSessionClose() *float64 { - return parseInterfaceToFloat64Opt(o.MC) + return o.MC } // IsITM はイン・ザ・マネーかどうかを判定します。 @@ -543,47 +512,3 @@ func (o *Option) GetTimeValue() *float64 { timeValue := *o.Theo - intrinsic return &timeValue } - -// Helper functions - -func parseInterfaceToFloat64Opt(v interface{}) *float64 { - switch val := v.(type) { - case float64: - return &val - case int: - f := float64(val) - return &f - case string: - if val == "" { - return nil - } - if f, err := strconv.ParseFloat(val, 64); err == nil { - return &f - } - } - return nil -} - -func parseOptionalFloatOpt(v interface{}) (float64, bool) { - switch val := v.(type) { - case float64: - return val, true - case int: - return float64(val), true - case string: - if val == "" { - return 0, false - } - if f, err := strconv.ParseFloat(val, 64); err == nil { - return f, true - } - } - return 0, false -} - -func parseOptionalStringOpt(v interface{}) (string, bool) { - if str, ok := v.(string); ok && str != "" { - return str, true - } - return "", false -} diff --git a/options_test.go b/options_test.go index b1478bd..4b4a1d8 100644 --- a/options_test.go +++ b/options_test.go @@ -81,18 +81,18 @@ func TestOptionsService_GetOptions(t *testing.T) { H: 0.0, L: 0.0, C: 0.0, - EO: "", - EH: "", - EL: "", - EC: "", + EO: nil, + EH: nil, + EL: nil, + EC: nil, AO: 0.0, AH: 0.0, AL: 0.0, AC: 0.0, - MO: "", - MH: "", - ML: "", - MC: "", + MO: nil, + MH: nil, + ML: nil, + MC: nil, Vo: 0.0, OI: 0.0, Va: 0.0, @@ -396,17 +396,17 @@ func TestOption_HelperMethods(t *testing.T) { t.Run("Session data helpers", func(t *testing.T) { optionWithNight := Option{ - EO: 100.0, - EH: 110.0, - EL: 90.0, - EC: 105.0, + EO: floatPtr(100.0), + EH: floatPtr(110.0), + EL: floatPtr(90.0), + EC: floatPtr(105.0), } optionNoNight := Option{ - EO: "", - EH: "", - EL: "", - EC: "", + EO: nil, + EH: nil, + EL: nil, + EC: nil, } if !optionWithNight.HasNightSession() { @@ -565,8 +565,8 @@ func TestOptionsResponse_UnmarshalJSON(t *testing.T) { } // Check empty string fields are handled correctly - if str, ok := opt.EO.(string); !ok || str != "" { - t.Errorf("UnmarshalJSON() EO = %v, want empty string", opt.EO) + if opt.EO != nil { + t.Errorf("UnmarshalJSON() EO = %v, want nil for empty string", *opt.EO) } // Check optional fields diff --git a/prices_am.go b/prices_am.go index 6450c2d..67742a5 100644 --- a/prices_am.go +++ b/prices_am.go @@ -63,14 +63,14 @@ type RawPriceAM struct { Code string `json:"Code"` // 前場四本値データ - MO *types.Float64String `json:"MO"` - MH *types.Float64String `json:"MH"` - ML *types.Float64String `json:"ML"` - MC *types.Float64String `json:"MC"` + MO types.NullableFloat64 `json:"MO"` + MH types.NullableFloat64 `json:"MH"` + ML types.NullableFloat64 `json:"ML"` + MC types.NullableFloat64 `json:"MC"` // 前場取引情報 - MVo *types.Float64String `json:"MVo"` - MVa *types.Float64String `json:"MVa"` + MVo types.NullableFloat64 `json:"MVo"` + MVa types.NullableFloat64 `json:"MVa"` } // UnmarshalJSON implements custom JSON unmarshaling for PricesAMResponse @@ -98,14 +98,14 @@ func (r *PricesAMResponse) UnmarshalJSON(data []byte) error { Code: rpa.Code, // 前場四本値データ - MO: types.ToFloat64Ptr(rpa.MO), - MH: types.ToFloat64Ptr(rpa.MH), - ML: types.ToFloat64Ptr(rpa.ML), - MC: types.ToFloat64Ptr(rpa.MC), + MO: rpa.MO.Ptr(), + MH: rpa.MH.Ptr(), + ML: rpa.ML.Ptr(), + MC: rpa.MC.Ptr(), // 前場取引情報 - MVo: types.ToFloat64Ptr(rpa.MVo), - MVa: types.ToFloat64Ptr(rpa.MVa), + MVo: rpa.MVo.Ptr(), + MVa: rpa.MVa.Ptr(), } } diff --git a/quotes.go b/quotes.go index 025f83b..1086928 100644 --- a/quotes.go +++ b/quotes.go @@ -83,48 +83,48 @@ type RawDailyQuote struct { Date string `json:"Date"` Code string `json:"Code"` // 日通しデータ - O *types.Float64String `json:"O"` - H *types.Float64String `json:"H"` - L *types.Float64String `json:"L"` - C *types.Float64String `json:"C"` - UL string `json:"UL"` - LL string `json:"LL"` - Vo *types.Float64String `json:"Vo"` - Va *types.Float64String `json:"Va"` - AdjFactor types.Float64String `json:"AdjFactor"` - AdjO *types.Float64String `json:"AdjO"` - AdjH *types.Float64String `json:"AdjH"` - AdjL *types.Float64String `json:"AdjL"` - AdjC *types.Float64String `json:"AdjC"` - AdjVo *types.Float64String `json:"AdjVo"` + O types.NullableFloat64 `json:"O"` + H types.NullableFloat64 `json:"H"` + L types.NullableFloat64 `json:"L"` + C types.NullableFloat64 `json:"C"` + UL string `json:"UL"` + LL string `json:"LL"` + Vo types.NullableFloat64 `json:"Vo"` + Va types.NullableFloat64 `json:"Va"` + AdjFactor types.NullableFloat64 `json:"AdjFactor"` + AdjO types.NullableFloat64 `json:"AdjO"` + AdjH types.NullableFloat64 `json:"AdjH"` + AdjL types.NullableFloat64 `json:"AdjL"` + AdjC types.NullableFloat64 `json:"AdjC"` + AdjVo types.NullableFloat64 `json:"AdjVo"` // 前場データ - MO *types.Float64String `json:"MO"` - MH *types.Float64String `json:"MH"` - ML *types.Float64String `json:"ML"` - MC *types.Float64String `json:"MC"` - MUL string `json:"MUL"` - MLL string `json:"MLL"` - MVo *types.Float64String `json:"MVo"` - MVa *types.Float64String `json:"MVa"` - MAdjO *types.Float64String `json:"MAdjO"` - MAdjH *types.Float64String `json:"MAdjH"` - MAdjL *types.Float64String `json:"MAdjL"` - MAdjC *types.Float64String `json:"MAdjC"` - MAdjVo *types.Float64String `json:"MAdjVo"` + MO types.NullableFloat64 `json:"MO"` + MH types.NullableFloat64 `json:"MH"` + ML types.NullableFloat64 `json:"ML"` + MC types.NullableFloat64 `json:"MC"` + MUL string `json:"MUL"` + MLL string `json:"MLL"` + MVo types.NullableFloat64 `json:"MVo"` + MVa types.NullableFloat64 `json:"MVa"` + MAdjO types.NullableFloat64 `json:"MAdjO"` + MAdjH types.NullableFloat64 `json:"MAdjH"` + MAdjL types.NullableFloat64 `json:"MAdjL"` + MAdjC types.NullableFloat64 `json:"MAdjC"` + MAdjVo types.NullableFloat64 `json:"MAdjVo"` // 後場データ - AO *types.Float64String `json:"AO"` - AH *types.Float64String `json:"AH"` - AL *types.Float64String `json:"AL"` - AC *types.Float64String `json:"AC"` - AUL string `json:"AUL"` - ALL string `json:"ALL"` - AVo *types.Float64String `json:"AVo"` - AVa *types.Float64String `json:"AVa"` - AAdjO *types.Float64String `json:"AAdjO"` - AAdjH *types.Float64String `json:"AAdjH"` - AAdjL *types.Float64String `json:"AAdjL"` - AAdjC *types.Float64String `json:"AAdjC"` - AAdjVo *types.Float64String `json:"AAdjVo"` + AO types.NullableFloat64 `json:"AO"` + AH types.NullableFloat64 `json:"AH"` + AL types.NullableFloat64 `json:"AL"` + AC types.NullableFloat64 `json:"AC"` + AUL string `json:"AUL"` + ALL string `json:"ALL"` + AVo types.NullableFloat64 `json:"AVo"` + AVa types.NullableFloat64 `json:"AVa"` + AAdjO types.NullableFloat64 `json:"AAdjO"` + AAdjH types.NullableFloat64 `json:"AAdjH"` + AAdjL types.NullableFloat64 `json:"AAdjL"` + AAdjC types.NullableFloat64 `json:"AAdjC"` + AAdjVo types.NullableFloat64 `json:"AAdjVo"` } type DailyQuotesResponse struct { @@ -155,48 +155,48 @@ func (d *DailyQuotesResponse) UnmarshalJSON(data []byte) error { Date: rdq.Date, Code: rdq.Code, // 日通しデータ - O: types.ToFloat64Ptr(rdq.O), - H: types.ToFloat64Ptr(rdq.H), - L: types.ToFloat64Ptr(rdq.L), - C: types.ToFloat64Ptr(rdq.C), + O: rdq.O.Ptr(), + H: rdq.H.Ptr(), + L: rdq.L.Ptr(), + C: rdq.C.Ptr(), UL: rdq.UL, LL: rdq.LL, - Vo: types.ToFloat64Ptr(rdq.Vo), - Va: types.ToFloat64Ptr(rdq.Va), - AdjFactor: float64(rdq.AdjFactor), - AdjO: types.ToFloat64Ptr(rdq.AdjO), - AdjH: types.ToFloat64Ptr(rdq.AdjH), - AdjL: types.ToFloat64Ptr(rdq.AdjL), - AdjC: types.ToFloat64Ptr(rdq.AdjC), - AdjVo: types.ToFloat64Ptr(rdq.AdjVo), + Vo: rdq.Vo.Ptr(), + Va: rdq.Va.Ptr(), + AdjFactor: rdq.AdjFactor.Or(0), + AdjO: rdq.AdjO.Ptr(), + AdjH: rdq.AdjH.Ptr(), + AdjL: rdq.AdjL.Ptr(), + AdjC: rdq.AdjC.Ptr(), + AdjVo: rdq.AdjVo.Ptr(), // 前場データ - MO: types.ToFloat64Ptr(rdq.MO), - MH: types.ToFloat64Ptr(rdq.MH), - ML: types.ToFloat64Ptr(rdq.ML), - MC: types.ToFloat64Ptr(rdq.MC), + MO: rdq.MO.Ptr(), + MH: rdq.MH.Ptr(), + ML: rdq.ML.Ptr(), + MC: rdq.MC.Ptr(), MUL: rdq.MUL, MLL: rdq.MLL, - MVo: types.ToFloat64Ptr(rdq.MVo), - MVa: types.ToFloat64Ptr(rdq.MVa), - MAdjO: types.ToFloat64Ptr(rdq.MAdjO), - MAdjH: types.ToFloat64Ptr(rdq.MAdjH), - MAdjL: types.ToFloat64Ptr(rdq.MAdjL), - MAdjC: types.ToFloat64Ptr(rdq.MAdjC), - MAdjVo: types.ToFloat64Ptr(rdq.MAdjVo), + MVo: rdq.MVo.Ptr(), + MVa: rdq.MVa.Ptr(), + MAdjO: rdq.MAdjO.Ptr(), + MAdjH: rdq.MAdjH.Ptr(), + MAdjL: rdq.MAdjL.Ptr(), + MAdjC: rdq.MAdjC.Ptr(), + MAdjVo: rdq.MAdjVo.Ptr(), // 後場データ - AO: types.ToFloat64Ptr(rdq.AO), - AH: types.ToFloat64Ptr(rdq.AH), - AL: types.ToFloat64Ptr(rdq.AL), - AC: types.ToFloat64Ptr(rdq.AC), + AO: rdq.AO.Ptr(), + AH: rdq.AH.Ptr(), + AL: rdq.AL.Ptr(), + AC: rdq.AC.Ptr(), AUL: rdq.AUL, ALL: rdq.ALL, - AVo: types.ToFloat64Ptr(rdq.AVo), - AVa: types.ToFloat64Ptr(rdq.AVa), - AAdjO: types.ToFloat64Ptr(rdq.AAdjO), - AAdjH: types.ToFloat64Ptr(rdq.AAdjH), - AAdjL: types.ToFloat64Ptr(rdq.AAdjL), - AAdjC: types.ToFloat64Ptr(rdq.AAdjC), - AAdjVo: types.ToFloat64Ptr(rdq.AAdjVo), + AVo: rdq.AVo.Ptr(), + AVa: rdq.AVa.Ptr(), + AAdjO: rdq.AAdjO.Ptr(), + AAdjH: rdq.AAdjH.Ptr(), + AAdjL: rdq.AAdjL.Ptr(), + AAdjC: rdq.AAdjC.Ptr(), + AAdjVo: rdq.AAdjVo.Ptr(), } } diff --git a/short_selling.go b/short_selling.go index 815bb7f..5f8c52d 100644 --- a/short_selling.go +++ b/short_selling.go @@ -54,9 +54,9 @@ type RawShortSelling struct { S33 string `json:"S33"` // 売買代金データ - SellExShortVa types.Float64String `json:"SellExShortVa"` - ShrtWithResVa types.Float64String `json:"ShrtWithResVa"` - ShrtNoResVa types.Float64String `json:"ShrtNoResVa"` + SellExShortVa types.NullableFloat64 `json:"SellExShortVa"` + ShrtWithResVa types.NullableFloat64 `json:"ShrtWithResVa"` + ShrtNoResVa types.NullableFloat64 `json:"ShrtNoResVa"` } // UnmarshalJSON implements custom JSON unmarshaling for ShortSellingResponse @@ -84,9 +84,9 @@ func (r *ShortSellingResponse) UnmarshalJSON(data []byte) error { S33: rs.S33, // 売買代金データ - SellExShortVa: float64(rs.SellExShortVa), - ShrtWithResVa: float64(rs.ShrtWithResVa), - ShrtNoResVa: float64(rs.ShrtNoResVa), + SellExShortVa: rs.SellExShortVa.Or(0), + ShrtWithResVa: rs.ShrtWithResVa.Or(0), + ShrtNoResVa: rs.ShrtNoResVa.Or(0), } } diff --git a/short_selling_positions.go b/short_selling_positions.go index d2ebdfe..592158b 100644 --- a/short_selling_positions.go +++ b/short_selling_positions.go @@ -54,9 +54,9 @@ type ShortSellingPosition struct { FundName string `json:"FundName"` // 信託財産・運用財産の名称 // 空売り残高情報 - ShrtPosToSO float64 `json:"ShrtPosToSO"` // 空売り残高割合(発行済株式総数に対する比率) - ShrtPosShares float64 `json:"ShrtPosShares"` // 空売り残高数量(株数) - ShrtPosUnits float64 `json:"ShrtPosUnits"` // 空売り残高売買単位数 + ShrtPosToSO float64 `json:"ShrtPosToSO"` // 空売り残高割合(発行済株式総数に対する比率) + ShrtPosShares float64 `json:"ShrtPosShares"` // 空売り残高数量(株数) + ShrtPosUnits float64 `json:"ShrtPosUnits"` // 空売り残高売買単位数 // 前回報告データ PrevRptDate string `json:"PrevRptDate"` // 直近計算年月日(YYYY-MM-DD形式) @@ -83,13 +83,13 @@ type RawShortSellingPosition struct { FundName string `json:"FundName"` // 空売り残高情報 - ShrtPosToSO types.Float64String `json:"ShrtPosToSO"` - ShrtPosShares types.Float64String `json:"ShrtPosShares"` - ShrtPosUnits types.Float64String `json:"ShrtPosUnits"` + ShrtPosToSO types.NullableFloat64 `json:"ShrtPosToSO"` + ShrtPosShares types.NullableFloat64 `json:"ShrtPosShares"` + ShrtPosUnits types.NullableFloat64 `json:"ShrtPosUnits"` // 前回報告データ - PrevRptDate string `json:"PrevRptDate"` - PrevRptRatio types.Float64String `json:"PrevRptRatio"` + PrevRptDate string `json:"PrevRptDate"` + PrevRptRatio types.NullableFloat64 `json:"PrevRptRatio"` // その他 Notes string `json:"Notes"` @@ -130,13 +130,13 @@ func (r *ShortSellingPositionsResponse) UnmarshalJSON(data []byte) error { FundName: rsp.FundName, // 空売り残高情報 - ShrtPosToSO: float64(rsp.ShrtPosToSO), - ShrtPosShares: float64(rsp.ShrtPosShares), - ShrtPosUnits: float64(rsp.ShrtPosUnits), + ShrtPosToSO: rsp.ShrtPosToSO.Or(0), + ShrtPosShares: rsp.ShrtPosShares.Or(0), + ShrtPosUnits: rsp.ShrtPosUnits.Or(0), // 前回報告データ PrevRptDate: rsp.PrevRptDate, - PrevRptRatio: float64(rsp.PrevRptRatio), + PrevRptRatio: rsp.PrevRptRatio.Or(0), // その他 Notes: rsp.Notes, diff --git a/statements.go b/statements.go index 262823e..8ca0b62 100644 --- a/statements.go +++ b/statements.go @@ -183,129 +183,129 @@ type RawStatement struct { NxtFYEn string `json:"NxtFYEn"` // 連結財務数値 - Sales types.Float64StringWithDash `json:"Sales"` - OP types.Float64StringWithDash `json:"OP"` - OdP types.Float64StringWithDash `json:"OdP"` - NP types.Float64StringWithDash `json:"NP"` - TA types.Float64StringWithDash `json:"TA"` - Eq types.Float64StringWithDash `json:"Eq"` - CashEq types.Float64StringWithDash `json:"CashEq"` - CFO types.Float64StringWithDash `json:"CFO"` - CFI types.Float64StringWithDash `json:"CFI"` - CFF types.Float64StringWithDash `json:"CFF"` + Sales types.NullableFloat64 `json:"Sales"` + OP types.NullableFloat64 `json:"OP"` + OdP types.NullableFloat64 `json:"OdP"` + NP types.NullableFloat64 `json:"NP"` + TA types.NullableFloat64 `json:"TA"` + Eq types.NullableFloat64 `json:"Eq"` + CashEq types.NullableFloat64 `json:"CashEq"` + CFO types.NullableFloat64 `json:"CFO"` + CFI types.NullableFloat64 `json:"CFI"` + CFF types.NullableFloat64 `json:"CFF"` // 財務指標 - EPS types.Float64StringWithDash `json:"EPS"` - DEPS types.Float64StringWithDash `json:"DEPS"` - BPS types.Float64StringWithDash `json:"BPS"` - EqAR types.Float64StringWithDash `json:"EqAR"` + EPS types.NullableFloat64 `json:"EPS"` + DEPS types.NullableFloat64 `json:"DEPS"` + BPS types.NullableFloat64 `json:"BPS"` + EqAR types.NullableFloat64 `json:"EqAR"` // 配当実績 - Div1Q types.Float64StringWithDash `json:"Div1Q"` - Div2Q types.Float64StringWithDash `json:"Div2Q"` - Div3Q types.Float64StringWithDash `json:"Div3Q"` - DivFY types.Float64StringWithDash `json:"DivFY"` - DivAnn types.Float64StringWithDash `json:"DivAnn"` - DivUnit types.Float64StringWithDash `json:"DivUnit"` - DivTotalAnn types.Float64StringWithDash `json:"DivTotalAnn"` - PayoutRatioAn types.Float64StringWithDash `json:"PayoutRatioAnn"` + Div1Q types.NullableFloat64 `json:"Div1Q"` + Div2Q types.NullableFloat64 `json:"Div2Q"` + Div3Q types.NullableFloat64 `json:"Div3Q"` + DivFY types.NullableFloat64 `json:"DivFY"` + DivAnn types.NullableFloat64 `json:"DivAnn"` + DivUnit types.NullableFloat64 `json:"DivUnit"` + DivTotalAnn types.NullableFloat64 `json:"DivTotalAnn"` + PayoutRatioAn types.NullableFloat64 `json:"PayoutRatioAnn"` // 配当予想 - FDiv1Q types.Float64StringWithDash `json:"FDiv1Q"` - FDiv2Q types.Float64StringWithDash `json:"FDiv2Q"` - FDiv3Q types.Float64StringWithDash `json:"FDiv3Q"` - FDivFY types.Float64StringWithDash `json:"FDivFY"` - FDivAnn types.Float64StringWithDash `json:"FDivAnn"` - FDivUnit types.Float64StringWithDash `json:"FDivUnit"` - FDivTotalAnn types.Float64StringWithDash `json:"FDivTotalAnn"` - FPayoutRatioAn types.Float64StringWithDash `json:"FPayoutRatioAnn"` + FDiv1Q types.NullableFloat64 `json:"FDiv1Q"` + FDiv2Q types.NullableFloat64 `json:"FDiv2Q"` + FDiv3Q types.NullableFloat64 `json:"FDiv3Q"` + FDivFY types.NullableFloat64 `json:"FDivFY"` + FDivAnn types.NullableFloat64 `json:"FDivAnn"` + FDivUnit types.NullableFloat64 `json:"FDivUnit"` + FDivTotalAnn types.NullableFloat64 `json:"FDivTotalAnn"` + FPayoutRatioAn types.NullableFloat64 `json:"FPayoutRatioAnn"` // 翌期配当予想 - NxFDiv1Q types.Float64StringWithDash `json:"NxFDiv1Q"` - NxFDiv2Q types.Float64StringWithDash `json:"NxFDiv2Q"` - NxFDiv3Q types.Float64StringWithDash `json:"NxFDiv3Q"` - NxFDivFY types.Float64StringWithDash `json:"NxFDivFY"` - NxFDivAnn types.Float64StringWithDash `json:"NxFDivAnn"` - NxFDivUnit types.Float64StringWithDash `json:"NxFDivUnit"` - NxFPayoutRatioAn types.Float64StringWithDash `json:"NxFPayoutRatioAnn"` + NxFDiv1Q types.NullableFloat64 `json:"NxFDiv1Q"` + NxFDiv2Q types.NullableFloat64 `json:"NxFDiv2Q"` + NxFDiv3Q types.NullableFloat64 `json:"NxFDiv3Q"` + NxFDivFY types.NullableFloat64 `json:"NxFDivFY"` + NxFDivAnn types.NullableFloat64 `json:"NxFDivAnn"` + NxFDivUnit types.NullableFloat64 `json:"NxFDivUnit"` + NxFPayoutRatioAn types.NullableFloat64 `json:"NxFPayoutRatioAnn"` // 第2四半期業績予想 - FSales2Q types.Float64StringWithDash `json:"FSales2Q"` - FOP2Q types.Float64StringWithDash `json:"FOP2Q"` - FOdP2Q types.Float64StringWithDash `json:"FOdP2Q"` - FNP2Q types.Float64StringWithDash `json:"FNP2Q"` - FEPS2Q types.Float64StringWithDash `json:"FEPS2Q"` + FSales2Q types.NullableFloat64 `json:"FSales2Q"` + FOP2Q types.NullableFloat64 `json:"FOP2Q"` + FOdP2Q types.NullableFloat64 `json:"FOdP2Q"` + FNP2Q types.NullableFloat64 `json:"FNP2Q"` + FEPS2Q types.NullableFloat64 `json:"FEPS2Q"` // 翌期第2四半期業績予想 - NxFSales2Q types.Float64StringWithDash `json:"NxFSales2Q"` - NxFOP2Q types.Float64StringWithDash `json:"NxFOP2Q"` - NxFOdP2Q types.Float64StringWithDash `json:"NxFOdP2Q"` - NxFNp2Q types.Float64StringWithDash `json:"NxFNp2Q"` - NxFEPS2Q types.Float64StringWithDash `json:"NxFEPS2Q"` + NxFSales2Q types.NullableFloat64 `json:"NxFSales2Q"` + NxFOP2Q types.NullableFloat64 `json:"NxFOP2Q"` + NxFOdP2Q types.NullableFloat64 `json:"NxFOdP2Q"` + NxFNp2Q types.NullableFloat64 `json:"NxFNp2Q"` + NxFEPS2Q types.NullableFloat64 `json:"NxFEPS2Q"` // 期末業績予想 - FSales types.Float64StringWithDash `json:"FSales"` - FOP types.Float64StringWithDash `json:"FOP"` - FOdP types.Float64StringWithDash `json:"FOdP"` - FNP types.Float64StringWithDash `json:"FNP"` - FEPS types.Float64StringWithDash `json:"FEPS"` + FSales types.NullableFloat64 `json:"FSales"` + FOP types.NullableFloat64 `json:"FOP"` + FOdP types.NullableFloat64 `json:"FOdP"` + FNP types.NullableFloat64 `json:"FNP"` + FEPS types.NullableFloat64 `json:"FEPS"` // 翌期末業績予想 - NxFSales types.Float64StringWithDash `json:"NxFSales"` - NxFOP types.Float64StringWithDash `json:"NxFOP"` - NxFOdP types.Float64StringWithDash `json:"NxFOdP"` - NxFNp types.Float64StringWithDash `json:"NxFNp"` - NxFEPS types.Float64StringWithDash `json:"NxFEPS"` + NxFSales types.NullableFloat64 `json:"NxFSales"` + NxFOP types.NullableFloat64 `json:"NxFOP"` + NxFOdP types.NullableFloat64 `json:"NxFOdP"` + NxFNp types.NullableFloat64 `json:"NxFNp"` + NxFEPS types.NullableFloat64 `json:"NxFEPS"` // その他 - MatChgSub string `json:"MatChgSub"` - SigChgInC string `json:"SigChgInC"` - ChgByASRev string `json:"ChgByASRev"` - ChgNoASRev string `json:"ChgNoASRev"` - ChgAcEst string `json:"ChgAcEst"` - RetroRst string `json:"RetroRst"` - ShOutFY types.Float64StringWithDash `json:"ShOutFY"` - TrShFY types.Float64StringWithDash `json:"TrShFY"` - AvgSh types.Float64StringWithDash `json:"AvgSh"` + MatChgSub string `json:"MatChgSub"` + SigChgInC string `json:"SigChgInC"` + ChgByASRev string `json:"ChgByASRev"` + ChgNoASRev string `json:"ChgNoASRev"` + ChgAcEst string `json:"ChgAcEst"` + RetroRst string `json:"RetroRst"` + ShOutFY types.NullableInt64 `json:"ShOutFY"` + TrShFY types.NullableInt64 `json:"TrShFY"` + AvgSh types.NullableInt64 `json:"AvgSh"` // 非連結財務数値 - NCSales types.Float64StringWithDash `json:"NCSales"` - NCOP types.Float64StringWithDash `json:"NCOP"` - NCOdP types.Float64StringWithDash `json:"NCOdP"` - NCNP types.Float64StringWithDash `json:"NCNP"` - NCEPS types.Float64StringWithDash `json:"NCEPS"` - NCTA types.Float64StringWithDash `json:"NCTA"` - NCEq types.Float64StringWithDash `json:"NCEq"` - NCEqAR types.Float64StringWithDash `json:"NCEqAR"` - NCBPS types.Float64StringWithDash `json:"NCBPS"` + NCSales types.NullableFloat64 `json:"NCSales"` + NCOP types.NullableFloat64 `json:"NCOP"` + NCOdP types.NullableFloat64 `json:"NCOdP"` + NCNP types.NullableFloat64 `json:"NCNP"` + NCEPS types.NullableFloat64 `json:"NCEPS"` + NCTA types.NullableFloat64 `json:"NCTA"` + NCEq types.NullableFloat64 `json:"NCEq"` + NCEqAR types.NullableFloat64 `json:"NCEqAR"` + NCBPS types.NullableFloat64 `json:"NCBPS"` // 非連結第2四半期予想 - FNCSales2Q types.Float64StringWithDash `json:"FNCSales2Q"` - FNCOP2Q types.Float64StringWithDash `json:"FNCOP2Q"` - FNCOdP2Q types.Float64StringWithDash `json:"FNCOdP2Q"` - FNCNP2Q types.Float64StringWithDash `json:"FNCNP2Q"` - FNCEPS2Q types.Float64StringWithDash `json:"FNCEPS2Q"` + FNCSales2Q types.NullableFloat64 `json:"FNCSales2Q"` + FNCOP2Q types.NullableFloat64 `json:"FNCOP2Q"` + FNCOdP2Q types.NullableFloat64 `json:"FNCOdP2Q"` + FNCNP2Q types.NullableFloat64 `json:"FNCNP2Q"` + FNCEPS2Q types.NullableFloat64 `json:"FNCEPS2Q"` // 翌期非連結第2四半期予想 - NxFNCSales2Q types.Float64StringWithDash `json:"NxFNCSales2Q"` - NxFNCOP2Q types.Float64StringWithDash `json:"NxFNCOP2Q"` - NxFNCOdP2Q types.Float64StringWithDash `json:"NxFNCOdP2Q"` - NxFNCNP2Q types.Float64StringWithDash `json:"NxFNCNP2Q"` - NxFNCEPS2Q types.Float64StringWithDash `json:"NxFNCEPS2Q"` + NxFNCSales2Q types.NullableFloat64 `json:"NxFNCSales2Q"` + NxFNCOP2Q types.NullableFloat64 `json:"NxFNCOP2Q"` + NxFNCOdP2Q types.NullableFloat64 `json:"NxFNCOdP2Q"` + NxFNCNP2Q types.NullableFloat64 `json:"NxFNCNP2Q"` + NxFNCEPS2Q types.NullableFloat64 `json:"NxFNCEPS2Q"` // 非連結期末予想 - FNCSales types.Float64StringWithDash `json:"FNCSales"` - FNCOP types.Float64StringWithDash `json:"FNCOP"` - FNCOdP types.Float64StringWithDash `json:"FNCOdP"` - FNCNP types.Float64StringWithDash `json:"FNCNP"` - FNCEPS types.Float64StringWithDash `json:"FNCEPS"` + FNCSales types.NullableFloat64 `json:"FNCSales"` + FNCOP types.NullableFloat64 `json:"FNCOP"` + FNCOdP types.NullableFloat64 `json:"FNCOdP"` + FNCNP types.NullableFloat64 `json:"FNCNP"` + FNCEPS types.NullableFloat64 `json:"FNCEPS"` // 翌期非連結期末予想 - NxFNCSales types.Float64StringWithDash `json:"NxFNCSales"` - NxFNCOP types.Float64StringWithDash `json:"NxFNCOP"` - NxFNCOdP types.Float64StringWithDash `json:"NxFNCOdP"` - NxFNCNP types.Float64StringWithDash `json:"NxFNCNP"` - NxFNCEPS types.Float64StringWithDash `json:"NxFNCEPS"` + NxFNCSales types.NullableFloat64 `json:"NxFNCSales"` + NxFNCOP types.NullableFloat64 `json:"NxFNCOP"` + NxFNCOdP types.NullableFloat64 `json:"NxFNCOdP"` + NxFNCNP types.NullableFloat64 `json:"NxFNCNP"` + NxFNCEPS types.NullableFloat64 `json:"NxFNCEPS"` } type StatementsResponse struct { @@ -347,79 +347,79 @@ func (s *StatementsResponse) UnmarshalJSON(data []byte) error { NxtFYEn: rs.NxtFYEn, // 連結財務数値 - Sales: rs.Sales.ToFloat64Ptr(), - OP: rs.OP.ToFloat64Ptr(), - OdP: rs.OdP.ToFloat64Ptr(), - NP: rs.NP.ToFloat64Ptr(), - TA: rs.TA.ToFloat64Ptr(), - Eq: rs.Eq.ToFloat64Ptr(), - CashEq: rs.CashEq.ToFloat64Ptr(), - CFO: rs.CFO.ToFloat64Ptr(), - CFI: rs.CFI.ToFloat64Ptr(), - CFF: rs.CFF.ToFloat64Ptr(), + Sales: rs.Sales.Ptr(), + OP: rs.OP.Ptr(), + OdP: rs.OdP.Ptr(), + NP: rs.NP.Ptr(), + TA: rs.TA.Ptr(), + Eq: rs.Eq.Ptr(), + CashEq: rs.CashEq.Ptr(), + CFO: rs.CFO.Ptr(), + CFI: rs.CFI.Ptr(), + CFF: rs.CFF.Ptr(), // 財務指標 - EPS: rs.EPS.ToFloat64Ptr(), - DEPS: rs.DEPS.ToFloat64Ptr(), - BPS: rs.BPS.ToFloat64Ptr(), - EqAR: rs.EqAR.ToFloat64Ptr(), + EPS: rs.EPS.Ptr(), + DEPS: rs.DEPS.Ptr(), + BPS: rs.BPS.Ptr(), + EqAR: rs.EqAR.Ptr(), // 配当実績 - Div1Q: rs.Div1Q.ToFloat64Ptr(), - Div2Q: rs.Div2Q.ToFloat64Ptr(), - Div3Q: rs.Div3Q.ToFloat64Ptr(), - DivFY: rs.DivFY.ToFloat64Ptr(), - DivAnn: rs.DivAnn.ToFloat64Ptr(), - DivUnit: rs.DivUnit.ToFloat64Ptr(), - DivTotalAnn: rs.DivTotalAnn.ToFloat64Ptr(), - PayoutRatioAn: rs.PayoutRatioAn.ToFloat64Ptr(), + Div1Q: rs.Div1Q.Ptr(), + Div2Q: rs.Div2Q.Ptr(), + Div3Q: rs.Div3Q.Ptr(), + DivFY: rs.DivFY.Ptr(), + DivAnn: rs.DivAnn.Ptr(), + DivUnit: rs.DivUnit.Ptr(), + DivTotalAnn: rs.DivTotalAnn.Ptr(), + PayoutRatioAn: rs.PayoutRatioAn.Ptr(), // 配当予想 - FDiv1Q: rs.FDiv1Q.ToFloat64Ptr(), - FDiv2Q: rs.FDiv2Q.ToFloat64Ptr(), - FDiv3Q: rs.FDiv3Q.ToFloat64Ptr(), - FDivFY: rs.FDivFY.ToFloat64Ptr(), - FDivAnn: rs.FDivAnn.ToFloat64Ptr(), - FDivUnit: rs.FDivUnit.ToFloat64Ptr(), - FDivTotalAnn: rs.FDivTotalAnn.ToFloat64Ptr(), - FPayoutRatioAn: rs.FPayoutRatioAn.ToFloat64Ptr(), + FDiv1Q: rs.FDiv1Q.Ptr(), + FDiv2Q: rs.FDiv2Q.Ptr(), + FDiv3Q: rs.FDiv3Q.Ptr(), + FDivFY: rs.FDivFY.Ptr(), + FDivAnn: rs.FDivAnn.Ptr(), + FDivUnit: rs.FDivUnit.Ptr(), + FDivTotalAnn: rs.FDivTotalAnn.Ptr(), + FPayoutRatioAn: rs.FPayoutRatioAn.Ptr(), // 翌期配当予想 - NxFDiv1Q: rs.NxFDiv1Q.ToFloat64Ptr(), - NxFDiv2Q: rs.NxFDiv2Q.ToFloat64Ptr(), - NxFDiv3Q: rs.NxFDiv3Q.ToFloat64Ptr(), - NxFDivFY: rs.NxFDivFY.ToFloat64Ptr(), - NxFDivAnn: rs.NxFDivAnn.ToFloat64Ptr(), - NxFDivUnit: rs.NxFDivUnit.ToFloat64Ptr(), - NxFPayoutRatioAn: rs.NxFPayoutRatioAn.ToFloat64Ptr(), + NxFDiv1Q: rs.NxFDiv1Q.Ptr(), + NxFDiv2Q: rs.NxFDiv2Q.Ptr(), + NxFDiv3Q: rs.NxFDiv3Q.Ptr(), + NxFDivFY: rs.NxFDivFY.Ptr(), + NxFDivAnn: rs.NxFDivAnn.Ptr(), + NxFDivUnit: rs.NxFDivUnit.Ptr(), + NxFPayoutRatioAn: rs.NxFPayoutRatioAn.Ptr(), // 第2四半期業績予想 - FSales2Q: rs.FSales2Q.ToFloat64Ptr(), - FOP2Q: rs.FOP2Q.ToFloat64Ptr(), - FOdP2Q: rs.FOdP2Q.ToFloat64Ptr(), - FNP2Q: rs.FNP2Q.ToFloat64Ptr(), - FEPS2Q: rs.FEPS2Q.ToFloat64Ptr(), + FSales2Q: rs.FSales2Q.Ptr(), + FOP2Q: rs.FOP2Q.Ptr(), + FOdP2Q: rs.FOdP2Q.Ptr(), + FNP2Q: rs.FNP2Q.Ptr(), + FEPS2Q: rs.FEPS2Q.Ptr(), // 翌期第2四半期業績予想 - NxFSales2Q: rs.NxFSales2Q.ToFloat64Ptr(), - NxFOP2Q: rs.NxFOP2Q.ToFloat64Ptr(), - NxFOdP2Q: rs.NxFOdP2Q.ToFloat64Ptr(), - NxFNp2Q: rs.NxFNp2Q.ToFloat64Ptr(), - NxFEPS2Q: rs.NxFEPS2Q.ToFloat64Ptr(), + NxFSales2Q: rs.NxFSales2Q.Ptr(), + NxFOP2Q: rs.NxFOP2Q.Ptr(), + NxFOdP2Q: rs.NxFOdP2Q.Ptr(), + NxFNp2Q: rs.NxFNp2Q.Ptr(), + NxFEPS2Q: rs.NxFEPS2Q.Ptr(), // 期末業績予想 - FSales: rs.FSales.ToFloat64Ptr(), - FOP: rs.FOP.ToFloat64Ptr(), - FOdP: rs.FOdP.ToFloat64Ptr(), - FNP: rs.FNP.ToFloat64Ptr(), - FEPS: rs.FEPS.ToFloat64Ptr(), + FSales: rs.FSales.Ptr(), + FOP: rs.FOP.Ptr(), + FOdP: rs.FOdP.Ptr(), + FNP: rs.FNP.Ptr(), + FEPS: rs.FEPS.Ptr(), // 翌期末業績予想 - NxFSales: rs.NxFSales.ToFloat64Ptr(), - NxFOP: rs.NxFOP.ToFloat64Ptr(), - NxFOdP: rs.NxFOdP.ToFloat64Ptr(), - NxFNp: rs.NxFNp.ToFloat64Ptr(), - NxFEPS: rs.NxFEPS.ToFloat64Ptr(), + NxFSales: rs.NxFSales.Ptr(), + NxFOP: rs.NxFOP.Ptr(), + NxFOdP: rs.NxFOdP.Ptr(), + NxFNp: rs.NxFNp.Ptr(), + NxFEPS: rs.NxFEPS.Ptr(), // その他 MatChgSub: rs.MatChgSub, @@ -428,48 +428,48 @@ func (s *StatementsResponse) UnmarshalJSON(data []byte) error { ChgNoASRev: rs.ChgNoASRev, ChgAcEst: rs.ChgAcEst, RetroRst: rs.RetroRst, - ShOutFY: rs.ShOutFY.ToInt64Ptr(), - TrShFY: rs.TrShFY.ToInt64Ptr(), - AvgSh: rs.AvgSh.ToInt64Ptr(), + ShOutFY: rs.ShOutFY.Ptr(), + TrShFY: rs.TrShFY.Ptr(), + AvgSh: rs.AvgSh.Ptr(), // 非連結財務数値 - NCSales: rs.NCSales.ToFloat64Ptr(), - NCOP: rs.NCOP.ToFloat64Ptr(), - NCOdP: rs.NCOdP.ToFloat64Ptr(), - NCNP: rs.NCNP.ToFloat64Ptr(), - NCEPS: rs.NCEPS.ToFloat64Ptr(), - NCTA: rs.NCTA.ToFloat64Ptr(), - NCEq: rs.NCEq.ToFloat64Ptr(), - NCEqAR: rs.NCEqAR.ToFloat64Ptr(), - NCBPS: rs.NCBPS.ToFloat64Ptr(), + NCSales: rs.NCSales.Ptr(), + NCOP: rs.NCOP.Ptr(), + NCOdP: rs.NCOdP.Ptr(), + NCNP: rs.NCNP.Ptr(), + NCEPS: rs.NCEPS.Ptr(), + NCTA: rs.NCTA.Ptr(), + NCEq: rs.NCEq.Ptr(), + NCEqAR: rs.NCEqAR.Ptr(), + NCBPS: rs.NCBPS.Ptr(), // 非連結第2四半期予想 - FNCSales2Q: rs.FNCSales2Q.ToFloat64Ptr(), - FNCOP2Q: rs.FNCOP2Q.ToFloat64Ptr(), - FNCOdP2Q: rs.FNCOdP2Q.ToFloat64Ptr(), - FNCNP2Q: rs.FNCNP2Q.ToFloat64Ptr(), - FNCEPS2Q: rs.FNCEPS2Q.ToFloat64Ptr(), + FNCSales2Q: rs.FNCSales2Q.Ptr(), + FNCOP2Q: rs.FNCOP2Q.Ptr(), + FNCOdP2Q: rs.FNCOdP2Q.Ptr(), + FNCNP2Q: rs.FNCNP2Q.Ptr(), + FNCEPS2Q: rs.FNCEPS2Q.Ptr(), // 翌期非連結第2四半期予想 - NxFNCSales2Q: rs.NxFNCSales2Q.ToFloat64Ptr(), - NxFNCOP2Q: rs.NxFNCOP2Q.ToFloat64Ptr(), - NxFNCOdP2Q: rs.NxFNCOdP2Q.ToFloat64Ptr(), - NxFNCNP2Q: rs.NxFNCNP2Q.ToFloat64Ptr(), - NxFNCEPS2Q: rs.NxFNCEPS2Q.ToFloat64Ptr(), + NxFNCSales2Q: rs.NxFNCSales2Q.Ptr(), + NxFNCOP2Q: rs.NxFNCOP2Q.Ptr(), + NxFNCOdP2Q: rs.NxFNCOdP2Q.Ptr(), + NxFNCNP2Q: rs.NxFNCNP2Q.Ptr(), + NxFNCEPS2Q: rs.NxFNCEPS2Q.Ptr(), // 非連結期末予想 - FNCSales: rs.FNCSales.ToFloat64Ptr(), - FNCOP: rs.FNCOP.ToFloat64Ptr(), - FNCOdP: rs.FNCOdP.ToFloat64Ptr(), - FNCNP: rs.FNCNP.ToFloat64Ptr(), - FNCEPS: rs.FNCEPS.ToFloat64Ptr(), + FNCSales: rs.FNCSales.Ptr(), + FNCOP: rs.FNCOP.Ptr(), + FNCOdP: rs.FNCOdP.Ptr(), + FNCNP: rs.FNCNP.Ptr(), + FNCEPS: rs.FNCEPS.Ptr(), // 翌期非連結期末予想 - NxFNCSales: rs.NxFNCSales.ToFloat64Ptr(), - NxFNCOP: rs.NxFNCOP.ToFloat64Ptr(), - NxFNCOdP: rs.NxFNCOdP.ToFloat64Ptr(), - NxFNCNP: rs.NxFNCNP.ToFloat64Ptr(), - NxFNCEPS: rs.NxFNCEPS.ToFloat64Ptr(), + NxFNCSales: rs.NxFNCSales.Ptr(), + NxFNCOP: rs.NxFNCOP.Ptr(), + NxFNCOdP: rs.NxFNCOdP.Ptr(), + NxFNCNP: rs.NxFNCNP.Ptr(), + NxFNCEPS: rs.NxFNCEPS.Ptr(), } } diff --git a/topix.go b/topix.go index c5e7ea2..7c91922 100644 --- a/topix.go +++ b/topix.go @@ -32,11 +32,11 @@ type TOPIXData struct { // RawTOPIXData is used for unmarshaling JSON response with mixed types type RawTOPIXData struct { - Date string `json:"Date"` - O types.Float64String `json:"O"` - H types.Float64String `json:"H"` - L types.Float64String `json:"L"` - C types.Float64String `json:"C"` + Date string `json:"Date"` + O types.NullableFloat64 `json:"O"` + H types.NullableFloat64 `json:"H"` + L types.NullableFloat64 `json:"L"` + C types.NullableFloat64 `json:"C"` } // TOPIXResponse はTOPIX指数のレスポンスです。 @@ -66,10 +66,10 @@ func (t *TOPIXResponse) UnmarshalJSON(data []byte) error { for idx, rt := range raw.Data { t.Data[idx] = TOPIXData{ Date: rt.Date, - O: float64(rt.O), - H: float64(rt.H), - L: float64(rt.L), - C: float64(rt.C), + O: rt.O.Or(0), + H: rt.H.Or(0), + L: rt.L.Or(0), + C: rt.C.Or(0), } } diff --git a/types/json.go b/types/json.go deleted file mode 100644 index 18bc627..0000000 --- a/types/json.go +++ /dev/null @@ -1,220 +0,0 @@ -package types - -import ( - "encoding/json" - "fmt" - "strconv" -) - -// Float64String is a custom type that can unmarshal both float64 and string -type Float64String float64 - -func (f *Float64String) UnmarshalJSON(data []byte) error { - // Try to unmarshal as float64 first - var floatVal float64 - if err := json.Unmarshal(data, &floatVal); err == nil { - *f = Float64String(floatVal) - return nil - } - - // If that fails, try as string - var strVal string - if err := json.Unmarshal(data, &strVal); err != nil { - return err - } - - // Empty string should be treated as nil - if strVal == "" || strVal == "-" { - return nil - } - - // Parse string to float64 - floatVal, err := strconv.ParseFloat(strVal, 64) - if err != nil { - return err - } - *f = Float64String(floatVal) - return nil -} - -// BoolString is a custom type that can unmarshal both bool and string -type BoolString bool - -func (b *BoolString) UnmarshalJSON(data []byte) error { - // Try to unmarshal as bool first - var boolVal bool - if err := json.Unmarshal(data, &boolVal); err == nil { - *b = BoolString(boolVal) - return nil - } - - // If that fails, try as string - var strVal string - if err := json.Unmarshal(data, &strVal); err != nil { - return err - } - - // Convert string to bool - switch strVal { - case "true", "True", "TRUE", "1": - *b = BoolString(true) - case "false", "False", "FALSE", "0", "": - *b = BoolString(false) - default: - return fmt.Errorf("cannot convert string %q to bool", strVal) - } - return nil -} - -// Int64String is a custom type that can unmarshal both int64 and string -type Int64String int64 - -func (i *Int64String) UnmarshalJSON(data []byte) error { - // Try to unmarshal as int64 first - var intVal int64 - if err := json.Unmarshal(data, &intVal); err == nil { - *i = Int64String(intVal) - return nil - } - - // If that fails, try as string - var strVal string - if err := json.Unmarshal(data, &strVal); err != nil { - return err - } - - // Empty string should be treated as nil - if strVal == "" || strVal == "-" { - return nil - } - - // Parse string to int64 - intVal, err := strconv.ParseInt(strVal, 10, 64) - if err != nil { - return err - } - *i = Int64String(intVal) - return nil -} - -// Helper functions for converting custom types to standard types - -// ToFloat64Ptr converts Float64String pointer to float64 pointer -func ToFloat64Ptr(f *Float64String) *float64 { - if f == nil { - return nil - } - val := float64(*f) - return &val -} - -// ToInt64Ptr converts Float64String pointer to int64 pointer -func ToInt64Ptr(f *Float64String) *int64 { - if f == nil { - return nil - } - val := int64(*f) - return &val -} - -// ToInt64PtrFromInt64String converts Int64String pointer to int64 pointer -func ToInt64PtrFromInt64String(i *Int64String) *int64 { - if i == nil { - return nil - } - val := int64(*i) - return &val -} - -// ToBool converts BoolString to bool -func ToBool(b BoolString) bool { - return bool(b) -} - -// Float64StringWithDash is a custom type that can unmarshal float64, string, and treats "-" as nil -type Float64StringWithDash struct { - value *float64 - isUndefined bool -} - -func (f *Float64StringWithDash) UnmarshalJSON(data []byte) error { - // JSON null means the value is absent. Without this guard the float64 - // branch below would succeed as a no-op and record 0. - if string(data) == "null" { - f.value = nil - f.isUndefined = false - return nil - } - - // Try to unmarshal as float64 first - var floatVal float64 - if err := json.Unmarshal(data, &floatVal); err == nil { - f.value = &floatVal - f.isUndefined = false - return nil - } - - // If that fails, try as string - var strVal string - if err := json.Unmarshal(data, &strVal); err != nil { - return err - } - - // Handle special cases - if strVal == "-" { - f.value = nil - f.isUndefined = true - return nil - } - - if strVal == "" { - f.value = nil - f.isUndefined = false - return nil - } - - // Parse string to float64 - floatVal, err := strconv.ParseFloat(strVal, 64) - if err != nil { - return err - } - f.value = &floatVal - f.isUndefined = false - return nil -} - -// ToFloat64Ptr returns the float64 pointer value -func (f *Float64StringWithDash) ToFloat64Ptr() *float64 { - return f.value -} - -// ToInt64Ptr returns the value as an int64 pointer -func (f *Float64StringWithDash) ToInt64Ptr() *int64 { - if f.value == nil { - return nil - } - val := int64(*f.value) - return &val -} - -// StringWithDash is a custom type that handles "-" as a special value -type StringWithDash struct { - value string -} - -func (s *StringWithDash) UnmarshalJSON(data []byte) error { - var strVal string - if err := json.Unmarshal(data, &strVal); err != nil { - return err - } - s.value = strVal - return nil -} - -// ToStringPtr returns the string pointer value -func (s *StringWithDash) ToStringPtr() *string { - if s.value == "" { - return nil - } - return &s.value -} \ No newline at end of file diff --git a/types/json_test.go b/types/json_test.go deleted file mode 100644 index 12f55d0..0000000 --- a/types/json_test.go +++ /dev/null @@ -1,242 +0,0 @@ -package types - -import ( - "encoding/json" - "testing" -) - -func TestFloat64String_UnmarshalJSON(t *testing.T) { - tests := []struct { - name string - json string - want *float64 - wantErr bool - }{ - { - name: "float64値", - json: `{"value": 123.45}`, - want: floatPtr(123.45), - }, - { - name: "文字列値", - json: `{"value": "678.90"}`, - want: floatPtr(678.90), - }, - { - name: "空文字列", - json: `{"value": ""}`, - want: floatPtr(0), // 空文字列は0として扱われる - }, - { - name: "ハイフン", - json: `{"value": "-"}`, - want: floatPtr(0), // ハイフンは0として扱われる - }, - { - name: "不正な文字列", - json: `{"value": "abc"}`, - wantErr: true, - }, - } - - for _, tt := range tests { - t.Run(tt.name, func(t *testing.T) { - var data struct { - Value *Float64String `json:"value"` - } - - err := json.Unmarshal([]byte(tt.json), &data) - if (err != nil) != tt.wantErr { - t.Errorf("UnmarshalJSON() error = %v, wantErr %v", err, tt.wantErr) - return - } - - if err == nil { - if tt.want == nil && data.Value != nil { - t.Errorf("Expected nil, got %v", *data.Value) - } else if tt.want != nil && data.Value == nil { - t.Errorf("Expected %v, got nil", *tt.want) - } else if tt.want != nil && data.Value != nil { - if float64(*data.Value) != *tt.want { - t.Errorf("Expected %v, got %v", *tt.want, float64(*data.Value)) - } - } - } - }) - } -} - -func TestBoolString_UnmarshalJSON(t *testing.T) { - tests := []struct { - name string - json string - want bool - wantErr bool - }{ - { - name: "bool true", - json: `{"value": true}`, - want: true, - }, - { - name: "bool false", - json: `{"value": false}`, - want: false, - }, - { - name: "文字列 true", - json: `{"value": "true"}`, - want: true, - }, - { - name: "文字列 false", - json: `{"value": "false"}`, - want: false, - }, - { - name: "文字列 1", - json: `{"value": "1"}`, - want: true, - }, - { - name: "文字列 0", - json: `{"value": "0"}`, - want: false, - }, - { - name: "空文字列", - json: `{"value": ""}`, - want: false, - }, - { - name: "不正な文字列", - json: `{"value": "invalid"}`, - wantErr: true, - }, - } - - for _, tt := range tests { - t.Run(tt.name, func(t *testing.T) { - var data struct { - Value BoolString `json:"value"` - } - - err := json.Unmarshal([]byte(tt.json), &data) - if (err != nil) != tt.wantErr { - t.Errorf("UnmarshalJSON() error = %v, wantErr %v", err, tt.wantErr) - return - } - - if err == nil && bool(data.Value) != tt.want { - t.Errorf("Expected %v, got %v", tt.want, bool(data.Value)) - } - }) - } -} - -func TestInt64String_UnmarshalJSON(t *testing.T) { - tests := []struct { - name string - json string - want *int64 - wantErr bool - }{ - { - name: "int64値", - json: `{"value": 12345}`, - want: int64Ptr(12345), - }, - { - name: "文字列値", - json: `{"value": "67890"}`, - want: int64Ptr(67890), - }, - { - name: "空文字列", - json: `{"value": ""}`, - want: int64Ptr(0), // 空文字列は0として扱われる - }, - { - name: "ハイフン", - json: `{"value": "-"}`, - want: int64Ptr(0), // ハイフンは0として扱われる - }, - { - name: "不正な文字列", - json: `{"value": "abc"}`, - wantErr: true, - }, - } - - for _, tt := range tests { - t.Run(tt.name, func(t *testing.T) { - var data struct { - Value *Int64String `json:"value"` - } - - err := json.Unmarshal([]byte(tt.json), &data) - if (err != nil) != tt.wantErr { - t.Errorf("UnmarshalJSON() error = %v, wantErr %v", err, tt.wantErr) - return - } - - if err == nil { - if tt.want == nil && data.Value != nil { - t.Errorf("Expected nil, got %v", *data.Value) - } else if tt.want != nil && data.Value == nil { - t.Errorf("Expected %v, got nil", *tt.want) - } else if tt.want != nil && data.Value != nil { - if int64(*data.Value) != *tt.want { - t.Errorf("Expected %v, got %v", *tt.want, int64(*data.Value)) - } - } - } - }) - } -} - -func floatPtr(f float64) *float64 { - return &f -} - -func int64Ptr(i int64) *int64 { - return &i -} - -func float64Ptr(f float64) *float64 { - return &f -} - -func TestFloat64StringWithDash_UnmarshalJSON(t *testing.T) { - tests := []struct { - name string - input string - want *float64 - wantInt *int64 - }{ - {name: "number", input: `123.45`, want: float64Ptr(123.45), wantInt: int64Ptr(123)}, - {name: "numeric string", input: `"678.9"`, want: float64Ptr(678.9), wantInt: int64Ptr(678)}, - {name: "empty string", input: `""`, want: nil, wantInt: nil}, - {name: "dash", input: `"-"`, want: nil, wantInt: nil}, - {name: "null", input: `null`, want: nil, wantInt: nil}, - } - - for _, tt := range tests { - t.Run(tt.name, func(t *testing.T) { - var f Float64StringWithDash - if err := json.Unmarshal([]byte(tt.input), &f); err != nil { - t.Fatalf("UnmarshalJSON(%s) error = %v", tt.input, err) - } - - got := f.ToFloat64Ptr() - if (got == nil) != (tt.want == nil) || (got != nil && *got != *tt.want) { - t.Errorf("ToFloat64Ptr() = %v, want %v", got, tt.want) - } - - gotInt := f.ToInt64Ptr() - if (gotInt == nil) != (tt.wantInt == nil) || (gotInt != nil && *gotInt != *tt.wantInt) { - t.Errorf("ToInt64Ptr() = %v, want %v", gotInt, tt.wantInt) - } - }) - } -} diff --git a/types/nullable.go b/types/nullable.go new file mode 100644 index 0000000..b37a9bd --- /dev/null +++ b/types/nullable.go @@ -0,0 +1,187 @@ +package types + +import ( + "encoding/json" + "fmt" + "math/big" + "strconv" +) + +// NullableValue はNullableが保持できる値の型集合です。 +type NullableValue interface { + float64 | int64 | string +} + +// Nullable はJ-Quants APIの「値が存在しない可能性のあるフィールド」を表します。 +// APIはエンドポイントによって欠損を null・空文字(非設定)・"-"(未定)で表現し、 +// 数値を数値型と文字列型の両方で返すため、それらすべてを単一の型で受けます。 +// +// - JSON値(数値・文字列): 値として保持 +// - 数値の文字列("678.9"): 数値型ではパースして保持 +// - null / ""(非設定) / "*"(該当なし。例: ETFの上場比): 値なし +// - "-"(未定): 値なし、IsUndetermined() が true +type Nullable[T NullableValue] struct { + value *T + undetermined bool +} + +// NewNullable は値を持つNullableを作成します。 +func NewNullable[T NullableValue](v T) Nullable[T] { + return Nullable[T]{value: &v} +} + +// NewUndetermined は「未定(-)」を表すNullableを作成します。 +func NewUndetermined[T NullableValue]() Nullable[T] { + return Nullable[T]{undetermined: true} +} + +// Get は値と、値が存在するかどうかを返します。 +func (n Nullable[T]) Get() (T, bool) { + if n.value == nil { + var zero T + return zero, false + } + return *n.value, true +} + +// Ptr は値のコピーへのポインタを返します。値が存在しない場合はnilです。 +func (n Nullable[T]) Ptr() *T { + if n.value == nil { + return nil + } + v := *n.value + return &v +} + +// Or は値を返します。値が存在しない場合はdefを返します。 +func (n Nullable[T]) Or(def T) T { + if n.value == nil { + return def + } + return *n.value +} + +// IsUndetermined は元の値が「未定(-)」だったかどうかを返します。 +// 「非設定(空文字・null)」との区別に使用します。どちらの場合も値は存在しません。 +func (n Nullable[T]) IsUndetermined() bool { + return n.undetermined +} + +// UnmarshalJSON implements json.Unmarshaler. +func (n *Nullable[T]) UnmarshalJSON(data []byte) error { + n.value = nil + n.undetermined = false + + if string(data) == "null" { + return nil + } + + // 文字列は特別扱い: "" は非設定、"*" は該当なし、"-" は未定、 + // 数値型では数値文字列を受ける + var s string + if err := json.Unmarshal(data, &s); err == nil { + switch s { + case "", "*": + return nil + case "-": + n.undetermined = true + return nil + } + v, err := valueFromString[T](s) + if err != nil { + return err + } + n.value = &v + return nil + } + + var v T + if err := json.Unmarshal(data, &v); err != nil { + // int64はJSON上小数・指数表現(例: 123.0, 1.23e5)で届くことがある + if p, ok := any(&v).(*int64); ok { + var f float64 + if err2 := json.Unmarshal(data, &f); err2 == nil { + // 数値であることを確認済み。値の評価はfloat64の丸めを避けて + // 元のテキストから厳密に行う + i, err3 := int64FromNumericText(string(data)) + if err3 != nil { + return err3 + } + *p = i + n.value = &v + return nil + } + } + return err + } + n.value = &v + return nil +} + +// MarshalJSON implements json.Marshaler. +// 値なしはnull、未定は"-"として出力します。 +func (n Nullable[T]) MarshalJSON() ([]byte, error) { + if n.undetermined { + return json.Marshal("-") + } + if n.value == nil { + return []byte("null"), nil + } + return json.Marshal(*n.value) +} + +func valueFromString[T NullableValue](s string) (T, error) { + var v T + switch p := any(&v).(type) { + case *string: + *p = s + case *float64: + f, err := strconv.ParseFloat(s, 64) + if err != nil { + return v, err + } + *p = f + case *int64: + // 数値文法の検証はfloat64パースで行い、値の評価は丸め誤差を避けるため + // 元のテキストから厳密に行う + if _, err := strconv.ParseFloat(s, 64); err != nil { + return v, err + } + i, err := int64FromNumericText(s) + if err != nil { + return v, err + } + *p = i + } + return v, nil +} + +// int64FromNumericText は10進の数値テキスト(整数・小数・指数表記)を +// 丸め誤差なくint64へ変換します。float64を経由すると2^53を超える整数で +// 精度が失われるため、big.Ratで元のテキストを厳密に評価します。 +// 非整数値やint64で表現できない値はエラーになります。 +func int64FromNumericText(s string) (int64, error) { + if i, err := strconv.ParseInt(s, 10, 64); err == nil { + return i, nil + } + r, ok := new(big.Rat).SetString(s) + if !ok { + return 0, fmt.Errorf("invalid numeric value %q", s) + } + if !r.IsInt() { + return 0, fmt.Errorf("value %q is not an integer", s) + } + if !r.Num().IsInt64() { + return 0, fmt.Errorf("value %q overflows int64", s) + } + return r.Num().Int64(), nil +} + +// NullableFloat64 は欠損しうるfloat64値です。 +type NullableFloat64 = Nullable[float64] + +// NullableInt64 は欠損しうるint64値です。 +type NullableInt64 = Nullable[int64] + +// NullableString は欠損しうるstring値です。 +type NullableString = Nullable[string] diff --git a/types/nullable_test.go b/types/nullable_test.go new file mode 100644 index 0000000..3d5205f --- /dev/null +++ b/types/nullable_test.go @@ -0,0 +1,205 @@ +package types + +import ( + "encoding/json" + "testing" +) + +func TestNullableFloat64_UnmarshalJSON(t *testing.T) { + tests := []struct { + name string + input string + want *float64 + wantUndetermined bool + wantErr bool + }{ + {name: "number", input: `123.45`, want: float64Ptr(123.45)}, + {name: "numeric string", input: `"678.9"`, want: float64Ptr(678.9)}, + {name: "empty string", input: `""`, want: nil}, + {name: "asterisk", input: `"*"`, want: nil}, + {name: "dash", input: `"-"`, want: nil, wantUndetermined: true}, + {name: "null", input: `null`, want: nil}, + {name: "invalid string", input: `"abc"`, wantErr: true}, + } + + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + var n NullableFloat64 + err := json.Unmarshal([]byte(tt.input), &n) + if (err != nil) != tt.wantErr { + t.Fatalf("UnmarshalJSON(%s) error = %v, wantErr %v", tt.input, err, tt.wantErr) + } + if tt.wantErr { + return + } + + got := n.Ptr() + if (got == nil) != (tt.want == nil) || (got != nil && *got != *tt.want) { + t.Errorf("Ptr() = %v, want %v", got, tt.want) + } + if n.IsUndetermined() != tt.wantUndetermined { + t.Errorf("IsUndetermined() = %v, want %v", n.IsUndetermined(), tt.wantUndetermined) + } + }) + } +} + +func TestNullableInt64_UnmarshalJSON(t *testing.T) { + tests := []struct { + name string + input string + want *int64 + wantErr bool + }{ + {name: "integer", input: `62000000`, want: int64Ptr(62000000)}, + {name: "decimal number", input: `123.0`, want: int64Ptr(123)}, + {name: "numeric string", input: `"456"`, want: int64Ptr(456)}, + {name: "empty string", input: `""`, want: nil}, + {name: "dash", input: `"-"`, want: nil}, + {name: "null", input: `null`, want: nil}, + // float64の仮数部(2^53)を超える整数も、小数・指数表記を含め正確にパースされること + {name: "large integer string", input: `"9007199254740993"`, want: int64Ptr(9007199254740993)}, + {name: "large integer number", input: `9007199254740993`, want: int64Ptr(9007199254740993)}, + {name: "large integer decimal string", input: `"9007199254740993.0"`, want: int64Ptr(9007199254740993)}, + {name: "large integer decimal number", input: `9007199254740993.0`, want: int64Ptr(9007199254740993)}, + {name: "large integer exponent number", input: `9.007199254740993e15`, want: int64Ptr(9007199254740993)}, + {name: "min int64 string", input: `"-9223372036854775808"`, want: int64Ptr(-9223372036854775808)}, + // 表現できない値はサイレントに壊れずエラーになること + {name: "overflow string", input: `"92233720368547758070"`, wantErr: true}, + {name: "overflow number", input: `92233720368547758070.0`, wantErr: true}, + {name: "below min int64 string", input: `"-9223372036854775809"`, wantErr: true}, + {name: "non-integral string", input: `"123.5"`, wantErr: true}, + {name: "non-integral number", input: `123.5`, wantErr: true}, + } + + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + var n NullableInt64 + err := json.Unmarshal([]byte(tt.input), &n) + if (err != nil) != tt.wantErr { + t.Fatalf("UnmarshalJSON(%s) error = %v, wantErr %v", tt.input, err, tt.wantErr) + } + if tt.wantErr { + return + } + got := n.Ptr() + if (got == nil) != (tt.want == nil) || (got != nil && *got != *tt.want) { + t.Errorf("Ptr() = %v, want %v", got, tt.want) + } + }) + } +} + +func TestNullableString_UnmarshalJSON(t *testing.T) { + tests := []struct { + name string + input string + want *string + wantUndetermined bool + }{ + {name: "string", input: `"2024-03-31"`, want: strPtr("2024-03-31")}, + {name: "empty string", input: `""`, want: nil}, + {name: "dash", input: `"-"`, want: nil, wantUndetermined: true}, + {name: "null", input: `null`, want: nil}, + } + + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + var n NullableString + if err := json.Unmarshal([]byte(tt.input), &n); err != nil { + t.Fatalf("UnmarshalJSON(%s) error = %v", tt.input, err) + } + got := n.Ptr() + if (got == nil) != (tt.want == nil) || (got != nil && *got != *tt.want) { + t.Errorf("Ptr() = %v, want %v", got, tt.want) + } + if n.IsUndetermined() != tt.wantUndetermined { + t.Errorf("IsUndetermined() = %v, want %v", n.IsUndetermined(), tt.wantUndetermined) + } + }) + } +} + +func TestNullable_MarshalJSON(t *testing.T) { + tests := []struct { + name string + value NullableFloat64 + want string + }{ + {name: "value", value: NewNullable(12.5), want: `12.5`}, + {name: "absent", value: NullableFloat64{}, want: `null`}, + {name: "undetermined", value: NewUndetermined[float64](), want: `"-"`}, + } + + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + got, err := json.Marshal(tt.value) + if err != nil { + t.Fatalf("MarshalJSON() error = %v", err) + } + if string(got) != tt.want { + t.Errorf("MarshalJSON() = %s, want %s", got, tt.want) + } + }) + } +} + +func TestNullable_RoundTrip(t *testing.T) { + // unmarshal -> marshal -> unmarshal で意味が保存されること + for _, input := range []string{`123.45`, `null`, `"-"`} { + var n1 NullableFloat64 + if err := json.Unmarshal([]byte(input), &n1); err != nil { + t.Fatalf("first unmarshal(%s): %v", input, err) + } + data, err := json.Marshal(n1) + if err != nil { + t.Fatalf("marshal(%s): %v", input, err) + } + var n2 NullableFloat64 + if err := json.Unmarshal(data, &n2); err != nil { + t.Fatalf("second unmarshal(%s): %v", input, err) + } + p1, p2 := n1.Ptr(), n2.Ptr() + if (p1 == nil) != (p2 == nil) || (p1 != nil && *p1 != *p2) || n1.IsUndetermined() != n2.IsUndetermined() { + t.Errorf("round trip changed meaning for %s: %v/%v -> %v/%v", + input, p1, n1.IsUndetermined(), p2, n2.IsUndetermined()) + } + } +} + +func TestNullable_Accessors(t *testing.T) { + n := NewNullable(42.0) + if v, ok := n.Get(); !ok || v != 42.0 { + t.Errorf("Get() = %v, %v; want 42.0, true", v, ok) + } + if n.Or(0) != 42.0 { + t.Errorf("Or(0) = %v, want 42.0", n.Or(0)) + } + + var absent NullableFloat64 + if _, ok := absent.Get(); ok { + t.Error("Get() on absent value should return ok=false") + } + if absent.Or(99.9) != 99.9 { + t.Errorf("Or(99.9) = %v, want 99.9", absent.Or(99.9)) + } + + // Ptr はコピーを返すため、書き換えても内部状態に影響しない + p := n.Ptr() + *p = 0 + if v, _ := n.Get(); v != 42.0 { + t.Errorf("mutating Ptr() result changed internal value: %v", v) + } +} + +func strPtr(s string) *string { + return &s +} + +func float64Ptr(f float64) *float64 { + return &f +} + +func int64Ptr(i int64) *int64 { + return &i +} diff --git a/weekly_margin_interest.go b/weekly_margin_interest.go index 514fafb..9277092 100644 --- a/weekly_margin_interest.go +++ b/weekly_margin_interest.go @@ -68,14 +68,14 @@ type RawWeeklyMarginInterest struct { IssType string `json:"IssType"` // 信用取引残高(売建) - ShrtVol types.Float64String `json:"ShrtVol"` - ShrtNegVol types.Float64String `json:"ShrtNegVol"` - ShrtStdVol types.Float64String `json:"ShrtStdVol"` + ShrtVol types.NullableFloat64 `json:"ShrtVol"` + ShrtNegVol types.NullableFloat64 `json:"ShrtNegVol"` + ShrtStdVol types.NullableFloat64 `json:"ShrtStdVol"` // 信用取引残高(買建) - LongVol types.Float64String `json:"LongVol"` - LongNegVol types.Float64String `json:"LongNegVol"` - LongStdVol types.Float64String `json:"LongStdVol"` + LongVol types.NullableFloat64 `json:"LongVol"` + LongNegVol types.NullableFloat64 `json:"LongNegVol"` + LongStdVol types.NullableFloat64 `json:"LongStdVol"` } // UnmarshalJSON implements custom JSON unmarshaling for WeeklyMarginInterestResponse @@ -104,14 +104,14 @@ func (r *WeeklyMarginInterestResponse) UnmarshalJSON(data []byte) error { IssType: rm.IssType, // 信用取引残高(売建) - ShrtVol: float64(rm.ShrtVol), - ShrtNegVol: float64(rm.ShrtNegVol), - ShrtStdVol: float64(rm.ShrtStdVol), + ShrtVol: rm.ShrtVol.Or(0), + ShrtNegVol: rm.ShrtNegVol.Or(0), + ShrtStdVol: rm.ShrtStdVol.Or(0), // 信用取引残高(買建) - LongVol: float64(rm.LongVol), - LongNegVol: float64(rm.LongNegVol), - LongStdVol: float64(rm.LongStdVol), + LongVol: rm.LongVol.Or(0), + LongNegVol: rm.LongNegVol.Or(0), + LongStdVol: rm.LongStdVol.Or(0), } }