Skip to content

News API Reference

financelib.news.client.News(data: Optional[Dict[str, str]] = None)

Represents a news article with metadata.

Parameters:

Name Type Description Default
data Optional[Dict[str, str]]

Dictionary with article data (title, content, date, author, etc.).

None

Attributes:

Name Type Description
title str

Article title.

content str

Article body text.

date str | date | datetime

Publication date.

author str

Author name(s).

category str

Article category (default: 'news').

source str

Source name.

article_url str

URL to the full article.

article_thumbnail_url str

URL to the article thumbnail image.

Example

article = News({'title': 'BIST Rallies', 'content': 'Market surged...', 'date': '2025-01-01'}) print(article.title)

Source code in financelib/news/client.py
def __init__(self, data: Optional[Dict[str, str]] = None) -> None:
    if data is None:
        data = {}
    data = {k.lower(): v for k, v in data.items()}

    self._title: str = data.get("title", "")
    self._content: str = data.get("content", "")
    self._date = data.get("date", "")
    self._author = data.get("author", "")
    self._category: str = data.get("category", "news")
    self._source: str = data.get("source", "")
    self._article_url: str = data.get("article_url", "")
    self._article_thumbnail_url: str = data.get("article_thumbnail_url", "")

Functions

to_dict() -> Dict[str, str]

Convert the news article to a dictionary.

Returns:

Type Description
Dict[str, str]

Dictionary with all article fields.

Source code in financelib/news/client.py
def to_dict(self) -> Dict[str, str]:
    """Convert the news article to a dictionary.

    Returns:
        Dictionary with all article fields.
    """
    return {
        "title": self.title,
        "content": self.content,
        "date": str(self.date),
        "author": self.author,
        "category": self.category,
        "source": self.source,
        "article_url": self.article_url,
        "article_thumbnail_url": self.article_thumbnail_url,
    }

financelib.news.client.BaseQueryClass

Base class for news query implementations.

Subclasses must implement the search_articles method.

Functions

search_articles(query: str, limit: int = 5, print_results: bool = False) -> List[News]

Search for articles matching a query.

Parameters:

Name Type Description Default
query str

Search query string.

required
limit int

Maximum number of results.

5
print_results bool

Whether to print results to console.

False

Returns:

Type Description
List[News]

List of News objects.

Source code in financelib/news/client.py
def search_articles(
    self, query: str, limit: int = 5, print_results: bool = False
) -> List[News]:
    """Search for articles matching a query.

    Args:
        query: Search query string.
        limit: Maximum number of results.
        print_results: Whether to print results to console.

    Returns:
        List of News objects.
    """
    raise NotImplementedError("Please implement this method in your subclass")

financelib.news.client.BloombergQuery()

Bases: BaseQueryClass

Bloomberg news scraper.

Fetches news articles from Bloomberg's search page via web scraping.

Example

query = BloombergQuery() articles = query.search_articles("Turkish stocks", limit=3)

Source code in financelib/news/client.py
def __init__(self) -> None:
    self.session = requests.Session()
    self.headers = {
        "User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36",
        "Accept": "text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8",
        "Accept-Language": "en-US,en;q=0.5",
        "Referer": "https://www.bloomberg.com",
        "DNT": "1",
    }

Functions

print_article_details(article: News) -> None

Print formatted article details to console.

Parameters:

Name Type Description Default
article News

News object to display.

required
Source code in financelib/news/client.py
def print_article_details(self, article: News) -> None:
    """Print formatted article details to console.

    Args:
        article: News object to display.
    """
    print()
    print("-----------------------------------")
    print("Title:", article.title)
    print("-----------------------------------")
    print(article.content)
    print("-----------------------------------")
    print("Category:", article.category)
    print("Date of Upload:", article.date)
    print("Author:", article.author)
    print("-----------------------------------")
    print()

search_articles(query: str, limit: int = 5, print_results: bool = False) -> List[News]

Search Bloomberg for articles matching a query.

Parameters:

Name Type Description Default
query str

Search query string.

required
limit int

Maximum number of articles to return.

5
print_results bool

Whether to print results to console.

False

Returns:

Type Description
List[News]

List of News objects.

