Skip to content

Fundamentals

Company information, financial statements and announcements from TWSE open data.

Warning

Every call is an HTTP request, the data changes daily, and errors are logged and returned as empty results rather than raised.

cjtrade.pkgs.analytics.fundamental

CJTrade Companies Module

This module provides access to company fundamental data from Taiwan Stock Exchange and other public sources. It includes company basic information, financial ratios, EPS data, and major announcements.

Announcement(symbol, company_name, event_date, announcement_date=None, publish_date=None, title='', content=None, category=None, url=None) dataclass

A TWSE major announcement (重大訊息).

event_date (事實發生日期) is the main date; announcement_date is when the company announced it and publish_date when the API published it.

is_recent property

Whether event_date is within the last 7 days.

Warnings

Depends on the current wall-clock time. As a property it cannot take days, so the default of 7 is always used.

days_since_event property

Whole days from event_date to now.

Warnings

Depends on the current wall-clock time.

announcement_delay property

Days from event_date to announcement_date, or None if not announced.

CompanyBasicInfo(symbol, name, industry, market, listing_date=None, capital=None, chairman=None, ceo=None, address=None, phone=None, website=None, business_scope=None) dataclass

公司基本資料

BalanceSheetInfo(symbol, company_name, year, quarter, total_assets=None, total_liabilities=None, shareholders_equity=None, current_assets=None, current_liabilities=None, long_term_debt=None, cash_and_equivalents=None, updated_at=None) dataclass

資產負債表資訊

EPSInfo(symbol, company_name, year, quarter=None, eps=None, revenue=None, net_income=None, updated_at=None) dataclass

每股盈餘資訊

FinancialRatios(symbol, company_name, pe_ratio=None, pb_ratio=None, dividend_yield=None, roe=None, roa=None, current_ratio=None, debt_ratio=None, updated_at=None) dataclass

財務比率資訊 (PE/PB Ratio)

IncomeStatementInfo(symbol, company_name, year, quarter, industry_type, revenue=None, operating_income=None, non_operating_income=None, pre_tax_income=None, net_income=None, comprehensive_income=None, eps=None, interest_income_net=None, non_interest_income=None, provision_expense=None, operating_expense=None, insurance_revenue=None, insurance_cost=None, updated_at=None) dataclass

綜合損益表資訊

TWSEProvider(timeout=30)

台灣證券交易所資料。

Async client for the TWSE open data API (BASE_URL). Use as an async context manager or call close.

Warnings

Makes HTTP requests to TWSE; data changes daily and endpoints may change. The HTTP session skips TLS certificate verification.

初始化TWSE提供者。

Parameters:

Name Type Description Default
timeout int

HTTP請求超時時間(秒)

30
Source code in src/cjtrade/pkgs/analytics/fundamental/providers/twse.py
61
62
63
64
65
66
67
68
69
70
def __init__(self, timeout: int = 30):
    """初始化TWSE提供者。

    Parameters
    ----------
    timeout : int
        HTTP請求超時時間(秒)
    """
    self.timeout = aiohttp.ClientTimeout(total=timeout)
    self._session: Optional[aiohttp.ClientSession] = None

close() async

關閉HTTP session。

Source code in src/cjtrade/pkgs/analytics/fundamental/providers/twse.py
85
86
87
88
async def close(self):
    """關閉HTTP session。"""
    if self._session and not self._session.closed:
        await self._session.close()

get_daily_announcements() async

獲取每日重大訊息。

Returns:

Type Description
List[Announcement]

重大訊息列表; empty on error.

Warnings

Makes HTTP requests to the TWSE open data API; data changes daily and the endpoints or field names may change.

Source code in src/cjtrade/pkgs/analytics/fundamental/providers/twse.py
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
async def get_daily_announcements(self) -> List[Announcement]:
    """獲取每日重大訊息。

    Returns
    -------
    List[Announcement]
        重大訊息列表; empty on error.

    Warnings
    --------
    Makes HTTP requests to the TWSE open data API; data changes daily and the
    endpoints or field names may change.
    """
    try:
        data = await self._fetch_data(self.ENDPOINTS['announcements'])
        announcements = []

        for item in data:
            try:
                # 實際欄位: 出表日期, 發言日期, 發言時間, 公司代號, 公司名稱, 主旨, 符合條款, 事實發生日, 說明

                def parse_roc_date(date_str):
                    """解析民國年日期格式 (例: 1141223)"""
                    if date_str and len(date_str) >= 7:
                        try:
                            year = int(date_str[:3]) + 1911  # 民國年轉西元年
                            month = int(date_str[3:5])
                            day = int(date_str[5:7])
                            return datetime(year, month, day)
                        except ValueError:
                            pass
                    return None

                # 解析三個重要日期
                event_date = parse_roc_date(item.get('事實發生日', ''))
                announcement_date = parse_roc_date(item.get('發言日期', ''))
                publish_date = parse_roc_date(item.get('出表日期', ''))

                # 如果事實發生日無法解析,使用發言日期作為備用
                if not event_date:
                    event_date = announcement_date or datetime.now()

                announcement = Announcement(
                    symbol=item.get('公司代號', ''),
                    company_name=item.get('公司名稱', ''),
                    event_date=event_date,
                    announcement_date=announcement_date,
                    publish_date=publish_date,
                    title=item.get('主旨 ', '').strip(),  # 移除前後空白和換行
                    content=item.get('說明', ''),
                    category=item.get('符合條款', ''),
                    url=None  # API未提供URL
                )
                announcements.append(announcement)

            except (ValueError, KeyError) as e:
                logger.warning(f"Failed to parse announcement item: {e}")
                continue

        return announcements

    except Exception as e:
        logger.error(f"Failed to get daily announcements: {e}")
        return []

