Skip to content

Config & CLI

config

LogLevelFilter

LogLevelFilter(levels: List[int])

Bases: Filter

Initializes the filter with specific logging levels.

Parameters:

Name Type Description Default
levels List[int]

A list of logging level values (integers) to include.

required
Source code in src/bbstrader/config.py
def __init__(self, levels: List[int]) -> None:
    """
    Initializes the filter with specific logging levels.

    Args:
        levels: A list of logging level values (integers) to include.
    """
    super().__init__()
    self.levels = levels

filter

filter(record: LogRecord) -> bool

Filters log records based on their level.

Parameters:

Name Type Description Default
record LogRecord

The log record to check.

required

Returns:

Type Description
bool

True if the record's level is in the allowed levels, False otherwise.

Source code in src/bbstrader/config.py
def filter(self, record: logging.LogRecord) -> bool:
    """
    Filters log records based on their level.

    Args:
        record: The log record to check.

    Returns:
        True if the record's level is in the allowed levels, False otherwise.
    """
    return record.levelno in self.levels

get_config_dir

get_config_dir(name: str = '.bbstrader') -> Path

Get the path to the configuration directory.

Parameters:

Name Type Description Default
name str

The name of the configuration directory.

'.bbstrader'

Returns:

Type Description
Path

The path to the configuration directory.

Source code in src/bbstrader/config.py
def get_config_dir(name: str = ".bbstrader") -> Path:
    """
    Get the path to the configuration directory.

    Args:
        name: The name of the configuration directory.

    Returns:
        The path to the configuration directory.
    """
    home_dir = Path.home() / name
    if not home_dir.exists():
        home_dir.mkdir()
    return home_dir

scripts

load_module

load_module(file_path: str) -> ModuleType

Load a module from a file path. Args: file_path: Path to the file to load. Returns: The loaded module.

Source code in src/bbstrader/scripts.py
def load_module(file_path: str) -> ModuleType:
    """Load a module from a file path.
    Args:
        file_path: Path to the file to load.
    Returns:
        The loaded module.
    """
    if not os.path.exists(file_path):
        raise FileNotFoundError(
            f"Strategy file {file_path} not found. Please create it."
        )
    spec = importlib.util.spec_from_file_location("bbstrader.cli", file_path)
    if spec is None or spec.loader is None:
        raise ImportError(f"Could not load spec for module at {file_path}")
    module = importlib.util.module_from_spec(spec)
    spec.loader.exec_module(module)
    return module

load_class

load_class(module: ModuleType, class_name: str, base_class: Type) -> Type

Load a class from a module. Args: module: The module to load the class from. class_name: The name of the class to load. base_class: The base class that the class must inherit from.

Source code in src/bbstrader/scripts.py
def load_class(module: ModuleType, class_name: str, base_class: Type) -> Type:
    """Load a class from a module.
    Args:
        module: The module to load the class from.
        class_name: The name of the class to load.
        base_class: The base class that the class must inherit from.
    """
    if not hasattr(module, class_name):
        raise AttributeError(f"{class_name} not found in {module}")
    class_ = getattr(module, class_name)
    if not issubclass(class_, base_class):
        raise TypeError(f"{class_name} must inherit from {base_class}.")
    return class_

summarize_text

summarize_text(text: str, sentences_count: int = 5) -> str

Generate a summary using TextRank algorithm.

Source code in src/bbstrader/scripts.py
def summarize_text(text: str, sentences_count: int = 5) -> str:
    """
    Generate a summary using TextRank algorithm.
    """
    Tokenizer = _require_nlp("sumy.nlp.tokenizers").Tokenizer
    PlaintextParser = _require_nlp("sumy.parsers.plaintext").PlaintextParser
    TextRankSummarizer = _require_nlp("sumy.summarizers.text_rank").TextRankSummarizer
    parser = PlaintextParser.from_string(text, Tokenizer("english"))
    summarizer = TextRankSummarizer()
    summary = summarizer(parser.document, sentences_count)
    return " ".join(str(sentence) for sentence in summary)

compat

setup_mock_modules

setup_mock_modules() -> None

Mock some modules not available on some OS to prevent import errors.

Source code in src/bbstrader/compat.py
def setup_mock_modules() -> None:
    """Mock some modules not available on some OS to prevent import errors."""
    from unittest.mock import MagicMock

    class Mock(MagicMock):
        @classmethod
        def __getattr__(cls, name: str) -> Any:
            return MagicMock()

    MOCK_MODULES = []

    # Mock Metatrader5 on Linux and MacOS
    if platform.system() != "Windows":
        MOCK_MODULES.append("MetaTrader5")

    # Mock posix On windows
    if platform.system() == "Windows":
        MOCK_MODULES.append("posix")

    sys.modules.update((mod_name, Mock()) for mod_name in MOCK_MODULES)