跳轉到

新聞

Warning

除了 mock 以外,每個來源都會連網路。cnyes 抓的是非官方 API,隨時可能改變;NewsAPI 會用掉你的 API 額度。

cjtrade.pkgs.analytics.informational.news_client

NewsProviderType

Bases: Enum

Supported news providers.

NewsClient(provider_type, **config)

An unified API to interact with different news providers.

Parameters:

Name Type Description Default
provider_type NewsProviderType or str

Provider to use; a string is converted with NewsProviderType(value).

required
**config Any

Passed to the provider constructor (e.g. api_key for NewsAPI).

{}

Raises:

Type Description
ValueError

If the provider type is not supported.

Warnings

All providers except MOCK make network calls; results vary over time.

Source code in src/cjtrade/pkgs/analytics/informational/news_client.py
37
38
39
40
41
def __init__(self, provider_type: NewsProviderType, **config):
    if isinstance(provider_type, str):
        provider_type = NewsProviderType(provider_type)
    self.provider_type = provider_type
    self.provider = self._create_provider(provider_type, **config)

current_provider_type property

The provider type this client was created with.

fetch_headline_news_async(n=10) async

Fetch up to n headline news items asynchronously from the provider.

Source code in src/cjtrade/pkgs/analytics/informational/news_client.py
59
60
61
async def fetch_headline_news_async(self, n: int = 10) -> List[News]:
    """Fetch up to `n` headline news items asynchronously from the provider."""
    return await self.provider.fetch_headline_news_async(n=n)

fetch_headline_news(n=10)

Fetch up to n headline news items from the provider (blocking).

Source code in src/cjtrade/pkgs/analytics/informational/news_client.py
63
64
65
def fetch_headline_news(self, n: int = 10) -> List[News]:
    """Fetch up to `n` headline news items from the provider (blocking)."""
    return self.provider.fetch_headline_news(n=n)

search_by_keyword(keyword, n=10)

Search the provider for up to n news items matching keyword.

Source code in src/cjtrade/pkgs/analytics/informational/news_client.py
67
68
69
def search_by_keyword(self, keyword: str, n: int = 10) -> List[News]:
    """Search the provider for up to `n` news items matching `keyword`."""
    return self.provider.search_by_keyword(keyword, n=n)

get_provider_name()

Return the provider name.

Source code in src/cjtrade/pkgs/analytics/informational/news_client.py
71
72
73
def get_provider_name(self) -> str:
    """Return the provider name."""
    return self.provider.get_provider_name()

cjtrade.pkgs.analytics.informational.news_providers

News(title, content)

A news item.

Parameters:

Name Type Description Default
title str

Headline.

required
content str

Body text or summary.

required
Source code in src/cjtrade/pkgs/analytics/informational/news_providers/_base.py
16
17
18
def __init__(self, title: str, content: str):
    self.title = title
    self.content = content

NewsInterface(**config)

Bases: ABC

An unified interface for different news providers. All news provider implementations must inherit from this class and implement all abstract methods.

Source code in src/cjtrade/pkgs/analytics/informational/news_providers/_base.py
26
27
def __init__(self, **config: Any):
    self.config = config

fetch_headline_news_async(n=10) abstractmethod async

Fetch latest news asynchronously.

Source code in src/cjtrade/pkgs/analytics/informational/news_providers/_base.py
29
30
31
32
@abstractmethod
async def fetch_headline_news_async(self, n: int = 10) -> List[News]:
    """Fetch latest news asynchronously."""
    pass

fetch_headline_news(n=10) abstractmethod

Fetch latest news. (blocking call)

Source code in src/cjtrade/pkgs/analytics/informational/news_providers/_base.py
34
35
36
37
@abstractmethod
def fetch_headline_news(self, n: int = 10) -> List[News]:
    """Fetch latest news. (blocking call)"""
    pass

search_by_keyword(keyword, n=10) abstractmethod

Search news by keyword.

Source code in src/cjtrade/pkgs/analytics/informational/news_providers/_base.py
39
40
41
42
@abstractmethod
def search_by_keyword(self, keyword: str, n: int = 10) -> List[News]:
    """Search news by keyword."""
    pass

get_provider_name() abstractmethod

Get the provider name.