get_company_basic_info(symbol=None) async

獲取上市公司基本資料。

Parameters:

Name Type Description Default
symbol str

股票代號,若為None則返回所有公司資料

None

Returns:

Type Description
List[CompanyBasicInfo]

公司基本資料列表; empty on error.

Warnings

Makes HTTP requests to the TWSE open data API; data changes daily and the endpoints or field names may change.

Source code in src/cjtrade/pkgs/analytics/fundamental/providers/twse.py
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
async def get_company_basic_info(self, symbol: Optional[str] = None) -> List[CompanyBasicInfo]:
    """獲取上市公司基本資料。

    Parameters
    ----------
    symbol : str, optional
        股票代號,若為None則返回所有公司資料

    Returns
    -------
    List[CompanyBasicInfo]
        公司基本資料列表; empty on error.

    Warnings
    --------
    Makes HTTP requests to the TWSE open data API; data changes daily and the
    endpoints or field names may change.
    """
    try:
        data = await self._fetch_data(self.ENDPOINTS['company_basic'])
        companies = []

        for item in data:
            try:
                # 實際欄位: 公司代號, 公司名稱, 公司簡稱, 產業別, 住址, 董事長, 總經理,
                # 成立日期, 上市日期, 實收資本額, 網址, 等等

                company_symbol = item.get('公司代號', '')

                # 如果指定了symbol,只返回該公司資料
                if symbol and company_symbol != symbol:
                    continue

                # 解析上市日期 (格式: 19620209)
                listing_date = None
                listing_date_str = item.get('上市日期', '')
                if listing_date_str and listing_date_str != '-':
                    try:
                        year = int(listing_date_str[:4])
                        month = int(listing_date_str[4:6])
                        day = int(listing_date_str[6:8])
                        listing_date = datetime(year, month, day)
                    except ValueError:
                        pass

                # 解析實收資本額
                capital = None
                capital_str = item.get('實收資本額', '')
                if capital_str and capital_str != '-':
                    try:
                        capital = float(capital_str)
                    except ValueError:
                        pass

                company = CompanyBasicInfo(
                    symbol=company_symbol,
                    name=item.get('公司名稱', ''),
                    industry=item.get('產業別', ''),
                    market='上市',  # 這個API專門提供上市公司資料
                    listing_date=listing_date,
                    capital=capital,
                    chairman=item.get('董事長', ''),
                    ceo=item.get('總經理', ''),
                    address=item.get('住址', ''),
                    phone=item.get('總機電話', ''),
                    website=item.get('網址', ''),
                    business_scope=None  # API未提供此欄位
                )
                companies.append(company)

            except (ValueError, KeyError) as e:
                logger.warning(f"Failed to parse company basic info item: {e}")
                continue

        return companies

    except Exception as e:
        logger.error(f"Failed to get company basic info: {e}")
        return []

get_eps_info(symbol=None) async

獲取上市公司EPS資訊。

Parameters:

Name Type Description Default
symbol str

股票代號,若為None則返回所有公司EPS資料

None

Returns:

Type Description
List[EPSInfo]

EPS資訊列表; empty on error.

Warnings

Makes HTTP requests to the TWSE open data API; data changes daily and the endpoints or field names may change.

Source code in src/cjtrade/pkgs/analytics/fundamental/providers/twse.py
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
async def get_eps_info(self, symbol: Optional[str] = None) -> List[EPSInfo]:
    """獲取上市公司EPS資訊。

    Parameters
    ----------
    symbol : str, optional
        股票代號,若為None則返回所有公司EPS資料

    Returns
    -------
    List[EPSInfo]
        EPS資訊列表; empty on error.

    Warnings
    --------
    Makes HTTP requests to the TWSE open data API; data changes daily and the
    endpoints or field names may change.
    """
    try:
        data = await self._fetch_data(self.ENDPOINTS['eps_info'])
        eps_list = []

        for item in data:
            try:
                # 實際欄位: 年度, 季別, 公司代號, 公司名稱, 產業別, 基本每股盈餘(元),
                # 營業收入, 營業利益, 營業外收入及支出, 稅後淨利

                company_symbol = item.get('公司代號', '')

                if symbol and company_symbol != symbol:
                    continue

                # 解析年度 (民國年, 如: 114)
                year_str = item.get('年度', '')
                year = int(year_str) + 1911 if year_str and year_str.isdigit() else 0

                # 解析季別
                quarter_str = item.get('季別', '')
                quarter = int(quarter_str) if quarter_str and quarter_str.isdigit() else None

                # 解析EPS
                eps_str = item.get('基本每股盈餘(元)', '')
                eps = float(eps_str) if eps_str and eps_str != '-' else None

                # 解析營收
                revenue_str = item.get('營業收入', '')
                revenue = float(revenue_str) if revenue_str and revenue_str != '-' else None

                # 解析稅後淨利
                net_income_str = item.get('稅後淨利', '')
                net_income = float(net_income_str) if net_income_str and net_income_str != '-' else None

                eps_info = EPSInfo(
                    symbol=company_symbol,
                    company_name=item.get('公司名稱', ''),
                    year=year,
                    quarter=quarter,
                    eps=eps,
                    revenue=revenue,
                    net_income=net_income,
                    updated_at=datetime.now()
                )
                eps_list.append(eps_info)

            except (ValueError, KeyError) as e:
                logger.warning(f"Failed to parse EPS info item: {e}")
                continue

        return eps_list

    except Exception as e:
        logger.error(f"Failed to get EPS info: {e}")
        return []

