sec

package module
v0.1.0 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Jun 5, 2026 License: MIT Imports: 14 Imported by: 0

README

SEC-Go

Go Reference Go Report Card

Go client library for the Thailand SEC OpenAPI V2 (api.sec.or.th).

Installation

go get github.com/jwitmann/sec-go

Quick Start

package main

import (
    "context"
    "fmt"
    "log"
    "os"

    sec "github.com/jwitmann/sec-go"
)

func main() {
    client, err := sec.NewClient(os.Getenv("SEC_API_KEY"))
    if err != nil {
        log.Fatal(err)
    }

    ctx := context.Background()
    amcs, _, err := client.ListAMCs(ctx, 10, "")
    if err != nil {
        log.Fatal(err)
    }
    for _, amc := range amcs {
        fmt.Println(amc.CompNameEN)
    }
}

Authentication

Pass your API key directly to the constructor:

client, err := sec.NewClient("your-api-key")

Or use the environment variable helper:

client, err := sec.ClientFromEnv() // reads SEC_API_KEY

For primary/secondary key support:

client, err := sec.NewClient(
    "primary-key",
    sec.WithSecondaryKey("secondary-key"),
)

client.UseSecondaryKey() // switch to secondary key
client.UsePrimaryKey()   // switch back to primary key

Configuration Options

client, err := sec.NewClient(
    "your-api-key",
    sec.WithTimeout(60*time.Second),
    sec.WithMaxRetries(5),
    sec.WithRetryDelay(200*time.Millisecond),
    sec.WithBaseURL("https://custom.api.sec.or.th"),
    sec.WithCache(cache, 5*time.Minute),
    sec.WithLogger(log.New(os.Stdout, "[sec] ", log.LstdFlags)),
    sec.WithRequestHook(func(req *http.Request) {
        // e.g., add tracing headers
    }),
    sec.WithResponseHook(func(req *http.Request, resp *http.Response, err error) {
        // e.g., record metrics
    }),
    sec.WithLanguage(sec.LanguageThai),
)

Supported Endpoints

General Info
  • ListAMCs/v2/fund/general-info/amcs
  • GetFundProfiles/v2/fund/general-info/profiles
  • GetFundSpecifications/v2/fund/general-info/specifications
  • GetMutualFundFees/v2/fund/general-info/mutual-fund-fees
  • GetFundInvolveParties/v2/fund/general-info/involve-parties
Daily Info
  • GetDailyNAV/v2/fund/daily-info/nav
  • GetDividendHistory/v2/fund/daily-info/dividend-history
Factsheet
  • GetFactsheetFees/v2/fund/factsheet/fees
  • GetFactsheetPerformance/v2/fund/factsheet/performance
  • GetFactsheetSubscriptionRedemptionMinimums/v2/fund/factsheet/subscription-redemption-minimums
  • GetFactsheetSubscriptionRedemptionPeriods/v2/fund/factsheet/subscription-redemption-periods
  • GetFactsheetStatistics/v2/fund/factsheet/statistics
  • GetFactsheetDividendPolicy/v2/fund/factsheet/dividend-policy
  • GetFactsheetBenchmarks/v2/fund/factsheet/benchmarks
  • GetFundFactsheetURLs/v2/fund/factsheet/urls
  • GetFundIPOs/v2/fund/factsheet/ipos
  • GetAssetAllocation/v2/fund/factsheet/asset-allocation
  • GetRiskSpectrum/v2/fund/factsheet/risk-spectrum
  • GetTop5Holdings/v2/fund/factsheet/top5-holdings
Outstanding
  • GetQuarterlyPortfolio/v2/fund/outstanding/portfolio
  • GetMonthlyPortfolioAssetType/v2/fund/outstanding/portfolio-asset-type

All endpoints return paginated results: ([]T, nextCursor, error). Use FetchAllPages to automatically traverse cursors.

Convenience Helpers

Search by Company or Name
// Get all funds managed by an AMC
profiles, err := client.GetFundsByCompany(ctx, "Krungthai Asset Management")

// Search across fund IDs, Thai names, English names, and abbreviations
profiles, err := client.SearchFunds(ctx, "alpha")

// Find an AMC by Thai/English name or unique ID
amc, err := client.FindAMC(ctx, "กรุงศรี")
Single-Fund Lookups
profile, err := client.GetFundProfile(ctx, "KT-Alpha")
nav, err := client.GetFundLatestNAV(ctx, "KT-Alpha")
rs, err := client.GetFundRiskSpectrum(ctx, "KT-Alpha")
fees, err := client.GetFundFactsheetFees(ctx, "KT-Alpha")
allocation, err := client.GetFundAssetAllocation(ctx, "KT-Alpha")
holdings, err := client.GetFundTop5Holdings(ctx, "KT-Alpha")
Unified Portfolio View

Fetches asset allocation, top 5 holdings, quarterly portfolio, and monthly asset breakdown concurrently:

portfolio, err := client.GetFundPortfolio(ctx, "KT-Alpha")
fmt.Println("Asset allocation:", portfolio.AssetAllocation)
fmt.Println("Top 5 holdings:", portfolio.Top5Holdings)
fmt.Println("Quarterly portfolio:", portfolio.QuarterlyPortfolio)
fmt.Println("Monthly asset breakdown:", portfolio.MonthlyAssetBreakdown)

