yfin

command module
v1.2.6 Latest Latest
Warning

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

Go to latest
Published: Aug 4, 2026 License: Apache-2.0 Imports: 8 Imported by: 0

README

yfin — Yahoo Finance Client for Go

yfin 是 Yahoo Finance 與 TWSE 市場資料的 Go SDK + flat CLI。它把 upstream HTTP、decode、validation、normalization 與 optional raw cache 收斂在同一個 client boundary,讓 downstream 專案不必各自維護 transport 或 persistence。

主要用途:

  • 擷取 daily bars、snapshot quote、company info、market data 與 fundamentals。
  • 明確使用 Yahoo web scrape 補足 API 沒有提供的 profile、statistics、analysis 與 news。
  • 查詢 23 個 TWSE open-data endpoints。
  • 以固定 command manifest 執行 30 個 yfinance-compatible foundation surfaces。
  • 讓 downstream consumer 使用 yfin-owned read-through raw cache。

技術 architecture、package ownership 與 dependency rules 由 CLAUDE.md 單一擁有。

能力邊界 (Capability Boundaries)

  • pull 只支援 daily interval。
  • Root CLI 不會從 API command 隱式切換到 scrape;scrape 必須明確執行。
  • Standalone soak runner 的 auto strategy 只有 fundamentals → financials 具備等價 fallback;quotedaily-bars 沒有 scrape fallback。
  • --fx-target 只驗證 source/target currency 是否相同;yfin 目前沒有 FX rate provider,不執行跨幣別 conversion。
  • Local export 目前只支援 JSON。
  • Plain SDK DTO 使用 float64;需要 ScaledDecimal 精度時,使用 Fetch*Norm normalized surface。
  • --sessions 是 deprecated compatibility flag,沒有 runtime effect。
  • Tracing flags 保留相容性,但目前 tracer 是 no-op;Prometheus metrics 與 structured logs 仍可使用。
  • yfin 不擁有 message bus、publisher 或 protobuf emission pipeline。

安裝與首次啟動 (Install and First Run)

需求:Go 1.26.0 或相容版本。

git clone https://github.com/bizshuk/yfin.git
cd yfin

# 建立 ~/.config/yfin/data 與 ~/.config/yfin/logs;不啟動程式
./run.sh

go build -o yfin .
./yfin --help

也可以安裝到 GOBIN

go install github.com/bizshuk/yfin@latest

預設設定檔是 config/effective.yaml。完整 precedence 與 schema 請見 Configuration Reference

CLI 快速開始 (CLI Quick Start)

Daily bars
go run . pull \
  --ticker AAPL \
  --start 2026-01-01 \
  --end 2026-07-01 \
  --adjusted split_dividend

寫入 JSON:

go run . pull \
  --ticker AAPL \
  --start 2026-01-01 \
  --end 2026-07-01 \
  --out json \
  --out-dir ./out
Snapshot quote
go run . quote --tickers AAPL,MSFT
Explicit scrape
# Connectivity check
go run . scrape --check --ticker AAPL --endpoint profile --preview

# Parse multiple scrape surfaces to JSON
go run . scrape \
  --preview-json \
  --ticker AAPL \
  --endpoints key-statistics,financials,analysis,profile

# Parse news
go run . scrape --preview-news --ticker AAPL
Foundation batch
# One ticker across the shared 30-command manifest
go run . batch --ticker AAPL --max-workers 6

Batch artifacts 使用 yfin-owned atomic raw cache,預設位於 ~/.config/yfin/data/raw/

TWSE
go run . twse --help

TWSE endpoint 所需的 --date--stock--month 依 endpoint metadata 驗證;請先用 help 查看當前 registry。

Standalone soak runner

soak 不是 yfin subcommand:

go run ./cmd/soak \
  --universe-file tests/testdata/universe/soak.txt \
  --duration 10m \
  --concurrency 4 \
  --qps 1 \
  --failure-rate 0.05

詳細 strategy、failure injection 與 live acceptance boundary 請見 Soak Testing Guide

Go SDK 快速開始 (SDK Quick Start)

package main