get_financial_ratios(symbol=None) async

獲取上市公司PE/PB Ratio等財務比率。

Parameters:

Name Type Description Default
symbol str

股票代號,若為None則返回所有公司財務比率

None

Returns:

Type Description
List[FinancialRatios]

財務比率列表; empty on error.

Warnings

Makes HTTP requests to the TWSE open data API; data changes daily and the endpoints or field names may change.

Source code in src/cjtrade/pkgs/analytics/fundamental/providers/twse.py
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
async def get_financial_ratios(self, symbol: Optional[str] = None) -> List[FinancialRatios]:
    """獲取上市公司PE/PB Ratio等財務比率。

    Parameters
    ----------
    symbol : str, optional
        股票代號,若為None則返回所有公司財務比率

    Returns
    -------
    List[FinancialRatios]
        財務比率列表; empty on error.

    Warnings
    --------
    Makes HTTP requests to the TWSE open data API; data changes daily and the
    endpoints or field names may change.
    """
    try:
        data = await self._fetch_data(self.ENDPOINTS['pe_pb_ratios'])
        ratios_list = []

        for item in data:
            try:
                # 實際欄位: Date, Code, Name, PEratio, DividendYield, PBratio

                company_symbol = item.get('Code', '')

                if symbol and company_symbol != symbol:
                    continue

                # 解析PE Ratio (可能為空字串)
                pe_ratio_str = item.get('PEratio', '')
                pe_ratio = float(pe_ratio_str) if pe_ratio_str and pe_ratio_str != '' else None

                # 解析PB Ratio
                pb_ratio_str = item.get('PBratio', '')
                pb_ratio = float(pb_ratio_str) if pb_ratio_str and pb_ratio_str != '' else None

                # 解析殖利率
                dividend_yield_str = item.get('DividendYield', '')
                dividend_yield = float(dividend_yield_str) if dividend_yield_str and dividend_yield_str != '' else None

                ratios = FinancialRatios(
                    symbol=company_symbol,
                    company_name=item.get('Name', ''),
                    pe_ratio=pe_ratio,
                    pb_ratio=pb_ratio,
                    dividend_yield=dividend_yield,
                    roe=None,  # 此API未提供
                    roa=None,  # 此API未提供
                    current_ratio=None,  # 此API未提供
                    debt_ratio=None,  # 此API未提供
                    updated_at=datetime.now()
                )
                ratios_list.append(ratios)

            except (ValueError, KeyError) as e:
                logger.warning(f"Failed to parse financial ratios item: {e}")
                continue

        return ratios_list

    except Exception as e:
        logger.error(f"Failed to get financial ratios: {e}")
        return []

get_balance_sheet_info(symbol=None) async

獲取上市公司資產負債表資訊。

Parameters:

Name Type Description Default
symbol str

股票代號,若為None則返回所有公司資產負債表資料

None

Returns:

Type Description
List[BalanceSheetInfo]

資產負債表資訊列表; empty on error.

Warnings

Makes HTTP requests to the TWSE open data API; data changes daily and the endpoints or field names may change.

Source code in src/cjtrade/pkgs/analytics/fundamental/providers/twse.py
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
async def get_balance_sheet_info(self, symbol: Optional[str] = None) -> List[BalanceSheetInfo]:
    """獲取上市公司資產負債表資訊。

    Parameters
    ----------
    symbol : str, optional
        股票代號,若為None則返回所有公司資產負債表資料

    Returns
    -------
    List[BalanceSheetInfo]
        資產負債表資訊列表; empty on error.

    Warnings
    --------
    Makes HTTP requests to the TWSE open data API; data changes daily and the
    endpoints or field names may change.
    """
    try:
        data = await self._fetch_data(self.ENDPOINTS['balance_sheet_general'])
        balance_sheet_list = []

        for item in data:
            try:
                # 實際欄位: 年度, 季別, 公司代號, 公司名稱, 流動資產, 非流動資產, 資產總計,
                # 流動負債, 非流動負債, 負債總計, 股本, 資本公積, 保留盈餘, 權益總計, 等等

                company_symbol = item.get('公司代號', '')

                # 跳過空資料
                if not company_symbol:
                    continue

                if symbol and company_symbol != symbol:
                    continue

                # 解析年度 (民國年)
                year_str = item.get('年度', '')
                year = int(year_str) + 1911 if year_str and year_str.isdigit() else 0

                # 解析季別
                quarter_str = item.get('季別', '')
                quarter = int(quarter_str) if quarter_str and quarter_str.isdigit() else 0

                # 跳過無效的年度/季別
                if year == 1911 or quarter == 0:
                    continue

                # 解析各項財務數據
                def safe_float(value_str):
                    if value_str and value_str != '' and value_str != '-':
                        try:
                            return float(value_str.replace(',', ''))
                        except ValueError:
                            pass
                    return None

                balance_sheet = BalanceSheetInfo(
                    symbol=company_symbol,
                    company_name=item.get('公司名稱', ''),
                    year=year,
                    quarter=quarter,
                    total_assets=safe_float(item.get('資產總計', '')),
                    total_liabilities=safe_float(item.get('負債總計', '')),
                    shareholders_equity=safe_float(item.get('歸屬於母公司業主之權益合計', '')),
                    current_assets=safe_float(item.get('流動資產', '')),
                    current_liabilities=safe_float(item.get('流動負債', '')),
                    long_term_debt=safe_float(item.get('非流動負債', '')),
                    cash_and_equivalents=None,  # API未提供具體現金項目
                    updated_at=datetime.now()
                )
                balance_sheet_list.append(balance_sheet)

            except (ValueError, KeyError) as e:
                logger.warning(f"Failed to parse balance sheet item: {e}")
                continue

        return balance_sheet_list

    except Exception as e:
        logger.error(f"Failed to get balance sheet info: {e}")
        return []