Source code in financelib/news/client.py
def search_articles(
    self, query: str, limit: int = 5, print_results: bool = False
) -> List[News]:
    """Search Bloomberg for articles matching a query.

    Args:
        query: Search query string.
        limit: Maximum number of articles to return.
        print_results: Whether to print results to console.

    Returns:
        List of News objects.
    """
    articles: List[News] = []
    try:
        params = {"query": query, "source": "news", "sort": "relevancy"}

        response = self.session.get(
            self.SEARCH_URL, params=params, headers=self.headers
        )
        response.raise_for_status()
        time.sleep(2)

        soup = BeautifulSoup(response.text, "html.parser")

        article_elements = (
            soup.find_all("article")
            or soup.find_all(
                "div", class_=lambda x: x and "story" in x.lower()
            )
            or soup.find_all(
                "div", class_=lambda x: x and "article" in x.lower()
            )
            or soup.find_all(
                "div", class_=lambda x: x and "news" in x.lower()
            )
        )

        for article in article_elements[:limit]:
            try:
                title_el = (
                    article.find(["h1", "h2", "h3"])
                    or article.find(
                        class_=lambda x: x and "title" in x.lower()
                    )
                    or article.find(
                        class_=lambda x: x and "headline" in x.lower()
                    )
                )
                title = title_el.get_text().strip() if title_el else ""

                content_el = (
                    article.find("p")
                    or article.find(
                        class_=lambda x: x and "summary" in x.lower()
                    )
                    or article.find(
                        class_=lambda x: x and "description" in x.lower()
                    )
                )
                content = content_el.get_text().strip() if content_el else ""

                date_el = (
                    article.find("time")
                    or article.find(
                        class_=lambda x: x and "date" in x.lower()
                    )
                )
                date = date_el.get_text().strip() if date_el else ""

                author_el = (
                    article.find(
                        class_=lambda x: x and "author" in x.lower()
                    )
                    or article.find(
                        class_=lambda x: x and "byline" in x.lower()
                    )
                )
                author = (
                    author_el.get_text().strip() if author_el else "Bloomberg"
                )

                category_el = (
                    article.find(
                        class_=lambda x: x and "category" in x.lower()
                    )
                    or article.find(
                        class_=lambda x: x and "tag" in x.lower()
                    )
                )
                category = (
                    category_el.get_text().strip().capitalize()
                    if category_el
                    else "news"
                )

                if title:
                    news = News(
                        {
                            "title": title,
                            "content": content,
                            "date": date,
                            "author": author,
                            "category": category,
                            "source": "Bloomberg",
                        }
                    )
                    articles.append(news)

            except Exception as e:
                logger.warning(f"Error parsing article: {e}")
                continue

        if print_results:
            for article in articles:
                self.print_article_details(article)

        return articles

    except Exception as e:
        logger.error(f"Error fetching articles from Bloomberg: {e}")
        return []

financelib.news.client.NewsAPIQuery(api_key: str = '')

Bases: BaseQueryClass

NewsAPI.org query client.

Fetches news articles via the NewsAPI service.

Parameters:

Name Type Description Default
api_key str

NewsAPI API key. If empty, loads from environment.

''
Example

query = NewsAPIQuery() articles = query.search_articles("Bitcoin", sources_from_ids=["bbc-news"])

Source code in financelib/news/client.py
def __init__(self, api_key: str = "") -> None:
    _api_key: str = news_api_setup(api_key)
    self.newsapi: NewsApiClient = NewsApiClient(api_key=_api_key)

Functions

get_all_news_source_ids() -> List[str]

Get all available NewsAPI source IDs.

Returns:

Type Description
List[str]

List of source ID strings.

Source code in financelib/news/client.py
def get_all_news_source_ids(self) -> List[str]:
    """Get all available NewsAPI source IDs.

    Returns:
        List of source ID strings.
    """
    sources = self.newsapi.get_sources()
    return [source["id"] for source in sources["sources"]]

get_all_news_sources_detailed() -> List[Dict[str, str]]

Get detailed information about all available NewsAPI sources.

Returns:

Type Description
List[Dict[str, str]]

List of source detail dictionaries.

Source code in financelib/news/client.py
def get_all_news_sources_detailed(self) -> List[Dict[str, str]]:
    """Get detailed information about all available NewsAPI sources.

    Returns:
        List of source detail dictionaries.
    """
    sources = self.newsapi.get_sources()
    return sources["sources"]

print_article_details(article: Dict) -> None

Print formatted article details from NewsAPI response.

Parameters:

Name Type Description Default
article Dict

Raw article dictionary from NewsAPI.

required
Source code in financelib/news/client.py
def print_article_details(self, article: Dict) -> None:
    """Print formatted article details from NewsAPI response.

    Args:
        article: Raw article dictionary from NewsAPI.
    """
    print()
    print("-----------------------------------")
    print("Title:", article.get("title", ""))
    print("-----------------------------------")
    print("Article Thumbnail:", article.get("urlToImage", ""))
    print("---")
    print(article.get("content", ""))
    print("-----------------------------------")
    print("Source:", article.get("source", {}).get("name", ""))
    print("Date of Publish:", article.get("publishedAt", ""))
    print("Article URL:", article.get("url", ""))
    print("-----------------------------------")
    print()

search_articles(query: str, sources_from_ids: Optional[str | List[str]] = None, limit: int = 5, print_results: bool = False) -> List[Dict]

Search for articles via NewsAPI.

Parameters:

Name Type Description Default
query str

Search query string.

required
sources_from_ids Optional[str | List[str]]

Source ID(s) to filter by (string or list).

None
limit int

Maximum number of articles.

5
print_results bool

Whether to print results to console.

False

Returns:

Type Description
List[Dict]

List of article dictionaries from NewsAPI.

Source code in financelib/news/client.py
def search_articles(
    self,
    query: str,
    sources_from_ids: Optional[str | List[str]] = None,
    limit: int = 5,
    print_results: bool = False,
) -> List[Dict]:
    """Search for articles via NewsAPI.

    Args:
        query: Search query string.
        sources_from_ids: Source ID(s) to filter by (string or list).
        limit: Maximum number of articles.
        print_results: Whether to print results to console.

    Returns:
        List of article dictionaries from NewsAPI.
    """
    sources = ""
    if sources_from_ids is not None:
        if isinstance(sources_from_ids, list):
            sources = ",".join(sources_from_ids)
        else:
            sources = sources_from_ids

    all_articles = self.newsapi.get_everything(
        q=query,
        sources=sources,
    )

    if print_results:
        for article in all_articles["articles"][:limit]:
            self.print_article_details(article)

    return all_articles["articles"][:limit]