Skip to content

Stock API Reference

financelib.stock.client.Stock(symbol: str)

Stock data fetcher and display utility.

Provides methods for fetching real-time stock prices, searching stocks by symbol or company name, and displaying formatted stock information.

Parameters:

Name Type Description Default
symbol str

Stock ticker symbol (e.g., 'THYAO.IS', 'AAPL').

required

Attributes:

Name Type Description
symbol

Uppercase stock ticker symbol.

COMMON_STOCKS Dict[str, str]

Dictionary of common BIST stock symbols and names.

Example

stock = Stock("THYAO.IS") data = stock.get_data() Stock.search_stock("Garanti")

Initialize stock with symbol.

Parameters:

Name Type Description Default
symbol str

Stock ticker symbol.

required
Source code in financelib/stock/client.py
def __init__(self, symbol: str) -> None:
    """Initialize stock with symbol.

    Args:
        symbol: Stock ticker symbol.
    """
    self.symbol = symbol.upper()
    self._ticker = yf.Ticker(self.symbol) if self.symbol else None

Functions

display_stock_info(company_name: str, return_info: bool = False) -> Optional[List[Dict[str, Any]]] classmethod

Display detailed stock information for a company.

Searches by company name, fetches full info from Yahoo Finance, and either prints or returns the results.

Parameters:

Name Type Description Default
company_name str

Company name or stock symbol to search for.

required
return_info bool

If True, return data instead of printing.

False

Returns:

Type Description
Optional[List[Dict[str, Any]]]

List of stock info dictionaries if return_info is True, else None.

Source code in financelib/stock/client.py
@classmethod
def display_stock_info(
    cls, company_name: str, return_info: bool = False
) -> Optional[List[Dict[str, Any]]]:
    """Display detailed stock information for a company.

    Searches by company name, fetches full info from Yahoo Finance,
    and either prints or returns the results.

    Args:
        company_name: Company name or stock symbol to search for.
        return_info: If True, return data instead of printing.

    Returns:
        List of stock info dictionaries if return_info is True, else None.
    """
    try:
        info = []
        search_result = yq.search(company_name)

        if (
            not search_result
            or "quotes" not in search_result
            or len(search_result["quotes"]) == 0
        ):
            logger.warning(f"No matching company found for '{company_name}'")
            return [{"error": "No matching company found"}]

        for quote in search_result["quotes"]:
            stock = yf.Ticker(quote.get("symbol"))
            stock_info = stock.info

            info.append(
                {
                    "symbol": stock_info.get("symbol"),
                    "short_name": stock_info.get("shortName"),
                    "long_name": stock_info.get("longName"),
                    "score": quote.get("score"),
                    "exchange": quote.get("exchange"),
                    "current_price": stock_info.get("currentPrice"),
                    "market_cap": stock_info.get("marketCap"),
                    "sector": stock_info.get("sector"),
                    "industry": stock_info.get("industry"),
                }
            )

        if return_info:
            return info

        __import__("pprint").pprint(info)
        return None
    except Exception as e:
        logger.error(f"Error displaying stock info for '{company_name}': {e}")
        return [{"error": str(e)}]

display_stock_infos(query_list: List[str], return_info: bool = False) -> Optional[List[Dict[str, Any]]] classmethod

Display information for multiple stocks.

Parameters:

Name Type Description Default
query_list List[str]

List of company names or symbols to look up.

required
return_info bool

If True, return the data instead of printing.

False

Returns:

Type Description
Optional[List[Dict[str, Any]]]

List of stock info dicts if return_info is True, else None.

Source code in financelib/stock/client.py
@classmethod
def display_stock_infos(
    cls, query_list: List[str], return_info: bool = False
) -> Optional[List[Dict[str, Any]]]:
    """Display information for multiple stocks.

    Args:
        query_list: List of company names or symbols to look up.
        return_info: If True, return the data instead of printing.

    Returns:
        List of stock info dicts if return_info is True, else None.
    """
    try:
        info = []
        for query in query_list:
            if return_info:
                temp = cls.display_stock_info(query, return_info=return_info)
                info.append(temp)
            else:
                cls.display_stock_info(query)

        if return_info:
            return info
    except Exception as e:
        logger.error(f"Error fetching multiple stock infos: {e}")
        return [{"error": str(e)}]

get_data() -> Dict[str, Any]

Get current stock quote data from Yahoo Finance.

Returns:

Type Description
Dict[str, Any]

Dictionary containing quote data (symbol, exchange, score, etc.).

Raises:

Type Description
InvalidSymbolError

If symbol is empty or no match is found.

Source code in financelib/stock/client.py
def get_data(self) -> Dict[str, Any]:
    """Get current stock quote data from Yahoo Finance.

    Returns:
        Dictionary containing quote data (symbol, exchange, score, etc.).

    Raises:
        InvalidSymbolError: If symbol is empty or no match is found.
    """
    if not self.symbol:
        raise InvalidSymbolError("No stock symbol provided")

    data = yq.search(self.symbol)
    if data is None or "quotes" not in data or len(data["quotes"]) == 0:
        raise InvalidSymbolError(f"No matching company found for '{self.symbol}'")

    return data["quotes"][0]

get_historical_data(period: str = '1mo', interval: str = '1d') -> Optional[pd.DataFrame]

Get historical price data.

Parameters:

Name Type Description Default
period str

Data period (e.g., '1d', '5d', '1mo', '3mo', '1y').

'1mo'
interval str

Data interval (e.g., '1m', '5m', '1h', '1d').

'1d'

Returns:

Type Description
Optional[DataFrame]

DataFrame with OHLCV data, or None on failure.

Source code in financelib/stock/client.py
def get_historical_data(
    self, period: str = "1mo", interval: str = "1d"
) -> Optional[pd.DataFrame]:
    """Get historical price data.

    Args:
        period: Data period (e.g., '1d', '5d', '1mo', '3mo', '1y').
        interval: Data interval (e.g., '1m', '5m', '1h', '1d').

    Returns:
        DataFrame with OHLCV data, or None on failure.
    """
    try:
        df = self._ticker.history(period=period, interval=interval)
        if df.empty:
            return None
        return df
    except Exception as e:
        logger.error(f"Error fetching historical data for {self.symbol}: {e}")
        return None

get_live_stock_state(symbol: str) -> None classmethod

Display real-time stock price with colored terminal output.

Parameters:

Name Type Description Default
symbol str

Stock ticker symbol (Yahoo Finance format, e.g., 'THYAO.IS').

required
Source code in financelib/stock/client.py
@classmethod
def get_live_stock_state(cls, symbol: str) -> None:
    """Display real-time stock price with colored terminal output.

    Args:
        symbol: Stock ticker symbol (Yahoo Finance format, e.g., 'THYAO.IS').
    """
    stock = cls(symbol)
    data = stock._get_stock()

    if data:
        change_symbol = (
            "▲" if data["change"] > 0 else "▼" if data["change"] < 0 else "■"
        )
        change_color = (
            "\033[92m"
            if data["change"] > 0
            else "\033[91m"
            if data["change"] < 0
            else "\033[0m"
        )

        print(f"\n{data['symbol']} - {data['timestamp']}")
        print(f"Price: {data['price']} {data['currency']}")
        print(
            f"Change: {change_color}{change_symbol} {data['change']} "
            f"({data['change_percent']}%)\033[0m"
        )
        print(f"Volume: {data['volume']:,}")
    else:
        print(f"\nUnable to fetch data for {symbol}")

get_price_data() -> Optional[Dict[str, Any]]

Get current price, change, and volume data.

Returns:

Type Description
Optional[Dict[str, Any]]

Dictionary with price data or None if fetch fails.

Source code in financelib/stock/client.py
def get_price_data(self) -> Optional[Dict[str, Any]]:
    """Get current price, change, and volume data.

    Returns:
        Dictionary with price data or None if fetch fails.
    """
    return self._get_stock()

search_stock(company_name: str) -> Dict[str, Any] classmethod

Search for a stock by company name or symbol.

Parameters:

Name Type Description Default
company_name str

Company name or stock symbol to search.

required

Returns:

Type Description
Dict[str, Any]

Dictionary with the first matching stock's data,

Dict[str, Any]

or an error dict if no match is found.

Source code in financelib/stock/client.py
@classmethod
def search_stock(cls, company_name: str) -> Dict[str, Any]:
    """Search for a stock by company name or symbol.

    Args:
        company_name: Company name or stock symbol to search.

    Returns:
        Dictionary with the first matching stock's data,
        or an error dict if no match is found.
    """
    try:
        search_result = yq.search(company_name)

        if (
            not search_result
            or "quotes" not in search_result
            or len(search_result["quotes"]) == 0
        ):
            return {"error": "No matching company found"}

        first_match = search_result.get("quotes")[0]
        return first_match

    except Exception as e:
        logger.error(f"Error searching for '{company_name}': {e}")
        return {"error": str(e)}