get_income_statements(symbol=None) async

獲取綜合損益表資訊 (自動選擇適當的行業API)。

Queries the general, banking, securities, insurance and financial holding endpoints.

Parameters:

Name Type Description Default
symbol str

股票代號,若為None則返回所有公司綜合損益表資料

None

Returns:

Type Description
List[IncomeStatementInfo]

綜合損益表資訊列表. An industry endpoint that fails is skipped.

Warnings

Makes HTTP requests to the TWSE open data API; data changes daily and the endpoints or field names may change.

Source code in src/cjtrade/pkgs/analytics/fundamental/providers/twse.py
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
async def get_income_statements(self, symbol: Optional[str] = None) -> List[IncomeStatementInfo]:
    """獲取綜合損益表資訊 (自動選擇適當的行業API)。

    Queries the general, banking, securities, insurance and financial holding
    endpoints.

    Parameters
    ----------
    symbol : str, optional
        股票代號,若為None則返回所有公司綜合損益表資料

    Returns
    -------
    List[IncomeStatementInfo]
        綜合損益表資訊列表. An industry endpoint that fails is skipped.

    Warnings
    --------
    Makes HTTP requests to the TWSE open data API; data changes daily and the
    endpoints or field names may change.
    """
    all_income_statements = []

    # 行業分類API映射
    industry_apis = {
        'banking': ('income_statement_banking', '金融業'),
        'securities': ('income_statement_securities', '證券期貨業'),
        'insurance': ('income_statement_insurance', '保險業'),
        'financial_holding': ('income_statement_financial_holding', '金控業'),
        'general': ('income_statement_general', '一般業')
    }

    for industry_key, (endpoint_key, industry_name) in industry_apis.items():
        try:
            data = await self._fetch_data(self.ENDPOINTS[endpoint_key])

            for item in data:
                try:
                    company_symbol = item.get('公司代號', '')

                    # 跳過空資料
                    if not company_symbol:
                        continue

                    if symbol and company_symbol != symbol:
                        continue

                    # 解析年度 (民國年)
                    year_str = item.get('年度', '')
                    year = int(year_str) + 1911 if year_str and year_str.isdigit() else 0

                    # 解析季別
                    quarter_str = item.get('季別', '')
                    quarter = int(quarter_str) if quarter_str and quarter_str.isdigit() else 0

                    # 跳過無效的年度/季別
                    if year == 1911 or quarter == 0:
                        continue

                    # 通用欄位解析函數
                    def safe_float(value_str):
                        if value_str and value_str != '' and value_str != '-':
                            try:
                                return float(str(value_str).replace(',', ''))
                            except ValueError:
                                pass
                        return None

                    # 解析EPS
                    eps = safe_float(item.get('基本每股盈餘(元)', ''))

                    # 建立基礎income statement
                    income_statement = IncomeStatementInfo(
                        symbol=company_symbol,
                        company_name=item.get('公司名稱', ''),
                        year=year,
                        quarter=quarter,
                        industry_type=industry_name,
                        eps=eps,
                        updated_at=datetime.now()
                    )

                    # 根據行業類型填入對應欄位
                    if industry_key == 'banking':
                        # 金融業欄位
                        income_statement.interest_income_net = safe_float(item.get('利息淨收益', ''))
                        income_statement.non_interest_income = safe_float(item.get('利息以外淨損益', ''))
                        income_statement.provision_expense = safe_float(item.get('呆帳費用、承諾及保證責任準備提存', ''))
                        income_statement.operating_expense = safe_float(item.get('營業費用', ''))
                        income_statement.pre_tax_income = safe_float(item.get('繼續營業單位稅前淨利(淨損)', ''))
                        income_statement.net_income = safe_float(item.get('本期稅後淨利(淨損)', ''))
                        income_statement.comprehensive_income = safe_float(item.get('本期綜合損益總額(稅後)', ''))

                    elif industry_key == 'securities':
                        # 證券期貨業欄位
                        income_statement.revenue = safe_float(item.get('收益', ''))
                        income_statement.operating_expense = safe_float(item.get('支出及費用', ''))
                        income_statement.operating_income = safe_float(item.get('營業利益', ''))
                        income_statement.non_operating_income = safe_float(item.get('營業外損益', ''))
                        income_statement.pre_tax_income = safe_float(item.get('稅前淨利(淨損)', ''))
                        income_statement.net_income = safe_float(item.get('本期淨利(淨損)', ''))
                        income_statement.comprehensive_income = safe_float(item.get('本期綜合損益總額', ''))

                    elif industry_key == 'insurance':
                        # 保險業欄位
                        income_statement.insurance_revenue = safe_float(item.get('營業收入', ''))
                        income_statement.insurance_cost = safe_float(item.get('營業成本', ''))
                        income_statement.operating_expense = safe_float(item.get('營業費用', ''))
                        income_statement.operating_income = safe_float(item.get('營業利益(損失)', ''))
                        income_statement.non_operating_income = safe_float(item.get('營業外收入及支出', ''))
                        income_statement.pre_tax_income = safe_float(item.get('繼續營業單位稅前純益(純損)', ''))
                        income_statement.net_income = safe_float(item.get('本期淨利(淨損)', ''))
                        income_statement.comprehensive_income = safe_float(item.get('本期綜合損益總額', ''))

                    # 其他行業的通用欄位處理可以在這裡添加

                    all_income_statements.append(income_statement)

                except (ValueError, KeyError) as e:
                    logger.warning(f"Failed to parse income statement item for {industry_name}: {e}")
                    continue

        except Exception as e:
            logger.warning(f"Failed to get {industry_name} income statements: {e}")
            continue

    return all_income_statements