import (
	"context"
	"fmt"
	"log"
	"time"

	"github.com/bizshuk/yfin/facade"
)

func main() {
	ctx, cancel := context.WithTimeout(context.Background(), 15*time.Second)
	defer cancel()

	client := facade.NewClient()
	quote, err := client.FetchQuote(ctx, "AAPL", "example-run")
	if err != nil {
		log.Fatal(err)
	}

	fmt.Printf("%s %.2f %s\n", quote.Symbol, quote.Price, quote.Currency)
}

常用 surface:

需求 Method
Plain daily bars FetchDailyBars
Precision-preserving daily bars FetchDailyBarsNorm
Plain quote FetchQuote
Precision-preserving quote FetchQuoteNorm
Company metadata FetchCompanyInfo
Current market state FetchMarketData
Quarterly fundamentals FetchFundamentalsQuarterly
Scraped financials DTO ScrapeFinancialsData
Scraped profile DTO ScrapeProfileData
Scraped key-statistics DTO ScrapeKeyStatisticsData
Shared foundation command FetchFoundation

Downstream cache ownership 與 constructors 請見 API Referencedownstream cache ownership

Data Flow

使用者只需選擇 API、explicit scrape、TWSE 或 cache surface;所有 transport 都由 facade client 統一建立:

CLI / downstream SDK consumer
            |
          facade
       /     |      \
 Yahoo API  scrape   TWSE
       \     |      /
       model DTO / normalization

完整 package graph 與 allowed imports 請見 CLAUDE.md

Configuration and Runtime Data

預設 runtime layout:

~/.config/yfin/
├── data/    # raw cache 與 batch artifacts
└── logs/    # PM2 / redirected process logs

run.sh 只初始化 metadata directories,可重複執行,不會啟動 CLI 或 background process。yfin 的 structured logs 預設寫到 stderr;logs/ 是 operator-owned redirection/PM2 target。

Verification

Deterministic checks:

./run_tests.sh
go vet ./...
go build ./...

Live integration 需要可連線至外部 providers,必須明確 opt in:

./run_tests.sh --live-integration

文件導覽 (Documentation)

Contributing

修改前先讀 CLAUDE.md 的 ownership 與 dependency contract。提交前至少執行:

go fmt ./...
go test ./...
go vet ./...

go test ./... 會執行 internal dependency boundary assertion。

License and Security

本專案使用 MIT License。安全問題請依 Security Policy 私下回報。

Documentation

Overview

main.go — yfin CLI composition root; wires every sub-package's `Register` onto `cmd.RootCmd` then forwards `cmd.Execute()` to the process. Exit non-zero on error.

Directories