Pagination

navs, err := sec.FetchAllPages(func(ctx context.Context, cursor string) ([]sec.DailyNAV, string, error) {
    return client.GetDailyNAV(ctx, sec.NAVOptions{
        ProjID:    "PRINCIPALi9",
        StartDate: start,
        EndDate:   end,
        Cursor:    cursor,
    })
})

Batch Operations

Fetch NAV history for multiple funds concurrently with built-in rate limiting:

results := sec.BatchGetNAVs(ctx, client, projIDs, startDate, endDate, sec.BatchNAVOptions{
    Concurrency: 4,
    Progress: func(completed, total int) {
        fmt.Printf("Progress: %d/%d\n", completed, total)
    },
})

for _, r := range results {
    if r.Err != nil {
        log.Printf("%s failed: %v", r.ProjID, r.Err)
        continue
    }
    fmt.Printf("%s: %d NAV records\n", r.ProjID, len(r.NAVs))
}

DateTime Handling

The SEC API returns datetime values in inconsistent formats (e.g., 2026-06-05T15:15:20.9 with fractional seconds but no timezone). The library uses a custom sec.DateTime type that transparently parses RFC3339, fractional-second timestamps, and plain dates (YYYY-MM-DD). You can use .Time() to get a standard time.Time value:

fmt.Println(amc.LastUpdDate.Time())

Rate Limiting

The client enforces a minimum 16ms delay between requests to comply with SEC's rate limits (5,000 calls per 300 seconds). The rate limiter is thread-safe and respects context cancellation.

Error Handling

var (
    sec.ErrRateLimited  // HTTP 429
    sec.ErrNotFound     // HTTP 204
    sec.ErrUnauthorized // HTTP 401 / missing API key
)

Retry behavior:

  • Retries on: 429, 500, 502, 503, 504, network errors
  • Does not retry on: 400, 401, 403, 404
  • Special handling for HTTP 421 with Retry-After header

Language Support

The SEC API returns bilingual fields (e.g., proj_name_th + proj_name_en) and some Thai-only fields. Use WithLanguage to set a client-wide preference, then use helper methods to pick the right value:

client, err := sec.NewClient("key", sec.WithLanguage(sec.LanguageThai))

profile := profiles[0]
fmt.Println(profile.Name(client.Language()))      // Thai or English fund name
fmt.Println(profile.CompanyName(client.Language())) // Thai or English AMC name

For Thai-only fields, use translation helpers (similar to finnomena-go):

fees, _, _ := client.GetMutualFundFees(ctx, sec.FeeOptions{})
sec.TranslateAllFees(fees, true) // true = use English

for _, fee := range fees {
    fmt.Println(fee.FeeTypeDesc) // "Management Fee" instead of "ค่าธรรมเนียมการจัดการ"
}

Supported translations:

  • TranslateFee / TranslateAllFees — fee types and units
  • TranslateFactsheetFee / TranslateAllFactsheetFees
  • TranslateAssetAllocation / TranslateAllAssetAllocations
  • TranslateTop5Holding / TranslateAllTop5Holdings
  • TranslateQuarterlyPortfolio / TranslateAllQuarterlyPortfolios
  • TranslateMonthlyPortfolioAssetType / TranslateAllMonthlyPortfolioAssetTypes

Extend the public FeeTypeTranslation, FeeUnitTranslation, AssetNameTranslation, and AssetLiabilityTranslation maps to add more translations as you discover them.

CLI Tool

A command-line tool is included for ad-hoc API queries:

go run ./cmd/sec-cli amcs
go run ./cmd/sec-cli profiles --company-info C0000000021
go run ./cmd/sec-cli nav --proj-id M0000_2552 --start 2024-01-01 --end 2024-01-31
go run ./cmd/sec-cli benchmarks --proj-id M0000_2552 --latest
go run ./cmd/sec-cli factsheet-urls --proj-id M0000_2552

The CLI reads API keys from config/sec-keys.json or falls back to the SEC_API_KEY environment variable.

Examples

See examples/:

  • examples/basic/ — list AMCs and get NAV
  • examples/batch/ — fetch NAV history for multiple funds
  • examples/thaifa/ — THAIFA fallback integration pattern

Testing

Run unit tests:

make test

Run all checks (format, lint, test, duplicate code):

make check

For integration tests (requires real API key in config/sec-keys.json):

make test-integration

Project Structure

sec-go/
├── client.go              # Core HTTP client
├── options.go             # Functional options
├── error.go               # Error types
├── rate.go                # Rate limiter
├── retry.go               # Retry logic
├── fund_service.go        # Fund API service methods (all 21 endpoints)
├── models.go              # V2 response models (includes flexible DateTime parsing)
├── pagination.go          # Pagination helpers
├── batch.go               # Batch/concurrent operations
├── language.go            # Language preference + Thai↔English translation helpers
├── helpers_fund.go        # Convenience helpers: SearchFunds, GetFundsByCompany, etc.
├── client_test.go         # Client unit tests
├── fund_service_test.go   # Service method tests
├── pagination_test.go     # Pagination tests
├── batch_test.go          # Batch operation tests
├── language_test.go       # Language/translation tests
├── helpers_fund_test.go   # Convenience helper tests
├── integration_test.go    # Real API integration tests
├── internal/
│   ├── cache/             # In-memory cache
│   └── testutil/          # Test helpers
├── config/
│   └── sec-keys.example.json  # API key config template
├── cmd/
│   ├── sec-cli/           # CLI tool for ad-hoc queries
│   └── sec-lookup/        # Debug tool for fund lookups
├── docs/
│   └── v2-schemas/        # Sample responses + API.md
├── examples/              # Usage examples
└── Makefile               # Build tasks