get_company_all_info(symbol) async

獲取特定公司的所有資訊。

Parameters:

Name Type Description Default
symbol str

股票代號

required

Returns:

Type Description
dict

Dict包含所有公司資訊: basic_info, eps_info, financial_ratios, balance_sheet.

Warnings

Makes HTTP requests to the TWSE open data API; data changes daily and the endpoints or field names may change.

Source code in src/cjtrade/pkgs/analytics/fundamental/providers/twse.py
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
async def get_company_all_info(self, symbol: str) -> Dict[str, Any]:
    """獲取特定公司的所有資訊。

    Parameters
    ----------
    symbol : str
        股票代號

    Returns
    -------
    dict
        Dict包含所有公司資訊: ``basic_info``, ``eps_info``, ``financial_ratios``,
        ``balance_sheet``.

    Warnings
    --------
    Makes HTTP requests to the TWSE open data API; data changes daily and the
    endpoints or field names may change.
    """
    tasks = [
        self.get_company_basic_info(symbol),
        self.get_eps_info(symbol),
        self.get_financial_ratios(symbol),
        self.get_balance_sheet_info(symbol)
    ]

    basic_info, eps_info, financial_ratios, balance_sheet = await asyncio.gather(*tasks)

    return {
        'basic_info': basic_info[0] if basic_info else None,
        'eps_info': eps_info,
        'financial_ratios': financial_ratios[0] if financial_ratios else None,
        'balance_sheet': balance_sheet
    }

TWSEDataParser

台灣證券交易所資料解析器

parse_date(date_str, formats=None) staticmethod

解析日期字串。

Parameters:

Name Type Description Default
date_str str

日期字串

required
formats List[str]

日期格式列表,預設為常見的台灣日期格式

None

Returns:

Type Description
datetime or None

datetime物件,解析失敗返回None

Source code in src/cjtrade/pkgs/analytics/fundamental/utils/parser.py
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
@staticmethod
def parse_date(date_str: str, formats: List[str] = None) -> Optional[datetime]:
    """解析日期字串。

    Parameters
    ----------
    date_str : str
        日期字串
    formats : List[str], optional
        日期格式列表,預設為常見的台灣日期格式

    Returns
    -------
    datetime or None
        datetime物件,解析失敗返回None
    """
    if not date_str:
        return None

    if formats is None:
        formats = [
            '%Y/%m/%d',     # 2023/12/26
            '%Y-%m-%d',     # 2023-12-26
            '%Y%m%d',       # 20231226
            '%m/%d/%Y',     # 12/26/2023
            '%d/%m/%Y',     # 26/12/2023
        ]

    for fmt in formats:
        try:
            return datetime.strptime(date_str.strip(), fmt)
        except ValueError:
            continue

    logger.warning(f"Unable to parse date: {date_str}")
    return None

parse_float(value, default=None) staticmethod

安全解析數值。

Parameters:

Name Type Description Default
value (str, int or float)

要解析的值

required
default float

解析失敗時的預設值

None

Returns:

Type Description
float or None

float值,解析失敗返回default

Source code in src/cjtrade/pkgs/analytics/fundamental/utils/parser.py
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
@staticmethod
def parse_float(value: Union[str, int, float], default: Optional[float] = None) -> Optional[float]:
    """安全解析數值。

    Parameters
    ----------
    value : str, int or float
        要解析的值
    default : float, optional
        解析失敗時的預設值

    Returns
    -------
    float or None
        float值,解析失敗返回default
    """
    if value is None or value == '':
        return default

    try:
        if isinstance(value, (int, float)):
            return float(value)

        # 處理字串中的逗號、空格等
        if isinstance(value, str):
            # 移除逗號、空格、括號等
            cleaned = value.replace(',', '').replace(' ', '').replace('(', '').replace(')', '')

            # 處理負數
            if cleaned.startswith('-') or cleaned.endswith('-'):
                cleaned = cleaned.replace('-', '')
                return -float(cleaned)

            # 處理百分比
            if '%' in cleaned:
                cleaned = cleaned.replace('%', '')
                return float(cleaned) / 100

            return float(cleaned)

    except (ValueError, TypeError) as e:
        logger.debug(f"Failed to parse float value '{value}': {e}")

    return default

parse_int(value, default=None) staticmethod

安全解析整數。

Parameters:

Name Type Description Default
value str or int

要解析的值

required
default int

解析失敗時的預設值

None

Returns:

Type Description
int or None

int值,解析失敗返回default