Source code in src/cjtrade/pkgs/analytics/informational/news_providers/_base.py
44
45
46
47
@abstractmethod
def get_provider_name(self) -> str:
    """Get the provider name."""
    pass

MockNewsProvider(**config)

Bases: NewsInterface

Offline news provider that returns three fixed Chinese news items.

Source code in src/cjtrade/pkgs/analytics/informational/news_providers/mock.py
10
11
12
13
14
15
16
17
18
19
20
21
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
58
59
60
61
62
63
64
65
66
67
def __init__(self, **config):
    super().__init__(**config)
    self.mock_data: List[News] = [
        News(
            title="台積電尾盤大漲15元寫1705新天價 台股再創30576點新高",
            content="在台積電強勢領漲的帶動之下,台股今日再創史上新高點,\
                台積電今日開低走高,而且尾盤再有戲劇性演出,一口氣上漲15元,\
                跨越1700元大關來到1705元,再創新高,也因此帶動台股尾盤再大漲\
                百點,收在30576.3點,上漲471.26點,漲幅1.57%。在台積電的氣勢\
                帶動之下,大型權值股台達電尾盤也大漲來到二個月來新高價位,\
                收1050元,而今日面板及DRAM股表現強勁,包括群創、力積電、旺宏、\
                友達、南亞科、華通、長興等都直攻漲停,整個大盤成交量在7335.47億,\
                接近昨日集中市場成交量7658億水準,盤後是否有鉅額交易再推升成交量\
                有待觀察。不過,台股目前仍有約四分之三個股並未漲到,對此台新投顧\
                副董事長、台新新光金控首席經濟學家李鎮宇認為,在全球的AI浪潮之下,\
                漲勢集中在AI大型權值股的趨勢在所難免,他形容,台股現在是「拉積盤」,\
                台積電一檔個股就決定大盤走勢,至於美國情況也差不多,他直接舉標普500\
                指數分析,前100檔大型股和最後100檔的中小型股的股價落差非常大,所以這\
                種漲勢分配不平均的現象並非台灣獨有。此外,一名業界高層說,台積電\
                ADR接連上漲,合計兩天漲超過6%,這麼驚人的漲勢全世界都注意到了,\
                「不只是台灣,已是世界級的權值股!」因此也難以避免外資集中投資在台積電。"
        ),
        News(
            title="群創、友達連2天漲停,10萬買單排隊憑什麼?原來不只基本面有曙光:它們操作手法也改了!",
            content="本土法人對群創相對看好,目標價從17元提升至19元。群創(3481)日\
                前公布11月每股淨損0.02元,虧損收斂幅度顯著優於預期,摩根士丹利(大摩)\
                出具最新報告,意味群創2025年第4季的最終淨損極有可能小於原先預期,\
                群創近期有FOPLP(扇出型面板封裝)及電視面板價格面臨拐點的2大動能,\
                給予群創「中性」評價,目標價11.5元。不過相較本土法人對群創相對看好,\
                將目標價從17元提升至19元,維持「買進」評等。群創先前傳出打入SpaceX供\
                應鏈引爆熱度升溫,大股東廣宇(2328)公告處分3.9萬張,一度讓周五群創股價\
                開低,但沒多久在買盤簇擁下走高,最高來到18.5元,最終以18.1元作收,\
                漲幅逾6%,成交量78.5萬張,較12/31的93萬張明顯減少,外資更是一口氣加碼\
                5.5萬張。日前群創公布11月營收為171.24億元,較上季獲利下降6%,和去年同\
                比較則減少9%,然而在獲利指標上表現亮眼,淨損為1.56億元,較去年同期改善\
                90%,每股淨損0.02元。大摩報告指出,這項表現遠優於市場預期,儘管有可能\
                受到外匯等有利因素支撐,仍意味群創2025年第4季的最終淨損極可能小於原先\
                預期。報告中強調,近期群創的股價波動主要受到扇出型面板級封裝(FOPLP)機\
                會帶動,根據大摩針對市場調查,群創在2025年上半年至2026年上半年確實有獲\
                得相關訂單,雖然短期內對營收的貢獻可能尚不明顯,但這已成為投資人關注\
                的長期增長點。"
        ),
        News(
            title="台達電漲近3%重返千金股!分析師卻曝2關鍵示警",
            content="電源供應器大廠台達電(2308)今(5)日股價終於重返千元,最高一度\
                觸及1025元、漲幅近3%。啟發投顧分析師郭憲政強調,台達電今日表現是「跟\
                著漲」是大盤為了攻3萬點因此上漲、且技術面壓力區未突破,後續動能恐怕很\
                難持續強勁,建議投資人不要太急於高點追入。台達電今日跟著台股同歡3萬點\
                行情,不僅台積電一早就大漲,聯發科、鴻海等權值股也全數跟漲,台達電也\
                同步拉出近3%的漲幅,股價重返千元,最高觸及1025元。不過,郭憲政認為,\
                台達電今日的漲勢延續性恐怕不強,首先是今日大盤衝擊3萬點,主要拉抬的都\
                是重量級權值股,從台積電上漲60點,幾乎就占了8成大盤漲點,加上台達電、\
                聯發科、鴻海等,其他個股漲勢反倒收斂。郭憲政表示,從技術面來看,台達電\
                雖然衝破千元壓力,但技術線型的壓力區在1030元,若沒有擴量攻破,技術面也\
                相對較弱。整體來說,郭憲政強調,台達電沒有新的題材,今日又是因衝指數拉\
                抬權值股,技術面又遇壓,漲勢延續性不佳,建議不要此時追高入場。"
        )
    ]