License

MIT

Documentation

Index

Constants

This section is empty.

Variables

View Source
var (
	ErrRateLimited  = errors.New("rate limited")
	ErrNotFound     = errors.New("data not found")
	ErrUnauthorized = errors.New("invalid API key")
)
View Source
var AssetLiabilityTranslation = map[string]string{
	"ตั๋วเงินคลัง (Treasury Bill)": "Treasury Bill",
	"ตั๋วเงินคลัง":                 "Treasury Bill",
	"พันธบัตรรัฐบาล":               "Government Bond",
	"เงินฝากธนาคาร":                "Bank Deposit",
	"หุ้นสามัญ":                    "Common Stock",
}

AssetLiabilityTranslation maps common Thai asset/liability category descriptions to English.

View Source
var AssetNameTranslation = map[string]string{
	"หน่วยลงทุน":             "Investment Units",
	"เงินฝากธนาคาร และอื่นๆ": "Bank Deposits and Others",
	"ตราสารหนี้":             "Debt Instruments",
	"หุ้นสามัญ":              "Common Stocks",
	"ทรัพย์สินอื่นๆ":         "Other Assets",
	"เงินสด":                 "Cash",
}

AssetNameTranslation maps common Thai asset type names to English.

View Source
var FeeTypeTranslation = map[string]string{
	"ค่าธรรมเนียมการจัดการ":                                  "Management Fee",
	"ค่าธรรมเนียมผู้ดูแลผลประโยชน์":                          "Trustee Fee",
	"ค่าธรรมเนียมนายทะเบียนหน่วย":                            "Registrar Fee",
	"ค่าธรรมเนียมการขายหน่วยลงทุน (Front-end Fee)":           "Front-end Fee",
	"ค่าธรรมเนียมการรับซื้อคืนหน่วยลงทุน (Back-end Fee)":     "Back-end Fee",
	"ค่าธรรมเนียมการสับเปลี่ยนหน่วยลงทุนเข้า (SWITCHING IN)": "Switch-in Fee",
	"ค่าธรรมเนียมการสับเปลี่ยนหน่วยลงทุนออก (SWITCHING OUT)": "Switch-out Fee",
	"ค่าธรรมเนียมการโอนหน่วยลงทุน":                           "Transfer Fee",
	"ค่าใช้จ่ายอื่นๆ":                                        "Other Fee",
	"ค่าธรรมเนียมและค่าใช้จ่ายรวมทั้งหมด":                    "Total Expense Ratio",
}

FeeTypeTranslation maps Thai fee type descriptions to English. Extend this map for additional fee descriptions returned by the SEC API.

View Source
var FeeUnitTranslation = map[string]string{
	"ต่อปี ของมูลค่าทรัพย์สินสุทธิของกองทุน": "per year of NAV",
	"% ต่อปี": "% per year",
	"บาท":     "baht",
}

FeeUnitTranslation maps Thai fee unit descriptions to English.

Functions

func FetchAllPages

func FetchAllPages[T any](ctx context.Context, fetch func(ctx context.Context, cursor string) ([]T, string, error)) ([]T, error)

func IsRetryable

func IsRetryable(statusCode int) bool

func TranslateAllAssetAllocations

func TranslateAllAssetAllocations(allocs []AssetAllocation, useEnglish bool)

TranslateAllAssetAllocations translates every allocation in the slice when useEnglish is true.

func TranslateAllFactsheetFees

func TranslateAllFactsheetFees(fees []FactsheetFee, useEnglish bool)

TranslateAllFactsheetFees translates every factsheet fee in the slice when useEnglish is true.

func TranslateAllFees

func TranslateAllFees(fees []MutualFundFee, useEnglish bool)

TranslateAllFees translates every fee in the slice when useEnglish is true.

func TranslateAllMonthlyPortfolioAssetTypes

func TranslateAllMonthlyPortfolioAssetTypes(items []MonthlyPortfolioAssetType, useEnglish bool)

TranslateAllMonthlyPortfolioAssetTypes translates every portfolio item in the slice when useEnglish is true.

func TranslateAllQuarterlyPortfolios

func TranslateAllQuarterlyPortfolios(items []QuarterlyPortfolio, useEnglish bool)

TranslateAllQuarterlyPortfolios translates every portfolio item in the slice when useEnglish is true.

func TranslateAllTop5Holdings

func TranslateAllTop5Holdings(holdings []Top5Holding, useEnglish bool)

TranslateAllTop5Holdings translates every holding in the slice when useEnglish is true.

func TranslateAssetAllocation

func TranslateAssetAllocation(alloc *AssetAllocation, useEnglish bool)

TranslateAssetAllocation translates the Thai asset name on an AssetAllocation to English when useEnglish is true. It mutates the provided allocation in place.