Source code in src/cjtrade/pkgs/analytics/fundamental/utils/parser.py
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
@staticmethod
def parse_int(value: Union[str, int], default: Optional[int] = None) -> Optional[int]:
    """安全解析整數。

    Parameters
    ----------
    value : str or int
        要解析的值
    default : int, optional
        解析失敗時的預設值

    Returns
    -------
    int or None
        int值,解析失敗返回default
    """
    if value is None or value == '':
        return default

    try:
        if isinstance(value, int):
            return value

        if isinstance(value, str):
            # 移除逗號、空格等
            cleaned = value.replace(',', '').replace(' ', '')
            return int(float(cleaned))  # 先轉float再轉int,處理如"123.0"的情況

    except (ValueError, TypeError) as e:
        logger.debug(f"Failed to parse int value '{value}': {e}")

    return default

safe_get(data, key, default=None) staticmethod

安全獲取字典值,支援多種key格式。

Parameters:

Name Type Description Default
data Dict[str, Any]

資料字典

required
key str

要獲取的key

required
default Any

預設值

None

Returns:

Type Description
Any

字典中的值或預設值

Source code in src/cjtrade/pkgs/analytics/fundamental/utils/parser.py
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
@staticmethod
def safe_get(data: Dict[str, Any], key: str, default: Any = None) -> Any:
    """安全獲取字典值,支援多種key格式。

    Parameters
    ----------
    data : Dict[str, Any]
        資料字典
    key : str
        要獲取的key
    default : Any
        預設值

    Returns
    -------
    Any
        字典中的值或預設值
    """
    if not isinstance(data, dict):
        return default

    # 直接匹配
    if key in data:
        return data[key]

    # 嘗試不同的key格式
    key_variants = [
        key,
        key.lower(),
        key.upper(),
        key.replace('_', ''),
        key.replace('_', '-'),
        key.replace('-', '_'),
        ''.join(word.capitalize() for word in key.split('_')),  # snake_case to PascalCase
    ]

    for variant in key_variants:
        if variant in data:
            return data[variant]

    return default

normalize_symbol(symbol) staticmethod

正規化股票代號。

Parameters:

Name Type Description Default
symbol str

原始股票代號

required

Returns:

Type Description
str

正規化後的股票代號

Source code in src/cjtrade/pkgs/analytics/fundamental/utils/parser.py
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
@staticmethod
def normalize_symbol(symbol: str) -> str:
    """正規化股票代號。

    Parameters
    ----------
    symbol : str
        原始股票代號

    Returns
    -------
    str
        正規化後的股票代號
    """
    if not symbol:
        return ""

    # 移除空格和特殊字符
    normalized = symbol.strip().replace(' ', '')

    # 確保是純數字格式(台股代號通常是4位數字)
    if normalized.isdigit():
        return normalized.zfill(4)  # 補齊到4位

    return normalized

validate_symbol(symbol) staticmethod

驗證股票代號格式。

Parameters:

Name Type Description Default
symbol str

股票代號

required

Returns:

Type Description
bool

是否為有效的股票代號

Source code in src/cjtrade/pkgs/analytics/fundamental/utils/parser.py
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
@staticmethod
def validate_symbol(symbol: str) -> bool:
    """驗證股票代號格式。

    Parameters
    ----------
    symbol : str
        股票代號

    Returns
    -------
    bool
        是否為有效的股票代號
    """
    if not symbol:
        return False

    # 台股代號通常是4位數字,ETF可能有英文字母
    symbol = symbol.strip()

    # 純數字4位
    if symbol.isdigit() and len(symbol) == 4:
        return True

    # ETF格式 (如 0050, 00878)
    if symbol.isdigit() and len(symbol) in [4, 5]:
        return True

    # 包含字母的代號 (較少見)
    if len(symbol) <= 6 and symbol.replace('.', '').replace('-', '').isalnum():
        return True

    return False

clean_company_name(name) staticmethod

清理公司名稱。

Parameters:

Name Type Description Default
name str

原始公司名稱

required

Returns:

Type Description
str

清理後的公司名稱

Source code in src/cjtrade/pkgs/analytics/fundamental/utils/parser.py
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
@staticmethod
def clean_company_name(name: str) -> str:
    """清理公司名稱。

    Parameters
    ----------
    name : str
        原始公司名稱

    Returns
    -------
    str
        清理後的公司名稱
    """
    if not name:
        return ""

    # 移除前後空格
    cleaned = name.strip()

    # 移除常見的後綴
    suffixes_to_remove = ['股份有限公司', '有限公司', '公司', '股份', '集團']
    for suffix in suffixes_to_remove:
        if cleaned.endswith(suffix):
            cleaned = cleaned[:-len(suffix)].strip()

    return cleaned

categorize_announcement(title, content='') staticmethod

根據公告標題和內容分類。

Parameters:

Name Type Description Default
title str

公告標題

required
content str

公告內容

''

Returns:

Type Description
str

公告分類

Source code in src/cjtrade/pkgs/analytics/fundamental/utils/parser.py
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
@staticmethod
def categorize_announcement(title: str, content: str = "") -> str:
    """根據公告標題和內容分類。

    Parameters
    ----------
    title : str
        公告標題
    content : str
        公告內容

    Returns
    -------
    str
        公告分類
    """
    if not title:
        return "其他"

    title_lower = title.lower()
    content_lower = content.lower() if content else ""

    # 財務相關
    if any(keyword in title_lower for keyword in ['財報', '財務', '營收', '獲利', '盈餘', '損益', 'eps']):
        return "財務業績"

    # 股利相關
    if any(keyword in title_lower for keyword in ['股利', '股息', '配息', '除息', '除權']):
        return "股利配發"

    # 重大事件
    if any(keyword in title_lower for keyword in ['合併', '收購', '投資', '處分', '轉讓']):
        return "重大投資"

    # 人事異動
    if any(keyword in title_lower for keyword in ['董事', '經理', '人事', '異動', '任命', '辭職']):
        return "人事異動"

    # 法規相關
    if any(keyword in title_lower for keyword in ['法規', '法院', '訴訟', '罰款', '違規']):
        return "法規事項"

    # 營運相關
    if any(keyword in title_lower for keyword in ['營運', '業務', '產品', '服務', '合約']):
        return "營運發展"

    return "其他"

