Skip to content

Utilities API Reference

financelib.utils

Utility functions for FinanceLib.

Functions

format_currency(amount: float, currency: str = 'TRY', decimals: int = 2) -> str

Format a number as currency.

Parameters:

Name Type Description Default
amount float

The monetary amount.

required
currency str

Currency code (e.g., 'TRY', 'USD').

'TRY'
decimals int

Number of decimal places.

2

Returns:

Type Description
str

Formatted string like '1,234.56 TRY'.

Source code in financelib/utils.py
def format_currency(amount: float, currency: str = "TRY", decimals: int = 2) -> str:
    """Format a number as currency.

    Args:
        amount: The monetary amount.
        currency: Currency code (e.g., 'TRY', 'USD').
        decimals: Number of decimal places.

    Returns:
        Formatted string like '1,234.56 TRY'.
    """
    return f"{amount:,.{decimals}f} {currency}"

format_percentage(value: float, decimals: int = 2) -> str

Format a number as a percentage string.

Parameters:

Name Type Description Default
value float

The percentage value.

required
decimals int

Number of decimal places.

2

Returns:

Type Description
str

Formatted string like '+1.44%' or '-2.30%'.

Source code in financelib/utils.py
def format_percentage(value: float, decimals: int = 2) -> str:
    """Format a number as a percentage string.

    Args:
        value: The percentage value.
        decimals: Number of decimal places.

    Returns:
        Formatted string like '+1.44%' or '-2.30%'.
    """
    sign = "+" if value > 0 else ""
    return f"{sign}{value:.{decimals}f}%"

get_today() -> datetime.datetime

Return the current date and time.

Source code in financelib/utils.py
def get_today() -> datetime.datetime:
    """Return the current date and time."""
    return datetime.datetime.today()

get_yesterday() -> datetime.datetime

Return yesterday's date and time.

Source code in financelib/utils.py
def get_yesterday() -> datetime.datetime:
    """Return yesterday's date and time."""
    return get_today() - datetime.timedelta(days=1)

rate_limiter(calls: int = 1, period: float = 1.0) -> Callable[[F], F]

Thread-safe rate limiter decorator.

Parameters:

Name Type Description Default
calls int

Maximum number of calls allowed per period.

1
period float

Time period in seconds.

1.0

Returns:

Type Description
Callable[[F], F]

Decorated function.

Source code in financelib/utils.py
def rate_limiter(calls: int = 1, period: float = 1.0) -> Callable[[F], F]:
    """Thread-safe rate limiter decorator.

    Args:
        calls: Maximum number of calls allowed per period.
        period: Time period in seconds.

    Returns:
        Decorated function.
    """
    import threading

    def decorator(func: F) -> F:
        timestamps: list[float] = []
        lock = threading.Lock()

        @functools.wraps(func)
        def wrapper(*args: Any, **kwargs: Any) -> Any:
            with lock:
                now = time.time()
                while timestamps and timestamps[0] < now - period:
                    timestamps.pop(0)
                if len(timestamps) >= calls:
                    sleep_time = period - (now - timestamps[0])
                    if sleep_time > 0:
                        time.sleep(sleep_time)
                    timestamps.pop(0)
                timestamps.append(time.time())
            return func(*args, **kwargs)
        return wrapper  # type: ignore[return-value]
    return decorator

retry(max_retries: int = 3, delay: float = 1.0, backoff: float = 2.0, exceptions: tuple = (Exception,)) -> Callable[[F], F]

Retry decorator with exponential backoff.

Parameters:

Name Type Description Default
max_retries int

Maximum number of retry attempts.

3
delay float

Initial delay between retries in seconds.

1.0
backoff float

Multiplier applied to delay after each retry.

2.0
exceptions tuple

Tuple of exception types to catch.

(Exception,)

Returns:

Type Description
Callable[[F], F]

Decorated function.