func TranslateFactsheetFee

func TranslateFactsheetFee(fee *FactsheetFee, useEnglish bool)

TranslateFactsheetFee translates Thai fee descriptions on a FactsheetFee to English when useEnglish is true. It mutates the provided fee in place.

func TranslateFee

func TranslateFee(fee *MutualFundFee, useEnglish bool)

TranslateFee translates Thai fee descriptions on a MutualFundFee to English when useEnglish is true. It mutates the provided fee in place.

func TranslateMonthlyPortfolioAssetType

func TranslateMonthlyPortfolioAssetType(item *MonthlyPortfolioAssetType, useEnglish bool)

TranslateMonthlyPortfolioAssetType translates Thai asset/liability descriptions on a MonthlyPortfolioAssetType to English when useEnglish is true.

func TranslateQuarterlyPortfolio

func TranslateQuarterlyPortfolio(item *QuarterlyPortfolio, useEnglish bool)

TranslateQuarterlyPortfolio translates Thai asset/liability descriptions on a QuarterlyPortfolio to English when useEnglish is true.

func TranslateTop5Holding

func TranslateTop5Holding(holding *Top5Holding, useEnglish bool)

TranslateTop5Holding translates the Thai asset name on a Top5Holding to English when useEnglish is true. It mutates the provided holding in place.

Types

type AMC

type AMC struct {
	UniqueID    string   `json:"unique_id"`
	CompNameTH  string   `json:"comp_name_th"`
	CompNameEN  string   `json:"comp_name_en"`
	LastUpdDate DateTime `json:"last_upd_date"`
}

func (AMC) Name

func (a AMC) Name(lang Language) string

Name returns the company name in the client's preferred language. Falls back to the other language if the preferred one is empty.

type APIError

type APIError struct {
	StatusCode int
	Message    string
	RawBody    []byte
}

func (*APIError) Error

func (e *APIError) Error() string

type AssetAllocation

type AssetAllocation struct {
	ProjID         string   `json:"proj_id"`
	StartDate      string   `json:"start_date"`
	EndDate        string   `json:"end_date"`
	ProspectusType string   `json:"prospectus_type"`
	AssetSeq       int      `json:"asset_seq"`
	AssetName      string   `json:"asset_name"`
	AssetRatio     float64  `json:"asset_ratio"`
	LastUpdDate    DateTime `json:"last_upd_date"`
}

type BatchFundProfileResult

type BatchFundProfileResult struct {
	ProjID  string
	Profile *FundProfile
	Err     error
}

func BatchGetFundProfiles

func BatchGetFundProfiles(ctx context.Context, c *Client, projIDs []string, opts BatchProfileOptions) []BatchFundProfileResult

type BatchNAVOptions

type BatchNAVOptions struct {
	Concurrency int
	Progress    func(completed, total int)
}

type BatchNAVResult

type BatchNAVResult struct {
	ProjID string
	NAVs   []DailyNAV
	Err    error
}

func BatchGetNAVs

func BatchGetNAVs(ctx context.Context, c *Client, projIDs []string, startDate, endDate time.Time, opts BatchNAVOptions) []BatchNAVResult

type BatchProfileOptions

type BatchProfileOptions struct {
	Concurrency int
	Progress    func(completed, total int)
}

type Client

type Client struct {
	// contains filtered or unexported fields
}

func ClientFromEnv

func ClientFromEnv(opts ...Option) (*Client, error)

func NewClient

func NewClient(apiKey string, opts ...Option) (*Client, error)

func (*Client) FindAMC

func (c *Client) FindAMC(ctx context.Context, query string) (*AMC, error)

FindAMC searches AMCs by Thai name, English name, or unique_id.

func (*Client) Get

func (c *Client) Get(ctx context.Context, path string) ([]byte, error)

func (*Client) GetAssetAllocation

func (c *Client) GetAssetAllocation(ctx context.Context, opts FactsheetOptions) ([]AssetAllocation, string, error)

func (*Client) GetDailyNAV

func (c *Client) GetDailyNAV(ctx context.Context, opts NAVOptions) ([]DailyNAV, string, error)

func (*Client) GetDividendHistory

func (c *Client) GetDividendHistory(ctx context.Context, opts DividendHistoryOptions) ([]DividendHistory, string, error)

func (*Client) GetFactsheetBenchmarks

func (c *Client) GetFactsheetBenchmarks(ctx context.Context, opts FactsheetOptions) ([]FactsheetBenchmark, string, error)

func (*Client) GetFactsheetDividendPolicy

func (c *Client) GetFactsheetDividendPolicy(ctx context.Context, opts FactsheetOptions) ([]FundDividendPolicy, string, error)

func (*Client) GetFactsheetFees

func (c *Client) GetFactsheetFees(ctx context.Context, opts FactsheetOptions) ([]FactsheetFee, string, error)

func (*Client) GetFactsheetPerformance

func (c *Client) GetFactsheetPerformance(ctx context.Context, opts FactsheetOptions) ([]FactsheetPerformance, string, error)

func (*Client) GetFactsheetStatistics

func (c *Client) GetFactsheetStatistics(ctx context.Context, opts FactsheetOptions) ([]FactsheetStatistics, string, error)

func (*Client) GetFactsheetSubscriptionRedemptionMinimums