CompanyInfoProvider(default_provider='twse', timeout=30)

Unified company information provider interface.

Integrates multiple data sources and provides a simple API to retrieve company fundamental information

Parameters:

Name Type Description Default
default_provider str

Provider used when a method gets no provider; only "twse" is supported.

'twse'
timeout int

HTTP timeout in seconds passed to the provider.

30
Warnings

All get_* methods make network calls to TWSE. They log errors and return None, an empty list or an error dict instead of raising.

Source code in src/cjtrade/pkgs/analytics/fundamental/__init__.py
58
59
60
61
def __init__(self, default_provider: str = "twse", timeout: int = 30):
    self.default_provider = default_provider
    self.timeout = timeout
    self._providers: Dict[str, Any] = {}

close() async

Close all created providers and forget them.

Source code in src/cjtrade/pkgs/analytics/fundamental/__init__.py
76
77
78
79
80
81
async def close(self):
    """Close all created providers and forget them."""
    for provider in self._providers.values():
        if hasattr(provider, 'close'):
            await provider.close()
    self._providers.clear()

get_company_basic_info(symbol, provider=None) async

Get company basic information.

Returns:

Type Description
CompanyBasicInfo or None

None if not found or on error.

Warnings

Makes HTTP requests to the TWSE open data API; data changes daily and the endpoints or field names may change.

Source code in src/cjtrade/pkgs/analytics/fundamental/__init__.py
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
async def get_company_basic_info(self, symbol: str, provider: str = None) -> Optional[CompanyBasicInfo]:
    """Get company basic information.

    Returns
    -------
    CompanyBasicInfo or None
        None if not found or on error.

    Warnings
    --------
    Makes HTTP requests to the TWSE open data API; data changes daily and the
    endpoints or field names may change.
    """
    try:
        provider_obj = self._get_provider(provider)
        companies = await provider_obj.get_company_basic_info(symbol)
        return companies[0] if companies else None
    except Exception as e:
        logger.error(f"Failed to get company basic info for {symbol}: {e}")
        return None

get_financial_ratios(symbol, provider=None) async

Get company financial ratios (PE/PB, etc.).

Returns:

Type Description
FinancialRatios or None

None if not found or on error.

Warnings

Makes HTTP requests to the TWSE open data API; data changes daily and the endpoints or field names may change.

Source code in src/cjtrade/pkgs/analytics/fundamental/__init__.py
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
async def get_financial_ratios(self, symbol: str, provider: str = None) -> Optional[FinancialRatios]:
    """Get company financial ratios (PE/PB, etc.).

    Returns
    -------
    FinancialRatios or None
        None if not found or on error.

    Warnings
    --------
    Makes HTTP requests to the TWSE open data API; data changes daily and the
    endpoints or field names may change.
    """
    try:
        provider_obj = self._get_provider(provider)
        ratios = await provider_obj.get_financial_ratios(symbol)
        return ratios[0] if ratios else None
    except Exception as e:
        logger.error(f"Failed to get financial ratios for {symbol}: {e}")
        return None

get_eps_info(symbol, provider=None) async

Get company EPS information.

Returns:

Type Description
list of EPSInfo

Empty on error.

Warnings

Makes HTTP requests to the TWSE open data API; data changes daily and the endpoints or field names may change.

Source code in src/cjtrade/pkgs/analytics/fundamental/__init__.py
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
async def get_eps_info(self, symbol: str, provider: str = None) -> List[EPSInfo]:
    """Get company EPS information.

    Returns
    -------
    list of EPSInfo
        Empty on error.

    Warnings
    --------
    Makes HTTP requests to the TWSE open data API; data changes daily and the
    endpoints or field names may change.
    """
    try:
        provider_obj = self._get_provider(provider)
        return await provider_obj.get_eps_info(symbol)
    except Exception as e:
        logger.error(f"Failed to get EPS info for {symbol}: {e}")
        return []

get_income_statements(symbol, provider=None) async

Get company consolidated statements of comprehensive income.

Parameters:

Name Type Description Default
symbol str

Stock symbol

required
provider str

Specify the data provider

None

Returns:

Type Description
List[IncomeStatementInfo]

List of comprehensive income statement information; empty on error.

Warnings

Makes HTTP requests to the TWSE open data API; data changes daily and the endpoints or field names may change.

Source code in src/cjtrade/pkgs/analytics/fundamental/__init__.py
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
async def get_income_statements(self, symbol: str, provider: str = None) -> List[IncomeStatementInfo]:
    """Get company consolidated statements of comprehensive income.

    Parameters
    ----------
    symbol : str
        Stock symbol
    provider : str, optional
        Specify the data provider

    Returns
    -------
    List[IncomeStatementInfo]
        List of comprehensive income statement information; empty on error.

    Warnings
    --------
    Makes HTTP requests to the TWSE open data API; data changes daily and the
    endpoints or field names may change.
    """
    try:
        provider_obj = self._get_provider(provider)
        return await provider_obj.get_income_statements(symbol)
    except Exception as e:
        logger.error(f"Failed to get income statements for {symbol}: {e}")
        return []