fetch_headline_news(n=10)

Return the first n mock news items.

Source code in src/cjtrade/pkgs/analytics/informational/news_providers/mock.py
70
71
72
def fetch_headline_news(self, n: int = 10) -> List[News]:
    """Return the first `n` mock news items."""
    return self.mock_data[:n]

fetch_headline_news_async(n=10) async

Return the first n mock news items after a simulated delay.

Warnings

Sleeps 5 seconds to simulate network latency.

Source code in src/cjtrade/pkgs/analytics/informational/news_providers/mock.py
74
75
76
77
78
79
80
81
82
async def fetch_headline_news_async(self, n: int = 10) -> List[News]:
    """Return the first `n` mock news items after a simulated delay.

    Warnings
    --------
    Sleeps 5 seconds to simulate network latency.
    """
    await asyncio.sleep(5)  # Simulate network delay
    return self.mock_data[:n]

search_by_keyword(keyword, n=10)

Return up to n mock items whose title or content contains keyword.

Source code in src/cjtrade/pkgs/analytics/informational/news_providers/mock.py
85
86
87
88
89
def search_by_keyword(self, keyword: str, n: int = 10) -> List[News]:
    # keyword search using simple substring match
    """Return up to `n` mock items whose title or content contains `keyword`."""
    all = [news for news in self.mock_data if keyword in news.title or keyword in news.content]
    return all[:n]

get_provider_name()

Return "mock".

Source code in src/cjtrade/pkgs/analytics/informational/news_providers/mock.py
92
93
94
def get_provider_name(self) -> str:
    """Return ``"mock"``."""
    return "mock"

NewsAPIProvider(**config)

Bases: NewsInterface

News provider backed by NewsAPI (newsapi.org).

Parameters:

Name Type Description Default
**config

Must include api_key, the NewsAPI key.

{}

Raises:

Type Description
ValueError

If api_key is missing.

Warnings

Requires the news extra. Methods call the NewsAPI web service; results change over time and count against the API quota.

Source code in src/cjtrade/pkgs/analytics/informational/news_providers/news_api.py
34
35
36
37
38
39
40
41
42
43
44
45
46
47
def __init__(self, **config):
    if NewsApiClient is None:
        raise missing_extra("news")
    super().__init__(**config)

    # check required config parameters like API key here
    required_params = ['api_key']
    for param in required_params:
        if param not in config:
            raise ValueError(f"Missing required config parameter: {param}")

    self.api_key = config['api_key']
    self.default_query = "Taiwan"
    self.today_date = datetime.today().strftime('%Y-%m-%d')

fetch_headline_news_async(n=10) async

Fetch up to n top business headlines for "Taiwan" (bbc-news, the-verge).

Warnings

Makes a network call to NewsAPI. Sleeps 1 s first; the NewsAPI call itself is blocking.