func (c *Client) GetFactsheetSubscriptionRedemptionMinimums(ctx context.Context, opts FactsheetOptions) ([]FactsheetSubscriptionRedemptionMinimum, string, error)

func (*Client) GetFactsheetSubscriptionRedemptionPeriods

func (c *Client) GetFactsheetSubscriptionRedemptionPeriods(ctx context.Context, opts FactsheetOptions) ([]FactsheetSubscriptionRedemptionPeriod, string, error)

func (*Client) GetFundAssetAllocation

func (c *Client) GetFundAssetAllocation(ctx context.Context, projID string) ([]AssetAllocation, error)

GetFundAssetAllocation returns the latest asset allocation for a single fund.

func (*Client) GetFundFactsheetFees

func (c *Client) GetFundFactsheetFees(ctx context.Context, projID string) ([]FactsheetFee, error)

GetFundFactsheetFees returns the latest factsheet fees for a single fund.

func (*Client) GetFundFactsheetURLs

func (c *Client) GetFundFactsheetURLs(ctx context.Context, opts FeeOptions) ([]FundFactsheetURL, string, error)

func (*Client) GetFundIPOs

func (c *Client) GetFundIPOs(ctx context.Context, opts FactsheetOptions) ([]FundIPO, string, error)

func (*Client) GetFundInvolveParties

func (c *Client) GetFundInvolveParties(ctx context.Context, opts InvolvePartyOptions) ([]FundInvolveParty, string, error)

func (*Client) GetFundLatestNAV

func (c *Client) GetFundLatestNAV(ctx context.Context, projID string) (*DailyNAV, error)

GetFundLatestNAV returns the most recent NAV for a single fund.

func (*Client) GetFundPortfolio

func (c *Client) GetFundPortfolio(ctx context.Context, projID string) (*FundPortfolioView, error)

GetFundPortfolio fetches asset allocation, top 5 holdings, quarterly portfolio, and monthly asset breakdown concurrently for a single fund.

func (*Client) GetFundProfile

func (c *Client) GetFundProfile(ctx context.Context, projID string) (*FundProfile, error)

GetFundProfile returns the latest profile for a single fund.

func (*Client) GetFundProfiles

func (c *Client) GetFundProfiles(ctx context.Context, opts ProfileOptions) ([]FundProfile, string, error)

func (*Client) GetFundRiskSpectrum

func (c *Client) GetFundRiskSpectrum(ctx context.Context, projID string) (*RiskSpectrum, error)

GetFundRiskSpectrum returns the latest risk spectrum for a single fund.

func (*Client) GetFundSpecifications

func (c *Client) GetFundSpecifications(ctx context.Context, opts FeeOptions) ([]FundSpecification, string, error)

func (*Client) GetFundTop5Holdings

func (c *Client) GetFundTop5Holdings(ctx context.Context, projID string) ([]Top5Holding, error)

GetFundTop5Holdings returns the latest top 5 holdings for a single fund.

func (*Client) GetFundsByCompany

func (c *Client) GetFundsByCompany(ctx context.Context, companyName string) ([]FundProfile, error)

GetFundsByCompany returns all fund profiles for a given AMC name or unique_id.

func (*Client) GetMonthlyPortfolioAssetType

func (c *Client) GetMonthlyPortfolioAssetType(ctx context.Context, opts OutstandingOptions) ([]MonthlyPortfolioAssetType, string, error)

func (*Client) GetMutualFundFees

func (c *Client) GetMutualFundFees(ctx context.Context, opts FeeOptions) ([]MutualFundFee, string, error)

func (*Client) GetQuarterlyPortfolio

func (c *Client) GetQuarterlyPortfolio(ctx context.Context, opts OutstandingOptions) ([]QuarterlyPortfolio, string, error)

func (*Client) GetRiskSpectrum

func (c *Client) GetRiskSpectrum(ctx context.Context, opts FactsheetOptions) ([]RiskSpectrum, string, error)

func (*Client) GetTop5Holdings

func (c *Client) GetTop5Holdings(ctx context.Context, opts FactsheetOptions) ([]Top5Holding, string, error)

func (*Client) Language

func (c *Client) Language() Language

func (*Client) ListAMCs

func (c *Client) ListAMCs(ctx context.Context, pageSize int, cursor string) ([]AMC, string, error)

func (*Client) Post

func (c *Client) Post(ctx context.Context, path string, payload []byte) ([]byte, error)

func (*Client) SearchFunds

func (c *Client) SearchFunds(ctx context.Context, query string) ([]FundProfile, error)

SearchFunds searches across proj_id, proj_name_th, proj_name_en, and proj_abbr_name.

func (*Client) UsePrimaryKey

func (c *Client) UsePrimaryKey()

func (*Client) UseSecondaryKey

func (c *Client) UseSecondaryKey()

type DailyNAV

type DailyNAV struct {
	ProjID        string   `json:"proj_id"`
	UniqueID      string   `json:"unique_id"`
	FundClassName string   `json:"fund_class_name"`
	NavDate       string   `json:"nav_date"`
	NetAsset      float64  `json:"net_asset"`
	LastVal       float64  `json:"last_val"`
	SellPrice     float64  `json:"sell_price"`
	BuyPrice      float64  `json:"buy_price"`
	SellSwapPrice float64  `json:"sell_swap_price"`
	BuySwapPrice  float64  `json:"buy_swap_price"`
	LastUpdDate   DateTime `json:"last_upd_date"`
}