get_balance_sheet(symbol, provider=None) async

Get company balance sheet.

Returns:

Type Description
list of BalanceSheetInfo

Empty on error.

Warnings

Makes HTTP requests to the TWSE open data API; data changes daily and the endpoints or field names may change.

Source code in src/cjtrade/pkgs/analytics/fundamental/__init__.py
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
async def get_balance_sheet(self, symbol: str, provider: str = None) -> List[BalanceSheetInfo]:
    """Get company balance sheet.

    Returns
    -------
    list of BalanceSheetInfo
        Empty on error.

    Warnings
    --------
    Makes HTTP requests to the TWSE open data API; data changes daily and the
    endpoints or field names may change.
    """
    try:
        provider_obj = self._get_provider(provider)
        return await provider_obj.get_balance_sheet_info(symbol)
    except Exception as e:
        logger.error(f"Failed to get balance sheet for {symbol}: {e}")
        return []

get_recent_announcements(days=7, provider=None) async

Get recent major announcements.

Keeps announcements whose event_date is within the last days days, newest first.

Returns:

Type Description
list of Announcement

Empty on error.

Warnings

Makes HTTP requests to TWSE. The cutoff is computed from the current wall-clock time.

Source code in src/cjtrade/pkgs/analytics/fundamental/__init__.py
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
async def get_recent_announcements(self, days: int = 7, provider: str = None) -> List[Announcement]:
    """Get recent major announcements.

    Keeps announcements whose ``event_date`` is within the last `days` days,
    newest first.

    Returns
    -------
    list of Announcement
        Empty on error.

    Warnings
    --------
    Makes HTTP requests to TWSE. The cutoff is computed from the current
    wall-clock time.
    """
    try:
        provider_obj = self._get_provider(provider)
        announcements = await provider_obj.get_daily_announcements()

        # Filter announcements within the specified days (based on event_date)
        from datetime import datetime, timedelta
        cutoff_date = datetime.now() - timedelta(days=days)
        recent_announcements = [
            ann for ann in announcements
            if ann.event_date >= cutoff_date
        ]

        recent_announcements.sort(key=lambda x: x.event_date, reverse=True)

        return recent_announcements
    except Exception as e:
        logger.error(f"Failed to get recent announcements: {e}")
        return []

get_company_summary(symbol, provider=None) async

Get complete company summary information.

Fetches basic info, ratios, EPS, balance sheet and income statements concurrently.

Returns:

Type Description
dict

Keys symbol, basic_info, financial_ratios, eps_info, balance_sheet, income_statements and updated_at; on error updated_at is replaced by error.

Warnings

Makes HTTP requests to the TWSE open data API; data changes daily and the endpoints or field names may change.

Source code in src/cjtrade/pkgs/analytics/fundamental/__init__.py
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
async def get_company_summary(self, symbol: str, provider: str = None) -> Dict[str, Any]:
    """Get complete company summary information.

    Fetches basic info, ratios, EPS, balance sheet and income statements
    concurrently.

    Returns
    -------
    dict
        Keys ``symbol``, ``basic_info``, ``financial_ratios``, ``eps_info``,
        ``balance_sheet``, ``income_statements`` and ``updated_at``; on error
        ``updated_at`` is replaced by ``error``.

    Warnings
    --------
    Makes HTTP requests to the TWSE open data API; data changes daily and the
    endpoints or field names may change.
    """
    try:
        provider_obj = self._get_provider(provider)

        # Fetch all information concurrently
        tasks = [
            provider_obj.get_company_basic_info(symbol),
            provider_obj.get_financial_ratios(symbol),
            provider_obj.get_eps_info(symbol),
            provider_obj.get_balance_sheet_info(symbol),
            provider_obj.get_income_statements(symbol)
        ]

        basic_info, financial_ratios, eps_info, balance_sheet, income_statements = await asyncio.gather(*tasks)

        return {
            'symbol': symbol,
            'basic_info': basic_info[0] if basic_info else None,
            'financial_ratios': financial_ratios[0] if financial_ratios else None,
            'eps_info': eps_info,
            'balance_sheet': balance_sheet,
            'income_statements': income_statements,
            'updated_at': datetime.now()
        }
    except Exception as e:
        logger.error(f"Failed to get company summary for {symbol}: {e}")
        return {
            'symbol': symbol,
            'basic_info': None,
            'financial_ratios': None,
            'eps_info': [],
            'balance_sheet': [],
            'income_statements': [],
            'error': str(e)
        }

example_usage() async

Print a TSMC (2330) summary and the past 7 days of announcements.

Warnings

Demo only; makes network calls to TWSE.

Source code in src/cjtrade/pkgs/analytics/fundamental/__init__.py
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
async def example_usage():
    """Print a TSMC (2330) summary and the past 7 days of announcements.

    Warnings
    --------
    Demo only; makes network calls to TWSE.
    """
    out = get_console("analytics.fundamental")
    async with CompanyInfoProvider() as provider:
        # Get complete information for TSMC (2330)
        summary = await provider.get_company_summary("2330")
        out.info("TSMC Summary: %s", summary['basic_info'])
        out.info("TSMC Financial Ratios: %s", summary['financial_ratios'])

        # Get major announcements from the past 7 days
        recent_news = await provider.get_recent_announcements(days=7)
        out.info(f"Major announcements from the past 7 days: {len(recent_news)} records")

        for news in recent_news[:3]:
            out.info(f"  {news}")