Source code in src/cjtrade/pkgs/analytics/informational/news_providers/news_api.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
async def fetch_headline_news_async(self, n: int = 10) -> List[News]:
    """Fetch up to `n` top business headlines for "Taiwan" (bbc-news, the-verge).

    Warnings
    --------
    Makes a network call to NewsAPI. Sleeps 1 s first; the NewsAPI call itself
    is blocking.
    """
    await asyncio.sleep(1)  # Simulate async behavior
    newsapi = NewsApiClient(api_key=self.api_key)
    all_articles = newsapi.get_top_headlines(q=self.default_query,
                                             sources='bbc-news,the-verge',
                                             category='business',
                                             language='en',
                                             country='tw')
    # all_articles = newsapi.get_everything(q=self.default_query,
    #                               sources='bbc-news,the-verge',
    #                               domains='bbc.co.uk,techcrunch.com',
    #                               from_param=(datetime.today() - timedelta(days=5)).strftime('%Y-%m-%d'),
    #                               to=self.today_date,
    #                               language='en',
    #                               sort_by='relevancy',
    #                               page=2)
    return self._response_to_news_list(all_articles)[:n]

fetch_headline_news(n=10)

Fetch up to n top headlines for "Taiwan" from bbc-news.

Warnings

Makes a network call to NewsAPI.

Source code in src/cjtrade/pkgs/analytics/informational/news_providers/news_api.py
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
def fetch_headline_news(self, n: int = 10) -> List[News]:
    """Fetch up to `n` top headlines for "Taiwan" from bbc-news.

    Warnings
    --------
    Makes a network call to NewsAPI.
    """
    newsapi = NewsApiClient(api_key=self.api_key)
    all_articles = newsapi.get_top_headlines(q=self.default_query,
                                             sources='bbc-news',
                                            #  category='business',
                                             language='en')
                                            #  language='en',
                                            #  country='us')
    return self._response_to_news_list(all_articles)[:n]

search_by_keyword(keyword, n=10)

Search the last 30 days of bbc-news and the-verge for keyword.

Warnings

Makes a network call to NewsAPI. The date range depends on the current date.

Source code in src/cjtrade/pkgs/analytics/informational/news_providers/news_api.py
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
def search_by_keyword(self, keyword: str, n: int = 10) -> List[News]:
    """Search the last 30 days of bbc-news and the-verge for `keyword`.

    Warnings
    --------
    Makes a network call to NewsAPI. The date range depends on the current date.
    """
    newsapi = NewsApiClient(api_key=self.api_key)
    all_articles = newsapi.get_everything(q=keyword,
                                  sources='bbc-news,the-verge',
                                #   domains='bbc.co.uk,techcrunch.com',
                                  from_param=(datetime.today() - timedelta(days=30)).strftime('%Y-%m-%d'),
                                  to=self.today_date,
                                  language='en',
                                  sort_by='relevancy',
                                  page=1)
    return self._response_to_news_list(all_articles)[:n]

get_provider_name()

Return "news_api".

Source code in src/cjtrade/pkgs/analytics/informational/news_providers/news_api.py
119
120
121
def get_provider_name(self) -> str:
    """Return ``"news_api"``."""
    return "news_api"

StatementDogProvider(**config)

Bases: NewsInterface

Placeholder provider for StatementDog (財報狗).

Warnings

Not implemented: the fetch and search methods return None.

Source code in src/cjtrade/pkgs/analytics/informational/news_providers/_base.py
26
27
def __init__(self, **config: Any):
    self.config = config

fetch_headline_news_async() async

Not implemented.

Warnings

Placeholder; returns None.

Source code in src/cjtrade/pkgs/analytics/informational/news_providers/statement_dog.py
13
14
15
16
17
18
19
20
async def fetch_headline_news_async(self) -> List[News]:
    """Not implemented.

    Warnings
    --------
    Placeholder; returns None.
    """
    pass

search_by_keyword(keyword)

Not implemented.

Warnings

Placeholder; returns None.

Source code in src/cjtrade/pkgs/analytics/informational/news_providers/statement_dog.py
22
23
24
25
26
27
28
29
def search_by_keyword(self, keyword: str) -> List[News]:
    """Not implemented.

    Warnings
    --------
    Placeholder; returns None.
    """
    pass

get_provider_name()

Return "StatementDog".

Source code in src/cjtrade/pkgs/analytics/informational/news_providers/statement_dog.py
31
32
33
def get_provider_name(self) -> str:
    """Return ``"StatementDog"``."""
    return "StatementDog"