type DateTime

type DateTime struct {
	time.Time
}

DateTime is a flexible time.Time that parses multiple SEC datetime formats.

func (DateTime) MarshalJSON

func (dt DateTime) MarshalJSON() ([]byte, error)

func (*DateTime) UnmarshalJSON

func (dt *DateTime) UnmarshalJSON(data []byte) error

type DividendHistory

type DividendHistory struct {
	ProjID        string   `json:"proj_id"`
	UniqueID      string   `json:"unique_id"`
	ClassAbbrName string   `json:"class_abbr_name"`
	BookCloseDate string   `json:"book_close_date"`
	DividendDate  string   `json:"dividend_date"`
	DividendValue float64  `json:"dividend_value"`
	LastUpdDate   DateTime `json:"last_upd_date"`
}

type DividendHistoryOptions

type DividendHistoryOptions struct {
	PageSize      int
	Cursor        string
	ProjID        string
	StartDate     time.Time
	EndDate       time.Time
	ClassAbbrName string
}

type FactsheetBenchmark

type FactsheetBenchmark struct {
	ProjID         string   `json:"proj_id"`
	StartDate      string   `json:"start_date"`
	EndDate        string   `json:"end_date"`
	ProspectusType string   `json:"prospectus_type"`
	GroupSeq       int      `json:"group_seq"`
	Benchmark      string   `json:"benchmark"`
	Remark         string   `json:"benchmark_remark"`
	LastUpdDate    DateTime `json:"last_upd_date"`
}

type FactsheetFee

type FactsheetFee struct {
	ProjID         string   `json:"proj_id"`
	FundClassName  string   `json:"fund_class_name"`
	StartDate      string   `json:"start_date"`
	EndDate        string   `json:"end_date"`
	ProspectusType string   `json:"prospectus_type"`
	FeeTypeDesc    string   `json:"fee_type_desc"`
	Rate           float64  `json:"rate"`
	ActualValue    float64  `json:"actual_value"`
	FeeOtherDesc   string   `json:"fee_other_desc"`
	LastUpdDate    DateTime `json:"last_upd_date"`
}

type FactsheetOptions

type FactsheetOptions struct {
	PageSize      int
	Cursor        string
	ProjID        string
	StartDate     time.Time
	EndDate       time.Time
	Latest        bool
	FundClassName string
}

type FactsheetPerformance

type FactsheetPerformance struct {
	ProjID              string   `json:"proj_id"`
	FundClassName       string   `json:"fund_class_name"`
	StartDate           string   `json:"start_date"`
	EndDate             string   `json:"end_date"`
	ProspectusType      string   `json:"prospectus_type"`
	PerformanceTypeDesc string   `json:"performance_type_desc"`
	ReferencePeriod     string   `json:"reference_period"`
	PerformanceValue    float64  `json:"performance_value"`
	LastUpdDate         DateTime `json:"last_upd_date"`
}

type FactsheetStatistics

type FactsheetStatistics struct {
	ProjID                  string   `json:"proj_id"`
	FundClassName           string   `json:"fund_class_name"`
	StartDate               string   `json:"start_date"`
	EndDate                 string   `json:"end_date"`
	ProspectusType          string   `json:"prospectus_type"`
	PortfolioTurnoverRatio  string   `json:"portfolio_turnover_ratio"`
	RecoveringPeriod        string   `json:"recovering_period"`
	PortfolioDurationPeriod string   `json:"portfolio_duration_period"`
	MaximumDrawdown         string   `json:"maximum_drawdown"`
	SharpeRatio             string   `json:"sharpe_ratio"`
	Beta                    string   `json:"beta"`
	Alpha                   string   `json:"alpha"`
	FXHedging               string   `json:"fx_hedging"`
	TrackingError           string   `json:"tracking_error"`
	YieldToMaturity         string   `json:"yield_to_maturity"`
	LastUpdDate             DateTime `json:"last_upd_date"`
}

type FactsheetSubscriptionRedemptionMinimum

type FactsheetSubscriptionRedemptionMinimum struct {
	ProjID             string   `json:"proj_id"`
	FundClassName      string   `json:"fund_class_name"`
	StartDate          string   `json:"start_date"`
	EndDate            string   `json:"end_date"`
	ProspectusType     string   `json:"prospectus_type"`
	MinimumSubIPO      float64  `json:"minimum_sub_ipo"`
	MinimumSubIPOCur   string   `json:"minimum_sub_ipo_cur"`
	MinimumSub         float64  `json:"minimum_sub"`
	MinimumSubCur      string   `json:"minimum_sub_cur"`
	MinimumSubUnit     string   `json:"minimum_sub_unit"`
	MinimumRedempt     float64  `json:"minimum_redempt"`
	MinimumRedemptCur  string   `json:"minimum_redempt_cur"`
	MinimumRedemptUnit string   `json:"minimum_redempt_unit"`
	LowbalVal          float64  `json:"lowbal_val"`
	LowbalValCur       string   `json:"lowbal_val_cur"`
	LowbalUnit         string   `json:"lowbal_unit"`
	LastUpdDate        DateTime `json:"last_upd_date"`
}