Source code in financelib/utils.py
def retry(
    max_retries: int = 3,
    delay: float = 1.0,
    backoff: float = 2.0,
    exceptions: tuple = (Exception,),
) -> Callable[[F], F]:
    """Retry decorator with exponential backoff.

    Args:
        max_retries: Maximum number of retry attempts.
        delay: Initial delay between retries in seconds.
        backoff: Multiplier applied to delay after each retry.
        exceptions: Tuple of exception types to catch.

    Returns:
        Decorated function.
    """
    def decorator(func: F) -> F:
        @functools.wraps(func)
        def wrapper(*args: Any, **kwargs: Any) -> Any:
            current_delay = delay
            last_exception: Optional[Exception] = None
            for attempt in range(max_retries + 1):
                try:
                    return func(*args, **kwargs)
                except exceptions as e:
                    last_exception = e
                    if attempt < max_retries:
                        time.sleep(current_delay)
                        current_delay *= backoff
            raise last_exception  # type: ignore[misc]
        return wrapper  # type: ignore[return-value]
    return decorator

today_str() -> str

Today's date as YYYY-MM-DD.

Source code in financelib/utils.py
def today_str() -> str:
    """Today's date as YYYY-MM-DD."""
    return get_today().strftime("%Y-%m-%d")

today_str_dmy() -> str

Today's date as DD-MM-YYYY.

Source code in financelib/utils.py
def today_str_dmy() -> str:
    """Today's date as DD-MM-YYYY."""
    return get_today().strftime("%d-%m-%Y")

today_str_slash() -> str

Today's date as YYYY/MM/DD.

Source code in financelib/utils.py
def today_str_slash() -> str:
    """Today's date as YYYY/MM/DD."""
    return get_today().strftime("%Y/%m/%d")

today_str_slash_dmy() -> str

Today's date as DD/MM/YYYY.

Source code in financelib/utils.py
def today_str_slash_dmy() -> str:
    """Today's date as DD/MM/YYYY."""
    return get_today().strftime("%d/%m/%Y")

today_str_underline() -> str

Today's date as YYYY_MM_DD.

Source code in financelib/utils.py
def today_str_underline() -> str:
    """Today's date as YYYY_MM_DD."""
    return get_today().strftime("%Y_%m_%d")

validate_stock_symbol(symbol: str) -> bool

Validate that a stock symbol is in the expected format.

Accepts symbols like 'THYAO', 'THYAO.IS', 'AAPL', 'GOOG'.

Parameters:

Name Type Description Default
symbol str

The stock symbol to validate.

required

Returns:

Type Description
bool

True if the symbol matches expected format, False otherwise.

Source code in financelib/utils.py
def validate_stock_symbol(symbol: str) -> bool:
    """Validate that a stock symbol is in the expected format.

    Accepts symbols like 'THYAO', 'THYAO.IS', 'AAPL', 'GOOG'.

    Args:
        symbol: The stock symbol to validate.

    Returns:
        True if the symbol matches expected format, False otherwise.
    """
    return bool(_SYMBOL_PATTERN.match(symbol.upper()))

yesterday_str() -> str

Yesterday's date as YYYY-MM-DD.

Source code in financelib/utils.py
def yesterday_str() -> str:
    """Yesterday's date as YYYY-MM-DD."""
    return get_yesterday().strftime("%Y-%m-%d")

yesterday_str_slash() -> str

Yesterday's date as YYYY/MM/DD.

Source code in financelib/utils.py
def yesterday_str_slash() -> str:
    """Yesterday's date as YYYY/MM/DD."""
    return get_yesterday().strftime("%Y/%m/%d")

yesterday_str_slash_dmy() -> str

Yesterday's date as DD/MM/YYYY.

Source code in financelib/utils.py
def yesterday_str_slash_dmy() -> str:
    """Yesterday's date as DD/MM/YYYY."""
    return get_yesterday().strftime("%d/%m/%Y")

yesterday_str_underline() -> str

Yesterday's date as YYYY_MM_DD.

Source code in financelib/utils.py
def yesterday_str_underline() -> str:
    """Yesterday's date as YYYY_MM_DD."""
    return get_yesterday().strftime("%Y_%m_%d")