Path Synopsis
cmd
build.go — build-time version variables injected via `-ldflags` at compile time.
build.go — build-time version variables injected via `-ldflags` at compile time.
admin
admin.go — `config` + `version` cobra subcommands grouped under one sub-package because both are admin/maintenance commands (no network I/O).
admin.go — `config` + `version` cobra subcommands grouped under one sub-package because both are admin/maintenance commands (no network I/O).
dispatch
batch.go — `batch` cobra subcommand + worker-pool driver that fans every ticker through every entry in `commandRegistry`, honoring the tiered cache and writing per-command JSON files (plus `_failed` error logs).
batch.go — `batch` cobra subcommand + worker-pool driver that fans every ticker through every entry in `commandRegistry`, honoring the tiered cache and writing per-command JSON files (plus `_failed` error logs).
format
financials.go — ComprehensiveFinancialsDTO → stdout summary, covering the financials / balance-sheet / cash-flow pages, plus the populated-field counter it reports.
financials.go — ComprehensiveFinancialsDTO → stdout summary, covering the financials / balance-sheet / cash-flow pages, plus the populated-field counter it reports.
fundamentals
fundamentals.go — `fundamentals` + `comprehensive-stats` + `comprehensive-profile` cobra subcommands 共用 sub-package。
fundamentals.go — `fundamentals` + `comprehensive-stats` + `comprehensive-profile` cobra subcommands 共用 sub-package。
market
client_json.go — local-export sink shared between `pull` and `quote`.
client_json.go — local-export sink shared between `pull` and `quote`.
scrape
format.go — pure DTO → stdout formatters for the scrape subcommand's preview modes (analysis / analyst-insights).
format.go — pure DTO → stdout formatters for the scrape subcommand's preview modes (analysis / analyst-insights).
soak command
client.go — builds the soak facade client from one loaded config snapshot.
client.go — builds the soak facade client from one loaded config snapshot.
tools/golden command
manifest_check.go — golden-manifest validator CLI: verifies file existence, SHA256 and schema-specific JSON shape, including daily-bar time semantics.
manifest_check.go — golden-manifest validator CLI: verifies file existence, SHA256 and schema-specific JSON shape, including daily-bar time semantics.
twse
twse.go — `twse` cobra subcommand.
twse.go — `twse` cobra subcommand.
adapters.go — mechanical accessors on `*Config` that hand out flat / nested views of the root config tree:
adapters.go — mechanical accessors on `*Config` that hand out flat / nested views of the root config tree:
Package facade owns yfin's public operation boundary.
Package facade owns yfin's public operation boundary.
samples/api_usage command
`api_usage.go` — programmatic tour of `facade.Client.Scrape*` covering financials, key statistics, analysis, news, and the all-fundamentals batch.
`api_usage.go` — programmatic tour of `facade.Client.Scrape*` covering financials, key statistics, analysis, news, and the all-fundamentals batch.
samples/historical_data command
`historical_data_example.go` — end-to-end look at `facade.Client` historical APIs: daily bars, intraday bars, and a spot quote.
`historical_data_example.go` — end-to-end look at `facade.Client` historical APIs: daily bars, intraday bars, and a spot quote.
samples/print_all_data_types command
`print_all_data_types.go` — exhaustive dump of every `facade.FundamentalsSnapshot` variant (analysis, analyst insights, balance sheet, cash flow) plus JSON marshaling and `ScrapeAllFundamentals` source differentiation.
`print_all_data_types.go` — exhaustive dump of every `facade.FundamentalsSnapshot` variant (analysis, analyst insights, balance sheet, cash flow) plus JSON marshaling and `ScrapeAllFundamentals` source differentiation.
samples/print_data_contents command
`print_data_contents.go` — field-by-field walk of `facade.Quote`, `facade.BarBatch`, news, financials, and key-statistics snapshots, including JSON marshaling.
`print_data_contents.go` — field-by-field walk of `facade.Quote`, `facade.BarBatch`, news, financials, and key-statistics snapshots, including JSON marshaling.
scrape_convert.go — DTO → model direct converters for the scrape path.
scrape_convert.go — DTO → model direct converters for the scrape path.
svc
scrape
analysis.go — parses Yahoo analysis pages into earnings/revenue estimates, history, EPS trend/revisions, and growth DTOs.
analysis.go — parses Yahoo analysis pages into earnings/revenue estimates, history, EPS trend/revisions, and growth DTOs.
twse
bfiauu_stock.go — `BFIAUU_STOCK` thin wrapper that adds `stockNo` requirement then delegates to `BFIAUU` (same 10-column row shape).
bfiauu_stock.go — `BFIAUU_STOCK` thin wrapper that adds `stockNo` requirement then delegates to `BFIAUU` (same 10-column row shape).
yahoo
Fetches/extracts Yahoo dividends + splits from `/v8/finance/chart` `events` (1-year lookback).
Fetches/extracts Yahoo dividends + splits from `/v8/finance/chart` `events` (1-year lookback).
utils
cache
Package cache owns reusable yfin cache mechanics.
Package cache owns reusable yfin cache mechanics.
httpx
body.go — Gzip auto-decode + per-response body size cap shared by `Caller.Get`.
body.go — Gzip auto-decode + per-response body size cap shared by `Caller.Get`.
obsv
metrics.go — Prometheus metrics for request, retry, backoff, decode, circuit-breaker, latency, and inflight HTTP state.
metrics.go — Prometheus metrics for request, retry, backoff, decode, circuit-breaker, latency, and inflight HTTP state.

Jump to

Keyboard shortcuts

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