type FactsheetSubscriptionRedemptionPeriod

type FactsheetSubscriptionRedemptionPeriod struct {
	ProjID           string   `json:"proj_id"`
	FundClassName    string   `json:"fund_class_name"`
	StartDate        string   `json:"start_date"`
	EndDate          string   `json:"end_date"`
	ProspectusType   string   `json:"prospectus_type"`
	Type             string   `json:"type"`
	Period           string   `json:"period"`
	RedempPeriodOth  string   `json:"redemp_period_oth"`
	SettlementPeriod string   `json:"settlement_period"`
	LastUpdDate      DateTime `json:"last_upd_date"`
}

type FeeOptions

type FeeOptions struct {
	PageSize      int
	Cursor        string
	ProjID        string
	FundClassName string
}

type FundDividendPolicy

type FundDividendPolicy struct {
	ProjID         string   `json:"proj_id"`
	FundClassName  string   `json:"fund_class_name"`
	StartDate      string   `json:"start_date"`
	EndDate        string   `json:"end_date"`
	ProspectusType string   `json:"prospectus_type"`
	DividendPolicy string   `json:"dividend_policy"`
	LastUpdDate    DateTime `json:"last_upd_date"`
}

type FundFactsheetURL

type FundFactsheetURL struct {
	ProjID          string   `json:"proj_id"`
	FundClassName   string   `json:"fund_class_name"`
	ProspectusType  string   `json:"prospectus_type"`
	AMCURLFactsheet string   `json:"amc_url_factsheet"`
	PDFFactsheet    string   `json:"pdf_factsheet"`
	AsOfDate        string   `json:"as_of_date"`
	LastUpdDate     DateTime `json:"last_upd_date"`
}

type FundIPO

type FundIPO struct {
	ProjID             string   `json:"proj_id"`
	StartDate          string   `json:"start_date"`
	EndDate            string   `json:"end_date"`
	ProspectusType     string   `json:"prospectus_type"`
	FirstSellStartDate string   `json:"first_sell_start_date"`
	FirstSellEndDate   string   `json:"first_sell_end_date"`
	LastUpdDate        DateTime `json:"last_upd_date"`
}

type FundInvolveParty

type FundInvolveParty struct {
	ProjID       string   `json:"proj_id"`
	EntityType   string   `json:"entity_type"`
	EntityNameTH string   `json:"entity_name_th"`
	EntityNameEN string   `json:"entity_name_en"`
	Address      string   `json:"address"`
	LastUpdDate  DateTime `json:"last_upd_date"`
}

func (FundInvolveParty) EntityName

func (f FundInvolveParty) EntityName(lang Language) string

EntityName returns the entity name in the client's preferred language.

type FundPortfolioView

type FundPortfolioView struct {
	ProjID                string
	AssetAllocation       []AssetAllocation
	Top5Holdings          []Top5Holding
	QuarterlyPortfolio    []QuarterlyPortfolio
	MonthlyAssetBreakdown []MonthlyPortfolioAssetType
}

FundPortfolioView aggregates the latest portfolio-related data for a single fund.

type FundProfile

type FundProfile struct {
	UniqueID                     string   `json:"unique_id"`
	CompNameTH                   string   `json:"comp_name_th"`
	CompNameEN                   string   `json:"comp_name_en"`
	ProjID                       string   `json:"proj_id"`
	RegisID                      string   `json:"regis_id"`
	InitDate                     string   `json:"init_date"`
	RegisDate                    string   `json:"regis_date"`
	CancelDate                   string   `json:"cancel_date"`
	ProjNameTH                   string   `json:"proj_name_th"`
	ProjNameEN                   string   `json:"proj_name_en"`
	ProjAbbrName                 string   `json:"proj_abbr_name"`
	FundStatus                   string   `json:"fund_status"`
	InvestCountryFlag            string   `json:"invest_country_flag"`
	ProjRetailType               string   `json:"proj_retail_type"`
	ProjTermFlag                 string   `json:"proj_term_flag"`
	ProjTermDay                  string   `json:"proj_term_day"`
	ProjTermMonth                string   `json:"proj_term_month"`
	ProjTermYear                 string   `json:"proj_term_year"`
	PolicyDesc                   string   `json:"policy_desc"`
	InvestmentPolicyDesc         string   `json:"investment_policy_desc"`
	ManagementStyle              string   `json:"management_style"`
	FeederFundMasterFund         string   `json:"feederfund_master_fund"`
	FeederFundCountry            string   `json:"feederfund_country"`
	ExchangeRateProtectionPolicy string   `json:"exchange_rate_protection_policy"`
	FundClassName                string   `json:"fund_class_name"`
	FundClassDetail              string   `json:"fund_class_detail"`
	FundClassDescription         string   `json:"fund_class_description"`
	FundClassTaxIncentiveType    string   `json:"fund_class_tax_incentive_type"`
	FundClassISINCode            string   `json:"fund_class_isin_code"`
	LastUpdDate                  DateTime `json:"last_upd_date"`
}

func (FundProfile) CompanyName

func (p FundProfile) CompanyName(lang Language) string

CompanyName returns the AMC name in the client's preferred language.

func (FundProfile) Name

func (p FundProfile) Name(lang Language) string

Name returns the fund name in the client's preferred language. Falls back to the other language if the preferred one is empty.

type FundSpecification

type FundSpecification struct {
	ProjID        string   `json:"proj_id"`
	FundClassName string   `json:"fund_class_name"`
	SpecCode      string   `json:"spec_code"`
	SpecDesc      string   `json:"spec_desc"`
	LastUpdDate   DateTime `json:"last_upd_date"`
}

type InvolvePartyOptions

type InvolvePartyOptions struct {
	PageSize   int
	Cursor     string
	ProjID     string
	EntityType string
}

type Language

type Language string

Language represents the preferred display language for bilingual fields.

const (
	LanguageThai    Language = "th"
	LanguageEnglish Language = "en"
)

type MonthlyPortfolioAssetType

type MonthlyPortfolioAssetType struct {
	ProjID        string  `json:"proj_id"`
	Period        int     `json:"period"`
	AssetliabCode string  `json:"assetliab_code"`
	AssetliabDesc string  `json:"assetliab_desc"`
	MarketValue   float64 `json:"market_value"`
	PercentNAV    float64 `json:"percent_nav"`
}

type MutualFundFee

type MutualFundFee struct {
	ProjID        string   `json:"proj_id"`
	FundClassName string   `json:"fund_class_name"`
	FeeTypeDesc   string   `json:"fee_type_desc"`
	Rate          float64  `json:"rate"`
	RateUnit      string   `json:"rate_unit"`
	FeeOtherDesc  string   `json:"fee_other_desc"`
	LastUpdDate   DateTime `json:"last_upd_date"`
}
type NAVOptions struct {
	PageSize      int
	Cursor        string
	ProjID        string
	StartDate     time.Time
	EndDate       time.Time
	FundClassName string
}

type Option

type Option func(*Client)

func WithBaseURL

func WithBaseURL(url string) Option

func WithCache

func WithCache(cache cacheClient, ttl time.Duration) Option

func WithHTTPClient

func WithHTTPClient(httpClient *http.Client) Option

func WithLanguage

func WithLanguage(lang Language) Option

func WithLogger

func WithLogger(l logger) Option

func WithMaxRetries

func WithMaxRetries(n int) Option

func WithRateLimiter

func WithRateLimiter(rl RateLimiter) Option

func WithRequestHook

func WithRequestHook(hook RequestHook) Option

func WithResponseHook

func WithResponseHook(hook ResponseHook) Option

func WithRetryDelay

func WithRetryDelay(d time.Duration) Option

func WithSecondaryKey

func WithSecondaryKey(key string) Option

func WithTimeout

func WithTimeout(d time.Duration) Option

type OutstandingOptions

type OutstandingOptions struct {
	PageSize    int
	Cursor      string
	ProjID      string
	StartPeriod string
	EndPeriod   string
}

type PaginatedResponse

type PaginatedResponse struct {
	Message    string `json:"message"`
	PageSize   int    `json:"page_size"`
	NextCursor string `json:"next_cursor"`
}

type ProfileOptions

type ProfileOptions struct {
	PageSize      int
	Cursor        string
	ProjID        string
	FundClassName string
	FundStatus    string
	ProjectInfo   string
	CompanyInfo   string
}

type QuarterlyPortfolio

type QuarterlyPortfolio struct {
	ProjID         string  `json:"proj_id"`
	Period         int     `json:"period"`
	AsOfDate       string  `json:"as_of_date"`
	AssetliabID    string  `json:"assetliab_id"`
	AssetliabDesc  string  `json:"assetliab_desc"`
	IssueCode      string  `json:"issue_code"`
	ISINCode       string  `json:"isin_code"`
	Issuer         string  `json:"issuer"`
	AssetliabValue float64 `json:"assetliab_value"`
	PercentNAV     float64 `json:"percent_nav"`
	LastUpdDate    string  `json:"last_upd_date"`
}

type RateLimiter

type RateLimiter interface {
	Wait(ctx context.Context) error
}

func NewRateLimiter

func NewRateLimiter() RateLimiter

type RequestHook

type RequestHook func(req *http.Request)

type ResponseHook

type ResponseHook func(req *http.Request, resp *http.Response, err error)

type RiskSpectrum

type RiskSpectrum struct {
	ProjID           string   `json:"proj_id"`
	StartDate        string   `json:"start_date"`
	EndDate          string   `json:"end_date"`
	ProspectusType   string   `json:"prospectus_type"`
	RiskSpectrum     string   `json:"risk_spectrum"`
	RiskSpectrumDesc string   `json:"risk_spectrum_desc"`
	LastUpdDate      DateTime `json:"last_upd_date"`
}

type Top5Holding

type Top5Holding struct {
	ProjID         string   `json:"proj_id"`
	StartDate      string   `json:"start_date"`
	EndDate        string   `json:"end_date"`
	ProspectusType string   `json:"prospectus_type"`
	AssetSeq       int      `json:"asset_seq"`
	AssetName      string   `json:"asset_name"`
	AssetRatio     float64  `json:"asset_ratio"`
	LastUpdDate    DateTime `json:"last_upd_date"`
}

Directories

Path Synopsis
cmd
sec-cli command
sec-lookup command
examples
basic command
batch command
thaifa command
internal

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL