diff --git a/.github/workflows/linting.yml b/.github/workflows/linting.yml index ff98d8e8f6e4..2f068019a351 100644 --- a/.github/workflows/linting.yml +++ b/.github/workflows/linting.yml @@ -70,6 +70,7 @@ jobs: if [ -n "${{ env.platform_files }}" ]; then pylint ${{ env.platform_files }} mypy ${{ env.platform_files }} --ignore-missing-imports --scripts-are-modules --check-untyped-defs + pydocstyle ${{ env.platform_files }} else echo "No Python files changed in openbb_platform" fi diff --git a/openbb_platform/core/integration/test_obbject.py b/openbb_platform/core/integration/test_obbject.py index 735dc5209696..4a2d1ad339f3 100644 --- a/openbb_platform/core/integration/test_obbject.py +++ b/openbb_platform/core/integration/test_obbject.py @@ -1,3 +1,5 @@ +"""Test the OBBject.""" + import contextlib import sys diff --git a/openbb_platform/core/openbb_core/__init__.py b/openbb_platform/core/openbb_core/__init__.py index e69de29bb2d1..13627db21b03 100644 --- a/openbb_platform/core/openbb_core/__init__.py +++ b/openbb_platform/core/openbb_core/__init__.py @@ -0,0 +1 @@ +"""OpenBB Core.""" diff --git a/openbb_platform/core/openbb_core/api/auth/user.py b/openbb_platform/core/openbb_core/api/auth/user.py index dab13cca5a97..c61aa5303cf1 100644 --- a/openbb_platform/core/openbb_core/api/auth/user.py +++ b/openbb_platform/core/openbb_core/api/auth/user.py @@ -1,3 +1,5 @@ +"""User authentication.""" + import secrets from typing import Optional @@ -15,7 +17,6 @@ async def authenticate_user( credentials: Annotated[Optional[HTTPBasicCredentials], Depends(security)] ): """Authenticate the user.""" - if credentials: username = Env().API_USERNAME password = Env().API_PASSWORD diff --git a/openbb_platform/core/openbb_core/api/dependency/__init__.py b/openbb_platform/core/openbb_core/api/dependency/__init__.py index e69de29bb2d1..4abe38b227a9 100644 --- a/openbb_platform/core/openbb_core/api/dependency/__init__.py +++ b/openbb_platform/core/openbb_core/api/dependency/__init__.py @@ -0,0 +1 @@ +"""OpenBB Core API Dependency.""" diff --git a/openbb_platform/core/openbb_core/api/router/__init__.py b/openbb_platform/core/openbb_core/api/router/__init__.py index e69de29bb2d1..93fabc683c4f 100644 --- a/openbb_platform/core/openbb_core/api/router/__init__.py +++ b/openbb_platform/core/openbb_core/api/router/__init__.py @@ -0,0 +1 @@ +"""OpenBB Core API Router.""" diff --git a/openbb_platform/core/openbb_core/app/__init__.py b/openbb_platform/core/openbb_core/app/__init__.py index e69de29bb2d1..6b3de9cda26a 100644 --- a/openbb_platform/core/openbb_core/app/__init__.py +++ b/openbb_platform/core/openbb_core/app/__init__.py @@ -0,0 +1 @@ +"""OpenBB Core App Module.""" diff --git a/openbb_platform/core/openbb_core/app/command_runner.py b/openbb_platform/core/openbb_core/app/command_runner.py index 3a43aba3e8a4..233d7be014f7 100644 --- a/openbb_platform/core/openbb_core/app/command_runner.py +++ b/openbb_platform/core/openbb_core/app/command_runner.py @@ -37,6 +37,7 @@ def __init__( system_settings: SystemSettings, user_settings: UserSettings, ) -> None: + """Initialize the execution context.""" self.command_map = command_map self.route = route self.system_settings = system_settings diff --git a/openbb_platform/core/openbb_core/app/deprecation.py b/openbb_platform/core/openbb_core/app/deprecation.py index 5dd38c1ae541..a771589913a8 100644 --- a/openbb_platform/core/openbb_core/app/deprecation.py +++ b/openbb_platform/core/openbb_core/app/deprecation.py @@ -50,6 +50,7 @@ def __init__( since: Optional[Tuple[int, int]] = None, expected_removal: Optional[Tuple[int, int]] = None, ) -> None: + """Initialize the warning.""" super().__init__(message, *args) self.message = message.rstrip(".") self.since = since or get_major_minor(VERSION) diff --git a/openbb_platform/core/openbb_core/app/logs/formatters/formatter_with_exceptions.py b/openbb_platform/core/openbb_core/app/logs/formatters/formatter_with_exceptions.py index 17ccd72ff646..f3f8c8f9066c 100644 --- a/openbb_platform/core/openbb_core/app/logs/formatters/formatter_with_exceptions.py +++ b/openbb_platform/core/openbb_core/app/logs/formatters/formatter_with_exceptions.py @@ -1,16 +1,15 @@ -# IMPORTATION STANDARD +"""Logging Formatter that includes formatting of Exceptions.""" + import logging import re from copy import deepcopy from pathlib import Path -# IMPORTATION THIRDPARTY -# IMPORTATION INTERNAL from openbb_core.app.logs.models.logging_settings import LoggingSettings class FormatterWithExceptions(logging.Formatter): - """Logging Formatter that includes formatting of Exceptions""" + """Logging Formatter that includes formatting of Exceptions.""" DATEFORMAT = "%Y-%m-%dT%H:%M:%S%z" LOGFORMAT = "%(asctime)s|%(name)s|%(funcName)s|%(lineno)s|%(message)s" @@ -20,6 +19,7 @@ class FormatterWithExceptions(logging.Formatter): @staticmethod def calculate_level_name(record: logging.LogRecord) -> str: + """Calculate the level name of the log record.""" if record.exc_text: level_name = "X" elif record.levelname: @@ -31,6 +31,7 @@ def calculate_level_name(record: logging.LogRecord) -> str: @staticmethod def extract_log_extra(record: logging.LogRecord): + """Extract extra log information from the record.""" log_extra = dict() if hasattr(record, "func_name_override"): @@ -44,6 +45,7 @@ def extract_log_extra(record: logging.LogRecord): @staticmethod def mock_ipv4(text: str) -> str: + """Mock IPv4 addresses in the text.""" pattern = r"\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}" replacement = " FILTERED_IP " text_mocked = re.sub(pattern, replacement, text) @@ -52,6 +54,7 @@ def mock_ipv4(text: str) -> str: @staticmethod def mock_email(text: str) -> str: + """Mock email addresses in the text.""" pattern = r"\b[A-Za-z0-9._%+-]+@[A-Za-z0-9.-]+\.[A-Z|a-z]{2,}\b" replacement = " FILTERED_EMAIL " text_mocked = re.sub(pattern, replacement, text) @@ -60,6 +63,7 @@ def mock_email(text: str) -> str: @staticmethod def mock_password(text: str) -> str: + """Mock passwords in the text.""" pattern = r'("password": ")[^"]+' replacement = r"\1 FILTERED_PASSWORD " text_mocked = re.sub(pattern, replacement, text) @@ -67,6 +71,7 @@ def mock_password(text: str) -> str: @staticmethod def mock_flair(text: str) -> str: + """Mock flair in the text.""" pattern = r'("FLAIR": "\[)(.*?)\]' replacement = r"\1 FILTERED_FLAIR ]" text_mocked = re.sub(pattern, replacement, text) @@ -75,6 +80,7 @@ def mock_flair(text: str) -> str: @staticmethod def mock_home_directory(text: str) -> str: + """Mock home directory in the text.""" user_home_directory = str(Path.home().as_posix()) text_mocked = text.replace("\\", "/").replace( user_home_directory, "MOCKING_USER_PATH" @@ -84,6 +90,7 @@ def mock_home_directory(text: str) -> str: @staticmethod def filter_special_tags(text: str) -> str: + """Filter special tags in the text.""" text_filtered = text.replace("\n", " MOCKING_BREAKLINE ") text_filtered = text_filtered.replace("'Traceback", "Traceback") @@ -91,6 +98,7 @@ def filter_special_tags(text: str) -> str: @classmethod def filter_piis(cls, text: str) -> str: + """Filter Personally Identifiable Information in the text.""" text_filtered = cls.mock_ipv4(text=text) text_filtered = cls.mock_email(text=text_filtered) text_filtered = cls.mock_password(text=text_filtered) @@ -101,6 +109,7 @@ def filter_piis(cls, text: str) -> str: @classmethod def filter_log_line(cls, text: str): + """Filter log line.""" text_filtered = cls.filter_special_tags(text=text) text_filtered = cls.filter_piis(text=text_filtered) @@ -113,6 +122,7 @@ def __init__( style="%", validate=True, ) -> None: + """Initialize the FormatterWithExceptions.""" super().__init__( fmt=self.LOGFORMAT, datefmt=self.DATEFORMAT, @@ -123,15 +133,18 @@ def __init__( @property def settings(self) -> LoggingSettings: + """Get the settings.""" return deepcopy(self.__settings) @settings.setter def settings(self, settings: LoggingSettings) -> None: + """Set the settings.""" self.__settings = settings # OVERRIDE def formatException(self, ei) -> str: - """Exception formatting handler + """Define the Exception formatting handler. + Parameters ---------- ei : logging._SysExcInfoType @@ -141,13 +154,13 @@ def formatException(self, ei) -> str: str Formatted exception """ - result = super().formatException(ei) return repr(result) # OVERRIDE def format(self, record: logging.LogRecord) -> str: - """Log formatter + """Define the Log formatter. + Parameters ---------- record : logging.LogRecord @@ -157,7 +170,6 @@ def format(self, record: logging.LogRecord) -> str: str Formatted_log message """ - level_name = self.calculate_level_name(record=record) log_prefix_content = { "appName": self.settings.app_name, diff --git a/openbb_platform/core/openbb_core/app/logs/handlers/path_tracking_file_handler.py b/openbb_platform/core/openbb_core/app/logs/handlers/path_tracking_file_handler.py index d8b65afaa22e..acf8a50d5cc6 100644 --- a/openbb_platform/core/openbb_core/app/logs/handlers/path_tracking_file_handler.py +++ b/openbb_platform/core/openbb_core/app/logs/handlers/path_tracking_file_handler.py @@ -1,3 +1,5 @@ +"""Path Tracking File Handler.""" + # IMPORTATION STANDARD from copy import deepcopy from logging.handlers import TimedRotatingFileHandler @@ -17,8 +19,11 @@ class PathTrackingFileHandler(TimedRotatingFileHandler): + """Path Tracking File Handler.""" + @staticmethod def build_log_file_path(settings: LoggingSettings) -> Path: + """Build the log file path.""" app_name = settings.app_name directory = settings.user_logs_directory session_id = settings.session_id @@ -27,8 +32,7 @@ def build_log_file_path(settings: LoggingSettings) -> Path: return path def clean_expired_files(self, before_timestamp: float): - """Remove expired files from logs directory""" - + """Remove expired files from logs directory.""" logs_dir = self.settings.user_logs_directory archives_directory = logs_dir / ARCHIVES_FOLDER_NAME tmp_directory = logs_dir / TMP_FOLDER_NAME @@ -51,10 +55,12 @@ def clean_expired_files(self, before_timestamp: float): @property def settings(self) -> LoggingSettings: + """Get the settings.""" return deepcopy(self.__settings) @settings.setter def settings(self, settings: LoggingSettings) -> None: + """Set the settings.""" self.__settings = settings # OVERRIDE @@ -64,6 +70,7 @@ def __init__( *args, **kwargs, ) -> None: + """Initialize the PathTrackingFileHandler.""" # SETUP PARENT CLASS filename = str(self.build_log_file_path(settings=settings)) frequency = settings.frequency diff --git a/openbb_platform/core/openbb_core/app/logs/handlers_manager.py b/openbb_platform/core/openbb_core/app/logs/handlers_manager.py index 3f2229b13c06..2d9a0efb927d 100644 --- a/openbb_platform/core/openbb_core/app/logs/handlers_manager.py +++ b/openbb_platform/core/openbb_core/app/logs/handlers_manager.py @@ -1,9 +1,8 @@ -# IMPORT STANDARD +"""Handlers Manager.""" + import logging import sys -# IMPORT THIRD-PARTY -# IMPORT INTERNAL from openbb_core.app.logs.formatters.formatter_with_exceptions import ( FormatterWithExceptions, ) @@ -15,7 +14,10 @@ class HandlersManager: + """Handlers Manager.""" + def __init__(self, settings: LoggingSettings): + """Initialize the HandlersManager.""" self._handlers = settings.handler_list self._settings = settings @@ -34,36 +36,42 @@ def __init__(self, settings: LoggingSettings): logging.getLogger().debug("Unknown log handler.") def _add_posthog_handler(self): + """Add a Posthog handler.""" handler = PosthogHandler(settings=self._settings) formatter = FormatterWithExceptions(settings=self._settings) handler.setFormatter(formatter) logging.getLogger().addHandler(handler) def _add_stdout_handler(self): + """Add a stdout handler.""" handler = logging.StreamHandler(sys.stdout) formatter = FormatterWithExceptions(settings=self._settings) handler.setFormatter(formatter) logging.getLogger().addHandler(handler) def _add_stderr_handler(self): + """Add a stderr handler.""" handler = logging.StreamHandler(sys.stderr) formatter = FormatterWithExceptions(settings=self._settings) handler.setFormatter(formatter) logging.getLogger().addHandler(handler) def _add_noop_handler(self): + """Add a null handler.""" handler = logging.NullHandler() formatter = FormatterWithExceptions(settings=self._settings) handler.setFormatter(formatter) logging.getLogger().addHandler(handler) def _add_file_handler(self): + """Add a file handler.""" handler = PathTrackingFileHandler(settings=self._settings) formatter = FormatterWithExceptions(settings=self._settings) handler.setFormatter(formatter) logging.getLogger().addHandler(handler) def update_handlers(self, settings: LoggingSettings): + """Update the handlers with new settings.""" logger = logging.getLogger() for hdlr in logger.handlers: if isinstance(hdlr, (PathTrackingFileHandler, PosthogHandler)): diff --git a/openbb_platform/core/openbb_core/app/logs/logging_service.py b/openbb_platform/core/openbb_core/app/logs/logging_service.py index 28067def6858..abc605ca7d81 100644 --- a/openbb_platform/core/openbb_core/app/logs/logging_service.py +++ b/openbb_platform/core/openbb_core/app/logs/logging_service.py @@ -19,8 +19,7 @@ class LoggingService(metaclass=SingletonMeta): - """ - Logging Manager class responsible for managing logging settings and handling logs. + """Logging Manager class responsible for managing logging settings and handling logs. Attributes ---------- @@ -59,8 +58,7 @@ def __init__( system_settings: SystemSettings, user_settings: UserSettings, ) -> None: - """ - Logging Service Constructor. + """Define the Logging Service Constructor. Sets up the logging settings and handlers and then logs the startup information. @@ -82,8 +80,7 @@ def __init__( @property def logging_settings(self) -> LoggingSettings: - """ - Current logging settings. + """Define the Current logging settings. Returns ------- @@ -94,8 +91,7 @@ def logging_settings(self) -> LoggingSettings: @logging_settings.setter def logging_settings(self, value: Tuple[SystemSettings, UserSettings]): - """ - Setter for updating the logging settings. + """Define the Setter for updating the logging settings. Parameters ---------- @@ -109,8 +105,7 @@ def logging_settings(self, value: Tuple[SystemSettings, UserSettings]): ) def _setup_handlers(self) -> HandlersManager: - """ - Setup Logging Handlers. + """Set up Logging Handlers. Returns ------- diff --git a/openbb_platform/core/openbb_core/app/logs/models/logging_settings.py b/openbb_platform/core/openbb_core/app/logs/models/logging_settings.py index 1cf14d5240f2..708246f9e9a4 100644 --- a/openbb_platform/core/openbb_core/app/logs/models/logging_settings.py +++ b/openbb_platform/core/openbb_core/app/logs/models/logging_settings.py @@ -1,3 +1,5 @@ +"""Logging settings.""" + from pathlib import Path from typing import List, Optional @@ -8,11 +10,14 @@ # pylint: disable=too-many-instance-attributes class LoggingSettings: + """Logging settings.""" + def __init__( self, user_settings: Optional[UserSettings] = None, system_settings: Optional[SystemSettings] = None, ): + """Initialize the logging settings.""" user_settings = user_settings or UserSettings() system_settings = system_settings or SystemSettings() diff --git a/openbb_platform/core/openbb_core/app/logs/utils/expired_files.py b/openbb_platform/core/openbb_core/app/logs/utils/expired_files.py index 4f101d23db8f..feb933c9a69b 100644 --- a/openbb_platform/core/openbb_core/app/logs/utils/expired_files.py +++ b/openbb_platform/core/openbb_core/app/logs/utils/expired_files.py @@ -1,20 +1,19 @@ -# IMPORTATION STANDARD +"""Expired files management utilities.""" + import contextlib from datetime import datetime from pathlib import Path from typing import List -# IMPORTATION THIRDPARTY - -# IMPORTATION INTERNAL - def get_timestamp_from_x_days(x: int) -> float: + """Get the timestamp from x days ago.""" timestamp_from_x_days = datetime.now().timestamp() - x * 86400 return timestamp_from_x_days def get_expired_file_list(directory: Path, before_timestamp: float) -> List[Path]: + """Get the list of expired files from a directory.""" expired_files = [] if directory.is_dir(): # Check if the directory exists and is a directory for file in directory.iterdir(): @@ -25,6 +24,7 @@ def get_expired_file_list(directory: Path, before_timestamp: float) -> List[Path def remove_file_list(file_list: List[Path]): + """Remove a list of files.""" for file in file_list: with contextlib.suppress(PermissionError): file.unlink(missing_ok=True) diff --git a/openbb_platform/core/openbb_core/app/logs/utils/utils.py b/openbb_platform/core/openbb_core/app/logs/utils/utils.py index a94efd331cbb..e150627b1473 100644 --- a/openbb_platform/core/openbb_core/app/logs/utils/utils.py +++ b/openbb_platform/core/openbb_core/app/logs/utils/utils.py @@ -1,12 +1,10 @@ -# IMPORT STANDARD +"""Utility functions for logging.""" + import time import uuid import warnings from pathlib import Path, PosixPath -# IMPORT THIRD-PARTY -# IMPORT INTERNAL - def get_session_id() -> str: """UUID of the current session.""" @@ -41,6 +39,7 @@ def get_log_dir(contextual_user_data_directory: str) -> PosixPath: def create_log_dir_if_not_exists(contextual_user_data_directory: str) -> Path: + """Create a log directory for the current installation.""" log_dir = Path(contextual_user_data_directory).joinpath("logs").absolute() if not log_dir.is_dir(): log_dir.mkdir(parents=True, exist_ok=True) @@ -49,6 +48,7 @@ def create_log_dir_if_not_exists(contextual_user_data_directory: str) -> Path: def create_log_uuid_if_not_exists(log_dir: Path) -> str: + """Create a log id file for the current logging session.""" log_id = get_log_id(log_dir) if not log_id.is_file(): logging_id = f"{uuid.uuid4()}" @@ -60,10 +60,12 @@ def create_log_uuid_if_not_exists(log_dir: Path) -> str: def get_log_id(log_dir): + """Get the log id file.""" return (log_dir / ".logid").absolute() def create_uuid_dir_if_not_exists(log_dir, logging_id) -> PosixPath: + """Create a directory for the current logging session.""" uuid_log_dir = (log_dir / logging_id).absolute() if not uuid_log_dir.is_dir(): diff --git a/openbb_platform/core/openbb_core/app/model/__init__.py b/openbb_platform/core/openbb_core/app/model/__init__.py index e69de29bb2d1..44adb9707fe7 100644 --- a/openbb_platform/core/openbb_core/app/model/__init__.py +++ b/openbb_platform/core/openbb_core/app/model/__init__.py @@ -0,0 +1 @@ +"""OpenBB Core App Model.""" diff --git a/openbb_platform/core/openbb_core/app/model/abstract/__init__.py b/openbb_platform/core/openbb_core/app/model/abstract/__init__.py index e69de29bb2d1..65daa6e56506 100644 --- a/openbb_platform/core/openbb_core/app/model/abstract/__init__.py +++ b/openbb_platform/core/openbb_core/app/model/abstract/__init__.py @@ -0,0 +1 @@ +"""OpenBB Core App Abstract Model.""" diff --git a/openbb_platform/core/openbb_core/app/model/abstract/error.py b/openbb_platform/core/openbb_core/app/model/abstract/error.py index 95cc53b434e8..91c67d9aa242 100644 --- a/openbb_platform/core/openbb_core/app/model/abstract/error.py +++ b/openbb_platform/core/openbb_core/app/model/abstract/error.py @@ -1,3 +1,5 @@ +"""OpenBB Error.""" + from typing import Optional, Union @@ -5,5 +7,6 @@ class OpenBBError(Exception): """OpenBB Error.""" def __init__(self, original: Optional[Union[str, Exception]] = None): + """Initialize the OpenBBError.""" self.original = original super().__init__(str(original)) diff --git a/openbb_platform/core/openbb_core/app/model/abstract/results.py b/openbb_platform/core/openbb_core/app/model/abstract/results.py index 5152f0fad580..a9456b991898 100644 --- a/openbb_platform/core/openbb_core/app/model/abstract/results.py +++ b/openbb_platform/core/openbb_core/app/model/abstract/results.py @@ -1,3 +1,5 @@ +"""OpenBB Core App Model Abstract Results.""" + from pydantic import BaseModel Results = BaseModel diff --git a/openbb_platform/core/openbb_core/app/model/abstract/singleton.py b/openbb_platform/core/openbb_core/app/model/abstract/singleton.py index 3575186ee22c..0ecccafc446a 100644 --- a/openbb_platform/core/openbb_core/app/model/abstract/singleton.py +++ b/openbb_platform/core/openbb_core/app/model/abstract/singleton.py @@ -1,13 +1,18 @@ +"""Singleton metaclass implementation.""" + from typing import Dict, Generic, TypeVar T = TypeVar("T") class SingletonMeta(type, Generic[T]): + """Singleton metaclass.""" + # TODO : check if we want to update this to be thread safe _instances: Dict[T, T] = {} def __call__(cls: "SingletonMeta", *args, **kwargs): + """Singleton pattern implementation.""" if cls not in cls._instances: instance = super().__call__(*args, **kwargs) cls._instances[cls] = instance diff --git a/openbb_platform/core/openbb_core/app/model/abstract/tagged.py b/openbb_platform/core/openbb_core/app/model/abstract/tagged.py index 134a26055679..80cfe1678e0a 100644 --- a/openbb_platform/core/openbb_core/app/model/abstract/tagged.py +++ b/openbb_platform/core/openbb_core/app/model/abstract/tagged.py @@ -1,6 +1,10 @@ +"""OpenBB Core App Abstract Model Tagged.""" + from pydantic import BaseModel, Field from uuid_extensions import uuid7str # type: ignore class Tagged(BaseModel): + """Model for Tagged.""" + id: str = Field(default_factory=uuid7str, alias="_id") diff --git a/openbb_platform/core/openbb_core/app/model/abstract/warning.py b/openbb_platform/core/openbb_core/app/model/abstract/warning.py index 2e2f778c397e..7914b6af7f7a 100644 --- a/openbb_platform/core/openbb_core/app/model/abstract/warning.py +++ b/openbb_platform/core/openbb_core/app/model/abstract/warning.py @@ -1,14 +1,19 @@ +"""Module for warnings.""" + from warnings import WarningMessage from pydantic import BaseModel class Warning_(BaseModel): + """Model for Warning.""" + category: str message: str def cast_warning(w: WarningMessage) -> Warning_: + """Cast a warning to a pydantic model.""" return Warning_( category=w.category.__name__, message=str(w.message), @@ -16,4 +21,4 @@ def cast_warning(w: WarningMessage) -> Warning_: class OpenBBWarning(Warning): - pass + """Base class for OpenBB warnings.""" diff --git a/openbb_platform/core/openbb_core/app/model/charts/chart.py b/openbb_platform/core/openbb_core/app/model/charts/chart.py index a825be1e9fe6..38d062d79665 100644 --- a/openbb_platform/core/openbb_core/app/model/charts/chart.py +++ b/openbb_platform/core/openbb_core/app/model/charts/chart.py @@ -1,3 +1,5 @@ +"""OpenBB Core Chart model.""" + from enum import Enum from typing import Any, Dict, Optional @@ -5,10 +7,14 @@ class ChartFormat(str, Enum): + """Chart format.""" + plotly = "plotly" class Chart(BaseModel): + """Model for Chart.""" + content: Optional[Dict[str, Any]] = Field( default=None, description="Raw textual representation of the chart.", @@ -25,6 +31,7 @@ class Chart(BaseModel): model_config = ConfigDict(validate_assignment=True) def __repr__(self) -> str: + """Return string representation.""" return f"{self.__class__.__name__}\n\n" + "\n".join( f"{k}: {v}" for k, v in self.model_dump().items() ) diff --git a/openbb_platform/core/openbb_core/app/model/command_context.py b/openbb_platform/core/openbb_core/app/model/command_context.py index 052fb5bc780b..977df7a485b7 100644 --- a/openbb_platform/core/openbb_core/app/model/command_context.py +++ b/openbb_platform/core/openbb_core/app/model/command_context.py @@ -1,3 +1,5 @@ +"""Command Context.""" + from pydantic import BaseModel, Field from openbb_core.app.model.system_settings import SystemSettings @@ -5,5 +7,7 @@ class CommandContext(BaseModel): + """Command Context.""" + user_settings: UserSettings = Field(default_factory=UserSettings) system_settings: SystemSettings = Field(default_factory=SystemSettings) diff --git a/openbb_platform/core/openbb_core/app/model/credentials.py b/openbb_platform/core/openbb_core/app/model/credentials.py index 30cae535ef7a..5ed7684e351e 100644 --- a/openbb_platform/core/openbb_core/app/model/credentials.py +++ b/openbb_platform/core/openbb_core/app/model/credentials.py @@ -100,7 +100,7 @@ class Credentials(_Credentials): # type: ignore """Credentials model used to store provider credentials.""" def __repr__(self) -> str: - """String representation of the credentials.""" + """Define the string representation of the credentials.""" return ( self.__class__.__name__ + "\n\n" diff --git a/openbb_platform/core/openbb_core/app/model/custom_parameter.py b/openbb_platform/core/openbb_core/app/model/custom_parameter.py index 06b947e0c552..58cfb3faa532 100644 --- a/openbb_platform/core/openbb_core/app/model/custom_parameter.py +++ b/openbb_platform/core/openbb_core/app/model/custom_parameter.py @@ -1,3 +1,5 @@ +"""Custom parameter and choices for OpenBB.""" + import sys from dataclasses import dataclass from typing import Dict, Optional diff --git a/openbb_platform/core/openbb_core/app/model/defaults.py b/openbb_platform/core/openbb_core/app/model/defaults.py index ad41b1dc2281..52007edf5dea 100644 --- a/openbb_platform/core/openbb_core/app/model/defaults.py +++ b/openbb_platform/core/openbb_core/app/model/defaults.py @@ -1,3 +1,5 @@ +"""Defaults model.""" + from typing import Dict, Optional from pydantic import BaseModel, ConfigDict, Field @@ -11,6 +13,7 @@ class Defaults(BaseModel): routes: Dict[str, Dict[str, Optional[str]]] = Field(default_factory=dict) def __repr__(self) -> str: + """Return string representation.""" return f"{self.__class__.__name__}\n\n" + "\n".join( f"{k}: {v}" for k, v in self.model_dump().items() ) diff --git a/openbb_platform/core/openbb_core/app/model/hub/features_keys.py b/openbb_platform/core/openbb_core/app/model/hub/features_keys.py index c0653ff443c7..b96186c6b356 100644 --- a/openbb_platform/core/openbb_core/app/model/hub/features_keys.py +++ b/openbb_platform/core/openbb_core/app/model/hub/features_keys.py @@ -1,9 +1,13 @@ +"""Model for API keys for various providers.""" + from typing import Optional from pydantic import BaseModel, Field class FeaturesKeys(BaseModel): + """API keys for various providers.""" + API_BITQUERY_KEY: Optional[str] = Field(default=None) API_BIZTOC_TOKEN: Optional[str] = Field(default=None) API_CMC_KEY: Optional[str] = Field(default=None) diff --git a/openbb_platform/core/openbb_core/app/model/hub/hub_session.py b/openbb_platform/core/openbb_core/app/model/hub/hub_session.py index fb0142eafc18..7a9cf6159913 100644 --- a/openbb_platform/core/openbb_core/app/model/hub/hub_session.py +++ b/openbb_platform/core/openbb_core/app/model/hub/hub_session.py @@ -1,9 +1,13 @@ +"""Model for HubSession.""" + from typing import Optional from pydantic import BaseModel, SecretStr, field_serializer class HubSession(BaseModel): + """Model for HubSession.""" + username: Optional[str] = None email: str primary_usage: str @@ -12,10 +16,12 @@ class HubSession(BaseModel): access_token: SecretStr def __repr__(self) -> str: + """Return string representation.""" return f"{self.__class__.__name__}\n\n" + "\n".join( f"{k}: {v}" for k, v in self.model_dump().items() ) @field_serializer("access_token", when_used="json-unless-none") def _dump_secret(self, v): + """Dump secret.""" return v.get_secret_value() diff --git a/openbb_platform/core/openbb_core/app/model/hub/hub_user_settings.py b/openbb_platform/core/openbb_core/app/model/hub/hub_user_settings.py index aebcf6afa312..34d385cacd76 100644 --- a/openbb_platform/core/openbb_core/app/model/hub/hub_user_settings.py +++ b/openbb_platform/core/openbb_core/app/model/hub/hub_user_settings.py @@ -1,3 +1,5 @@ +"""Hub user settings model.""" + # from typing import Dict, List, Union from openbb_core.app.model.hub.features_keys import FeaturesKeys @@ -5,6 +7,8 @@ class HubUserSettings(BaseModel): + """User settings for the Hub.""" + # features_settings: Dict[str, str] features_keys: FeaturesKeys = Field(default_factory=FeaturesKeys) # features_sources: Dict[str, List[str]] diff --git a/openbb_platform/core/openbb_core/app/model/metadata.py b/openbb_platform/core/openbb_core/app/model/metadata.py index cf421fca7e0c..eca37b061f99 100644 --- a/openbb_platform/core/openbb_core/app/model/metadata.py +++ b/openbb_platform/core/openbb_core/app/model/metadata.py @@ -1,3 +1,5 @@ +"""Metadata model.""" + from datetime import datetime from inspect import isclass from typing import Any, Dict, Optional, Sequence, Union @@ -10,6 +12,8 @@ class Metadata(BaseModel): + """Metadata of a command execution.""" + arguments: Dict[str, Any] = Field( default_factory=dict, description="Arguments of the command.", @@ -21,6 +25,7 @@ class Metadata(BaseModel): timestamp: datetime = Field(description="Execution starting timestamp.") def __repr__(self) -> str: + """Return string representation.""" return f"{self.__class__.__name__}\n\n" + "\n".join( f"{k}: {v}" for k, v in self.model_dump().items() ) @@ -29,6 +34,7 @@ def __repr__(self) -> str: @classmethod def scale_arguments(cls, v): """Scale arguments. + This function is meant to limit the size of the input arguments of a command. If the type is one of the following: `Data`, `List[Data]`, `DataFrame`, `List[DataFrame]`, `Series`, `List[Series]` or `ndarray`, the value of the argument is swapped by a dictionary diff --git a/openbb_platform/core/openbb_core/app/model/profile.py b/openbb_platform/core/openbb_core/app/model/profile.py index 64959e5c7987..f1e62db03934 100644 --- a/openbb_platform/core/openbb_core/app/model/profile.py +++ b/openbb_platform/core/openbb_core/app/model/profile.py @@ -1,3 +1,5 @@ +"""Profile model.""" + from typing import Optional from pydantic import BaseModel, ConfigDict, Field @@ -6,10 +8,13 @@ class Profile(BaseModel): + """Profile.""" + hub_session: Optional[HubSession] = Field(default=None) model_config = ConfigDict(validate_assignment=True) def __repr__(self) -> str: + """Return string representation.""" return f"{self.__class__.__name__}\n\n" + "\n".join( f"{k}: {v}" for k, v in self.model_dump().items() ) diff --git a/openbb_platform/core/openbb_core/app/model/results/__init__.py b/openbb_platform/core/openbb_core/app/model/results/__init__.py index e69de29bb2d1..a87e3e8784fc 100644 --- a/openbb_platform/core/openbb_core/app/model/results/__init__.py +++ b/openbb_platform/core/openbb_core/app/model/results/__init__.py @@ -0,0 +1 @@ +"""OpenBB Core App Model Results.""" diff --git a/openbb_platform/core/openbb_core/app/model/results/empty.py b/openbb_platform/core/openbb_core/app/model/results/empty.py index 4b23c9030333..0f9779a681d0 100644 --- a/openbb_platform/core/openbb_core/app/model/results/empty.py +++ b/openbb_platform/core/openbb_core/app/model/results/empty.py @@ -1,5 +1,7 @@ +"""Empty results.""" + from openbb_core.app.model.abstract.results import Results class Empty(Results): - pass + """Empty results.""" diff --git a/openbb_platform/core/openbb_core/app/service/auth_service.py b/openbb_platform/core/openbb_core/app/service/auth_service.py index 6ce4ecbb2211..3bbe97c92dcb 100644 --- a/openbb_platform/core/openbb_core/app/service/auth_service.py +++ b/openbb_platform/core/openbb_core/app/service/auth_service.py @@ -29,7 +29,7 @@ class AuthService(metaclass=SingletonMeta): """Auth service.""" def __init__(self, ext_name: Optional[str] = EXT_NAME) -> None: - """Initializes AuthService.""" + """Initialize AuthService.""" if not self._load_extension(ext_name): self._router = default_router self._auth_hook = default_auth_hook @@ -37,22 +37,22 @@ def __init__(self, ext_name: Optional[str] = EXT_NAME) -> None: @property def router(self) -> APIRouter: - """Gets router.""" + """Get router.""" return self._router @property def auth_hook(self) -> Callable[..., Awaitable[None]]: - """Gets general authentication hook.""" + """Get general authentication hook.""" return self._auth_hook @property def user_settings_hook(self) -> Callable[..., Awaitable[UserSettings]]: - """Gets user settings hook.""" + """Get user settings hook.""" return self._user_settings_hook @staticmethod def _is_installed(ext_name: str) -> bool: - """Checks if auth_extension is installed.""" + """Check if auth_extension is installed.""" extension = ExtensionLoader().get_core_entry_point(ext_name) or False return extension and ext_name == extension.name # type: ignore diff --git a/openbb_platform/core/openbb_core/app/service/hub_service.py b/openbb_platform/core/openbb_core/app/service/hub_service.py index 22e6330bd76e..390f5e3c5c25 100644 --- a/openbb_platform/core/openbb_core/app/service/hub_service.py +++ b/openbb_platform/core/openbb_core/app/service/hub_service.py @@ -28,6 +28,7 @@ def __init__( session: Optional[HubSession] = None, base_url: Optional[str] = None, ): + """Initialize Hub service.""" self._base_url = base_url or Env().HUB_BACKEND self._session = session diff --git a/openbb_platform/core/openbb_core/app/service/system_service.py b/openbb_platform/core/openbb_core/app/service/system_service.py index c18bc1354ef6..fd7b565b588a 100644 --- a/openbb_platform/core/openbb_core/app/service/system_service.py +++ b/openbb_platform/core/openbb_core/app/service/system_service.py @@ -29,6 +29,7 @@ def __init__( self, **kwargs, ): + """Initialize system service.""" self._system_settings = self._read_default_system_settings( path=self.SYSTEM_SETTINGS_PATH, **kwargs ) diff --git a/openbb_platform/core/openbb_core/app/service/user_service.py b/openbb_platform/core/openbb_core/app/service/user_service.py index 9b6fcff50bcd..8ab438782ebe 100644 --- a/openbb_platform/core/openbb_core/app/service/user_service.py +++ b/openbb_platform/core/openbb_core/app/service/user_service.py @@ -20,6 +20,7 @@ def __init__( self, default_user_settings: Optional[UserSettings] = None, ): + """Initialize user service.""" self._default_user_settings = ( default_user_settings or self.read_default_user_settings() ) diff --git a/openbb_platform/core/openbb_core/app/static/__init__.py b/openbb_platform/core/openbb_core/app/static/__init__.py index e69de29bb2d1..bbfce45ce157 100644 --- a/openbb_platform/core/openbb_core/app/static/__init__.py +++ b/openbb_platform/core/openbb_core/app/static/__init__.py @@ -0,0 +1 @@ +"""OpenBB Core App Static.""" diff --git a/openbb_platform/core/openbb_core/app/static/app_factory.py b/openbb_platform/core/openbb_core/app/static/app_factory.py index e63c73d09842..6e022b9812ac 100644 --- a/openbb_platform/core/openbb_core/app/static/app_factory.py +++ b/openbb_platform/core/openbb_core/app/static/app_factory.py @@ -26,6 +26,7 @@ class BaseApp: """Base app.""" def __init__(self, command_runner: CommandRunner): + """Initialize the app.""" command_runner.init_logging_service() self._command_runner = command_runner self._account = Account(self) diff --git a/openbb_platform/core/openbb_core/app/static/container.py b/openbb_platform/core/openbb_core/app/static/container.py index a8a38b62963d..60fc1def9bbd 100644 --- a/openbb_platform/core/openbb_core/app/static/container.py +++ b/openbb_platform/core/openbb_core/app/static/container.py @@ -11,6 +11,7 @@ class Container: """Container class for the command runner session.""" def __init__(self, command_runner: CommandRunner) -> None: + """Initialize the container.""" self._command_runner = command_runner OBBject._user_settings = command_runner.user_settings OBBject._system_settings = command_runner.system_settings diff --git a/openbb_platform/core/openbb_core/app/static/utils/decorators.py b/openbb_platform/core/openbb_core/app/static/utils/decorators.py index 61d9b46578b7..a8fbf1f0d591 100644 --- a/openbb_platform/core/openbb_core/app/static/utils/decorators.py +++ b/openbb_platform/core/openbb_core/app/static/utils/decorators.py @@ -29,7 +29,7 @@ def validate( """Validate function calls.""" def decorated(f: Callable[P, R]): - """Decorated function.""" + """Use for decorating functions.""" @wraps(f) def wrapper(*f_args, **f_kwargs): diff --git a/openbb_platform/core/openbb_core/env.py b/openbb_platform/core/openbb_core/env.py index e4e4c1df4619..9249658ffbc8 100644 --- a/openbb_platform/core/openbb_core/env.py +++ b/openbb_platform/core/openbb_core/env.py @@ -1,3 +1,5 @@ +"""Environment variables.""" + import os from pathlib import Path from typing import Dict, Optional @@ -14,47 +16,48 @@ class Env(metaclass=SingletonMeta): _environ: Dict[str, str] def __init__(self) -> None: + """Initialize the environment.""" dotenv.load_dotenv(Path(OPENBB_DIRECTORY, ".env")) self._environ = os.environ.copy() @property def API_AUTH(self) -> bool: - """API authentication: enables API endpoint authentication""" + """API authentication: enables API endpoint authentication.""" return self.str2bool(self._environ.get("OPENBB_API_AUTH", False)) @property def API_USERNAME(self) -> Optional[str]: - """API username: sets API username""" + """API username: sets API username.""" return self._environ.get("OPENBB_API_USERNAME", None) @property def API_PASSWORD(self) -> Optional[str]: - """API password: sets API password""" + """API password: sets API password.""" return self._environ.get("OPENBB_API_PASSWORD", None) @property def API_AUTH_EXTENSION(self) -> Optional[str]: - """Auth extension: specifies which authentication extension to use""" + """Auth extension: specifies which authentication extension to use.""" return self._environ.get("OPENBB_API_AUTH_EXTENSION", None) @property def AUTO_BUILD(self) -> bool: - """Automatic build: enables automatic package build on import""" + """Automatic build: enables automatic package build on import.""" return self.str2bool(self._environ.get("OPENBB_AUTO_BUILD", True)) @property def DEBUG_MODE(self) -> bool: - """Debug mode: enables debug mode""" + """Debug mode: enables debug mode.""" return self.str2bool(self._environ.get("OPENBB_DEBUG_MODE", False)) @property def DEV_MODE(self) -> bool: - """Dev mode: enables development mode""" + """Dev mode: enables development mode.""" return self.str2bool(self._environ.get("OPENBB_DEV_MODE", False)) @property def HUB_BACKEND(self) -> str: - """Hub backend: sets the backend for the OpenBB Hub""" + """Hub backend: sets the backend for the OpenBB Hub.""" return self._environ.get("OPENBB_HUB_BACKEND", "https://payments.openbb.co") @staticmethod diff --git a/openbb_platform/core/openbb_core/provider/standard_models/options_chains.py b/openbb_platform/core/openbb_core/provider/standard_models/options_chains.py index ddde23dc45c3..231945419ed3 100644 --- a/openbb_platform/core/openbb_core/provider/standard_models/options_chains.py +++ b/openbb_platform/core/openbb_core/provider/standard_models/options_chains.py @@ -24,6 +24,7 @@ class OptionsChainsQueryParams(QueryParams): @classmethod @field_validator("symbol", mode="before", check_fields=False) def to_upper(cls, v: str) -> str: + """Return the symbol in uppercase.""" return v.upper() @@ -151,7 +152,7 @@ class OptionsChainsData(Data): @field_validator("expiration", mode="before", check_fields=False) @classmethod def date_validate(cls, v): # pylint: disable=E0213 - """Return the datetime object from the date string""" + """Return the datetime object from the date string.""" if isinstance(v, datetime): return datetime.strftime(v, "%Y-%m-%d") if isinstance(v, str): diff --git a/openbb_platform/core/openbb_core/provider/utils/client.py b/openbb_platform/core/openbb_core/provider/utils/client.py index 0bec922d9acd..f093a90d4b16 100644 --- a/openbb_platform/core/openbb_core/provider/utils/client.py +++ b/openbb_platform/core/openbb_core/provider/utils/client.py @@ -41,6 +41,7 @@ class ClientResponse(aiohttp.ClientResponse): """Client response class.""" def __init__(self, *args, **kwargs): + """Initialize the response.""" kwargs["request_info"] = self.obfuscate_request_info(kwargs["request_info"]) super().__init__(*args, **kwargs) @@ -61,10 +62,13 @@ async def json(self, **kwargs) -> Union[dict, list]: class ClientSession(aiohttp.ClientSession): + """Client session.""" + _response_class: Type[ClientResponse] _session: "ClientSession" def __init__(self, *args, **kwargs): + """Initialize the session.""" kwargs["connector"] = kwargs.get( "connector", aiohttp.TCPConnector(ttl_dns_cache=300) ) diff --git a/openbb_platform/core/tests/api/test_dependency/__init__.py b/openbb_platform/core/tests/api/test_dependency/__init__.py index e69de29bb2d1..55cb40ff9e8e 100644 --- a/openbb_platform/core/tests/api/test_dependency/__init__.py +++ b/openbb_platform/core/tests/api/test_dependency/__init__.py @@ -0,0 +1 @@ +"""OpenBB Platform Core tests.""" diff --git a/openbb_platform/core/tests/api/test_router/__init__.py b/openbb_platform/core/tests/api/test_router/__init__.py index e69de29bb2d1..21bb0e0cc06b 100644 --- a/openbb_platform/core/tests/api/test_router/__init__.py +++ b/openbb_platform/core/tests/api/test_router/__init__.py @@ -0,0 +1 @@ +"""OpenBB Platform Core API router tests.""" diff --git a/openbb_platform/core/tests/app/__init__.py b/openbb_platform/core/tests/app/__init__.py index e69de29bb2d1..3f4c8aabddaf 100644 --- a/openbb_platform/core/tests/app/__init__.py +++ b/openbb_platform/core/tests/app/__init__.py @@ -0,0 +1 @@ +"""OpenBB Platform core tests.""" diff --git a/openbb_platform/core/tests/app/logs/__init__.py b/openbb_platform/core/tests/app/logs/__init__.py index e69de29bb2d1..673bc2dec2f0 100644 --- a/openbb_platform/core/tests/app/logs/__init__.py +++ b/openbb_platform/core/tests/app/logs/__init__.py @@ -0,0 +1 @@ +"""OpenBB Platform Core.""" diff --git a/openbb_platform/core/tests/app/logs/formatters/__init__.py b/openbb_platform/core/tests/app/logs/formatters/__init__.py index e69de29bb2d1..3f4c8aabddaf 100644 --- a/openbb_platform/core/tests/app/logs/formatters/__init__.py +++ b/openbb_platform/core/tests/app/logs/formatters/__init__.py @@ -0,0 +1 @@ +"""OpenBB Platform core tests.""" diff --git a/openbb_platform/core/tests/app/logs/formatters/test_formatter_with_exceptions.py b/openbb_platform/core/tests/app/logs/formatters/test_formatter_with_exceptions.py index 90a2cae1b37d..625c0bc87cc8 100644 --- a/openbb_platform/core/tests/app/logs/formatters/test_formatter_with_exceptions.py +++ b/openbb_platform/core/tests/app/logs/formatters/test_formatter_with_exceptions.py @@ -1,3 +1,5 @@ +"""Tests for the FormatterWithExceptions class.""" + import logging import os from unittest.mock import Mock @@ -7,6 +9,8 @@ FormatterWithExceptions, ) +# pylint: disable=W0621 + logging_settings = Mock() logging_settings.app_name = "test_app_name" logging_settings.app_id = "test_app_id" @@ -16,11 +20,13 @@ @pytest.fixture def formatter(): + """Return a FormatterWithExceptions instance.""" return FormatterWithExceptions(logging_settings) # Test when exc_text is not empty (should return "X") def test_level_name_with_exc_text(formatter): + """Test the calculate_level_name method.""" record = logging.LogRecord( name="test_logger", level=logging.INFO, @@ -37,6 +43,7 @@ def test_level_name_with_exc_text(formatter): # Test when levelname is not empty (should return the first character of levelname) def test_level_name_with_levelname(formatter): + """Test the calculate_level_name method.""" record = logging.LogRecord( name="test_logger", level=logging.WARNING, @@ -53,6 +60,7 @@ def test_level_name_with_levelname(formatter): # Test when func_name_override and session_id are present in the record def test_extract_log_extra_with_override_and_session_id(formatter): + """Test the extract_log_extra method.""" record = logging.LogRecord( name="test_logger", level=logging.INFO, @@ -75,6 +83,7 @@ def test_extract_log_extra_with_override_and_session_id(formatter): # Test when only func_name_override is present in the record def test_extract_log_extra_with_override(formatter): + """Test the extract_log_extra method.""" record = logging.LogRecord( name="test_logger", level=logging.INFO, @@ -96,6 +105,7 @@ def test_extract_log_extra_with_override(formatter): # Test when only session_id is present in the record def test_extract_log_extra_with_session_id(formatter): + """Test the extract_log_extra method.""" record = logging.LogRecord( name="test_logger", level=logging.INFO, @@ -117,6 +127,7 @@ def test_extract_log_extra_with_session_id(formatter): # Test when neither func_name_override nor session_id are present in the record def test_extract_log_extra_with_no_override_or_session_id(formatter): + """Test the extract_log_extra method.""" record = logging.LogRecord( name="test_logger", level=logging.INFO, @@ -144,6 +155,7 @@ def test_extract_log_extra_with_no_override_or_session_id(formatter): ], ) def test_mock_ipv4(input_text, expected_output, formatter): + """Test the mock_ipv4 method.""" assert formatter.mock_ipv4(input_text) == expected_output @@ -158,6 +170,7 @@ def test_mock_ipv4(input_text, expected_output, formatter): ], ) def test_mock_email(input_text, expected_output, formatter): + """Test the mock_email method.""" assert formatter.mock_email(input_text) == expected_output @@ -175,6 +188,7 @@ def test_mock_email(input_text, expected_output, formatter): ], ) def test_mock_password(input_text, expected_output, formatter): + """Test the mock_password method.""" assert formatter.mock_password(input_text) == expected_output @@ -190,6 +204,7 @@ def test_mock_password(input_text, expected_output, formatter): ], ) def test_mock_flair(input_text, expected_output, formatter): + """Test the mock_flair method.""" assert formatter.mock_flair(input_text) == expected_output @@ -212,6 +227,7 @@ def test_mock_flair(input_text, expected_output, formatter): ], ) def test_mock_home_directory(input_text, expected_output, formatter): + """Test the mock_home_directory method.""" assert formatter.mock_home_directory(input_text) == expected_output @@ -232,6 +248,7 @@ def test_mock_home_directory(input_text, expected_output, formatter): ], ) def test_filter_special_tags(input_text, expected_output, formatter): + """Test the filter_special_tags method.""" assert formatter.filter_special_tags(input_text) == expected_output @@ -249,6 +266,7 @@ def test_filter_special_tags(input_text, expected_output, formatter): ], ) def test_filter_piis(input_text, expected_output, formatter): + """Test the filter_piis method.""" assert formatter.filter_piis(input_text) == expected_output @@ -267,15 +285,18 @@ def test_filter_piis(input_text, expected_output, formatter): ], ) def test_filter_log_line(input_text, expected_output, formatter): + """Test the filter_log_line method.""" assert formatter.filter_log_line(input_text) == expected_output def test_formatException_invalid(): + """Test the formatException method with an invalid exception.""" with pytest.raises(Exception): formatter.formatException(Exception("Big bad error")) # type: ignore[attr-defined] def test_format(formatter): + """Test the format method.""" # Prepare the log record log_record = logging.LogRecord( name="test_logger", diff --git a/openbb_platform/core/tests/app/logs/handlers/__init__.py b/openbb_platform/core/tests/app/logs/handlers/__init__.py index e69de29bb2d1..55cb40ff9e8e 100644 --- a/openbb_platform/core/tests/app/logs/handlers/__init__.py +++ b/openbb_platform/core/tests/app/logs/handlers/__init__.py @@ -0,0 +1 @@ +"""OpenBB Platform Core tests.""" diff --git a/openbb_platform/core/tests/app/logs/handlers/test_path_tracking_file_handler.py b/openbb_platform/core/tests/app/logs/handlers/test_path_tracking_file_handler.py index 40dae4a702fb..ba81d15e1ab7 100644 --- a/openbb_platform/core/tests/app/logs/handlers/test_path_tracking_file_handler.py +++ b/openbb_platform/core/tests/app/logs/handlers/test_path_tracking_file_handler.py @@ -12,7 +12,10 @@ class MockLoggingSettings: + """Mock logging settings.""" + def __init__(self, app_name, user_logs_directory, session_id, frequency): + """Initialize the mock logging settings.""" self.app_name = app_name self.user_logs_directory = Path(user_logs_directory) self.session_id = session_id @@ -31,17 +34,20 @@ def __init__(self, app_name, user_logs_directory, session_id, frequency): @pytest.fixture(scope="module") def mocked_path(tmp_path_factory): + """Fixture to create a mocked file path.""" return tmp_path_factory.mktemp("mocked_path") / "mocked_file.log" @pytest.fixture(scope="module") def handler(mocked_path): + """Fixture to create a PathTrackingFileHandler instance.""" # patch `pathlib.Path.joinpath` to return a string containing the joined path with patch.object(Path, "joinpath", return_value=mocked_path): return PathTrackingFileHandler(logging_settings) def test_build_log_file_path(handler, mocked_path): + """Test build_log_file_path method.""" # Define a sample LoggingSettings object with mock attributes settings = MagicMock(spec=MockLoggingSettings) settings.app_name = "my_app" @@ -60,6 +66,7 @@ def test_build_log_file_path(handler, mocked_path): def test_clean_expired_files(handler): + """Test clean_expired_files method.""" with patch( "openbb_core.app.logs.handlers.path_tracking_file_handler.get_expired_file_list" ) as mock_get_expired_file_list, patch( diff --git a/openbb_platform/core/tests/app/logs/handlers/test_posthog_handler.py b/openbb_platform/core/tests/app/logs/handlers/test_posthog_handler.py index 5038f3ec016b..5e795a4bf5fa 100644 --- a/openbb_platform/core/tests/app/logs/handlers/test_posthog_handler.py +++ b/openbb_platform/core/tests/app/logs/handlers/test_posthog_handler.py @@ -1,3 +1,5 @@ +"""Tests for the PosthogHandler class.""" + import logging from pathlib import Path from unittest.mock import MagicMock @@ -8,7 +10,10 @@ ) +# pylint: disable=W0621, R0913 class MockLoggingSettings: + """Mock logging settings.""" + def __init__( self, app_name, @@ -22,6 +27,7 @@ def __init__( platform_version, userid, ): + """Initialize the mock logging settings.""" self.app_name = app_name self.sub_app_name = sub_app_name self.user_logs_directory = Path(user_logs_directory) @@ -52,10 +58,12 @@ def __init__( @pytest.fixture def handler(): + """Fixture to create a PosthogHandler instance.""" return PosthogHandler(logging_settings) def test_emit_calls_send(handler): + """Test the emit method.""" # Arrange record = logging.LogRecord( name="test_logger", @@ -78,6 +86,7 @@ def test_emit_calls_send(handler): def test_emit_calls_handleError_when_send_raises_exception(handler): + """Test the emit method.""" # Arrange record = logging.LogRecord( name="test_logger", @@ -104,6 +113,7 @@ def test_emit_calls_handleError_when_send_raises_exception(handler): def test_emit_calls_handleError_when_send_raises_exception_of_specific_type(handler): + """Test the emit method.""" # Arrange record = logging.LogRecord( name="test_logger", @@ -130,6 +140,7 @@ def test_emit_calls_handleError_when_send_raises_exception_of_specific_type(hand def test_emit_calls_handleError_when_send_raises_exception_of_another_type(handler): + """Test the emit method.""" # Arrange record = logging.LogRecord( name="test_logger", @@ -176,6 +187,7 @@ def test_emit_calls_handleError_when_send_raises_exception_of_another_type(handl ], ) def test_log_to_dict(handler, log_info, expected_dict): + """Test the log_to_dict method.""" # Act result = handler.log_to_dict(log_info) @@ -204,6 +216,7 @@ def test_log_to_dict(handler, log_info, expected_dict): ], ) def test_extract_log_extra(handler, record, expected_extra): + """Test the extract_log_extra method.""" # Act result = handler.extract_log_extra(record) diff --git a/openbb_platform/core/tests/app/logs/test_handlers_manager.py b/openbb_platform/core/tests/app/logs/test_handlers_manager.py index 43c23214e886..d46451c63146 100644 --- a/openbb_platform/core/tests/app/logs/test_handlers_manager.py +++ b/openbb_platform/core/tests/app/logs/test_handlers_manager.py @@ -1,3 +1,5 @@ +"""Tests for the handlers manager.""" + import logging from unittest.mock import Mock, patch @@ -7,25 +9,37 @@ PosthogHandler, ) +# pylint: disable=W0231 + class MockPosthogHandler(logging.NullHandler): + """Mock posthog handler.""" + def __init__(self, settings): + """Initialize the handler.""" self.settings = settings self.level = logging.DEBUG class MockPathTrackingFileHandler(logging.NullHandler): + """Mock path tracking file handler.""" + def __init__(self, settings): + """Initialize the handler.""" self.settings = settings self.level = logging.DEBUG class MockFormatterWithExceptions(logging.Formatter): + """Mock formatter with exceptions.""" + def __init__(self, settings): + """Initialize the formatter.""" self.settings = settings def test_handlers_added_correctly(): + """Test if the handlers are added correctly.""" with patch( "openbb_core.app.logs.handlers_manager.PosthogHandler", MockPosthogHandler, @@ -60,6 +74,7 @@ def test_handlers_added_correctly(): def test_update_handlers(): + """Test if the handlers are updated correctly.""" with patch( "openbb_core.app.logs.handlers_manager.PosthogHandler", MockPosthogHandler, diff --git a/openbb_platform/core/tests/app/logs/test_logging_service.py b/openbb_platform/core/tests/app/logs/test_logging_service.py index 316b603588c9..8eef4b90137e 100644 --- a/openbb_platform/core/tests/app/logs/test_logging_service.py +++ b/openbb_platform/core/tests/app/logs/test_logging_service.py @@ -1,3 +1,5 @@ +"""Test LoggingService class.""" + import json from typing import Optional from unittest.mock import MagicMock, Mock, patch @@ -12,18 +14,24 @@ class MockLoggingSettings: + """Mock logging settings.""" + def __init__(self, system_settings, user_settings): + """Initialize the mock logging settings.""" self.system_settings = system_settings self.user_settings = user_settings class MockOBBject(BaseModel): + """Mock object for testing.""" + output: Optional[str] = None error: Optional[str] = None @pytest.fixture(scope="function") def logging_service(): + """Return a LoggingService instance.""" mock_system_settings = Mock() mock_user_settings = Mock() mock_setup_handlers = Mock() @@ -48,6 +56,7 @@ def logging_service(): def test_correctly_initialized(): + """Test the LoggingService is correctly initialized.""" mock_system_settings = Mock() mock_user_settings = Mock() mock_setup_handlers = Mock() @@ -73,6 +82,7 @@ def test_correctly_initialized(): def test_logging_settings_setter(logging_service): + """Test the logging_settings setter.""" custom_user_settings = "custom_user_settings" custom_system_settings = "custom_system_settings" @@ -90,6 +100,7 @@ def test_logging_settings_setter(logging_service): def test_log_startup(logging_service): + """Test the log_startup method.""" with patch("logging.getLogger") as mock_get_logger: mock_info = mock_get_logger.return_value.info @@ -166,6 +177,7 @@ def test_log( exec_info, custom_headers, ): + """Test the log method.""" with patch( "openbb_core.app.logs.logging_service.LoggingSettings", MockLoggingSettings, diff --git a/openbb_platform/core/tests/app/logs/utils/__init__.py b/openbb_platform/core/tests/app/logs/utils/__init__.py index e69de29bb2d1..55cb40ff9e8e 100644 --- a/openbb_platform/core/tests/app/logs/utils/__init__.py +++ b/openbb_platform/core/tests/app/logs/utils/__init__.py @@ -0,0 +1 @@ +"""OpenBB Platform Core tests.""" diff --git a/openbb_platform/core/tests/app/logs/utils/test_expired_files.py b/openbb_platform/core/tests/app/logs/utils/test_expired_files.py index 7e2721b10589..1cb7897eb259 100644 --- a/openbb_platform/core/tests/app/logs/utils/test_expired_files.py +++ b/openbb_platform/core/tests/app/logs/utils/test_expired_files.py @@ -1,3 +1,5 @@ +"""Tests for the expired_files module.""" + import os import tempfile from pathlib import Path @@ -12,9 +14,12 @@ remove_file_list, ) +# pylint: disable=W0621 + @pytest.fixture def temp_test_files(): + """Create temporary files for testing.""" with tempfile.TemporaryDirectory() as temp_dir: temp_files = [ Path(temp_dir) / "file1.txt", @@ -30,12 +35,14 @@ def temp_test_files(): def test_get_timestamp_from_x_days(): + """Test get_timestamp_from_x_days.""" result = get_timestamp_from_x_days(0) assert isinstance(result, float) # Test case when all files are expired def test_all_files_expired(temp_test_files): + """Test get_expired_file_list when all files are expired.""" temp_dir, temp_files = temp_test_files before_timestamp = time() + 3 * 86400 # timestamp 3 days from now expired_files = get_expired_file_list(Path(temp_dir), before_timestamp) @@ -44,14 +51,16 @@ def test_all_files_expired(temp_test_files): # Test case when no files are expired def test_no_files_expired(temp_test_files): + """Test get_expired_file_list when no files are expired.""" temp_dir, _ = temp_test_files before_timestamp = 0 expired_files = get_expired_file_list(Path(temp_dir), before_timestamp) - assert expired_files == [] + assert not expired_files # Test case when some files are expired and some are not def test_some_files_expired(temp_test_files): + """Test get_expired_file_list when some files are expired and some are not.""" temp_dir, _ = temp_test_files # add temp file to temp_dir with timestamp in the future @@ -70,27 +79,31 @@ def test_some_files_expired(temp_test_files): # Test case when the directory does not exist def test_directory_not_exists(): + """Test get_expired_file_list when the directory does not exist.""" directory = Path("/path/that/does/not/exist") before_timestamp = time() expired_files = get_expired_file_list(directory, before_timestamp) - assert expired_files == [] + assert not expired_files # Test case when the directory is not a directory def test_directory_not_dir(temp_test_files): + """Test get_expired_file_list when the directory is not a directory.""" _, temp_files = temp_test_files before_timestamp = time() expired_files = get_expired_file_list(temp_files[0], before_timestamp) - assert expired_files == [] + assert not expired_files @pytest.fixture def mock_path(): + """Return a MagicMock for the Path class.""" # Create a MagicMock for the Path class to represent a file path return MagicMock() def test_remove_file_list_no_files(mock_path): + """Test remove_file_list when there are no files to remove.""" # Arrange # Let's assume the file list is empty, meaning there are no files to remove file_list: List[Path] = [] @@ -104,6 +117,7 @@ def test_remove_file_list_no_files(mock_path): def test_remove_file_list_remove_files_successfully(mock_path): + """Test remove_file_list when unlink is successful.""" # Arrange # Let's assume we have three files in the file list file_list = [mock_path, mock_path, mock_path] @@ -120,6 +134,7 @@ def test_remove_file_list_remove_files_successfully(mock_path): def test_remove_file_list_ignore_permission_error(mock_path): + """Test remove_file_list when unlink raises a PermissionError.""" # Arrange # Let's assume we have three files in the file list file_list = [mock_path, mock_path, mock_path] @@ -136,6 +151,7 @@ def test_remove_file_list_ignore_permission_error(mock_path): def test_remove_file_list_other_exception(mock_path): + """Test remove_file_list when unlink raises an exception other than PermissionError.""" # Arrange # Let's assume we have three files in the file list file_list = [mock_path, mock_path, mock_path] diff --git a/openbb_platform/core/tests/app/logs/utils/test_utils.py b/openbb_platform/core/tests/app/logs/utils/test_utils.py index f3715abc4349..9cda5662e2f3 100644 --- a/openbb_platform/core/tests/app/logs/utils/test_utils.py +++ b/openbb_platform/core/tests/app/logs/utils/test_utils.py @@ -1,3 +1,5 @@ +"""OpenBB Platform Core tests.""" + import uuid from pathlib import Path from unittest.mock import patch @@ -9,12 +11,14 @@ def test_get_session_id_return_type(): + """Test if the returned value is a string.""" # Test if the returned value is a string session_id = get_session_id() assert isinstance(session_id, str) def test_get_session_id_format(): + """Test if the returned string has the format "UUID-current_time.""" # Test if the returned string has the format "UUID-current_time" session_id = get_session_id() @@ -33,6 +37,7 @@ def test_get_session_id_format(): def test_get_session_id_uniqueness(): + """Test if subsequent calls return different session IDs.""" # Test if subsequent calls return different session IDs session_id1 = get_session_id() session_id2 = get_session_id() @@ -43,9 +48,10 @@ def test_get_session_id_uniqueness(): def test_get_app_id_success(): + """Test get_app_id function.""" # Mock the return value of get_log_dir to simulate a successful scenario with patch("openbb_core.app.logs.utils.utils.get_log_dir") as mock_get_log_dir: - mock_get_log_dir + mock_get_log_dir # pylint: disable=pointless-statement mock_get_log_dir.return_value = Path( "/path/to/contextual_user_data_directory/app_id.log" ) @@ -54,6 +60,7 @@ def test_get_app_id_success(): def test_get_app_id_os_error(): + """Test handling of OSError with errno 30.""" # Test handling of OSError with errno 30 (Read-only file system) with patch("openbb_core.app.logs.utils.utils.get_log_dir") as mock_get_log_dir: mock_get_log_dir.side_effect = OSError(30, "Read-only file system") @@ -62,6 +69,7 @@ def test_get_app_id_os_error(): def test_get_app_id_other_exception(): + """Test handling of other exceptions.""" # Test handling of other exceptions with patch("openbb_core.app.logs.utils.utils.get_log_dir") as mock_get_log_dir: mock_get_log_dir.side_effect = Exception("Some other error") @@ -73,6 +81,7 @@ def test_get_app_id_other_exception(): def test_get_log_dir(): + """Test get_log_dir function.""" with patch( "openbb_core.app.logs.utils.utils.create_log_dir_if_not_exists", return_value="/test_dir", diff --git a/openbb_platform/core/tests/app/model/__init__.py b/openbb_platform/core/tests/app/model/__init__.py index e69de29bb2d1..55cb40ff9e8e 100644 --- a/openbb_platform/core/tests/app/model/__init__.py +++ b/openbb_platform/core/tests/app/model/__init__.py @@ -0,0 +1 @@ +"""OpenBB Platform Core tests.""" diff --git a/openbb_platform/core/tests/app/model/abstract/__init__.py b/openbb_platform/core/tests/app/model/abstract/__init__.py index e69de29bb2d1..55cb40ff9e8e 100644 --- a/openbb_platform/core/tests/app/model/abstract/__init__.py +++ b/openbb_platform/core/tests/app/model/abstract/__init__.py @@ -0,0 +1 @@ +"""OpenBB Platform Core tests.""" diff --git a/openbb_platform/core/tests/app/model/abstract/test_results.py b/openbb_platform/core/tests/app/model/abstract/test_results.py index c3dd548ea3ac..ccdd5b8a0366 100644 --- a/openbb_platform/core/tests/app/model/abstract/test_results.py +++ b/openbb_platform/core/tests/app/model/abstract/test_results.py @@ -1,12 +1,15 @@ +"""Tests for the Results model.""" + from openbb_core.app.model.abstract.results import Results from pydantic import BaseModel class MockResults(Results): - pass + """Mock Results class.""" def test_results_model(): + """Test the Results model.""" res = MockResults() assert isinstance(res, BaseModel) diff --git a/openbb_platform/core/tests/app/model/abstract/test_singleton.py b/openbb_platform/core/tests/app/model/abstract/test_singleton.py index d87502e2f678..e586fb00e9d3 100644 --- a/openbb_platform/core/tests/app/model/abstract/test_singleton.py +++ b/openbb_platform/core/tests/app/model/abstract/test_singleton.py @@ -1,12 +1,18 @@ +"""Tests for the SingletonMeta metaclass.""" + from openbb_core.app.model.abstract.singleton import SingletonMeta class MyClass(metaclass=SingletonMeta): + """A simple class.""" + def __init__(self, value): + """Initialize the class.""" self.value = value def test_singleton_instance_creation(): + """Test the SingletonMeta metaclass with instance creation.""" # Arrange instance1 = MyClass(42) instance2 = MyClass(100) @@ -18,6 +24,8 @@ def test_singleton_instance_creation(): def test_singleton_multiple_classes(): + """Test the SingletonMeta metaclass with multiple classes.""" + # Arrange class AnotherClass(metaclass=SingletonMeta): def __init__(self, data): diff --git a/openbb_platform/core/tests/app/model/abstract/test_tagged.py b/openbb_platform/core/tests/app/model/abstract/test_tagged.py index 33df298ad583..7c40d15b675f 100644 --- a/openbb_platform/core/tests/app/model/abstract/test_tagged.py +++ b/openbb_platform/core/tests/app/model/abstract/test_tagged.py @@ -1,13 +1,17 @@ +"""Test the Tagged model.""" + from openbb_core.app.model.abstract.tagged import Tagged def test_tagged_model(): + """Test the Tagged model.""" tagged = Tagged() assert hasattr(tagged, "id") def test_fields(): + """Test the Tagged fields.""" fields = Tagged.model_fields fields_keys = fields.keys() diff --git a/openbb_platform/core/tests/app/model/abstract/test_warning.py b/openbb_platform/core/tests/app/model/abstract/test_warning.py index 46692077cddb..3a506e6d6588 100644 --- a/openbb_platform/core/tests/app/model/abstract/test_warning.py +++ b/openbb_platform/core/tests/app/model/abstract/test_warning.py @@ -1,3 +1,5 @@ +"""Test the Warnings model.""" + from unittest.mock import Mock import pytest @@ -12,6 +14,7 @@ ], ) def test_warn_model(category, message): + """Test the Warning_ model.""" war = Warning_(category=category, message=message) assert war.category == category @@ -19,6 +22,7 @@ def test_warn_model(category, message): def test_fields(): + """Test the Warning_ fields.""" fields = Warning_.model_fields fields_keys = fields.keys() @@ -27,6 +31,7 @@ def test_fields(): def test_cast_warning(): + """Test the cast_warning function.""" mock_warning_message = Mock() mock_warning_message.category.__name__ = "test" mock_warning_message.message = "test" diff --git a/openbb_platform/core/tests/app/model/charts/__init__.py b/openbb_platform/core/tests/app/model/charts/__init__.py index e69de29bb2d1..55cb40ff9e8e 100644 --- a/openbb_platform/core/tests/app/model/charts/__init__.py +++ b/openbb_platform/core/tests/app/model/charts/__init__.py @@ -0,0 +1 @@ +"""OpenBB Platform Core tests.""" diff --git a/openbb_platform/core/tests/app/model/charts/test_chart.py b/openbb_platform/core/tests/app/model/charts/test_chart.py index 3d3ff9960bdc..4f0eb140f42a 100644 --- a/openbb_platform/core/tests/app/model/charts/test_chart.py +++ b/openbb_platform/core/tests/app/model/charts/test_chart.py @@ -1,8 +1,11 @@ +"""Test the chart model.""" + import pytest from openbb_core.app.model.charts.chart import Chart, ChartFormat def test_charting_default_values(): + """Test the charting default values.""" # Arrange & Act chart = Chart() @@ -12,6 +15,7 @@ def test_charting_default_values(): def test_charting_custom_values(): + """Test the charting custom values.""" # Arrange content = {"data": [1, 2, 3]} chart_format = ChartFormat.plotly @@ -25,6 +29,7 @@ def test_charting_custom_values(): def test_charting_assignment_validation(): + """Test the charting assignment validation.""" # Arrange chart = Chart() @@ -34,6 +39,7 @@ def test_charting_assignment_validation(): def test_charting_config_validation(): + """Test the charting config validation.""" # Arrange content = {"data": [1, 2, 3]} chart_format = ChartFormat.plotly @@ -48,5 +54,5 @@ def test_charting_config_validation(): def test_show(): + """Test the show method.""" # TODO : add test after the function is properly refactored - pass diff --git a/openbb_platform/core/tests/app/model/hub/__init__.py b/openbb_platform/core/tests/app/model/hub/__init__.py index e69de29bb2d1..55cb40ff9e8e 100644 --- a/openbb_platform/core/tests/app/model/hub/__init__.py +++ b/openbb_platform/core/tests/app/model/hub/__init__.py @@ -0,0 +1 @@ +"""OpenBB Platform Core tests.""" diff --git a/openbb_platform/core/tests/app/model/hub/test_features_keys.py b/openbb_platform/core/tests/app/model/hub/test_features_keys.py index 4f3a85246e0d..19bd0a9519c8 100644 --- a/openbb_platform/core/tests/app/model/hub/test_features_keys.py +++ b/openbb_platform/core/tests/app/model/hub/test_features_keys.py @@ -1,9 +1,12 @@ +"""Test the FeaturesKeys class.""" + from openbb_core.app.model.hub.features_keys import FeaturesKeys # ruff: noqa: S105 S106 def test_features_keys(): + """Test the FeaturesKeys class.""" fk = FeaturesKeys(API_BITQUERY_KEY="test", API_BIZTOC_TOKEN="test2") assert fk.API_BITQUERY_KEY == "test" diff --git a/openbb_platform/core/tests/app/model/hub/test_hub_session.py b/openbb_platform/core/tests/app/model/hub/test_hub_session.py index 645a097ac1fd..19638f22cb90 100644 --- a/openbb_platform/core/tests/app/model/hub/test_hub_session.py +++ b/openbb_platform/core/tests/app/model/hub/test_hub_session.py @@ -1,3 +1,5 @@ +"""Test the HubSession class.""" + from openbb_core.app.model.hub.hub_session import HubSession from pydantic import SecretStr @@ -5,6 +7,7 @@ def test_hub_session(): + """Test the HubSession class.""" session = HubSession( access_token=SecretStr("mock_access_token"), token_type="mock_token_type", @@ -22,6 +25,7 @@ def test_hub_session(): def test_fields(): + """Test the HubSession fields.""" fields = HubSession.model_fields fields_keys = fields.keys() diff --git a/openbb_platform/core/tests/app/model/hub/test_hub_user_settings.py b/openbb_platform/core/tests/app/model/hub/test_hub_user_settings.py index ca2f78ff9a8c..5fdcde411fae 100644 --- a/openbb_platform/core/tests/app/model/hub/test_hub_user_settings.py +++ b/openbb_platform/core/tests/app/model/hub/test_hub_user_settings.py @@ -1,7 +1,10 @@ +"""Test the HubUserSettings class.""" + from openbb_core.app.model.hub.hub_user_settings import HubUserSettings def test_hub_user_settings(): + """Test the HubUserSettings class.""" hub_settings = HubUserSettings() assert isinstance(hub_settings, HubUserSettings) diff --git a/openbb_platform/core/tests/app/model/test_command_context.py b/openbb_platform/core/tests/app/model/test_command_context.py index 76423c8b9c56..57d982f58c2a 100644 --- a/openbb_platform/core/tests/app/model/test_command_context.py +++ b/openbb_platform/core/tests/app/model/test_command_context.py @@ -1,3 +1,5 @@ +"""Test the CommandContext model.""" + from openbb_core.app.model.command_context import ( CommandContext, SystemSettings, @@ -6,6 +8,7 @@ def test_command_context(): + """Test the CommandContext model.""" cc = CommandContext() assert isinstance(cc, CommandContext) assert isinstance(cc.user_settings, UserSettings) @@ -13,6 +16,7 @@ def test_command_context(): def test_fields(): + """Test the CommandContext fields.""" fields = CommandContext.model_fields fields_keys = fields.keys() diff --git a/openbb_platform/core/tests/app/model/test_credentials.py b/openbb_platform/core/tests/app/model/test_credentials.py index 041ca5f16e63..52f0d25126c0 100644 --- a/openbb_platform/core/tests/app/model/test_credentials.py +++ b/openbb_platform/core/tests/app/model/test_credentials.py @@ -1,8 +1,11 @@ +"""Test the Credentials model.""" + import typing from unittest.mock import patch def test_credentials(): + """Test the Credentials model.""" with patch( target="openbb_core.app.model.credentials.ProviderInterface" ) as mock_provider_interface: @@ -10,7 +13,9 @@ def test_credentials(): "benzinga_api_key": (typing.Optional[str], None), "polygon_api_key": (typing.Optional[str], None), } - from openbb_core.app.model.credentials import Credentials + from openbb_core.app.model.credentials import ( # pylint: disable=import-outside-toplevel + Credentials, + ) creds = Credentials( benzinga_api_key="mock_benzinga_api_key", diff --git a/openbb_platform/core/tests/app/model/test_defaults.py b/openbb_platform/core/tests/app/model/test_defaults.py index af87fa52e241..e4a3df6dd21d 100644 --- a/openbb_platform/core/tests/app/model/test_defaults.py +++ b/openbb_platform/core/tests/app/model/test_defaults.py @@ -1,13 +1,17 @@ +"""Test the Defaults class.""" + from openbb_core.app.model.defaults import Defaults def test_defaults(): + """Test the Defaults class.""" cc = Defaults(routes={"test": {"test": "test"}}) assert isinstance(cc, Defaults) assert cc.routes == {"test": {"test": "test"}} def test_fields(): + """Test the Defaults fields.""" fields = Defaults.model_fields fields_keys = fields.keys() diff --git a/openbb_platform/core/tests/app/model/test_metadata.py b/openbb_platform/core/tests/app/model/test_metadata.py index 60c4f95c5831..0368271c6ef5 100644 --- a/openbb_platform/core/tests/app/model/test_metadata.py +++ b/openbb_platform/core/tests/app/model/test_metadata.py @@ -1,3 +1,5 @@ +"""Test the Metadata model.""" + from datetime import datetime import numpy as np @@ -8,7 +10,7 @@ def test_Metadata(): - "Smoke test" + """Run Smoke test.""" m = Metadata( arguments={"test": "test"}, route="test", @@ -20,7 +22,7 @@ def test_Metadata(): def test_fields(): - "Smoke test" + """Run Smoke test.""" fields = Metadata.model_fields.keys() assert "arguments" in fields assert "duration" in fields @@ -98,6 +100,7 @@ def test_fields(): ], ) def test_scale_arguments(input_data, expected_output): + """Test the scale_arguments method.""" m = Metadata( arguments=input_data, route="test", @@ -106,7 +109,7 @@ def test_scale_arguments(input_data, expected_output): ) arguments = m.arguments - for arg in arguments: + for arg in arguments: # pylint: disable=E1133 if "columns" in arguments[arg]: # compare the column names disregarding the order with the expected output assert sorted(arguments[arg]["columns"]) == sorted( diff --git a/openbb_platform/core/tests/app/model/test_preferences.py b/openbb_platform/core/tests/app/model/test_preferences.py index ca3bae14af07..dacfc708ed91 100644 --- a/openbb_platform/core/tests/app/model/test_preferences.py +++ b/openbb_platform/core/tests/app/model/test_preferences.py @@ -1,6 +1,9 @@ +"""Test the preferences class.""" + from openbb_core.app.model.preferences import Preferences def test_preferences(): + """Test the preferences class.""" preferences = Preferences() assert isinstance(preferences, Preferences) diff --git a/openbb_platform/core/tests/app/model/test_profile.py b/openbb_platform/core/tests/app/model/test_profile.py index 5c22d7ee73d9..7f8a4795327f 100644 --- a/openbb_platform/core/tests/app/model/test_profile.py +++ b/openbb_platform/core/tests/app/model/test_profile.py @@ -1,6 +1,9 @@ +"""Test the profile class.""" + from openbb_core.app.model.profile import Profile def test_preferences(): + """Test the preferences class.""" preferences = Profile() assert isinstance(preferences, Profile) diff --git a/openbb_platform/core/tests/app/model/test_system_settings.py b/openbb_platform/core/tests/app/model/test_system_settings.py index 90a1c63778f9..1ead135bfe43 100644 --- a/openbb_platform/core/tests/app/model/test_system_settings.py +++ b/openbb_platform/core/tests/app/model/test_system_settings.py @@ -1,3 +1,5 @@ +"""Tests for the SystemSettings class.""" + import os from pathlib import Path @@ -13,11 +15,13 @@ class MockSystemSettings(BaseModel): def test_system_settings(): + """Test the SystemSettings class.""" sys = SystemSettings() assert isinstance(sys, SystemSettings) def test_create_openbb_directory_directory_and_files_not_exist(tmpdir): + """Test the create_openbb_directory method.""" # Arrange values = MockSystemSettings( **{ @@ -37,6 +41,7 @@ def test_create_openbb_directory_directory_and_files_not_exist(tmpdir): def test_create_openbb_directory_directory_exists_user_settings_missing(tmpdir): + """Test the create_openbb_directory method.""" # Arrange values = MockSystemSettings( **{ @@ -59,6 +64,7 @@ def test_create_openbb_directory_directory_exists_user_settings_missing(tmpdir): def test_create_openbb_directory_directory_exists_system_settings_missing(tmpdir): + """Test the create_openbb_directory method.""" # Arrange values = MockSystemSettings( **{ @@ -136,6 +142,7 @@ def test_create_openbb_directory_directory_exists_system_settings_missing(tmpdir ], ) def test_validate_posthog_handler(values, expected_handlers): + """Test the validate_posthog_handler method.""" values = MockSystemSettings(**values) # Act result = SystemSettings.validate_posthog_handler(values) # type: ignore[operator] @@ -158,6 +165,7 @@ def test_validate_posthog_handler(values, expected_handlers): ], ) def test_validate_logging_handlers(handlers, valid): + """Test the validate_logging_handlers method.""" # Act and Assert if valid: assert SystemSettings.validate_logging_handlers(handlers) == handlers # type: ignore[call-arg] diff --git a/openbb_platform/core/tests/app/model/test_user_settings.py b/openbb_platform/core/tests/app/model/test_user_settings.py index b24fb23cae11..ebc78faf4d99 100644 --- a/openbb_platform/core/tests/app/model/test_user_settings.py +++ b/openbb_platform/core/tests/app/model/test_user_settings.py @@ -1,3 +1,5 @@ +"""Test the UserSettings model.""" + from openbb_core.app.model.credentials import Credentials from openbb_core.app.model.defaults import Defaults from openbb_core.app.model.preferences import Preferences @@ -6,6 +8,7 @@ def test_user_settings(): + """Test the UserSettings model.""" settings = UserSettings( credentials=Credentials(), profile=Profile(), diff --git a/openbb_platform/core/tests/app/results/__init__.py b/openbb_platform/core/tests/app/results/__init__.py index e69de29bb2d1..55cb40ff9e8e 100644 --- a/openbb_platform/core/tests/app/results/__init__.py +++ b/openbb_platform/core/tests/app/results/__init__.py @@ -0,0 +1 @@ +"""OpenBB Platform Core tests.""" diff --git a/openbb_platform/core/tests/app/results/test_empty.py b/openbb_platform/core/tests/app/results/test_empty.py index 23a73ff369e9..5ce63f4a5c50 100644 --- a/openbb_platform/core/tests/app/results/test_empty.py +++ b/openbb_platform/core/tests/app/results/test_empty.py @@ -1,8 +1,11 @@ +"""Test the Empty model.""" + from openbb_core.app.model.results.empty import Empty from pydantic import BaseModel def test_empty_model(): + """Test the Empty model.""" empty = Empty() assert isinstance(empty, Empty) diff --git a/openbb_platform/core/tests/app/service/__init__.py b/openbb_platform/core/tests/app/service/__init__.py index e69de29bb2d1..55cb40ff9e8e 100644 --- a/openbb_platform/core/tests/app/service/__init__.py +++ b/openbb_platform/core/tests/app/service/__init__.py @@ -0,0 +1 @@ +"""OpenBB Platform Core tests.""" diff --git a/openbb_platform/core/tests/app/static/__init__.py b/openbb_platform/core/tests/app/static/__init__.py index e69de29bb2d1..3f4c8aabddaf 100644 --- a/openbb_platform/core/tests/app/static/__init__.py +++ b/openbb_platform/core/tests/app/static/__init__.py @@ -0,0 +1 @@ +"""OpenBB Platform core tests.""" diff --git a/openbb_platform/core/tests/app/static/test_filters.py b/openbb_platform/core/tests/app/static/test_filters.py index 1f06dc0955d9..9532867fe4b1 100644 --- a/openbb_platform/core/tests/app/static/test_filters.py +++ b/openbb_platform/core/tests/app/static/test_filters.py @@ -49,6 +49,7 @@ def test_filter_inputs_df(): def test_filter_inputs( input_data, ): + """Test the filter_inputs function.""" result = filter_inputs(data=input_data, data_processing=True) # Assert that the result is a dictionary diff --git a/openbb_platform/core/tests/app/static/test_package_builder.py b/openbb_platform/core/tests/app/static/test_package_builder.py index 3a2725976b7d..5a93349c42cc 100644 --- a/openbb_platform/core/tests/app/static/test_package_builder.py +++ b/openbb_platform/core/tests/app/static/test_package_builder.py @@ -27,6 +27,7 @@ @pytest.fixture(scope="module") def tmp_openbb_dir(tmp_path_factory): + """Return a temporary openbb directory.""" return tmp_path_factory.mktemp("openbb") @@ -564,7 +565,7 @@ def test_generate(docstring_generator): """Test generate docstring.""" def some_func(): - """Some func docstring.""" + """Define Some func docstring.""" formatted_params = { "param1": Parameter("NoneType", kind=Parameter.POSITIONAL_OR_KEYWORD), @@ -655,6 +656,7 @@ def test_package_diff( """Test package differences.""" def mock_entry_points(group): + """Mock entry points.""" return ext_installed.select(**{"group": group}) PATH = "openbb_core.app.static.package_builder." diff --git a/openbb_platform/core/tests/app/static/test_reference_loader.py b/openbb_platform/core/tests/app/static/test_reference_loader.py index 1980ac4611af..20ef1fabf966 100644 --- a/openbb_platform/core/tests/app/static/test_reference_loader.py +++ b/openbb_platform/core/tests/app/static/test_reference_loader.py @@ -1,12 +1,17 @@ +"""Tests for the ReferenceLoader class.""" + import json from pathlib import Path import pytest from openbb_core.app.static.reference_loader import ReferenceLoader +# pylint: disable=W0212, W0621 + @pytest.fixture(scope="function") def reference_loader(): + """Fixture to create a ReferenceLoader instance.""" ReferenceLoader._instances = {} yield ReferenceLoader ReferenceLoader._instances = {} diff --git a/openbb_platform/core/tests/app/static/utils/test_linters.py b/openbb_platform/core/tests/app/static/utils/test_linters.py index 37f57e39592f..1ebd54b66d02 100644 --- a/openbb_platform/core/tests/app/static/utils/test_linters.py +++ b/openbb_platform/core/tests/app/static/utils/test_linters.py @@ -10,6 +10,7 @@ @pytest.fixture(scope="module") def tmp_package_dir(tmp_path_factory): + """Return a temporary package directory.""" return tmp_path_factory.mktemp("package") diff --git a/openbb_platform/core/tests/app/test_charting_manager.py b/openbb_platform/core/tests/app/test_charting_manager.py index e69de29bb2d1..06b5fb096915 100644 --- a/openbb_platform/core/tests/app/test_charting_manager.py +++ b/openbb_platform/core/tests/app/test_charting_manager.py @@ -0,0 +1 @@ +"""Test ChartingManager.""" diff --git a/openbb_platform/core/tests/app/test_command_runner.py b/openbb_platform/core/tests/app/test_command_runner.py index 4b1b35da92d1..446d64ce061c 100644 --- a/openbb_platform/core/tests/app/test_command_runner.py +++ b/openbb_platform/core/tests/app/test_command_runner.py @@ -1,3 +1,5 @@ +"""Test command runner.""" + from dataclasses import dataclass from inspect import Parameter from typing import Dict, List @@ -20,6 +22,8 @@ from openbb_core.app.router import CommandMap from pydantic import BaseModel, ConfigDict +# pylint: disable=W0613, W0621, W0102, W0212 + @pytest.fixture() def execution_context(): @@ -37,7 +41,7 @@ def mock_func(): def mock_func( a: int, b: int, c: float = 10.0, d: int = 5, provider_choices: Dict = {} ) -> None: - pass + """Mock function.""" return mock_func @@ -155,12 +159,14 @@ def test_parameters_builder_merge_args_and_kwargs( def test_parameters_builder_update_command_context( kwargs, system_settings, user_settings, expected_result ): + """Test update_command_context.""" + def other_mock_func( cc: CommandContext, a: int, b: int, ) -> None: - pass + """Mock function.""" result = ParametersBuilder.update_command_context( other_mock_func, kwargs, system_settings, user_settings @@ -207,6 +213,7 @@ def other_mock_func( def test_parameters_builder_update_provider_choices( command_coverage, route, kwargs, route_default, expected_result ): + """Test update_provider_choices.""" with patch("openbb_core.app.command_runner.ProviderInterface") as mock_pi: mock_pi.available_providers = ["provider1", "provider2"] result = ParametersBuilder.update_provider_choices( @@ -218,7 +225,6 @@ def test_parameters_builder_update_provider_choices( def test_parameters_builder_validate_kwargs(mock_func): """Test validate_kwargs.""" - # TODO: add more test cases with @pytest.mark.parametrize result = ParametersBuilder.validate_kwargs( @@ -268,7 +274,6 @@ class Model(BaseModel): def test_parameters_builder_build(mock_func, execution_context): """Test build.""" - # TODO: add more test cases with @pytest.mark.parametrize with patch("openbb_core.app.command_runner.ProviderInterface") as mock_pi: @@ -298,14 +303,12 @@ def test_parameters_builder_build(mock_func, execution_context): @patch("openbb_core.app.command_runner.LoggingService") def test_command_runner(_): """Test command runner.""" - assert CommandRunner() @patch("openbb_core.app.command_runner.LoggingService") def test_command_runner_properties(mock_logging_service): """Test properties.""" - sys = SystemSettings() user = UserSettings() cmd_map = CommandMap() @@ -320,6 +323,7 @@ def test_command_runner_properties(mock_logging_service): @patch("openbb_core.app.command_runner.LoggingService") def test_command_runner_run(_): + """Test run.""" runner = CommandRunner() with patch( @@ -338,12 +342,14 @@ async def test_static_command_runner_run( """Test static command runner run.""" def other_mock_func(a: int, b: int, c: int, d: int) -> List[int]: + """Mock function.""" return [a, b, c, d] class MockOBBject: """Mock OBBject""" def __init__(self, results): + """Initialize the mock object.""" self.results = results self.extra = {} diff --git a/openbb_platform/core/tests/app/test_deprecation.py b/openbb_platform/core/tests/app/test_deprecation.py index 926fe991a7ba..bca6c5381ae3 100644 --- a/openbb_platform/core/tests/app/test_deprecation.py +++ b/openbb_platform/core/tests/app/test_deprecation.py @@ -1,3 +1,5 @@ +"""Test deprecated commands.""" + import unittest from openbb_core.app.static.package_builder import PathHandler diff --git a/openbb_platform/core/tests/app/test_utils.py b/openbb_platform/core/tests/app/test_utils.py index 4b2bcfc5fb24..ab07be91597d 100644 --- a/openbb_platform/core/tests/app/test_utils.py +++ b/openbb_platform/core/tests/app/test_utils.py @@ -1,3 +1,5 @@ +"""OpenBB Platform Core app utils tests.""" + import numpy as np import pandas as pd import pytest @@ -14,6 +16,8 @@ ) from openbb_core.provider.abstract.data import Data +# pylint: disable=W0621 + df = pd.DataFrame( { "x": [1, 2, 3, 4, 5, 6, 7, 8, 9, 10], @@ -37,36 +41,42 @@ def test_df_to_basemodel(): + """Test the df_to_basemodel helper.""" base_model = df_to_basemodel(df) assert isinstance(base_model, list) assert base_model[0].x == 1 # type: ignore[attr-defined] def test_df_to_basemodel_multiindex(): + """Test the df_to_basemodel helper with a multi-index DataFrame.""" base_model = df_to_basemodel(df_multiindex) assert isinstance(base_model, list) assert hasattr(base_model[0], "is_multiindex") def test_basemodel_to_df(): + """Test the basemodel_to_df helper.""" df = basemodel_to_df(simple_base_model) assert isinstance(df, pd.DataFrame) assert df.shape == (8, 3) def test_basemodel_to_multiindex_df(): + """Test the basemodel_to_df helper with a multi-index DataFrame.""" df = basemodel_to_df(multi_index_base_model) assert isinstance(df, pd.DataFrame) assert isinstance(df.index, pd.MultiIndex) def test_get_target_column(): + """Test the get_target_column helper.""" target = get_target_column(df, "x") assert isinstance(target, pd.Series) assert target[0] == 1 def test_get_target_columns(): + """Test the get_target_columns helper.""" targets = get_target_columns(df, ["x", "y"]) assert isinstance(targets, pd.DataFrame) assert targets.shape == (10, 2) @@ -84,6 +94,7 @@ def test_get_target_columns(): ], ) def test_list_to_basemodel(data_list, expected): + """Test the list_to_basemodel helper.""" result = list_to_basemodel(data_list) for r, e in zip(result, expected): assert r.model_dump() == e.model_dump() @@ -101,6 +112,7 @@ def test_list_to_basemodel(data_list, expected): ], ) def test_dict_to_basemodel(data_dict, expected): + """Test the dict_to_basemodel helper.""" result = dict_to_basemodel(data_dict) assert result.model_dump() == expected.model_dump() @@ -123,6 +135,7 @@ def test_dict_to_basemodel(data_dict, expected): ], ) def test_ndarray_to_basemodel(array, expected): + """Test the ndarray_to_basemodel helper.""" result = ndarray_to_basemodel(array) for r, e in zip(result, expected): assert r.model_dump() == e.model_dump() @@ -139,6 +152,7 @@ def test_ndarray_to_basemodel(array, expected): ], ) def test_check_single_item(item, expected): + """Test the check_single_item helper.""" if expected is OpenBBError: with pytest.raises(OpenBBError): check_single_item(item) diff --git a/openbb_platform/core/tests/provider/utils/test_client.py b/openbb_platform/core/tests/provider/utils/test_client.py index 1c88c9588535..5b018994d9b4 100644 --- a/openbb_platform/core/tests/provider/utils/test_client.py +++ b/openbb_platform/core/tests/provider/utils/test_client.py @@ -1,3 +1,5 @@ +"""Test the client helper.""" + import gzip import json import zlib @@ -80,6 +82,7 @@ def __del__(self): # type: ignore async def request( # type: ignore self, *args, raise_for_status: bool = False, **kwargs ) -> client.ClientResponse: + """Mock the request method.""" response = MockResponse(*args, **kwargs) if raise_for_status: diff --git a/openbb_platform/core/tests/provider/utils/test_helpers.py b/openbb_platform/core/tests/provider/utils/test_helpers.py index 4d37084e4e3c..741ce6ee914c 100644 --- a/openbb_platform/core/tests/provider/utils/test_helpers.py +++ b/openbb_platform/core/tests/provider/utils/test_helpers.py @@ -11,21 +11,31 @@ to_snake_case, ) +# pylint: disable=unused-argument + class MockResponse: + """Mock the response.""" + def __init__(self): + """Initialize the mock response.""" self.status_code = 200 self.status = 200 async def json(self): + """Return the json response.""" return {"test": "test"} class MockSession: + """Mock the ClientSession.""" + def __init__(self): + """Initialize the mock session.""" self.response = MockResponse() - async def request(self, *args, **kwargs): + async def request(self, *args, **kwargs): # pylint: disable=unused-argument + """Mock the ClientSession.request method.""" if kwargs.get("raise_for_status", False): raise Exception("Test") diff --git a/openbb_platform/extensions/__init__.py b/openbb_platform/extensions/__init__.py index e69de29bb2d1..a2fa55684fc1 100644 --- a/openbb_platform/extensions/__init__.py +++ b/openbb_platform/extensions/__init__.py @@ -0,0 +1 @@ +"""OpenBB Platform Extensions.""" diff --git a/openbb_platform/extensions/commodity/integration/test_commodity_api.py b/openbb_platform/extensions/commodity/integration/test_commodity_api.py index 89f22935c9cc..56e06076e4de 100644 --- a/openbb_platform/extensions/commodity/integration/test_commodity_api.py +++ b/openbb_platform/extensions/commodity/integration/test_commodity_api.py @@ -12,6 +12,7 @@ @pytest.fixture(scope="session") def headers(): + """Get the headers for the API request.""" userpass = f"{Env().API_USERNAME}:{Env().API_PASSWORD}" userpass_bytes = userpass.encode("ascii") base64_bytes = base64.b64encode(userpass_bytes) @@ -46,6 +47,7 @@ def headers(): ) @pytest.mark.integration def test_commodity_lbma_fixing(params, headers): + """Test the LBMA fixing endpoint.""" params = {p: v for p, v in params.items() if v} query_str = get_querystring(params, []) diff --git a/openbb_platform/extensions/commodity/integration/test_commodity_python.py b/openbb_platform/extensions/commodity/integration/test_commodity_python.py index c805ffcb2694..192dac81a198 100644 --- a/openbb_platform/extensions/commodity/integration/test_commodity_python.py +++ b/openbb_platform/extensions/commodity/integration/test_commodity_python.py @@ -42,6 +42,7 @@ def obb(pytestconfig): # pylint: disable=inconsistent-return-statements ) @pytest.mark.integration def test_commodity_lbma_fixing(params, obb): + """Test the LBMA fixing endpoint.""" params = {p: v for p, v in params.items() if v} result = obb.commodity.lbma_fixing(**params) diff --git a/openbb_platform/extensions/commodity/openbb_commodity/__init__.py b/openbb_platform/extensions/commodity/openbb_commodity/__init__.py index e69de29bb2d1..c38801bad616 100644 --- a/openbb_platform/extensions/commodity/openbb_commodity/__init__.py +++ b/openbb_platform/extensions/commodity/openbb_commodity/__init__.py @@ -0,0 +1 @@ +"""OpenBB Commodity Extension.""" diff --git a/openbb_platform/extensions/crypto/integration/test_crypto_api.py b/openbb_platform/extensions/crypto/integration/test_crypto_api.py index 6d38f1681a57..96a2fec38064 100644 --- a/openbb_platform/extensions/crypto/integration/test_crypto_api.py +++ b/openbb_platform/extensions/crypto/integration/test_crypto_api.py @@ -13,6 +13,7 @@ @pytest.fixture(scope="session") def headers(): + """Get the headers for the API request.""" userpass = f"{Env().API_USERNAME}:{Env().API_PASSWORD}" userpass_bytes = userpass.encode("ascii") base64_bytes = base64.b64encode(userpass_bytes) @@ -29,6 +30,7 @@ def headers(): ) @pytest.mark.integration def test_crypto_search(params, headers): + """Test the crypto search endpoint.""" params = {p: v for p, v in params.items() if v} query_str = get_querystring(params, []) @@ -114,6 +116,7 @@ def test_crypto_search(params, headers): ) @pytest.mark.integration def test_crypto_price_historical(params, headers): + """Test the crypto historical price endpoint.""" params = {p: v for p, v in params.items() if v} query_str = get_querystring(params, []) diff --git a/openbb_platform/extensions/crypto/integration/test_crypto_python.py b/openbb_platform/extensions/crypto/integration/test_crypto_python.py index b22c29d4daed..7a3073620ef8 100644 --- a/openbb_platform/extensions/crypto/integration/test_crypto_python.py +++ b/openbb_platform/extensions/crypto/integration/test_crypto_python.py @@ -25,6 +25,7 @@ def obb(pytestconfig): # pylint: disable=inconsistent-return-statements ) @pytest.mark.integration def test_crypto_search(params, obb): + """Test the crypto search endpoint.""" params = {p: v for p, v in params.items() if v} result = obb.crypto.search(**params) @@ -109,6 +110,7 @@ def test_crypto_search(params, obb): ) @pytest.mark.integration def test_crypto_price_historical(params, obb): + """Test crypto price historical.""" result = obb.crypto.price.historical(**params) assert result assert isinstance(result, OBBject) diff --git a/openbb_platform/extensions/crypto/openbb_crypto/__init__.py b/openbb_platform/extensions/crypto/openbb_crypto/__init__.py index e69de29bb2d1..2ce9b051267a 100644 --- a/openbb_platform/extensions/crypto/openbb_crypto/__init__.py +++ b/openbb_platform/extensions/crypto/openbb_crypto/__init__.py @@ -0,0 +1 @@ +"""OpenBB Crypto Extension.""" diff --git a/openbb_platform/extensions/crypto/openbb_crypto/price/__init__.py b/openbb_platform/extensions/crypto/openbb_crypto/price/__init__.py index e69de29bb2d1..71f078e3f0ac 100644 --- a/openbb_platform/extensions/crypto/openbb_crypto/price/__init__.py +++ b/openbb_platform/extensions/crypto/openbb_crypto/price/__init__.py @@ -0,0 +1 @@ +"""OpenBB Crypto Price Router.""" diff --git a/openbb_platform/extensions/currency/integration/test_currency_api.py b/openbb_platform/extensions/currency/integration/test_currency_api.py index bc80a5d75bc7..f2f5d56e34ee 100644 --- a/openbb_platform/extensions/currency/integration/test_currency_api.py +++ b/openbb_platform/extensions/currency/integration/test_currency_api.py @@ -13,6 +13,7 @@ @pytest.fixture(scope="session") def headers(): + """Get the headers for the API request.""" userpass = f"{Env().API_USERNAME}:{Env().API_PASSWORD}" userpass_bytes = userpass.encode("ascii") base64_bytes = base64.b64encode(userpass_bytes) @@ -49,6 +50,7 @@ def headers(): ) @pytest.mark.integration def test_currency_search(params, headers): + """Test the currency search endpoint.""" params = {p: v for p, v in params.items() if v} query_str = get_querystring(params, []) @@ -141,6 +143,7 @@ def test_currency_search(params, headers): ) @pytest.mark.integration def test_currency_price_historical(params, headers): + """Test the currency historical price endpoint.""" params = {p: v for p, v in params.items() if v} query_str = get_querystring(params, []) @@ -156,6 +159,7 @@ def test_currency_price_historical(params, headers): ) @pytest.mark.integration def test_currency_reference_rates(params, headers): + """Test the currency reference rates endpoint.""" params = {p: v for p, v in params.items() if v} query_str = get_querystring(params, []) @@ -180,6 +184,7 @@ def test_currency_reference_rates(params, headers): ) @pytest.mark.integration def test_currency_snapshots(params, headers): + """Test the currency snapshots endpoint.""" params = {p: v for p, v in params.items() if v} query_str = get_querystring(params, []) diff --git a/openbb_platform/extensions/currency/integration/test_currency_python.py b/openbb_platform/extensions/currency/integration/test_currency_python.py index 445e42938380..f2352a1669c4 100644 --- a/openbb_platform/extensions/currency/integration/test_currency_python.py +++ b/openbb_platform/extensions/currency/integration/test_currency_python.py @@ -47,6 +47,7 @@ def obb(pytestconfig): ) @pytest.mark.integration def test_currency_search(params, obb): + """Test the currency search endpoint.""" result = obb.currency.search(**params) assert result assert isinstance(result, OBBject) @@ -136,6 +137,7 @@ def test_currency_search(params, obb): ) @pytest.mark.integration def test_currency_price_historical(params, obb): + """Test the currency historical price endpoint.""" result = obb.currency.price.historical(**params) assert result assert isinstance(result, OBBject) @@ -148,6 +150,7 @@ def test_currency_price_historical(params, obb): ) @pytest.mark.integration def test_currency_reference_rates(params, obb): + """Test the currency reference rates endpoint.""" result = obb.currency.reference_rates(**params) assert result assert isinstance(result, OBBject) @@ -169,6 +172,7 @@ def test_currency_reference_rates(params, obb): ) @pytest.mark.integration def test_currency_snapshots(params, obb): + """Test the currency snapshots endpoint.""" result = obb.currency.snapshots(**params) assert result assert isinstance(result, OBBject) diff --git a/openbb_platform/extensions/currency/openbb_currency/currency_router.py b/openbb_platform/extensions/currency/openbb_currency/currency_router.py index d329486a6125..111acd3b5e22 100644 --- a/openbb_platform/extensions/currency/openbb_currency/currency_router.py +++ b/openbb_platform/extensions/currency/openbb_currency/currency_router.py @@ -65,7 +65,7 @@ async def reference_rates( standard_params: StandardParams, extra_params: ExtraParams, ) -> OBBject: - """Current, official, currency reference rates. + """Get current, official, currency reference rates. Foreign exchange reference rates are the exchange rates set by a major financial institution or regulatory body, serving as a benchmark for the value of currencies around the world. diff --git a/openbb_platform/extensions/derivatives/integration/test_derivatives_api.py b/openbb_platform/extensions/derivatives/integration/test_derivatives_api.py index aa8103f2cf0a..a777ddb3bf59 100644 --- a/openbb_platform/extensions/derivatives/integration/test_derivatives_api.py +++ b/openbb_platform/extensions/derivatives/integration/test_derivatives_api.py @@ -13,6 +13,7 @@ @pytest.fixture(scope="session") def headers(): + """Get the headers for the API request.""" userpass = f"{Env().API_USERNAME}:{Env().API_PASSWORD}" userpass_bytes = userpass.encode("ascii") base64_bytes = base64.b64encode(userpass_bytes) @@ -38,6 +39,7 @@ def headers(): ) @pytest.mark.integration def test_derivatives_options_chains(params, headers): + """Test the options chains endpoint.""" params = {p: v for p, v in params.items() if v} query_str = get_querystring(params, []) @@ -68,6 +70,7 @@ def test_derivatives_options_chains(params, headers): ) @pytest.mark.integration def test_derivatives_options_unusual(params, headers): + """Test the unusual options endpoint.""" params = {p: v for p, v in params.items() if v} query_str = get_querystring(params, []) @@ -94,6 +97,7 @@ def test_derivatives_options_unusual(params, headers): ) @pytest.mark.integration def test_derivatives_futures_historical(params, headers): + """Test the futures historical endpoint.""" params = {p: v for p, v in params.items() if v} query_str = get_querystring(params, []) @@ -112,6 +116,7 @@ def test_derivatives_futures_historical(params, headers): ) @pytest.mark.integration def test_derivatives_futures_curve(params, headers): + """Test the futures curve endpoint.""" params = {p: v for p, v in params.items() if v} query_str = get_querystring(params, []) diff --git a/openbb_platform/extensions/derivatives/integration/test_derivatives_python.py b/openbb_platform/extensions/derivatives/integration/test_derivatives_python.py index 8a961c6f652a..1ba7c63fd2d7 100644 --- a/openbb_platform/extensions/derivatives/integration/test_derivatives_python.py +++ b/openbb_platform/extensions/derivatives/integration/test_derivatives_python.py @@ -35,6 +35,7 @@ def obb(pytestconfig): ) @pytest.mark.integration def test_derivatives_options_chains(params, obb): + """Test the options chains endpoint.""" result = obb.derivatives.options.chains(**params) assert result assert isinstance(result, OBBject) @@ -62,6 +63,7 @@ def test_derivatives_options_chains(params, obb): ) @pytest.mark.integration def test_derivatives_options_unusual(params, obb): + """Test the unusual options endpoint.""" result = obb.derivatives.options.unusual(**params) assert result assert isinstance(result, OBBject) @@ -85,6 +87,7 @@ def test_derivatives_options_unusual(params, obb): ) @pytest.mark.integration def test_derivatives_futures_historical(params, obb): + """Test the futures historical endpoint.""" result = obb.derivatives.futures.historical(**params) assert result assert isinstance(result, OBBject) @@ -100,6 +103,7 @@ def test_derivatives_futures_historical(params, obb): ) @pytest.mark.integration def test_derivatives_futures_curve(params, obb): + """Test the futures curve endpoint.""" result = obb.derivatives.futures.curve(**params) assert result assert isinstance(result, OBBject) diff --git a/openbb_platform/extensions/econometrics/integration/test_econometrics_api.py b/openbb_platform/extensions/econometrics/integration/test_econometrics_api.py index 0cf0851b4512..068c6d02e3a6 100644 --- a/openbb_platform/extensions/econometrics/integration/test_econometrics_api.py +++ b/openbb_platform/extensions/econometrics/integration/test_econometrics_api.py @@ -14,6 +14,7 @@ def get_headers(): + """Get the headers for the API request.""" if "headers" in data: return data["headers"] @@ -33,6 +34,7 @@ def request_data(menu: str, symbol: str, provider: str): def get_equity_data(): + """Get equity data.""" if "equity_data" in data: return data["equity_data"] @@ -44,6 +46,7 @@ def get_equity_data(): def get_crypto_data(): + """Get crypto data.""" if "crypto_data" in data: return data["crypto_data"] @@ -60,6 +63,7 @@ def get_crypto_data(): def get_data(menu: Literal["equity", "crypto"]): + """Get data based on the selected menu.""" funcs = {"equity": get_equity_data, "crypto": get_crypto_data} return funcs[menu]() @@ -73,6 +77,7 @@ def get_data(menu: Literal["equity", "crypto"]): ) @pytest.mark.integration def test_econometrics_correlation_matrix(params, data_type): + """Test the correlation matrix endpoint.""" params = {p: v for p, v in params.items() if v} body = json.dumps(get_data(data_type)) @@ -99,6 +104,7 @@ def test_econometrics_correlation_matrix(params, data_type): ) @pytest.mark.integration def test_econometrics_ols_regression_summary(params, data_type): + """Test the OLS regression summary endpoint.""" params = {p: v for p, v in params.items() if v} body = json.dumps( @@ -130,6 +136,7 @@ def test_econometrics_ols_regression_summary(params, data_type): ) @pytest.mark.integration def test_econometrics_autocorrelation(params, data_type): + """Test the autocorrelation endpoint.""" params = {p: v for p, v in params.items() if v} body = json.dumps( @@ -171,6 +178,7 @@ def test_econometrics_autocorrelation(params, data_type): ) @pytest.mark.integration def test_econometrics_residual_autocorrelation(params, data_type): + """Test the residual autocorrelation endpoint.""" params = {p: v for p, v in params.items() if v} body = json.dumps( @@ -210,6 +218,7 @@ def test_econometrics_residual_autocorrelation(params, data_type): ) @pytest.mark.integration def test_econometrics_cointegration(params, data_type): + """Test the cointegration endpoint.""" params = {p: v for p, v in params.items() if v} body = json.dumps( @@ -241,6 +250,7 @@ def test_econometrics_cointegration(params, data_type): ) @pytest.mark.integration def test_econometrics_causality(params, data_type): + """Test the causality endpoint.""" params = {p: v for p, v in params.items() if v} body = json.dumps(get_data(data_type)) @@ -257,6 +267,7 @@ def test_econometrics_causality(params, data_type): ) @pytest.mark.integration def test_econometrics_unit_root(params, data_type): + """Test the unit root endpoint.""" params = {p: v for p, v in params.items() if v} body = json.dumps(get_data(data_type)) diff --git a/openbb_platform/extensions/econometrics/integration/test_econometrics_python.py b/openbb_platform/extensions/econometrics/integration/test_econometrics_python.py index ec67c062f36d..752156ed6df8 100644 --- a/openbb_platform/extensions/econometrics/integration/test_econometrics_python.py +++ b/openbb_platform/extensions/econometrics/integration/test_econometrics_python.py @@ -25,6 +25,7 @@ def obb(pytestconfig): def get_stocks_data(): + """Get stocks data.""" import openbb # pylint:disable=import-outside-toplevel if "stocks_data" in data: @@ -40,6 +41,7 @@ def get_stocks_data(): def get_crypto_data(): + """Get crypto data.""" import openbb # pylint:disable=import-outside-toplevel if "crypto_data" in data: @@ -56,6 +58,7 @@ def get_crypto_data(): def get_data(menu: Literal["equity", "crypto"]): + """Get data.""" funcs = {"equity": get_stocks_data, "crypto": get_crypto_data} return funcs[menu]() @@ -69,6 +72,7 @@ def get_data(menu: Literal["equity", "crypto"]): ) @pytest.mark.integration def test_econometrics_correlation_matrix(params, data_type, obb): + """Test the econometrics correlation matrix.""" params = {p: v for p, v in params.items() if v} params["data"] = get_data(data_type) @@ -94,6 +98,7 @@ def test_econometrics_correlation_matrix(params, data_type, obb): ) @pytest.mark.integration def test_econometrics_ols_regression(params, data_type, obb): + """Test the econometrics OLS regression.""" params = {p: v for p, v in params.items() if v} params["data"] = get_data(data_type) @@ -119,6 +124,7 @@ def test_econometrics_ols_regression(params, data_type, obb): ) @pytest.mark.integration def test_econometrics_ols_regression_summary(params, data_type, obb): + """Test the econometrics OLS regression summary.""" params = {p: v for p, v in params.items() if v} params["data"] = get_data(data_type) @@ -143,6 +149,7 @@ def test_econometrics_ols_regression_summary(params, data_type, obb): ) @pytest.mark.integration def test_econometrics_autocorrelation(params, data_type, obb): + """Test the econometrics autocorrelation.""" params = {p: v for p, v in params.items() if v} params["data"] = get_data(data_type) @@ -177,6 +184,7 @@ def test_econometrics_autocorrelation(params, data_type, obb): ) @pytest.mark.integration def test_econometrics_residual_autocorrelation(params, data_type, obb): + """Test the econometrics residual autocorrelation.""" params = {p: v for p, v in params.items() if v} params["data"] = get_data(data_type) @@ -207,6 +215,7 @@ def test_econometrics_residual_autocorrelation(params, data_type, obb): ) @pytest.mark.integration def test_econometrics_cointegration(params, data_type, obb): + """Test the econometrics cointegration.""" params = {p: v for p, v in params.items() if v} params["data"] = get_data(data_type) @@ -242,6 +251,7 @@ def test_econometrics_cointegration(params, data_type, obb): ) @pytest.mark.integration def test_econometrics_causality(params, data_type, obb): + """Test the econometrics causality.""" params = {p: v for p, v in params.items() if v} params["data"] = get_data(data_type) @@ -264,6 +274,7 @@ def test_econometrics_causality(params, data_type, obb): ) @pytest.mark.integration def test_econometrics_unit_root(params, data_type, obb): + """Test the econometrics unit root.""" params = {p: v for p, v in params.items() if v} params["data"] = get_data(data_type) @@ -282,6 +293,7 @@ def test_econometrics_unit_root(params, data_type, obb): ) @pytest.mark.integration def test_econometrics_panel_random_effects(params, obb): + """Test the econometrics panel random effects.""" params = {p: v for p, v in params.items() if v} params["data"] = mock_multi_index_data() @@ -301,6 +313,7 @@ def test_econometrics_panel_random_effects(params, obb): ) @pytest.mark.integration def test_econometrics_panel_between(params, obb): + """Test the econometrics panel between.""" params = {p: v for p, v in params.items() if v} params["data"] = mock_multi_index_data() @@ -320,6 +333,7 @@ def test_econometrics_panel_between(params, obb): ) @pytest.mark.integration def test_econometrics_panel_pooled(params, obb): + """Test the econometrics panel pooled.""" params = {p: v for p, v in params.items() if v} params["data"] = mock_multi_index_data() @@ -339,6 +353,7 @@ def test_econometrics_panel_pooled(params, obb): ) @pytest.mark.integration def test_econometrics_panel_fixed(params, obb): + """Test the econometrics panel fixed.""" params = {p: v for p, v in params.items() if v} params["data"] = mock_multi_index_data() @@ -358,6 +373,7 @@ def test_econometrics_panel_fixed(params, obb): ) @pytest.mark.integration def test_econometrics_panel_first_difference(params, obb): + """Test the econometrics panel first difference.""" params = {p: v for p, v in params.items() if v} params["data"] = mock_multi_index_data() @@ -377,11 +393,13 @@ def test_econometrics_panel_first_difference(params, obb): ) @pytest.mark.integration def test_econometrics_panel_fmac(params, obb): + """Test the econometrics panel fmac.""" params = {p: v for p, v in params.items() if v} params["data"] = mock_multi_index_data() result = obb.econometrics.panel_fmac(**params) + """Test the econometrics panel fmac.""" assert result assert isinstance(result, OBBject) assert len(result.results) > 0 diff --git a/openbb_platform/extensions/econometrics/openbb_econometrics/__init__.py b/openbb_platform/extensions/econometrics/openbb_econometrics/__init__.py index e69de29bb2d1..cd48520387fb 100644 --- a/openbb_platform/extensions/econometrics/openbb_econometrics/__init__.py +++ b/openbb_platform/extensions/econometrics/openbb_econometrics/__init__.py @@ -0,0 +1 @@ +"""OpenBB Econometrics Extension.""" diff --git a/openbb_platform/extensions/econometrics/openbb_econometrics/utils.py b/openbb_platform/extensions/econometrics/openbb_econometrics/utils.py index 008c23fce72f..6e3745fa54e1 100644 --- a/openbb_platform/extensions/econometrics/openbb_econometrics/utils.py +++ b/openbb_platform/extensions/econometrics/openbb_econometrics/utils.py @@ -1,3 +1,5 @@ +"""Utility functions for the econometrics extension of the OpenBB platform.""" + import warnings from typing import Tuple @@ -10,8 +12,9 @@ def get_engle_granger_two_step_cointegration_test( dependent_series: pd.Series, independent_series: pd.Series ) -> Tuple[float, float, float, pd.Series, float, float]: - """Estimates long-run and short-run cointegration relationship for series y and x and apply - the two-step Engle & Granger test for cointegration. + """Estimate long-run and short-run cointegration relationship for series y and x. + + Then apply the two-step Engle & Granger test for cointegration. Uses a 2-step process to first estimate coefficients for the long-run relationship y_t = c + gamma * x_t + z_t @@ -87,7 +90,7 @@ def get_engle_granger_two_step_cointegration_test( def mock_multi_index_data(): - """Creates a mock multi-index dataframe for testing purposes.""" + """Create a mock multi-index dataframe for testing purposes.""" arrays = [ ["individual_" + str(i) for i in range(1, 11) for _ in range(5)], list(range(1, 6)) * 10, diff --git a/openbb_platform/extensions/economy/integration/test_economy_api.py b/openbb_platform/extensions/economy/integration/test_economy_api.py index 8ce32c0e1dbb..9563b7194599 100644 --- a/openbb_platform/extensions/economy/integration/test_economy_api.py +++ b/openbb_platform/extensions/economy/integration/test_economy_api.py @@ -1,3 +1,5 @@ +"""Test Economy API.""" + import base64 import pytest @@ -9,6 +11,7 @@ @pytest.fixture(scope="session") def headers(): + """Get the headers for the API request.""" userpass = f"{Env().API_USERNAME}:{Env().API_PASSWORD}" userpass_bytes = userpass.encode("ascii") base64_bytes = base64.b64encode(userpass_bytes) @@ -49,6 +52,7 @@ def headers(): ) @pytest.mark.integration def test_economy_calendar(params, headers): + """Test the economy calendar endpoint.""" params = {p: v for p, v in params.items() if v} query_str = get_querystring(params, []) @@ -87,6 +91,7 @@ def test_economy_calendar(params, headers): ) @pytest.mark.integration def test_economy_cpi(params, headers): + """Test the economy CPI endpoint.""" params = {p: v for p, v in params.items() if v} query_str = get_querystring(params, []) @@ -102,6 +107,7 @@ def test_economy_cpi(params, headers): ) @pytest.mark.integration def test_economy_risk_premium(params, headers): + """Test the economy risk premium endpoint.""" params = {p: v for p, v in params.items() if v} query_str = get_querystring(params, []) @@ -137,6 +143,7 @@ def test_economy_risk_premium(params, headers): ) @pytest.mark.integration def test_economy_gdp_forecast(params, headers): + """Test the economy GDP forecast endpoint.""" params = {p: v for p, v in params.items() if v} query_str = get_querystring(params, []) @@ -170,6 +177,7 @@ def test_economy_gdp_forecast(params, headers): ) @pytest.mark.integration def test_economy_gdp_nominal(params, headers): + """Test the economy GDP nominal endpoint.""" params = {p: v for p, v in params.items() if v} query_str = get_querystring(params, []) @@ -203,6 +211,7 @@ def test_economy_gdp_nominal(params, headers): ) @pytest.mark.integration def test_economy_gdp_real(params, headers): + """Test the economy GDP real endpoint.""" params = {p: v for p, v in params.items() if v} query_str = get_querystring(params, []) @@ -243,6 +252,7 @@ def test_economy_gdp_real(params, headers): ) @pytest.mark.integration def test_economy_balance_of_payments(params, headers): + """Test the economy balance of payments endpoint.""" params = {p: v for p, v in params.items() if v} query_str = get_querystring(params, []) @@ -319,6 +329,7 @@ def test_economy_balance_of_payments(params, headers): ) @pytest.mark.integration def test_economy_fred_search(params, headers): + """Test the economy FRED search endpoint.""" params = {p: v for p, v in params.items() if v} query_str = get_querystring(params, []) @@ -358,6 +369,7 @@ def test_economy_fred_search(params, headers): ) @pytest.mark.integration def test_economy_fred_series(params, headers): + """Test the economy FRED series endpoint.""" params = {p: v for p, v in params.items() if v} query_str = get_querystring(params, []) @@ -383,6 +395,7 @@ def test_economy_fred_series(params, headers): ) @pytest.mark.integration def test_economy_money_measures(params, headers): + """Test the economy money measures endpoint.""" params = {p: v for p, v in params.items() if v} query_str = get_querystring(params, []) @@ -412,6 +425,7 @@ def test_economy_money_measures(params, headers): ) @pytest.mark.integration def test_economy_unemployment(params, headers): + """Test the economy unemployment endpoint.""" params = {p: v for p, v in params.items() if v} query_str = get_querystring(params, []) @@ -437,6 +451,7 @@ def test_economy_unemployment(params, headers): ) @pytest.mark.integration def test_economy_composite_leading_indicator(params, headers): + """Test the economy composite leading indicator endpoint.""" params = {p: v for p, v in params.items() if v} query_str = get_querystring(params, []) @@ -463,6 +478,7 @@ def test_economy_composite_leading_indicator(params, headers): ) @pytest.mark.integration def test_economy_short_term_interest_rate(params, headers): + """Test the economy short term interest rate endpoint.""" params = {p: v for p, v in params.items() if v} query_str = get_querystring(params, []) @@ -489,6 +505,7 @@ def test_economy_short_term_interest_rate(params, headers): ) @pytest.mark.integration def test_economy_long_term_interest_rate(params, headers): + """Test the economy long term interest rate endpoint.""" params = {p: v for p, v in params.items() if v} query_str = get_querystring(params, []) @@ -537,6 +554,7 @@ def test_economy_long_term_interest_rate(params, headers): ) @pytest.mark.integration def test_economy_fred_regional(params, headers): + """Test the economy FRED regional endpoint.""" params = {p: v for p, v in params.items() if v} query_str = get_querystring(params, []) diff --git a/openbb_platform/extensions/economy/integration/test_economy_python.py b/openbb_platform/extensions/economy/integration/test_economy_python.py index 8973e2688849..bf9c7bfa1e7e 100644 --- a/openbb_platform/extensions/economy/integration/test_economy_python.py +++ b/openbb_platform/extensions/economy/integration/test_economy_python.py @@ -44,6 +44,7 @@ def obb(pytestconfig): # pylint: disable=inconsistent-return-statements ) @pytest.mark.integration def test_economy_calendar(params, obb): + """Test economy calendar.""" params = {p: v for p, v in params.items() if v} result = obb.economy.calendar(**params) @@ -69,6 +70,7 @@ def test_economy_calendar(params, obb): ) @pytest.mark.integration def test_economy_cpi(params, obb): + """Test economy cpi.""" result = obb.economy.cpi(**params) assert result assert isinstance(result, OBBject) @@ -83,6 +85,7 @@ def test_economy_cpi(params, obb): ) @pytest.mark.integration def test_economy_risk_premium(params, obb): + """Test economy risk premium.""" result = obb.economy.risk_premium(**params) assert result assert isinstance(result, OBBject) @@ -114,6 +117,7 @@ def test_economy_risk_premium(params, obb): ) @pytest.mark.integration def test_economy_gdp_forecast(params, obb): + """Test economy gdp forecast.""" params = {p: v for p, v in params.items() if v} result = obb.economy.gdp.forecast(**params) @@ -139,6 +143,7 @@ def test_economy_gdp_forecast(params, obb): ) @pytest.mark.integration def test_economy_gdp_nominal(params, obb): + """Test economy gdp nominal.""" params = {p: v for p, v in params.items() if v} result = obb.economy.gdp.nominal(**params) @@ -164,6 +169,7 @@ def test_economy_gdp_nominal(params, obb): ) @pytest.mark.integration def test_economy_gdp_real(params, obb): + """Test economy gdp real.""" params = {p: v for p, v in params.items() if v} result = obb.economy.gdp.real(**params) @@ -203,6 +209,7 @@ def test_economy_gdp_real(params, obb): ) @pytest.mark.integration def test_economy_balance_of_payments(params, obb): + """Test economy balance of payments.""" params = {p: v for p, v in params.items() if v} result = obb.economy.balance_of_payments(**params) @@ -278,6 +285,7 @@ def test_economy_balance_of_payments(params, obb): ) @pytest.mark.integration def test_economy_fred_search(params, obb): + """Test economy fred search.""" params = {p: v for p, v in params.items() if v} result = obb.economy.fred_search(**params) @@ -316,6 +324,7 @@ def test_economy_fred_search(params, obb): ) @pytest.mark.integration def test_economy_fred_series(params, obb): + """Test economy fred series.""" params = {p: v for p, v in params.items() if v} result = obb.economy.fred_series(**params) @@ -340,6 +349,7 @@ def test_economy_fred_series(params, obb): ) @pytest.mark.integration def test_economy_money_measures(params, obb): + """Test economy money measures.""" params = {p: v for p, v in params.items() if v} result = obb.economy.money_measures(**params) @@ -368,6 +378,7 @@ def test_economy_money_measures(params, obb): ) @pytest.mark.integration def test_economy_unemployment(params, obb): + """Test economy unemployment.""" params = {p: v for p, v in params.items() if v} result = obb.economy.unemployment(**params) @@ -392,6 +403,7 @@ def test_economy_unemployment(params, obb): ) @pytest.mark.integration def test_economy_composite_leading_indicator(params, obb): + """Test economy composite leading indicator.""" params = {p: v for p, v in params.items() if v} result = obb.economy.composite_leading_indicator(**params) @@ -417,6 +429,7 @@ def test_economy_composite_leading_indicator(params, obb): ) @pytest.mark.integration def test_economy_short_term_interest_rate(params, obb): + """Test economy short term interest rate.""" params = {p: v for p, v in params.items() if v} result = obb.economy.short_term_interest_rate(**params) @@ -442,6 +455,7 @@ def test_economy_short_term_interest_rate(params, obb): ) @pytest.mark.integration def test_economy_long_term_interest_rate(params, obb): + """Test economy long term interest rate.""" params = {p: v for p, v in params.items() if v} result = obb.economy.long_term_interest_rate(**params) @@ -489,6 +503,7 @@ def test_economy_long_term_interest_rate(params, obb): ) @pytest.mark.integration def test_economy_fred_regional(params, obb): + """Test economy fred regional.""" params = {p: v for p, v in params.items() if v} result = obb.economy.fred_regional(**params) diff --git a/openbb_platform/extensions/economy/openbb_economy/__init__.py b/openbb_platform/extensions/economy/openbb_economy/__init__.py index e69de29bb2d1..8eb8dbd57c85 100644 --- a/openbb_platform/extensions/economy/openbb_economy/__init__.py +++ b/openbb_platform/extensions/economy/openbb_economy/__init__.py @@ -0,0 +1 @@ +"""OpenBB Economy Extension.""" diff --git a/openbb_platform/extensions/economy/openbb_economy/economy_router.py b/openbb_platform/extensions/economy/openbb_economy/economy_router.py index d540db8e9c40..9f3b6e05577f 100644 --- a/openbb_platform/extensions/economy/openbb_economy/economy_router.py +++ b/openbb_platform/extensions/economy/openbb_economy/economy_router.py @@ -69,7 +69,10 @@ async def cpi( standard_params: StandardParams, extra_params: ExtraParams, ) -> OBBject: - """Consumer Price Index (CPI). Returns either the rescaled index value, or a rate of change (inflation).""" + """Get Consumer Price Index (CPI). + + Returns either the rescaled index value, or a rate of change (inflation). + """ return await OBBject.from_query(Query(**locals())) @@ -83,7 +86,7 @@ async def risk_premium( standard_params: StandardParams, extra_params: ExtraParams, ) -> OBBject: - """Market Risk Premium by country.""" + """Get Market Risk Premium by country.""" return await OBBject.from_query(Query(**locals())) @@ -115,8 +118,8 @@ async def fred_search( standard_params: StandardParams, extra_params: ExtraParams, ) -> OBBject: - """ - Search for FRED series or economic releases by ID or string. + """Search for FRED series or economic releases by ID or string. + This does not return the observation values, only the metadata. Use this function to find series IDs for `fred_series()`. """ @@ -160,7 +163,10 @@ async def money_measures( standard_params: StandardParams, extra_params: ExtraParams, ) -> OBBject: - """Money Measures (M1/M2 and components). The Federal Reserve publishes as part of the H.6 Release.""" + """Get Money Measures (M1/M2 and components). + + The Federal Reserve publishes as part of the H.6 Release. + """ return await OBBject.from_query(Query(**locals())) @@ -188,7 +194,7 @@ async def unemployment( standard_params: StandardParams, extra_params: ExtraParams, ) -> OBBject: - """Global unemployment data.""" + """Get global unemployment data.""" return await OBBject.from_query(Query(**locals())) @@ -205,8 +211,11 @@ async def composite_leading_indicator( standard_params: StandardParams, extra_params: ExtraParams, ) -> OBBject: - """The composite leading indicator (CLI) is designed to provide early signals of turning points + """Use the composite leading indicator (CLI). + + It is designed to provide early signals of turning points in business cycles showing fluctuation of the economic activity around its long term potential level. + CLIs show short-term economic movements in qualitative rather than quantitative terms. """ return await OBBject.from_query(Query(**locals())) @@ -227,9 +236,11 @@ async def short_term_interest_rate( standard_params: StandardParams, extra_params: ExtraParams, ) -> OBBject: - """ - Short-term interest rates are the rates at which short-term borrowings are effected between + """Get Short-term interest rates. + + They are the rates at which short-term borrowings are effected between financial institutions or the rate at which short-term government paper is issued or traded in the market. + Short-term interest rates are generally averages of daily rates, measured as a percentage. Short-term interest rates are based on three-month money market rates where available. Typical standardised names are "money market rate" and "treasury bill rate". @@ -252,8 +263,8 @@ async def long_term_interest_rate( standard_params: StandardParams, extra_params: ExtraParams, ) -> OBBject: - """ - Long-term interest rates refer to government bonds maturing in ten years. + """Get Long-term interest rates that refer to government bonds maturing in ten years. + Rates are mainly determined by the price charged by the lender, the risk from the borrower and the fall in the capital value. Long-term interest rates are generally averages of daily rates, measured as a percentage. These interest rates are implied by the prices at which the government bonds are @@ -261,7 +272,8 @@ async def long_term_interest_rate( In all cases, they refer to bonds whose capital repayment is guaranteed by governments. Long-term interest rates are one of the determinants of business investment. Low long-term interest rates encourage investment in new equipment and high interest rates discourage it. - Investment is, in turn, a major source of economic growth.""" + Investment is, in turn, a major source of economic growth. + """ return await OBBject.from_query(Query(**locals())) @@ -289,8 +301,8 @@ async def fred_regional( standard_params: StandardParams, extra_params: ExtraParams, ) -> OBBject: - """ - Query the Geo Fred API for regional economic data by series group. + """Query the Geo Fred API for regional economic data by series group. + The series group ID is found by using `fred_search` and the `series_id` parameter. """ return await OBBject.from_query(Query(**locals())) diff --git a/openbb_platform/extensions/economy/openbb_economy/gdp/gdp_router.py b/openbb_platform/extensions/economy/openbb_economy/gdp/gdp_router.py index 024fc8e2ff86..a257a1e2c85e 100644 --- a/openbb_platform/extensions/economy/openbb_economy/gdp/gdp_router.py +++ b/openbb_platform/extensions/economy/openbb_economy/gdp/gdp_router.py @@ -29,7 +29,7 @@ async def forecast( standard_params: StandardParams, extra_params: ExtraParams, ) -> OBBject: - """Forecasted GDP Data.""" + """Get Forecasted GDP Data.""" return await OBBject.from_query(Query(**locals())) @@ -46,7 +46,7 @@ async def nominal( standard_params: StandardParams, extra_params: ExtraParams, ) -> OBBject: - """Nominal GDP Data.""" + """Get Nominal GDP Data.""" return await OBBject.from_query(Query(**locals())) @@ -63,5 +63,5 @@ async def real( standard_params: StandardParams, extra_params: ExtraParams, ) -> OBBject: - """Real GDP Data.""" + """Get Real GDP Data.""" return await OBBject.from_query(Query(**locals())) diff --git a/openbb_platform/extensions/equity/integration/test_equity_api.py b/openbb_platform/extensions/equity/integration/test_equity_api.py index 5b3d5bd56b3b..84aaba03678b 100644 --- a/openbb_platform/extensions/equity/integration/test_equity_api.py +++ b/openbb_platform/extensions/equity/integration/test_equity_api.py @@ -13,6 +13,7 @@ @pytest.fixture(scope="session") def headers(): + """Get the headers for the API request.""" userpass = f"{Env().API_USERNAME}:{Env().API_PASSWORD}" userpass_bytes = userpass.encode("ascii") base64_bytes = base64.b64encode(userpass_bytes) @@ -74,6 +75,7 @@ def headers(): ) @pytest.mark.integration def test_equity_fundamental_balance(params, headers): + """Test the equity fundamental balance endpoint.""" params = {p: v for p, v in params.items() if v} query_str = get_querystring(params, []) @@ -89,6 +91,7 @@ def test_equity_fundamental_balance(params, headers): ) @pytest.mark.integration def test_equity_fundamental_balance_growth(params, headers): + """Test the equity fundamental balance growth endpoint.""" params = {p: v for p, v in params.items() if v} query_str = get_querystring(params, []) @@ -107,6 +110,7 @@ def test_equity_fundamental_balance_growth(params, headers): ) @pytest.mark.integration def test_equity_calendar_dividend(params, headers): + """Test the equity calendar dividend endpoint.""" params = {p: v for p, v in params.items() if v} query_str = get_querystring(params, []) @@ -124,6 +128,7 @@ def test_equity_calendar_dividend(params, headers): ) @pytest.mark.integration def test_equity_calendar_splits(params, headers): + """Test the equity calendar splits endpoint.""" params = {p: v for p, v in params.items() if v} query_str = get_querystring(params, []) @@ -143,6 +148,7 @@ def test_equity_calendar_splits(params, headers): ) @pytest.mark.integration def test_equity_calendar_earnings(params, headers): + """Test the equity calendar earnings endpoint.""" params = {p: v for p, v in params.items() if v} query_str = get_querystring(params, []) @@ -205,6 +211,7 @@ def test_equity_calendar_earnings(params, headers): ) @pytest.mark.integration def test_equity_fundamental_cash(params, headers): + """Test the equity fundamental cash endpoint.""" params = {p: v for p, v in params.items() if v} query_str = get_querystring(params, []) @@ -220,6 +227,7 @@ def test_equity_fundamental_cash(params, headers): ) @pytest.mark.integration def test_equity_fundamental_cash_growth(params, headers): + """Test the equity fundamental cash growth endpoint.""" params = {p: v for p, v in params.items() if v} query_str = get_querystring(params, []) @@ -257,6 +265,7 @@ def test_equity_fundamental_cash_growth(params, headers): ) @pytest.mark.integration def test_equity_fundamental_management_compensation(params, headers): + """Test the equity fundamental management compensation endpoint.""" params = {p: v for p, v in params.items() if v} query_str = get_querystring(params, []) @@ -272,6 +281,7 @@ def test_equity_fundamental_management_compensation(params, headers): ) @pytest.mark.integration def test_equity_fundamental_historical_splits(params, headers): + """Test the equity fundamental historical splits endpoint.""" params = {p: v for p, v in params.items() if v} query_str = get_querystring(params, []) @@ -333,6 +343,7 @@ def test_equity_fundamental_historical_splits(params, headers): ) @pytest.mark.integration def test_equity_fundamental_dividends(params, headers): + """Test the equity fundamental dividends endpoint.""" params = {p: v for p, v in params.items() if v} query_str = get_querystring(params, []) @@ -348,6 +359,7 @@ def test_equity_fundamental_dividends(params, headers): ) @pytest.mark.integration def test_equity_fundamental_employee_count(params, headers): + """Test the equity fundamental employee count endpoint.""" params = {p: v for p, v in params.items() if v} query_str = get_querystring(params, []) @@ -363,6 +375,7 @@ def test_equity_fundamental_employee_count(params, headers): ) @pytest.mark.integration def test_equity_estimates_historical(params, headers): + """Test the equity estimates historical endpoint.""" params = {p: v for p, v in params.items() if v} query_str = get_querystring(params, []) @@ -389,6 +402,7 @@ def test_equity_estimates_historical(params, headers): ) @pytest.mark.integration def test_equity_estimates_forward_sales(params, headers): + """Test the equity estimates forward sales endpoint.""" params = {p: v for p, v in params.items() if v} query_str = get_querystring(params, []) @@ -424,6 +438,7 @@ def test_equity_estimates_forward_sales(params, headers): ) @pytest.mark.integration def test_equity_estimates_forward_eps(params, headers): + """Test the equity estimates forward EPS endpoint.""" params = {p: v for p, v in params.items() if v} query_str = get_querystring(params, []) @@ -487,6 +502,7 @@ def test_equity_estimates_forward_eps(params, headers): ) @pytest.mark.integration def test_equity_fundamental_income(params, headers): + """Test the equity fundamental income endpoint.""" params = {p: v for p, v in params.items() if v} query_str = get_querystring(params, []) @@ -502,6 +518,7 @@ def test_equity_fundamental_income(params, headers): ) @pytest.mark.integration def test_equity_fundamental_income_growth(params, headers): + """Test the equity fundamental income growth endpoint.""" params = {p: v for p, v in params.items() if v} query_str = get_querystring(params, []) @@ -544,6 +561,7 @@ def test_equity_fundamental_income_growth(params, headers): ) @pytest.mark.integration def test_equity_ownership_insider_trading(params, headers): + """Test the equity ownership insider trading endpoint.""" params = {p: v for p, v in params.items() if v} query_str = get_querystring(params, []) @@ -576,6 +594,7 @@ def test_equity_ownership_insider_trading(params, headers): ) @pytest.mark.integration def test_equity_ownership_institutional(params, headers): + """Test the equity ownership institutional endpoint.""" params = {p: v for p, v in params.items() if v} query_str = get_querystring(params, []) @@ -610,6 +629,7 @@ def test_equity_ownership_institutional(params, headers): ) @pytest.mark.integration def test_equity_calendar_ipo(params, headers): + """Test the equity calendar IPO endpoint.""" params = {p: v for p, v in params.items() if v} query_str = get_querystring(params, []) @@ -638,6 +658,7 @@ def test_equity_calendar_ipo(params, headers): ) @pytest.mark.integration def test_equity_fundamental_metrics(params, headers): + """Test the equity fundamental metrics endpoint.""" params = {p: v for p, v in params.items() if v} query_str = get_querystring(params, []) @@ -656,6 +677,7 @@ def test_equity_fundamental_metrics(params, headers): ) @pytest.mark.integration def test_equity_fundamental_management(params, headers): + """Test the equity fundamental management endpoint.""" params = {p: v for p, v in params.items() if v} query_str = get_querystring(params, []) @@ -671,6 +693,7 @@ def test_equity_fundamental_management(params, headers): ) @pytest.mark.integration def test_equity_fundamental_overview(params, headers): + """Test the equity fundamental overview endpoint.""" params = {p: v for p, v in params.items() if v} query_str = get_querystring(params, []) @@ -686,6 +709,7 @@ def test_equity_fundamental_overview(params, headers): ) @pytest.mark.integration def test_equity_ownership_major_holders(params, headers): + """Test the equity ownership major holders endpoint.""" params = {p: v for p, v in params.items() if v} query_str = get_querystring(params, []) @@ -722,6 +746,7 @@ def test_equity_ownership_major_holders(params, headers): ) @pytest.mark.integration def test_equity_estimates_price_target(params, headers): + """Test the equity estimates price target endpoint.""" params = {p: v for p, v in params.items() if v} query_str = get_querystring(params, []) @@ -764,6 +789,7 @@ def test_equity_estimates_price_target(params, headers): ) @pytest.mark.integration def test_equity_estimates_analyst_search(params, headers): + """Test the equity estimates analyst search endpoint.""" params = {p: v for p, v in params.items() if v} query_str = get_querystring(params, []) @@ -790,6 +816,7 @@ def test_equity_estimates_analyst_search(params, headers): ) @pytest.mark.integration def test_equity_estimates_consensus(params, headers): + """Test the equity estimates consensus endpoint.""" params = {p: v for p, v in params.items() if v} query_str = get_querystring(params, []) @@ -816,6 +843,7 @@ def test_equity_estimates_consensus(params, headers): ) @pytest.mark.integration def test_equity_fundamental_ratios(params, headers): + """Test the equity fundamental ratios endpoint.""" params = {p: v for p, v in params.items() if v} query_str = get_querystring(params, []) @@ -831,6 +859,7 @@ def test_equity_fundamental_ratios(params, headers): ) @pytest.mark.integration def test_equity_fundamental_revenue_per_geography(params, headers): + """Test the equity fundamental revenue per geography endpoint.""" params = {p: v for p, v in params.items() if v} query_str = get_querystring(params, []) @@ -846,6 +875,7 @@ def test_equity_fundamental_revenue_per_geography(params, headers): ) @pytest.mark.integration def test_equity_fundamental_revenue_per_segment(params, headers): + """Test the equity fundamental revenue per segment endpoint.""" params = {p: v for p, v in params.items() if v} query_str = get_querystring(params, []) @@ -906,6 +936,7 @@ def test_equity_fundamental_revenue_per_segment(params, headers): ) @pytest.mark.integration def test_equity_fundamental_filings(params, headers): + """Test the equity fundamental filings endpoint.""" params = {p: v for p, v in params.items() if v} query_str = get_querystring(params, []) @@ -925,6 +956,7 @@ def test_equity_fundamental_filings(params, headers): ) @pytest.mark.integration def test_equity_ownership_share_statistics(params, headers): + """Test the equity ownership share statistics endpoint.""" params = {p: v for p, v in params.items() if v} query_str = get_querystring(params, []) @@ -940,6 +972,7 @@ def test_equity_ownership_share_statistics(params, headers): ) @pytest.mark.integration def test_equity_fundamental_transcript(params, headers): + """Test the equity fundamental transcript endpoint.""" params = {p: v for p, v in params.items() if v} query_str = get_querystring(params, []) @@ -955,6 +988,7 @@ def test_equity_fundamental_transcript(params, headers): ) @pytest.mark.integration def test_equity_compare_peers(params, headers): + """Test the equity compare peers endpoint.""" params = {p: v for p, v in params.items() if v} query_str = get_querystring(params, []) @@ -970,6 +1004,7 @@ def test_equity_compare_peers(params, headers): ) @pytest.mark.integration def test_equity_compare_groups(params, headers): + """Test the equity compare groups endpoint.""" params = {p: v for p, v in params.items() if v} query_str = get_querystring(params, []) @@ -1163,6 +1198,7 @@ def test_equity_compare_groups(params, headers): ) @pytest.mark.integration def test_equity_price_historical(params, headers): + """Test the equity price historical endpoint.""" params = {p: v for p, v in params.items() if v} query_str = get_querystring(params, []) @@ -1179,6 +1215,7 @@ def test_equity_price_historical(params, headers): ) @pytest.mark.integration def test_equity_fundamental_multiples(params, headers): + """Test the equity fundamental multiples endpoint.""" params = {p: v for p, v in params.items() if v} query_str = get_querystring(params, []) @@ -1196,6 +1233,7 @@ def test_equity_fundamental_multiples(params, headers): ) @pytest.mark.integration def test_equity_fundamental_search_attributes(params, headers): + """Test the equity fundamental search attributes endpoint.""" params = {p: v for p, v in params.items() if v} query_str = get_querystring(params, []) @@ -1277,6 +1315,7 @@ def test_equity_fundamental_search_attributes(params, headers): ) @pytest.mark.integration def test_equity_fundamental_historical_attributes(params, headers): + """Test the equity fundamental historical attributes endpoint.""" params = {p: v for p, v in params.items() if v} query_str = get_querystring(params, []) @@ -1335,6 +1374,7 @@ def test_equity_fundamental_historical_attributes(params, headers): ) @pytest.mark.integration def test_equity_fundamental_latest_attributes(params, headers): + """Test the equity fundamental latest attributes endpoint.""" params = {p: v for p, v in params.items() if v} query_str = get_querystring(params, []) @@ -1365,6 +1405,7 @@ def test_equity_fundamental_latest_attributes(params, headers): ) @pytest.mark.integration def test_equity_search(params, headers): + """Test the equity search endpoint.""" params = {p: v for p, v in params.items() if v} query_str = get_querystring(params, []) @@ -1403,6 +1444,7 @@ def test_equity_search(params, headers): ) @pytest.mark.integration def test_equity_screener(params, headers): + """Test the equity screener endpoint.""" params = {p: v for p, v in params.items() if v} query_str = get_querystring(params, []) @@ -1425,6 +1467,7 @@ def test_equity_screener(params, headers): ) @pytest.mark.integration def test_equity_price_quote(params, headers): + """Test the equity price quote endpoint.""" params = {p: v for p, v in params.items() if v} query_str = get_querystring(params, []) @@ -1447,6 +1490,7 @@ def test_equity_price_quote(params, headers): ) @pytest.mark.integration def test_equity_profile(params, headers): + """Test the equity profile endpoint.""" params = {p: v for p, v in params.items() if v} query_str = get_querystring(params, []) @@ -1465,6 +1509,7 @@ def test_equity_profile(params, headers): ) @pytest.mark.integration def test_equity_discovery_gainers(params, headers): + """Test the equity discovery gainers endpoint.""" params = {p: v for p, v in params.items() if v} query_str = get_querystring(params, []) @@ -1480,6 +1525,7 @@ def test_equity_discovery_gainers(params, headers): ) @pytest.mark.integration def test_equity_discovery_losers(params, headers): + """Test the equity discovery losers endpoint.""" params = {p: v for p, v in params.items() if v} query_str = get_querystring(params, []) @@ -1495,6 +1541,7 @@ def test_equity_discovery_losers(params, headers): ) @pytest.mark.integration def test_equity_discovery_active(params, headers): + """Test the equity discovery active endpoint.""" params = {p: v for p, v in params.items() if v} query_str = get_querystring(params, []) @@ -1513,6 +1560,7 @@ def test_equity_discovery_active(params, headers): ) @pytest.mark.integration def test_equity_price_performance(params, headers): + """Test the equity price performance endpoint.""" params = {p: v for p, v in params.items() if v} query_str = get_querystring(params, []) @@ -1528,6 +1576,7 @@ def test_equity_price_performance(params, headers): ) @pytest.mark.integration def test_equity_discovery_undervalued_large_caps(params, headers): + """Test the equity discovery undervalued large caps endpoint.""" params = {p: v for p, v in params.items() if v} query_str = get_querystring(params, []) @@ -1543,6 +1592,7 @@ def test_equity_discovery_undervalued_large_caps(params, headers): ) @pytest.mark.integration def test_equity_discovery_undervalued_growth(params, headers): + """Test the equity discovery undervalued growth endpoint.""" params = {p: v for p, v in params.items() if v} query_str = get_querystring(params, []) @@ -1558,6 +1608,7 @@ def test_equity_discovery_undervalued_growth(params, headers): ) @pytest.mark.integration def test_equity_discovery_aggressive_small_caps(params, headers): + """Test the equity discovery aggressive small caps endpoint.""" params = {p: v for p, v in params.items() if v} query_str = get_querystring(params, []) @@ -1575,6 +1626,7 @@ def test_equity_discovery_aggressive_small_caps(params, headers): ) @pytest.mark.integration def test_equity_discovery_growth_tech(params, headers): + """Test the equity discovery growth tech endpoint.""" params = {p: v for p, v in params.items() if v} query_str = get_querystring(params, []) @@ -1590,6 +1642,7 @@ def test_equity_discovery_growth_tech(params, headers): ) @pytest.mark.integration def test_equity_discovery_top_retail(params, headers): + """Test the equity discovery top retail endpoint.""" params = {p: v for p, v in params.items() if v} query_str = get_querystring(params, []) @@ -1605,6 +1658,7 @@ def test_equity_discovery_top_retail(params, headers): ) @pytest.mark.integration def test_equity_discovery_upcoming_release_days(params, headers): + """Test the equity discovery upcoming release days endpoint.""" params = {p: v for p, v in params.items() if v} query_str = get_querystring(params, []) @@ -1643,6 +1697,7 @@ def test_equity_discovery_upcoming_release_days(params, headers): ) @pytest.mark.integration def test_equity_discovery_filings(params, headers): + """Test the equity discovery filings endpoint.""" params = {p: v for p, v in params.items() if v} query_str = get_querystring(params, []) @@ -1661,6 +1716,7 @@ def test_equity_discovery_filings(params, headers): ) @pytest.mark.integration def test_equity_shorts_fails_to_deliver(params, headers): + """Test the equity shorts fails to deliver endpoint.""" params = {p: v for p, v in params.items() if v} query_str = get_querystring(params, []) @@ -1676,6 +1732,7 @@ def test_equity_shorts_fails_to_deliver(params, headers): ) @pytest.mark.integration def test_equity_shorts_short_volume(params, headers): + """Test the equity shorts short volume endpoint.""" params = {p: v for p, v in params.items() if v} query_str = get_querystring(params, []) @@ -1691,6 +1748,7 @@ def test_equity_shorts_short_volume(params, headers): ) @pytest.mark.integration def test_equity_shorts_short_interest(params, headers): + """Test the equity shorts short interest endpoint.""" params = {p: v for p, v in params.items() if v} query_str = get_querystring(params, []) @@ -1719,6 +1777,7 @@ def test_equity_shorts_short_interest(params, headers): ) @pytest.mark.integration def test_equity_price_nbbo(params, headers): + """Test the equity price NBBO endpoint.""" params = {p: v for p, v in params.items() if v} query_str = get_querystring(params, []) @@ -1737,6 +1796,7 @@ def test_equity_price_nbbo(params, headers): ) @pytest.mark.integration def test_equity_darkpool_otc(params, headers): + """Test the equity darkpool otc endpoint.""" params = {p: v for p, v in params.items() if v} query_str = get_querystring(params, []) @@ -1761,6 +1821,7 @@ def test_equity_darkpool_otc(params, headers): ) @pytest.mark.integration def test_equity_market_snapshots(params, headers): + """Test the equity market snapshots endpoint.""" params = {p: v for p, v in params.items() if v} query_str = get_querystring(params, []) @@ -1786,6 +1847,7 @@ def test_equity_market_snapshots(params, headers): ) @pytest.mark.integration def test_equity_fundamental_historical_eps(params, headers): + """Test the equity fundamental historical eps endpoint.""" params = {p: v for p, v in params.items() if v} query_str = get_querystring(params, []) @@ -1801,6 +1863,7 @@ def test_equity_fundamental_historical_eps(params, headers): ) @pytest.mark.integration def test_equity_fundamental_trailing_dividend_yield(params, headers): + """Test the equity fundamental trailing dividend yield endpoint.""" params = {p: v for p, v in params.items() if v} query_str = get_querystring(params, []) @@ -1847,6 +1910,7 @@ def test_equity_fundamental_trailing_dividend_yield(params, headers): ) @pytest.mark.integration def test_equity_fundamental_reported_financials(params, headers): + """Test the equity fundamental reported financials endpoint.""" params = {p: v for p, v in params.items() if v} query_str = get_querystring(params, []) @@ -1873,6 +1937,7 @@ def test_equity_fundamental_reported_financials(params, headers): ) @pytest.mark.integration def test_equity_ownership_form_13f(params, headers): + """Test the equity ownership form 13f endpoint.""" params = {p: v for p, v in params.items() if v} query_str = get_querystring(params, []) diff --git a/openbb_platform/extensions/equity/integration/test_equity_python.py b/openbb_platform/extensions/equity/integration/test_equity_python.py index ce4217760808..9b0f5bb530d2 100644 --- a/openbb_platform/extensions/equity/integration/test_equity_python.py +++ b/openbb_platform/extensions/equity/integration/test_equity_python.py @@ -73,6 +73,7 @@ def obb(pytestconfig): ) @pytest.mark.integration def test_equity_fundamental_balance(params, obb): + """Test the equity fundamental balance endpoint.""" result = obb.equity.fundamental.balance(**params) assert result assert isinstance(result, OBBject) @@ -87,6 +88,7 @@ def test_equity_fundamental_balance(params, obb): ) @pytest.mark.integration def test_equity_fundamental_balance_growth(params, obb): + """Test the equity fundamental balance growth endpoint.""" result = obb.equity.fundamental.balance_growth(**params) assert result assert isinstance(result, OBBject) @@ -102,6 +104,7 @@ def test_equity_fundamental_balance_growth(params, obb): ) @pytest.mark.integration def test_equity_calendar_dividend(params, obb): + """Test the equity calendar dividend endpoint.""" result = obb.equity.calendar.dividend(**params) assert result assert isinstance(result, OBBject) @@ -116,6 +119,7 @@ def test_equity_calendar_dividend(params, obb): ) @pytest.mark.integration def test_equity_calendar_splits(params, obb): + """Test the equity calendar splits endpoint.""" result = obb.equity.calendar.splits(**params) assert result assert isinstance(result, OBBject) @@ -132,6 +136,7 @@ def test_equity_calendar_splits(params, obb): ) @pytest.mark.integration def test_equity_calendar_earnings(params, obb): + """Test the equity calendar earnings endpoint.""" result = obb.equity.calendar.earnings(**params) assert result assert isinstance(result, OBBject) @@ -191,6 +196,7 @@ def test_equity_calendar_earnings(params, obb): ) @pytest.mark.integration def test_equity_fundamental_cash(params, obb): + """Test the equity fundamental cash endpoint.""" result = obb.equity.fundamental.cash(**params) assert result assert isinstance(result, OBBject) @@ -205,6 +211,7 @@ def test_equity_fundamental_cash(params, obb): ) @pytest.mark.integration def test_equity_fundamental_cash_growth(params, obb): + """Test the equity fundamental cash growth endpoint.""" result = obb.equity.fundamental.cash_growth(**params) assert result assert isinstance(result, OBBject) @@ -239,6 +246,7 @@ def test_equity_fundamental_cash_growth(params, obb): ) @pytest.mark.integration def test_equity_fundamental_management_compensation(params, obb): + """Test the equity fundamental management compensation endpoint.""" result = obb.equity.fundamental.management_compensation(**params) assert result assert isinstance(result, OBBject) @@ -253,6 +261,7 @@ def test_equity_fundamental_management_compensation(params, obb): ) @pytest.mark.integration def test_equity_fundamental_historical_splits(params, obb): + """Test the equity fundamental historical splits endpoint.""" result = obb.equity.fundamental.historical_splits(**params) assert result assert isinstance(result, OBBject) @@ -311,6 +320,7 @@ def test_equity_fundamental_historical_splits(params, obb): ) @pytest.mark.integration def test_equity_fundamental_dividends(params, obb): + """Test the equity fundamental dividends endpoint.""" result = obb.equity.fundamental.dividends(**params) assert result assert isinstance(result, OBBject) @@ -325,6 +335,7 @@ def test_equity_fundamental_dividends(params, obb): ) @pytest.mark.integration def test_equity_fundamental_employee_count(params, obb): + """Test the equity fundamental employee count endpoint.""" result = obb.equity.fundamental.employee_count(**params) assert result assert isinstance(result, OBBject) @@ -339,6 +350,7 @@ def test_equity_fundamental_employee_count(params, obb): ) @pytest.mark.integration def test_equity_estimates_historical(params, obb): + """Test the equity estimates historical endpoint.""" result = obb.equity.estimates.historical(**params) assert result assert isinstance(result, OBBject) @@ -399,6 +411,7 @@ def test_equity_estimates_historical(params, obb): ) @pytest.mark.integration def test_equity_fundamental_income(params, obb): + """Test the equity fundamental income endpoint.""" result = obb.equity.fundamental.income(**params) assert result assert isinstance(result, OBBject) @@ -411,6 +424,7 @@ def test_equity_fundamental_income(params, obb): ) @pytest.mark.integration def test_equity_fundamental_income_growth(params, obb): + """Test the equity fundamental income growth endpoint.""" result = obb.equity.fundamental.income_growth(**params) assert result assert isinstance(result, OBBject) @@ -450,6 +464,7 @@ def test_equity_fundamental_income_growth(params, obb): ) @pytest.mark.integration def test_equity_ownership_insider_trading(params, obb): + """Test the equity ownership insider trading endpoint.""" result = obb.equity.ownership.insider_trading(**params) assert result assert isinstance(result, OBBject) @@ -479,6 +494,7 @@ def test_equity_ownership_insider_trading(params, obb): ) @pytest.mark.integration def test_equity_ownership_institutional(params, obb): + """Test the equity ownership institutional endpoint.""" result = obb.equity.ownership.institutional(**params) assert result assert isinstance(result, OBBject) @@ -510,6 +526,7 @@ def test_equity_ownership_institutional(params, obb): ) @pytest.mark.integration def test_equity_calendar_ipo(params, obb): + """Test the equity calendar IPO endpoint.""" result = obb.equity.calendar.ipo(**params) assert result assert isinstance(result, OBBject) @@ -536,6 +553,7 @@ def test_equity_calendar_ipo(params, obb): ) @pytest.mark.integration def test_equity_fundamental_metrics(params, obb): + """Test the equity fundamental metrics endpoint.""" result = obb.equity.fundamental.metrics(**params) assert result assert isinstance(result, OBBject) @@ -554,6 +572,7 @@ def test_equity_fundamental_metrics(params, obb): ) @pytest.mark.integration def test_equity_fundamental_management(params, obb): + """Test the equity fundamental management endpoint.""" result = obb.equity.fundamental.management(**params) assert result assert isinstance(result, OBBject) @@ -568,6 +587,7 @@ def test_equity_fundamental_management(params, obb): ) @pytest.mark.integration def test_equity_fundamental_overview(params, obb): + """Test the equity fundamental overview endpoint.""" result = obb.equity.fundamental.overview(**params) assert result assert isinstance(result, OBBject) @@ -582,6 +602,7 @@ def test_equity_fundamental_overview(params, obb): ) @pytest.mark.integration def test_equity_ownership_major_holders(params, obb): + """Test the equity ownership major holders endpoint.""" result = obb.equity.ownership.major_holders(**params) assert result assert isinstance(result, OBBject) @@ -615,6 +636,7 @@ def test_equity_ownership_major_holders(params, obb): ) @pytest.mark.integration def test_equity_estimates_price_target(params, obb): + """Test the equity estimates price target endpoint.""" result = obb.equity.estimates.price_target(**params) assert result assert isinstance(result, OBBject) @@ -640,6 +662,7 @@ def test_equity_estimates_price_target(params, obb): ) @pytest.mark.integration def test_equity_estimates_analyst_search(params, obb): + """Test the equity estimates analyst search endpoint.""" result = obb.equity.estimates.analyst_search(**params) assert result assert isinstance(result, OBBject) @@ -663,6 +686,7 @@ def test_equity_estimates_analyst_search(params, obb): ) @pytest.mark.integration def test_equity_estimates_consensus(params, obb): + """Test the equity estimates consensus endpoint.""" result = obb.equity.estimates.consensus(**params) assert result assert isinstance(result, OBBject) @@ -686,6 +710,7 @@ def test_equity_estimates_consensus(params, obb): ) @pytest.mark.integration def test_equity_estimates_forward_sales(params, obb): + """Test the equity estimates forward sales endpoint.""" result = obb.equity.estimates.forward_sales(**params) assert result assert isinstance(result, OBBject) @@ -718,6 +743,7 @@ def test_equity_estimates_forward_sales(params, obb): ) @pytest.mark.integration def test_equity_estimates_forward_eps(params, obb): + """Test the equity estimates forward EPS endpoint.""" result = obb.equity.estimates.forward_eps(**params) assert result assert isinstance(result, OBBject) @@ -741,6 +767,7 @@ def test_equity_estimates_forward_eps(params, obb): ) @pytest.mark.integration def test_equity_fundamental_ratios(params, obb): + """Test the equity fundamental ratios endpoint.""" result = obb.equity.fundamental.ratios(**params) assert result assert isinstance(result, OBBject) @@ -762,6 +789,7 @@ def test_equity_fundamental_ratios(params, obb): ) @pytest.mark.integration def test_equity_fundamental_revenue_per_geography(params, obb): + """Test the equity fundamental revenue per geography endpoint.""" result = obb.equity.fundamental.revenue_per_geography(**params) assert result assert isinstance(result, OBBject) @@ -783,6 +811,7 @@ def test_equity_fundamental_revenue_per_geography(params, obb): ) @pytest.mark.integration def test_equity_fundamental_revenue_per_segment(params, obb): + """Test the equity fundamental revenue per segment endpoint.""" result = obb.equity.fundamental.revenue_per_segment(**params) assert result assert isinstance(result, OBBject) @@ -836,6 +865,7 @@ def test_equity_fundamental_revenue_per_segment(params, obb): ) @pytest.mark.integration def test_equity_fundamental_filings(params, obb): + """Test the equity fundamental filings endpoint.""" result = obb.equity.fundamental.filings(**params) assert result assert isinstance(result, OBBject) @@ -852,6 +882,7 @@ def test_equity_fundamental_filings(params, obb): ) @pytest.mark.integration def test_equity_ownership_share_statistics(params, obb): + """Test the equity ownership share statistics endpoint.""" result = obb.equity.ownership.share_statistics(**params) assert result assert isinstance(result, OBBject) @@ -866,6 +897,7 @@ def test_equity_ownership_share_statistics(params, obb): ) @pytest.mark.integration def test_equity_fundamental_transcript(params, obb): + """Test the equity fundamental transcript endpoint.""" result = obb.equity.fundamental.transcript(**params) assert result assert isinstance(result, OBBject) @@ -880,6 +912,7 @@ def test_equity_fundamental_transcript(params, obb): ) @pytest.mark.integration def test_equity_compare_peers(params, obb): + """Test the equity compare peers endpoint.""" result = obb.equity.compare.peers(**params) assert result assert isinstance(result, OBBject) @@ -892,6 +925,7 @@ def test_equity_compare_peers(params, obb): ) @pytest.mark.integration def test_equity_compare_groups(params, obb): + """Test the equity compare groups endpoint.""" result = obb.equity.compare.groups(**params) assert result assert isinstance(result, OBBject) @@ -1082,6 +1116,7 @@ def test_equity_compare_groups(params, obb): ) @pytest.mark.integration def test_equity_price_historical(params, obb): + """Test the equity price historical endpoint.""" result = obb.equity.price.historical(**params) assert result assert isinstance(result, OBBject) @@ -1096,6 +1131,7 @@ def test_equity_price_historical(params, obb): ) @pytest.mark.integration def test_equity_fundamental_multiples(params, obb): + """Test the equity fundamental multiples endpoint.""" result = obb.equity.fundamental.multiples(**params) assert result assert isinstance(result, OBBject) @@ -1110,6 +1146,7 @@ def test_equity_fundamental_multiples(params, obb): ) @pytest.mark.integration def test_equity_fundamental_search_attributes(params, obb): + """Test the equity fundamental search attributes endpoint.""" result = obb.equity.fundamental.search_attributes(**params) assert result assert isinstance(result, OBBject) @@ -1188,6 +1225,7 @@ def test_equity_fundamental_search_attributes(params, obb): ) @pytest.mark.integration def test_equity_fundamental_historical_attributes(params, obb): + """Test the equity fundamental historical attributes endpoint.""" result = obb.equity.fundamental.historical_attributes(**params) assert result assert isinstance(result, OBBject) @@ -1243,6 +1281,7 @@ def test_equity_fundamental_historical_attributes(params, obb): ) @pytest.mark.integration def test_equity_fundamental_latest_attributes(params, obb): + """Test the equity fundamental latest attributes endpoint.""" result = obb.equity.fundamental.latest_attributes(**params) assert result assert isinstance(result, OBBject) @@ -1273,6 +1312,7 @@ def test_equity_fundamental_latest_attributes(params, obb): ) @pytest.mark.integration def test_equity_search(params, obb): + """Test the equity search endpoint.""" result = obb.equity.search(**params) assert result assert isinstance(result, OBBject) @@ -1308,6 +1348,7 @@ def test_equity_search(params, obb): ) @pytest.mark.integration def test_equity_screener(params, obb): + """Test the equity screener endpoint.""" result = obb.equity.screener(**params) assert result assert isinstance(result, OBBject) @@ -1328,6 +1369,7 @@ def test_equity_screener(params, obb): ) @pytest.mark.integration def test_equity_price_quote(params, obb): + """Test the equity price quote endpoint.""" result = obb.equity.price.quote(**params) assert result assert isinstance(result, OBBject) @@ -1347,6 +1389,7 @@ def test_equity_price_quote(params, obb): ) @pytest.mark.integration def test_equity_profile(params, obb): + """Test the equity profile endpoint.""" result = obb.equity.profile(**params) assert result assert isinstance(result, OBBject) @@ -1365,6 +1408,7 @@ def test_equity_profile(params, obb): ) @pytest.mark.integration def test_equity_discovery_gainers(params, obb): + """Test the equity discovery gainers endpoint.""" params = {p: v for p, v in params.items() if v} result = obb.equity.discovery.gainers(**params) @@ -1379,6 +1423,7 @@ def test_equity_discovery_gainers(params, obb): ) @pytest.mark.integration def test_equity_discovery_losers(params, obb): + """Test the equity discovery losers endpoint.""" params = {p: v for p, v in params.items() if v} result = obb.equity.discovery.losers(**params) @@ -1393,6 +1438,7 @@ def test_equity_discovery_losers(params, obb): ) @pytest.mark.integration def test_equity_discovery_active(params, obb): + """Test the equity discovery active endpoint.""" params = {p: v for p, v in params.items() if v} result = obb.equity.discovery.active(**params) @@ -1410,6 +1456,7 @@ def test_equity_discovery_active(params, obb): ) @pytest.mark.integration def test_equity_price_performance(params, obb): + """Test the equity price performance endpoint.""" params = {p: v for p, v in params.items() if v} result = obb.equity.price.performance(**params) @@ -1424,6 +1471,7 @@ def test_equity_price_performance(params, obb): ) @pytest.mark.integration def test_equity_discovery_undervalued_large_caps(params, obb): + """Test the equity discovery undervalued large caps endpoint.""" params = {p: v for p, v in params.items() if v} result = obb.equity.discovery.undervalued_large_caps(**params) @@ -1438,6 +1486,7 @@ def test_equity_discovery_undervalued_large_caps(params, obb): ) @pytest.mark.integration def test_equity_discovery_undervalued_growth(params, obb): + """Test the equity discovery undervalued growth endpoint.""" params = {p: v for p, v in params.items() if v} result = obb.equity.discovery.undervalued_growth(**params) @@ -1452,6 +1501,7 @@ def test_equity_discovery_undervalued_growth(params, obb): ) @pytest.mark.integration def test_equity_discovery_aggressive_small_caps(params, obb): + """Test the equity discovery aggressive small caps endpoint.""" params = {p: v for p, v in params.items() if v} result = obb.equity.discovery.aggressive_small_caps(**params) @@ -1466,6 +1516,7 @@ def test_equity_discovery_aggressive_small_caps(params, obb): ) @pytest.mark.integration def test_equity_discovery_growth_tech(params, obb): + """Test the equity discovery growth tech endpoint.""" params = {p: v for p, v in params.items() if v} result = obb.equity.discovery.growth_tech(**params) @@ -1480,6 +1531,7 @@ def test_equity_discovery_growth_tech(params, obb): ) @pytest.mark.integration def test_equity_discovery_top_retail(params, obb): + """Test the equity discovery top retail endpoint.""" params = {p: v for p, v in params.items() if v} result = obb.equity.discovery.top_retail(**params) @@ -1494,6 +1546,7 @@ def test_equity_discovery_top_retail(params, obb): ) @pytest.mark.integration def test_equity_discovery_upcoming_release_days(params, obb): + """Test the equity discovery upcoming release days endpoint.""" params = {p: v for p, v in params.items() if v} result = obb.equity.discovery.upcoming_release_days(**params) @@ -1529,6 +1582,7 @@ def test_equity_discovery_upcoming_release_days(params, obb): ) @pytest.mark.integration def test_equity_discovery_filings(params, obb): + """Test the equity discovery filings endpoint.""" params = {p: v for p, v in params.items() if v} result = obb.equity.discovery.filings(**params) @@ -1549,6 +1603,7 @@ def test_equity_discovery_filings(params, obb): ) @pytest.mark.integration def test_equity_shorts_fails_to_deliver(params, obb): + """Test the equity shorts fails to deliver endpoint.""" params = {p: v for p, v in params.items() if v} result = obb.equity.shorts.fails_to_deliver(**params) @@ -1563,6 +1618,7 @@ def test_equity_shorts_fails_to_deliver(params, obb): ) @pytest.mark.integration def test_equity_shorts_short_volume(params, obb): + """Test the equity shorts short volume endpoint.""" params = {p: v for p, v in params.items() if v} result = obb.equity.shorts.short_volume(**params) @@ -1577,6 +1633,7 @@ def test_equity_shorts_short_volume(params, obb): ) @pytest.mark.integration def test_equity_shorts_short_interest(params, obb): + """Test the equity shorts short interest endpoint.""" params = {p: v for p, v in params.items() if v} result = obb.equity.shorts.short_interest(**params) @@ -1604,6 +1661,7 @@ def test_equity_shorts_short_interest(params, obb): ) @pytest.mark.integration def test_equity_price_nbbo(params, obb): + """Test the equity price nbbo endpoint.""" result = obb.equity.price.nbbo(**params) assert result assert isinstance(result, OBBject) @@ -1619,6 +1677,7 @@ def test_equity_price_nbbo(params, obb): ) @pytest.mark.integration def test_equity_darkpool_otc(params, obb): + """Test the equity darkpool otc endpoint.""" params = {p: v for p, v in params.items() if v} result = obb.equity.darkpool.otc(**params) @@ -1637,6 +1696,7 @@ def test_equity_darkpool_otc(params, obb): ) @pytest.mark.integration def test_equity_market_snapshots(params, obb): + """Test the equity market snapshots endpoint.""" result = obb.equity.market_snapshots(**params) assert result assert isinstance(result, OBBject) @@ -1659,6 +1719,7 @@ def test_equity_market_snapshots(params, obb): ) @pytest.mark.integration def test_equity_fundamental_historical_eps(params, obb): + """Test the equity fundamental historical eps endpoint.""" params = {p: v for p, v in params.items() if v} result = obb.equity.fundamental.historical_eps(**params) @@ -1673,6 +1734,7 @@ def test_equity_fundamental_historical_eps(params, obb): ) @pytest.mark.integration def test_equity_fundamental_trailing_dividend_yield(params, obb): + """Test the equity fundamental trailing dividend yield endpoint.""" params = {p: v for p, v in params.items() if v} result = obb.equity.fundamental.trailing_dividend_yield(**params) @@ -1718,6 +1780,7 @@ def test_equity_fundamental_trailing_dividend_yield(params, obb): ) @pytest.mark.integration def test_equity_fundamental_reported_financials(params, obb): + """Test the equity fundamental reported financials endpoint.""" params = {p: v for p, v in params.items() if v} result = obb.equity.fundamental.reported_financials(**params) @@ -1741,6 +1804,7 @@ def test_equity_fundamental_reported_financials(params, obb): ) @pytest.mark.integration def test_equity_ownership_form_13f(params, obb): + """Test the equity ownership form 13f endpoint.""" params = {p: v for p, v in params.items() if v} result = obb.equity.ownership.form_13f(**params) diff --git a/openbb_platform/extensions/equity/openbb_equity/compare/compare_router.py b/openbb_platform/extensions/equity/openbb_equity/compare/compare_router.py index 2f585055e3fb..1737cd2dd087 100644 --- a/openbb_platform/extensions/equity/openbb_equity/compare/compare_router.py +++ b/openbb_platform/extensions/equity/openbb_equity/compare/compare_router.py @@ -28,7 +28,8 @@ async def peers( """Get the closest peers for a given company. Peers consist of companies trading on the same exchange, operating within the same sector - and with comparable market capitalizations.""" + and with comparable market capitalizations. + """ return await OBBject.from_query(Query(**locals())) @@ -67,5 +68,6 @@ async def groups( """Get company data grouped by sector, industry or country and display either performance or valuation metrics. Valuation metrics include price to earnings, price to book, price to sales ratios and price to cash flow. - Performance metrics include the stock price change for different time periods.""" + Performance metrics include the stock price change for different time periods. + """ return await OBBject.from_query(Query(**locals())) diff --git a/openbb_platform/extensions/equity/openbb_equity/darkpool/darkpool_router.py b/openbb_platform/extensions/equity/openbb_equity/darkpool/darkpool_router.py index 67307cbeec0e..e9db292bcebb 100644 --- a/openbb_platform/extensions/equity/openbb_equity/darkpool/darkpool_router.py +++ b/openbb_platform/extensions/equity/openbb_equity/darkpool/darkpool_router.py @@ -35,5 +35,6 @@ async def otc( """Get the weekly aggregate trade data for Over The Counter deals. ATS and non-ATS trading data for each ATS/firm - with trade reporting obligations under FINRA rules.""" + with trade reporting obligations under FINRA rules. + """ return await OBBject.from_query(Query(**locals())) diff --git a/openbb_platform/extensions/equity/openbb_equity/discovery/discovery_router.py b/openbb_platform/extensions/equity/openbb_equity/discovery/discovery_router.py index 86ccde2857d2..b8fbbc1a7be7 100644 --- a/openbb_platform/extensions/equity/openbb_equity/discovery/discovery_router.py +++ b/openbb_platform/extensions/equity/openbb_equity/discovery/discovery_router.py @@ -144,10 +144,11 @@ async def top_retail( standard_params: StandardParams, extra_params: ExtraParams, ) -> OBBject: - """Tracks over $30B USD/day of individual investors trades. + """Track over $30B USD/day of individual investors trades. It gives a daily view into retail activity and sentiment for over 9,500 US traded stocks, - ADRs, and ETPs.""" + ADRs, and ETPs. + """ return await OBBject.from_query(Query(**locals())) @@ -186,8 +187,9 @@ async def filings( standard_params: StandardParams, extra_params: ExtraParams, ) -> OBBject: - """Get the URLs to SEC filings reported to EDGAR database, such as 10-K, 10-Q, 8-K, and more. SEC - filings include Form 10-K, Form 10-Q, Form 8-K, the proxy statement, Forms 3, 4, and 5, Schedule 13, Form 114, + """Get the URLs to SEC filings reported to EDGAR database, such as 10-K, 10-Q, 8-K, and more. + + SEC filings include Form 10-K, Form 10-Q, Form 8-K, the proxy statement, Forms 3, 4, and 5, Schedule 13, Form 114, Foreign Investment Disclosures and others. The annual 10-K report is required to be filed annually and includes the company's financial statements, management discussion and analysis, and audited financial statements. diff --git a/openbb_platform/extensions/equity/openbb_equity/equity_router.py b/openbb_platform/extensions/equity/openbb_equity/equity_router.py index b1522f43c052..1ba9b0215870 100644 --- a/openbb_platform/extensions/equity/openbb_equity/equity_router.py +++ b/openbb_platform/extensions/equity/openbb_equity/equity_router.py @@ -68,8 +68,10 @@ async def screener( standard_params: StandardParams, extra_params: ExtraParams, ) -> OBBject: - """Screen for companies meeting various criteria. These criteria include - market cap, price, beta, volume, and dividend yield.""" + """Screen for companies meeting various criteria. + + These criteria include market cap, price, beta, volume, and dividend yield. + """ return await OBBject.from_query(Query(**locals())) diff --git a/openbb_platform/extensions/equity/openbb_equity/ownership/ownership_router.py b/openbb_platform/extensions/equity/openbb_equity/ownership/ownership_router.py index 8095164823e0..4f118d27b633 100644 --- a/openbb_platform/extensions/equity/openbb_equity/ownership/ownership_router.py +++ b/openbb_platform/extensions/equity/openbb_equity/ownership/ownership_router.py @@ -102,7 +102,8 @@ async def form_13f( standard_params: StandardParams, extra_params: ExtraParams, ) -> OBBject: - """ + """Get the form 13F. + The Securities and Exchange Commission's (SEC) Form 13F is a quarterly report that is required to be filed by all institutional investment managers with at least $100 million in assets under management. diff --git a/openbb_platform/extensions/etf/integration/test_etf_api.py b/openbb_platform/extensions/etf/integration/test_etf_api.py index e3dffef2c63c..b83964cd656f 100644 --- a/openbb_platform/extensions/etf/integration/test_etf_api.py +++ b/openbb_platform/extensions/etf/integration/test_etf_api.py @@ -1,3 +1,5 @@ +"""Integration tests for the ETF API.""" + import base64 import pytest @@ -9,6 +11,7 @@ @pytest.fixture(scope="session") def headers(): + """Get the headers for the API request.""" userpass = f"{Env().API_USERNAME}:{Env().API_PASSWORD}" userpass_bytes = userpass.encode("ascii") base64_bytes = base64.b64encode(userpass_bytes) @@ -43,6 +46,7 @@ def headers(): ) @pytest.mark.integration def test_etf_search(params, headers): + """Test the ETF search endpoint.""" params = {p: v for p, v in params.items() if v} query_str = get_querystring(params, []) @@ -227,6 +231,7 @@ def test_etf_search(params, headers): ) @pytest.mark.integration def test_etf_historical(params, headers): + """Test the ETF historical endpoint.""" params = {p: v for p, v in params.items() if v} query_str = get_querystring(params, []) @@ -247,6 +252,7 @@ def test_etf_historical(params, headers): ) @pytest.mark.integration def test_etf_info(params, headers): + """Test the ETF info endpoint.""" params = {p: v for p, v in params.items() if v} query_str = get_querystring(params, []) @@ -265,6 +271,7 @@ def test_etf_info(params, headers): ) @pytest.mark.integration def test_etf_sectors(params, headers): + """Test the ETF sectors endpoint.""" params = {p: v for p, v in params.items() if v} query_str = get_querystring(params, []) @@ -282,6 +289,7 @@ def test_etf_sectors(params, headers): ) @pytest.mark.integration def test_etf_holdings_date(params, headers): + """Test the ETF holdings date endpoint.""" params = {p: v for p, v in params.items() if v} query_str = get_querystring(params, []) @@ -351,6 +359,7 @@ def test_etf_holdings_date(params, headers): ) @pytest.mark.integration def test_etf_holdings(params, headers): + """Test the ETF holdings endpoint.""" params = {p: v for p, v in params.items() if v} query_str = get_querystring(params, []) @@ -377,6 +386,7 @@ def test_etf_holdings(params, headers): ) @pytest.mark.integration def test_etf_price_performance(params, headers): + """Test the ETF price performance endpoint.""" params = {p: v for p, v in params.items() if v} query_str = get_querystring(params, []) @@ -395,6 +405,7 @@ def test_etf_price_performance(params, headers): ) @pytest.mark.integration def test_etf_countries(params, headers): + """Test the ETF countries endpoint.""" params = {p: v for p, v in params.items() if v} query_str = get_querystring(params, []) @@ -410,6 +421,7 @@ def test_etf_countries(params, headers): ) @pytest.mark.integration def test_etf_discovery_gainers(params, headers): + """Test the ETF discovery gainers endpoint.""" params = {p: v for p, v in params.items() if v} query_str = get_querystring(params, []) @@ -425,6 +437,7 @@ def test_etf_discovery_gainers(params, headers): ) @pytest.mark.integration def test_etf_discovery_losers(params, headers): + """Test the ETF discovery losers endpoint.""" params = {p: v for p, v in params.items() if v} query_str = get_querystring(params, []) @@ -440,6 +453,7 @@ def test_etf_discovery_losers(params, headers): ) @pytest.mark.integration def test_etf_discovery_active(params, headers): + """Test the ETF discovery active endpoint.""" params = {p: v for p, v in params.items() if v} query_str = get_querystring(params, []) @@ -458,6 +472,7 @@ def test_etf_discovery_active(params, headers): ) @pytest.mark.integration def test_etf_holdings_performance(params, headers): + """Test the ETF holdings performance endpoint.""" params = {p: v for p, v in params.items() if v} query_str = get_querystring(params, []) @@ -475,6 +490,7 @@ def test_etf_holdings_performance(params, headers): ) @pytest.mark.integration def test_etf_equity_exposure(params, headers): + """Test the ETF equity exposure endpoint.""" params = {p: v for p, v in params.items() if v} query_str = get_querystring(params, []) diff --git a/openbb_platform/extensions/etf/integration/test_etf_python.py b/openbb_platform/extensions/etf/integration/test_etf_python.py index 568c0eab2b23..db3c71580b01 100644 --- a/openbb_platform/extensions/etf/integration/test_etf_python.py +++ b/openbb_platform/extensions/etf/integration/test_etf_python.py @@ -42,6 +42,7 @@ def obb(pytestconfig): # pylint: disable=inconsistent-return-statements ) @pytest.mark.integration def test_etf_search(params, obb): + """Test the ETF search endpoint.""" params = {p: v for p, v in params.items() if v} result = obb.etf.search(**params) @@ -225,6 +226,7 @@ def test_etf_search(params, obb): ) @pytest.mark.integration def test_etf_historical(params, obb): + """Test the ETF historical endpoint.""" result = obb.equity.price.historical(**params) assert result assert isinstance(result, OBBject) @@ -242,6 +244,7 @@ def test_etf_historical(params, obb): ) @pytest.mark.integration def test_etf_info(params, obb): + """Test the ETF info endpoint.""" params = {p: v for p, v in params.items() if v} result = obb.etf.info(**params) @@ -259,6 +262,7 @@ def test_etf_info(params, obb): ) @pytest.mark.integration def test_etf_sectors(params, obb): + """Test the ETF sectors endpoint.""" params = {p: v for p, v in params.items() if v} result = obb.etf.sectors(**params) @@ -275,6 +279,7 @@ def test_etf_sectors(params, obb): ) @pytest.mark.integration def test_etf_holdings_date(params, obb): + """Test the ETF holdings date endpoint.""" params = {p: v for p, v in params.items() if v} result = obb.etf.holdings_date(**params) @@ -343,6 +348,7 @@ def test_etf_holdings_date(params, obb): ) @pytest.mark.integration def test_etf_holdings(params, obb): + """Test the ETF holdings endpoint.""" params = {p: v for p, v in params.items() if v} result = obb.etf.holdings(**params) @@ -368,6 +374,7 @@ def test_etf_holdings(params, obb): ) @pytest.mark.integration def test_etf_price_performance(params, obb): + """Test the ETF price performance endpoint.""" params = {p: v for p, v in params.items() if v} result = obb.etf.price_performance(**params) @@ -385,6 +392,7 @@ def test_etf_price_performance(params, obb): ) @pytest.mark.integration def test_etf_countries(params, obb): + """Test the ETF countries endpoint.""" params = {p: v for p, v in params.items() if v} result = obb.etf.countries(**params) @@ -399,6 +407,7 @@ def test_etf_countries(params, obb): ) @pytest.mark.integration def test_etf_discovery_gainers(params, obb): + """Test the ETF discovery gainers endpoint.""" params = {p: v for p, v in params.items() if v} result = obb.etf.discovery.gainers(**params) @@ -413,6 +422,7 @@ def test_etf_discovery_gainers(params, obb): ) @pytest.mark.integration def test_etf_discovery_losers(params, obb): + """Test the ETF discovery losers endpoint.""" params = {p: v for p, v in params.items() if v} result = obb.etf.discovery.losers(**params) @@ -427,6 +437,7 @@ def test_etf_discovery_losers(params, obb): ) @pytest.mark.integration def test_etf_discovery_active(params, obb): + """Test the ETF discovery active endpoint.""" params = {p: v for p, v in params.items() if v} result = obb.etf.discovery.active(**params) @@ -444,6 +455,7 @@ def test_etf_discovery_active(params, obb): ) @pytest.mark.integration def test_etf_holdings_performance(params, obb): + """Test the ETF holdings performance endpoint.""" params = {p: v for p, v in params.items() if v} result = obb.etf.holdings_performance(**params) @@ -460,6 +472,7 @@ def test_etf_holdings_performance(params, obb): ) @pytest.mark.integration def test_etf_equity_exposure(params, obb): + """Test the ETF equity exposure endpoint.""" params = {p: v for p, v in params.items() if v} result = obb.etf.equity_exposure(**params) diff --git a/openbb_platform/extensions/fixedincome/integration/test_fixedincome_api.py b/openbb_platform/extensions/fixedincome/integration/test_fixedincome_api.py index 95b759beaac7..2a4489afaf6d 100644 --- a/openbb_platform/extensions/fixedincome/integration/test_fixedincome_api.py +++ b/openbb_platform/extensions/fixedincome/integration/test_fixedincome_api.py @@ -1,3 +1,5 @@ +"""Test fixedincome API endpoints.""" + import base64 import pytest @@ -11,6 +13,7 @@ @pytest.fixture(scope="session") def headers(): + """Get the headers for the API request.""" userpass = f"{Env().API_USERNAME}:{Env().API_PASSWORD}" userpass_bytes = userpass.encode("ascii") base64_bytes = base64.b64encode(userpass_bytes) @@ -24,6 +27,7 @@ def headers(): ) @pytest.mark.integration def test_fixedincome_government_treasury_rates(params, headers): + """Test the treasury rates endpoint.""" params = {p: v for p, v in params.items() if v} query_str = get_querystring(params, []) @@ -41,6 +45,7 @@ def test_fixedincome_government_treasury_rates(params, headers): ) @pytest.mark.integration def test_fixedincome_government_us_yield_curve(params, headers): + """Test the US yield curve endpoint.""" params = {p: v for p, v in params.items() if v} query_str = get_querystring(params, []) @@ -68,6 +73,7 @@ def test_fixedincome_government_us_yield_curve(params, headers): ) @pytest.mark.integration def test_fixedincome_sofr(params, headers): + """Test the SOFR endpoint.""" params = {p: v for p, v in params.items() if v} query_str = get_querystring(params, []) @@ -93,6 +99,7 @@ def test_fixedincome_sofr(params, headers): ) @pytest.mark.integration def test_fixedincome_rate_estr(params, headers): + """Test the ESTR rate endpoint.""" params = {p: v for p, v in params.items() if v} query_str = get_querystring(params, []) @@ -118,6 +125,7 @@ def test_fixedincome_rate_estr(params, headers): ) @pytest.mark.integration def test_fixedincome_rate_sonia(params, headers): + """Test the SONIA rate endpoint.""" params = {p: v for p, v in params.items() if v} query_str = get_querystring(params, []) @@ -143,6 +151,7 @@ def test_fixedincome_rate_sonia(params, headers): ) @pytest.mark.integration def test_fixedincome_rate_ameribor(params, headers): + """Test the Ameribor rate endpoint.""" params = {p: v for p, v in params.items() if v} query_str = get_querystring(params, []) @@ -174,6 +183,7 @@ def test_fixedincome_rate_ameribor(params, headers): ) @pytest.mark.integration def test_fixedincome_rate_effr(params, headers): + """Test the EFFR rate endpoint.""" params = {p: v for p, v in params.items() if v} query_str = get_querystring(params, []) @@ -189,6 +199,7 @@ def test_fixedincome_rate_effr(params, headers): ) @pytest.mark.integration def test_fixedincome_rate_effr_forecast(params, headers): + """Test the EFFR forecast rate endpoint.""" params = {p: v for p, v in params.items() if v} query_str = get_querystring(params, []) @@ -204,6 +215,7 @@ def test_fixedincome_rate_effr_forecast(params, headers): ) @pytest.mark.integration def test_fixedincome_rate_iorb(params, headers): + """Test the IORB rate endpoint.""" params = {p: v for p, v in params.items() if v} query_str = get_querystring(params, []) @@ -229,6 +241,7 @@ def test_fixedincome_rate_iorb(params, headers): ) @pytest.mark.integration def test_fixedincome_rate_dpcredit(params, headers): + """Test the DPCredit rate endpoint.""" params = {p: v for p, v in params.items() if v} query_str = get_querystring(params, []) @@ -252,6 +265,7 @@ def test_fixedincome_rate_dpcredit(params, headers): ) @pytest.mark.integration def test_fixedincome_rate_ecb(params, headers): + """Test the ECB rate endpoint.""" params = {p: v for p, v in params.items() if v} query_str = get_querystring(params, []) @@ -281,6 +295,7 @@ def test_fixedincome_rate_ecb(params, headers): ) @pytest.mark.integration def test_fixedincome_corporate_ice_bofa(params, headers): + """Test the ICE BofA corporate yield index endpoint.""" params = {p: v for p, v in params.items() if v} query_str = get_querystring(params, []) @@ -296,6 +311,7 @@ def test_fixedincome_corporate_ice_bofa(params, headers): ) @pytest.mark.integration def test_fixedincome_corporate_moody(params, headers): + """Test the Moody's corporate yield index endpoint.""" params = {p: v for p, v in params.items() if v} query_str = get_querystring(params, []) @@ -322,6 +338,7 @@ def test_fixedincome_corporate_moody(params, headers): ) @pytest.mark.integration def test_fixedincome_corporate_commercial_paper(params, headers): + """Test the commercial paper endpoint.""" params = {p: v for p, v in params.items() if v} query_str = get_querystring(params, []) @@ -365,6 +382,7 @@ def test_fixedincome_corporate_commercial_paper(params, headers): ) @pytest.mark.integration def test_fixedincome_corporate_spot_rates(params, headers): + """Test the corporate spot rates endpoint.""" params = {p: v for p, v in params.items() if v} query_str = get_querystring(params, []) @@ -380,6 +398,7 @@ def test_fixedincome_corporate_spot_rates(params, headers): ) @pytest.mark.integration def test_fixedincome_corporate_hqm(params, headers): + """Test the HQM corporate yield curve endpoint.""" params = {p: v for p, v in params.items() if v} query_str = get_querystring(params, []) @@ -395,6 +414,7 @@ def test_fixedincome_corporate_hqm(params, headers): ) @pytest.mark.integration def test_fixedincome_spreads_tcm(params, headers): + """Test the TCM spreads endpoint.""" params = {p: v for p, v in params.items() if v} query_str = get_querystring(params, []) @@ -419,6 +439,7 @@ def test_fixedincome_spreads_tcm(params, headers): ) @pytest.mark.integration def test_fixedincome_spreads_tcm_effr(params, headers): + """Test the TCM EFFR spreads endpoint.""" params = {p: v for p, v in params.items() if v} query_str = get_querystring(params, []) @@ -443,6 +464,7 @@ def test_fixedincome_spreads_tcm_effr(params, headers): ) @pytest.mark.integration def test_fixedincome_spreads_treasury_effr(params, headers): + """Test the treasury EFFR spreads endpoint.""" params = {p: v for p, v in params.items() if v} query_str = get_querystring(params, []) @@ -467,6 +489,7 @@ def test_fixedincome_spreads_treasury_effr(params, headers): ) @pytest.mark.integration def test_fixedincome_government_eu_yield_curve(params, headers): + """Test the EU yield curve endpoint.""" params = {p: v for p, v in params.items() if v} query_str = get_querystring(params, []) @@ -507,6 +530,7 @@ def test_fixedincome_government_eu_yield_curve(params, headers): ) @pytest.mark.integration def test_fixedincome_government_treasury_auctions(params, headers): + """Test the treasury auctions endpoint.""" params = {p: v for p, v in params.items() if v} query_str = get_querystring(params, []) @@ -552,6 +576,7 @@ def test_fixedincome_government_treasury_auctions(params, headers): ) @pytest.mark.integration def test_fixedincome_government_treasury_prices(params, headers): + """Test the treasury prices endpoint.""" params = {p: v for p, v in params.items() if v} query_str = get_querystring(params, []) @@ -590,6 +615,7 @@ def test_fixedincome_government_treasury_prices(params, headers): ) @pytest.mark.integration def test_fixedincome_corporate_bond_prices(params, headers): + """Test the corporate bond prices endpoint.""" params = {p: v for p, v in params.items() if v} query_str = get_querystring(params, []) diff --git a/openbb_platform/extensions/fixedincome/integration/test_fixedincome_python.py b/openbb_platform/extensions/fixedincome/integration/test_fixedincome_python.py index 40c73bf077d5..57ba30d7fad1 100644 --- a/openbb_platform/extensions/fixedincome/integration/test_fixedincome_python.py +++ b/openbb_platform/extensions/fixedincome/integration/test_fixedincome_python.py @@ -26,6 +26,7 @@ def obb(pytestconfig): ) @pytest.mark.integration def test_fixedincome_government_treasury_rates(params, obb): + """Test the treasury rates endpoint.""" result = obb.fixedincome.government.treasury_rates(**params) assert result assert isinstance(result, OBBject) @@ -40,6 +41,7 @@ def test_fixedincome_government_treasury_rates(params, obb): ) @pytest.mark.integration def test_fixedincome_government_us_yield_curve(params, obb): + """Test the US yield curve endpoint.""" result = obb.fixedincome.government.us_yield_curve(**params) assert result assert isinstance(result, OBBject) @@ -62,6 +64,7 @@ def test_fixedincome_government_us_yield_curve(params, obb): ) @pytest.mark.integration def test_fixedincome_sofr(params, obb): + """Test the SOFR endpoint.""" result = obb.fixedincome.sofr(**params) assert result assert isinstance(result, OBBject) @@ -84,6 +87,7 @@ def test_fixedincome_sofr(params, obb): ) @pytest.mark.integration def test_fixedincome_rate_estr(params, obb): + """Test the ESTR endpoint.""" result = obb.fixedincome.rate.estr(**params) assert result assert isinstance(result, OBBject) @@ -106,6 +110,7 @@ def test_fixedincome_rate_estr(params, obb): ) @pytest.mark.integration def test_fixedincome_rate_sonia(params, obb): + """Test the SONIA endpoint.""" result = obb.fixedincome.rate.sonia(**params) assert result assert isinstance(result, OBBject) @@ -128,6 +133,7 @@ def test_fixedincome_rate_sonia(params, obb): ) @pytest.mark.integration def test_fixedincome_rate_ameribor(params, obb): + """Test the Ameribor endpoint.""" result = obb.fixedincome.rate.ameribor(**params) assert result assert isinstance(result, OBBject) @@ -156,6 +162,7 @@ def test_fixedincome_rate_ameribor(params, obb): ) @pytest.mark.integration def test_fixedincome_rate_effr(params, obb): + """Test the EFFR endpoint.""" result = obb.fixedincome.rate.effr(**params) assert result assert isinstance(result, OBBject) @@ -171,6 +178,7 @@ def test_fixedincome_rate_effr(params, obb): ) @pytest.mark.integration def test_fixedincome_rate_effr_forecast(params, obb): + """Test the EFFR forecast endpoint.""" result = obb.fixedincome.rate.effr_forecast(**params) assert result assert isinstance(result, OBBject) @@ -185,6 +193,7 @@ def test_fixedincome_rate_effr_forecast(params, obb): ) @pytest.mark.integration def test_fixedincome_rate_iorb(params, obb): + """Test the IORB endpoint.""" result = obb.fixedincome.rate.iorb(**params) assert result assert isinstance(result, OBBject) @@ -207,6 +216,7 @@ def test_fixedincome_rate_iorb(params, obb): ) @pytest.mark.integration def test_fixedincome_rate_dpcredit(params, obb): + """Test the DPCREDIT endpoint.""" params = {p: v for p, v in params.items() if v} result = obb.fixedincome.rate.dpcredit(**params) @@ -229,6 +239,7 @@ def test_fixedincome_rate_dpcredit(params, obb): ) @pytest.mark.integration def test_fixedincome_rate_ecb(params, obb): + """Test the ECB endpoint.""" params = {p: v for p, v in params.items() if v} result = obb.fixedincome.rate.ecb(**params) @@ -257,6 +268,7 @@ def test_fixedincome_rate_ecb(params, obb): ) @pytest.mark.integration def test_fixedincome_corporate_ice_bofa(params, obb): + """Test the ICE BofA endpoint.""" params = {p: v for p, v in params.items() if v} result = obb.fixedincome.corporate.ice_bofa(**params) @@ -271,6 +283,7 @@ def test_fixedincome_corporate_ice_bofa(params, obb): ) @pytest.mark.integration def test_fixedincome_corporate_moody(params, obb): + """Test the Moody endpoint.""" params = {p: v for p, v in params.items() if v} result = obb.fixedincome.corporate.moody(**params) @@ -296,6 +309,7 @@ def test_fixedincome_corporate_moody(params, obb): ) @pytest.mark.integration def test_fixedincome_corporate_commercial_paper(params, obb): + """Test the commercial paper endpoint.""" params = {p: v for p, v in params.items() if v} result = obb.fixedincome.corporate.commercial_paper(**params) @@ -336,6 +350,7 @@ def test_fixedincome_corporate_commercial_paper(params, obb): ) @pytest.mark.integration def test_fixedincome_corporate_spot_rates(params, obb): + """Test the spot rates endpoint.""" params = {p: v for p, v in params.items() if v} result = obb.fixedincome.corporate.spot_rates(**params) @@ -350,6 +365,7 @@ def test_fixedincome_corporate_spot_rates(params, obb): ) @pytest.mark.integration def test_fixedincome_corporate_hqm(params, obb): + """Test the HQM endpoint.""" params = {p: v for p, v in params.items() if v} result = obb.fixedincome.corporate.hqm(**params) @@ -364,6 +380,7 @@ def test_fixedincome_corporate_hqm(params, obb): ) @pytest.mark.integration def test_fixedincome_spreads_tcm(params, obb): + """Test the TCM endpoint.""" params = {p: v for p, v in params.items() if v} result = obb.fixedincome.spreads.tcm(**params) @@ -387,6 +404,7 @@ def test_fixedincome_spreads_tcm(params, obb): ) @pytest.mark.integration def test_fixedincome_spreads_tcm_effr(params, obb): + """Test the TCM EFFR endpoint.""" params = {p: v for p, v in params.items() if v} result = obb.fixedincome.spreads.tcm_effr(**params) @@ -410,6 +428,7 @@ def test_fixedincome_spreads_tcm_effr(params, obb): ) @pytest.mark.integration def test_fixedincome_spreads_treasury_effr(params, obb): + """Test the treasury EFFR endpoint.""" params = {p: v for p, v in params.items() if v} result = obb.fixedincome.spreads.treasury_effr(**params) @@ -433,6 +452,7 @@ def test_fixedincome_spreads_treasury_effr(params, obb): ) @pytest.mark.integration def test_fixedincome_government_eu_yield_curve(params, obb): + """Test the EU yield curve endpoint.""" params = {p: v for p, v in params.items() if v} result = obb.fixedincome.government.eu_yield_curve(**params) @@ -470,6 +490,7 @@ def test_fixedincome_government_eu_yield_curve(params, obb): ) @pytest.mark.integration def test_fixedincome_government_treasury_auctions(params, obb): + """Test the treasury auctions endpoint.""" params = {p: v for p, v in params.items() if v} result = obb.fixedincome.government.treasury_auctions(**params) @@ -514,6 +535,7 @@ def test_fixedincome_government_treasury_auctions(params, obb): ) @pytest.mark.integration def test_fixedincome_government_treasury_prices(params, obb): + """Test the treasury prices endpoint.""" params = {p: v for p, v in params.items() if v} result = obb.fixedincome.government.treasury_prices(**params) @@ -549,6 +571,7 @@ def test_fixedincome_government_treasury_prices(params, obb): ) @pytest.mark.integration def test_fixedincome_corporate_bond_prices(params, obb): + """Test the bond prices endpoint.""" params = {p: v for p, v in params.items() if v} result = obb.fixedincome.corporate.bond_prices(**params) diff --git a/openbb_platform/extensions/index/integration/test_index_api.py b/openbb_platform/extensions/index/integration/test_index_api.py index 0b5006c80f5d..c7ec360663da 100644 --- a/openbb_platform/extensions/index/integration/test_index_api.py +++ b/openbb_platform/extensions/index/integration/test_index_api.py @@ -1,3 +1,5 @@ +"""Test the index API endpoints.""" + import base64 import pytest @@ -9,6 +11,7 @@ @pytest.fixture(scope="session") def headers(): + """Get the headers for the API request.""" userpass = f"{Env().API_USERNAME}:{Env().API_PASSWORD}" userpass_bytes = userpass.encode("ascii") base64_bytes = base64.b64encode(userpass_bytes) @@ -29,6 +32,7 @@ def headers(): ) @pytest.mark.integration def test_index_constituents(params, headers): + """Test the index constituents endpoint.""" params = {p: v for p, v in params.items() if v} query_str = get_querystring(params, []) @@ -114,6 +118,7 @@ def test_index_constituents(params, headers): ) @pytest.mark.integration def test_index_price_historical(params, headers): + """Test the index historical price endpoint.""" params = {p: v for p, v in params.items() if v} query_str = get_querystring(params, []) @@ -191,6 +196,7 @@ def test_index_price_historical(params, headers): @pytest.mark.integration @pytest.mark.skip(reason="Deprecating this endpoint") def test_index_market(params, headers): + """Test the index market endpoint.""" params = {p: v for p, v in params.items() if v} query_str = get_querystring(params, []) @@ -211,6 +217,7 @@ def test_index_market(params, headers): ) @pytest.mark.integration def test_index_available(params, headers): + """Test the index available endpoint.""" params = {p: v for p, v in params.items() if v} query_str = get_querystring(params, []) @@ -228,6 +235,7 @@ def test_index_available(params, headers): ) @pytest.mark.integration def test_index_search(params, headers): + """Test the index search endpoint.""" params = {p: v for p, v in params.items() if v} query_str = get_querystring(params, []) @@ -246,6 +254,7 @@ def test_index_search(params, headers): ) @pytest.mark.integration def test_index_snapshots(params, headers): + """Test the index snapshots endpoint.""" params = {p: v for p, v in params.items() if v} query_str = get_querystring(params, []) @@ -272,6 +281,7 @@ def test_index_snapshots(params, headers): ) @pytest.mark.integration def test_index_sp500_multiples(params, headers): + """Test the index sp500 multiples endpoint.""" params = {p: v for p, v in params.items() if v} query_str = get_querystring(params, []) @@ -289,6 +299,7 @@ def test_index_sp500_multiples(params, headers): ) @pytest.mark.integration def test_index_sectors(params, headers): + """Test the index sectors endpoint.""" params = {p: v for p, v in params.items() if v} query_str = get_querystring(params, []) diff --git a/openbb_platform/extensions/index/integration/test_index_python.py b/openbb_platform/extensions/index/integration/test_index_python.py index 1082fce00baa..af8d2b54983e 100644 --- a/openbb_platform/extensions/index/integration/test_index_python.py +++ b/openbb_platform/extensions/index/integration/test_index_python.py @@ -28,6 +28,7 @@ def obb(pytestconfig): # pylint: disable=inconsistent-return-statements ) @pytest.mark.integration def test_index_constituents(params, obb): + """Test the index constituents endpoint.""" result = obb.index.constituents(**params) assert result assert isinstance(result, OBBject) @@ -110,6 +111,7 @@ def test_index_constituents(params, obb): ) @pytest.mark.integration def test_index_price_historical(params, obb): + """Test the index historical price endpoint.""" result = obb.index.price.historical(**params) assert result assert isinstance(result, OBBject) @@ -184,6 +186,7 @@ def test_index_price_historical(params, obb): @pytest.mark.integration @pytest.mark.skip(reason="Deprecating this endpoint") def test_index_market(params, obb): + """Test the index market endpoint.""" result = obb.index.market(**params) assert result assert isinstance(result, OBBject) @@ -202,6 +205,7 @@ def test_index_market(params, obb): ) @pytest.mark.integration def test_index_available(params, obb): + """Test the index available endpoint.""" result = obb.index.available(**params) assert result assert isinstance(result, OBBject) @@ -223,6 +227,7 @@ def test_index_available(params, obb): ) @pytest.mark.integration def test_index_search(params, obb): + """Test the index search endpoint.""" result = obb.index.search(**params) assert result assert isinstance(result, OBBject) @@ -238,6 +243,7 @@ def test_index_search(params, obb): ) @pytest.mark.integration def test_index_snapshots(params, obb): + """Test the index snapshots endpoint.""" result = obb.index.snapshots(**params) assert result assert isinstance(result, OBBject) @@ -261,6 +267,7 @@ def test_index_snapshots(params, obb): ) @pytest.mark.integration def test_index_sp500_multiples(params, obb): + """Test the index sp500 multiples endpoint.""" result = obb.index.sp500_multiples(**params) assert result assert isinstance(result, OBBject) @@ -275,6 +282,7 @@ def test_index_sp500_multiples(params, obb): ) @pytest.mark.integration def test_index_sectors(params, obb): + """Test the index sectors endpoint.""" result = obb.index.sectors(**params) assert result assert isinstance(result, OBBject) diff --git a/openbb_platform/extensions/index/openbb_index/index_router.py b/openbb_platform/extensions/index/openbb_index/index_router.py index dcc425ad43b0..4ad7d3937261 100644 --- a/openbb_platform/extensions/index/openbb_index/index_router.py +++ b/openbb_platform/extensions/index/openbb_index/index_router.py @@ -36,7 +36,7 @@ async def market( standard_params: StandardParams, extra_params: ExtraParams, ) -> OBBject: - """Historical Market Indices.""" + """Get Historical Market Indices.""" return await OBBject.from_query(Query(**locals())) @@ -56,7 +56,7 @@ async def constituents( standard_params: StandardParams, extra_params: ExtraParams, ) -> OBBject: - """Index Constituents.""" + """Get Index Constituents.""" return await OBBject.from_query(Query(**locals())) @@ -107,7 +107,7 @@ async def search( standard_params: StandardParams, extra_params: ExtraParams, ) -> OBBject: - """Filters indices for rows containing the query.""" + """Filter indices for rows containing the query.""" return await OBBject.from_query(Query(**locals())) @@ -124,7 +124,7 @@ async def sp500_multiples( standard_params: StandardParams, extra_params: ExtraParams, ) -> OBBject: - """Historical S&P 500 multiples and Shiller PE ratios.""" + """Get historical S&P 500 multiples and Shiller PE ratios.""" return await OBBject.from_query(Query(**locals())) @@ -138,5 +138,5 @@ async def sectors( standard_params: StandardParams, extra_params: ExtraParams, ) -> OBBject: - """Index Sectors. Sector weighting of an index.""" + """Get Index Sectors. Sector weighting of an index.""" return await OBBject.from_query(Query(**locals())) diff --git a/openbb_platform/extensions/news/integration/test_news_api.py b/openbb_platform/extensions/news/integration/test_news_api.py index 2b685a34857b..fe8fc4dac53d 100644 --- a/openbb_platform/extensions/news/integration/test_news_api.py +++ b/openbb_platform/extensions/news/integration/test_news_api.py @@ -1,3 +1,5 @@ +"""Test News API.""" + import base64 import pytest @@ -9,6 +11,7 @@ @pytest.fixture(scope="session") def headers(): + """Generate headers for API requests with basic authentication.""" userpass = f"{Env().API_USERNAME}:{Env().API_PASSWORD}" userpass_bytes = userpass.encode("ascii") base64_bytes = base64.b64encode(userpass_bytes) @@ -83,6 +86,7 @@ def headers(): ) @pytest.mark.integration def test_news_world(params, headers): + """Test retrieval of world news with various parameters.""" params = {p: v for p, v in params.items() if v} query_str = get_querystring(params, []) @@ -187,6 +191,7 @@ def test_news_world(params, headers): ) @pytest.mark.integration def test_news_company(params, headers): + """Test retrieval of company-specific news with various parameters.""" params = {p: v for p, v in params.items() if v} query_str = get_querystring(params, []) diff --git a/openbb_platform/extensions/news/integration/test_news_python.py b/openbb_platform/extensions/news/integration/test_news_python.py index 38bbbbfded1f..2b876d19391b 100644 --- a/openbb_platform/extensions/news/integration/test_news_python.py +++ b/openbb_platform/extensions/news/integration/test_news_python.py @@ -82,6 +82,7 @@ def obb(pytestconfig): # pylint: disable=inconsistent-return-statements ) @pytest.mark.integration def test_news_world(params, obb): + """Test the news world endpoint.""" result = obb.news.world(**params) assert result assert isinstance(result, OBBject) @@ -172,6 +173,7 @@ def test_news_world(params, obb): ) @pytest.mark.integration def test_news_company(params, obb): + """Test the news company endpoint.""" params = {p: v for p, v in params.items() if v} result = obb.news.company(**params) diff --git a/openbb_platform/extensions/news/openbb_news/__init__.py b/openbb_platform/extensions/news/openbb_news/__init__.py index e69de29bb2d1..5d8180026052 100644 --- a/openbb_platform/extensions/news/openbb_news/__init__.py +++ b/openbb_platform/extensions/news/openbb_news/__init__.py @@ -0,0 +1 @@ +"""OpenBB News extension.""" diff --git a/openbb_platform/extensions/quantitative/integration/test_quantitative_api.py b/openbb_platform/extensions/quantitative/integration/test_quantitative_api.py index 57782126fc78..ce16394488bc 100644 --- a/openbb_platform/extensions/quantitative/integration/test_quantitative_api.py +++ b/openbb_platform/extensions/quantitative/integration/test_quantitative_api.py @@ -1,3 +1,5 @@ +"""Integration tests for the quantitative extension.""" + import base64 import json import random @@ -15,6 +17,7 @@ def get_headers(): + """Get the headers for the API request.""" if "headers" in data: return data["headers"] @@ -30,12 +33,13 @@ def request_data( menu: str, symbol: str, provider: str, start_date: str = "", end_date: str = "" ): """Randomly pick a symbol and a provider and get data from the selected menu.""" - url = f"http://0.0.0.0:8000/api/v1/{menu}/price/historical?symbol={symbol}&provider={provider}&start_date={start_date}&end_date={end_date}" + url = f"http://0.0.0.0:8000/api/v1/{menu}/price/historical?symbol={symbol}&provider={provider}&start_date={start_date}&end_date={end_date}" # pylint: disable=line-too-long # noqa: E501 result = requests.get(url, headers=get_headers(), timeout=10) return result.json()["results"] def get_stocks_data(): + """Get stocks data.""" if "stocks_data" in data: return data["stocks_data"] @@ -53,6 +57,7 @@ def get_stocks_data(): def get_crypto_data(): + """Get crypto data.""" if "crypto_data" in data: return data["crypto_data"] @@ -71,6 +76,7 @@ def get_crypto_data(): def get_data(menu: Literal["equity", "crypto"]): + """Get data based on the selected menu.""" funcs = {"equity": get_stocks_data, "crypto": get_crypto_data} return funcs[menu]() @@ -84,6 +90,7 @@ def get_data(menu: Literal["equity", "crypto"]): ) @pytest.mark.integration def test_quantitative_normality(params, data_type): + """Test the normality endpoint.""" params = {p: v for p, v in params.items() if v} data = json.dumps(get_data(data_type)) @@ -103,6 +110,7 @@ def test_quantitative_normality(params, data_type): ) @pytest.mark.integration def test_quantitative_capm(params, data_type): + """Test the CAPM endpoint.""" params = {p: v for p, v in params.items() if v} data = json.dumps(get_data(data_type)) @@ -138,6 +146,7 @@ def test_quantitative_capm(params, data_type): ) @pytest.mark.integration def test_quantitative_performance_omega_ratio(params, data_type): + """Test the Omega Ratio endpoint.""" params = {p: v for p, v in params.items() if v} data = json.dumps(get_data(data_type)) @@ -157,6 +166,7 @@ def test_quantitative_performance_omega_ratio(params, data_type): ) @pytest.mark.integration def test_quantitative_rolling_kurtosis(params, data_type): + """Test the rolling kurtosis endpoint.""" params = {p: v for p, v in params.items() if v} data = json.dumps(get_data(data_type)) @@ -192,6 +202,7 @@ def test_quantitative_rolling_kurtosis(params, data_type): ) @pytest.mark.integration def test_quantitative_unitroot_test(params, data_type): + """Test the unit root test endpoint.""" params = {p: v for p, v in params.items() if v} data = json.dumps(get_data(data_type)) @@ -229,6 +240,7 @@ def test_quantitative_unitroot_test(params, data_type): ) @pytest.mark.integration def test_quantitative_performance_sharpe_ratio(params, data_type): + """Test the Sharpe Ratio endpoint.""" params = {p: v for p, v in params.items() if v} data = json.dumps(get_data(data_type)) @@ -270,6 +282,7 @@ def test_quantitative_performance_sharpe_ratio(params, data_type): ) @pytest.mark.integration def test_quantitative_performance_sortino_ratio(params, data_type): + """Test the Sortino Ratio endpoint.""" params = {p: v for p, v in params.items() if v} data = json.dumps(get_data(data_type)) @@ -290,6 +303,7 @@ def test_quantitative_performance_sortino_ratio(params, data_type): ) @pytest.mark.integration def test_quantitative_rolling_skew(params, data_type): + """Test the rolling skew endpoint.""" params = {p: v for p, v in params.items() if v} data = json.dumps(get_data(data_type)) @@ -308,6 +322,7 @@ def test_quantitative_rolling_skew(params, data_type): ) @pytest.mark.integration def test_quantitative_rolling_variance(params, data_type): + """Test the rolling variance endpoint.""" params = {p: v for p, v in params.items() if v} data = json.dumps(get_data(data_type)) @@ -326,6 +341,7 @@ def test_quantitative_rolling_variance(params, data_type): ) @pytest.mark.integration def test_quantitative_rolling_stdev(params, data_type): + """Test the rolling standard deviation endpoint.""" params = {p: v for p, v in params.items() if v} data = json.dumps(get_data(data_type)) @@ -344,6 +360,7 @@ def test_quantitative_rolling_stdev(params, data_type): ) @pytest.mark.integration def test_quantitative_rolling_mean(params, data_type): + """Test the rolling mean endpoint.""" params = {p: v for p, v in params.items() if v} data = json.dumps(get_data(data_type)) @@ -381,6 +398,7 @@ def test_quantitative_rolling_mean(params, data_type): ) @pytest.mark.integration def test_quantitative_rolling_quantile(params, data_type): + """Test the rolling quantile endpoint.""" params = {p: v for p, v in params.items() if v} data = json.dumps(get_data(data_type)) @@ -400,6 +418,7 @@ def test_quantitative_rolling_quantile(params, data_type): ) @pytest.mark.integration def test_quantitative_summary(params, data_type): + """Test the summary endpoint.""" params = {p: v for p, v in params.items() if v} data = json.dumps(get_data(data_type)) @@ -423,6 +442,7 @@ def test_quantitative_summary(params, data_type): ) @pytest.mark.integration def test_quantitative_stats_skew(params, data_type): + """Test the skew endpoint.""" params = {p: v for p, v in params.items() if v} data = json.dumps(get_data(data_type)) @@ -441,6 +461,7 @@ def test_quantitative_stats_skew(params, data_type): ) @pytest.mark.integration def test_quantitative_stats_kurtosis(params, data_type): + """Test the kurtosis endpoint.""" params = {p: v for p, v in params.items() if v} data = json.dumps(get_data(data_type)) @@ -459,6 +480,7 @@ def test_quantitative_stats_kurtosis(params, data_type): ) @pytest.mark.integration def test_quantitative_stats_mean(params, data_type): + """Test the mean endpoint.""" params = {p: v for p, v in params.items() if v} data = json.dumps(get_data(data_type)) @@ -477,6 +499,7 @@ def test_quantitative_stats_mean(params, data_type): ) @pytest.mark.integration def test_quantitative_stats_stdev(params, data_type): + """Test the standard deviation endpoint.""" params = {p: v for p, v in params.items() if v} data = json.dumps(get_data(data_type)) @@ -495,6 +518,7 @@ def test_quantitative_stats_stdev(params, data_type): ) @pytest.mark.integration def test_quantitative_stats_variance(params, data_type): + """Test the variance endpoint.""" params = {p: v for p, v in params.items() if v} data = json.dumps(get_data(data_type)) @@ -530,6 +554,7 @@ def test_quantitative_stats_variance(params, data_type): ) @pytest.mark.integration def test_quantitative_stats_quantile(params, data_type): + """Test the quantile endpoint.""" params = {p: v for p, v in params.items() if v} data = json.dumps(get_data(data_type)) diff --git a/openbb_platform/extensions/quantitative/integration/test_quantitative_python.py b/openbb_platform/extensions/quantitative/integration/test_quantitative_python.py index f9fd73b832df..4a2433e8ba7e 100644 --- a/openbb_platform/extensions/quantitative/integration/test_quantitative_python.py +++ b/openbb_platform/extensions/quantitative/integration/test_quantitative_python.py @@ -24,6 +24,7 @@ def obb(pytestconfig): def get_stocks_data(): + """Get stocks data.""" import openbb # pylint:disable=import-outside-toplevel if "stocks_data" in data: @@ -39,6 +40,7 @@ def get_stocks_data(): def get_crypto_data(): + """Get crypto data.""" import openbb # pylint:disable=import-outside-toplevel if "crypto_data" in data: @@ -55,6 +57,7 @@ def get_crypto_data(): def get_data(menu: Literal["equity", "crypto"]): + """Get data.""" funcs = {"equity": get_stocks_data, "crypto": get_crypto_data} return funcs[menu]() @@ -68,6 +71,7 @@ def get_data(menu: Literal["equity", "crypto"]): ) @pytest.mark.integration def test_quantitative_normality(params, data_type, obb): + """Test normality.""" params = {p: v for p, v in params.items() if v} params["data"] = get_data(data_type) @@ -85,6 +89,7 @@ def test_quantitative_normality(params, data_type, obb): ) @pytest.mark.integration def test_quantitative_capm(params, data_type, obb): + """Test capm.""" params = {p: v for p, v in params.items() if v} params["data"] = get_data(data_type) @@ -118,6 +123,7 @@ def test_quantitative_capm(params, data_type, obb): ) @pytest.mark.integration def test_quantitative_performance_omega_ratio(params, data_type, obb): + """Test omega ratio.""" params = {p: v for p, v in params.items() if v} params["data"] = get_data(data_type) @@ -135,6 +141,7 @@ def test_quantitative_performance_omega_ratio(params, data_type, obb): ) @pytest.mark.integration def test_quantitative_rolling_kurtosis(params, data_type, obb): + """Test rolling kurtosis.""" params = {p: v for p, v in params.items() if v} params["data"] = get_data(data_type) @@ -169,6 +176,7 @@ def test_quantitative_rolling_kurtosis(params, data_type, obb): ) @pytest.mark.integration def test_quantitative_unitroot_test(params, data_type, obb): + """Test unitroot test.""" params = {p: v for p, v in params.items() if v} params["data"] = get_data(data_type) @@ -204,6 +212,7 @@ def test_quantitative_unitroot_test(params, data_type, obb): ) @pytest.mark.integration def test_quantitative_performance_sharpe_ratio(params, data_type, obb): + """Test sharpe ratio.""" params = {p: v for p, v in params.items() if v} params["data"] = get_data(data_type) @@ -241,6 +250,7 @@ def test_quantitative_performance_sharpe_ratio(params, data_type, obb): ) @pytest.mark.integration def test_quantitative_performance_sortino_ratio(params, data_type, obb): + """Test sortino ratio.""" params = {p: v for p, v in params.items() if v} params["data"] = get_data(data_type) @@ -257,6 +267,7 @@ def test_quantitative_performance_sortino_ratio(params, data_type, obb): ) @pytest.mark.integration def test_quantitative_rolling_skew(params, data_type, obb): + """Test rolling skew.""" params = {p: v for p, v in params.items() if v} params["data"] = get_data(data_type) @@ -293,6 +304,7 @@ def test_quantitative_rolling_skew(params, data_type, obb): ) @pytest.mark.integration def test_quantitative_rolling_quantile(params, data_type, obb): + """Test rolling quantile.""" params = {p: v for p, v in params.items() if v} params["data"] = get_data(data_type) @@ -311,6 +323,7 @@ def test_quantitative_rolling_quantile(params, data_type, obb): ) @pytest.mark.integration def test_quantitative_summary(params, data_type, obb): + """Test summary.""" params = {p: v for p, v in params.items() if v} params["data"] = get_data(data_type) @@ -344,6 +357,7 @@ def test_quantitative_summary(params, data_type, obb): ) @pytest.mark.integration def test_quantitative_rolling_stdev(params, data_type, obb): + """Test rolling stdev.""" params = {p: v for p, v in params.items() if v} params["data"] = get_data(data_type) @@ -378,6 +392,7 @@ def test_quantitative_rolling_stdev(params, data_type, obb): ) @pytest.mark.integration def test_quantitative_rolling_mean(params, data_type, obb): + """Test rolling mean.""" params = {p: v for p, v in params.items() if v} params["data"] = get_data(data_type) @@ -412,6 +427,7 @@ def test_quantitative_rolling_mean(params, data_type, obb): ) @pytest.mark.integration def test_quantitative_rolling_variance(params, data_type, obb): + """Test rolling variance.""" params = {p: v for p, v in params.items() if v} params["data"] = get_data(data_type) @@ -429,6 +445,7 @@ def test_quantitative_rolling_variance(params, data_type, obb): ) @pytest.mark.integration def test_quantitative_stats_skew(params, data_type, obb): + """Test skew.""" params = {p: v for p, v in params.items() if v} params["data"] = get_data(data_type) @@ -446,6 +463,7 @@ def test_quantitative_stats_skew(params, data_type, obb): ) @pytest.mark.integration def test_quantitative_stats_kurtosis(params, data_type, obb): + """Test kurtosis.""" params = {p: v for p, v in params.items() if v} params["data"] = get_data(data_type) @@ -463,6 +481,7 @@ def test_quantitative_stats_kurtosis(params, data_type, obb): ) @pytest.mark.integration def test_quantitative_stats_variance(params, data_type, obb): + """Test variance.""" params = {p: v for p, v in params.items() if v} params["data"] = get_data(data_type) @@ -480,6 +499,7 @@ def test_quantitative_stats_variance(params, data_type, obb): ) @pytest.mark.integration def test_quantitative_stats_stdev(params, data_type, obb): + """Test stdev.""" params = {p: v for p, v in params.items() if v} params["data"] = get_data(data_type) @@ -497,6 +517,7 @@ def test_quantitative_stats_stdev(params, data_type, obb): ) @pytest.mark.integration def test_quantitative_stats_mean(params, data_type, obb): + """Test mean.""" params = {p: v for p, v in params.items() if v} params["data"] = get_data(data_type) @@ -529,6 +550,7 @@ def test_quantitative_stats_mean(params, data_type, obb): ) @pytest.mark.integration def test_quantitative_stats_quantile(params, data_type, obb): + """Test quantile.""" params = {p: v for p, v in params.items() if v} params["data"] = get_data(data_type) diff --git a/openbb_platform/extensions/quantitative/openbb_quantitative/performance/performance_router.py b/openbb_platform/extensions/quantitative/openbb_quantitative/performance/performance_router.py index 025df52bb20a..1f5110cc409d 100644 --- a/openbb_platform/extensions/quantitative/openbb_quantitative/performance/performance_router.py +++ b/openbb_platform/extensions/quantitative/openbb_quantitative/performance/performance_router.py @@ -1,3 +1,5 @@ +"""OpenBB Performance Extension router.""" + from typing import List import numpy as np diff --git a/openbb_platform/extensions/quantitative/openbb_quantitative/rolling/rolling_router.py b/openbb_platform/extensions/quantitative/openbb_quantitative/rolling/rolling_router.py index 34ef9be67a1b..8bcfaa051431 100644 --- a/openbb_platform/extensions/quantitative/openbb_quantitative/rolling/rolling_router.py +++ b/openbb_platform/extensions/quantitative/openbb_quantitative/rolling/rolling_router.py @@ -376,8 +376,7 @@ def quantile( def mean( data: List[Data], target: str, window: PositiveInt = 21, index: str = "date" ) -> OBBject[List[Data]]: - """ - Calculate the rolling mean (average) of a target column within a given window size. + """Calculate the rolling average of a target column within a given window size. The rolling mean is a simple moving average that calculates the average of a target variable over a specified window. This function is widely used in financial analysis to smooth short-term fluctuations and highlight longer-term trends diff --git a/openbb_platform/extensions/quantitative/openbb_quantitative/statistics.py b/openbb_platform/extensions/quantitative/openbb_quantitative/statistics.py index db137ac77cfc..e3339107364a 100644 --- a/openbb_platform/extensions/quantitative/openbb_quantitative/statistics.py +++ b/openbb_platform/extensions/quantitative/openbb_quantitative/statistics.py @@ -1,4 +1,4 @@ -"""Statistics Functions""" +"""Statistics Functions.""" from typing import Union @@ -16,26 +16,32 @@ def kurtosis_(data: Union[DataFrame, Series, ndarray]) -> float: - """Kurtosis is a measure of the "tailedness" of the probability distribution of a real-valued random variable.""" + """Get Kurtosis. + + It is a measure of the "tailedness" of the probability distribution of a real-valued random variable. + """ return stats.kurtosis(data) def skew_(data: Union[DataFrame, Series, ndarray]) -> float: - """Skewness is a measure of the asymmetry of the probability distribution of a - real-valued random variable about its mean.""" + """Get Skewness. + + It is a measure of the asymmetry of the probability distribution of a + real-valued random variable about its mean. + """ return stats.skew(data) def mean_(data: Union[DataFrame, Series, ndarray]) -> float: - """Mean is the average of the numbers.""" + """Get Mean which is the average of the numbers.""" return mean_np(data) def std_dev_(data: Union[DataFrame, Series, ndarray]) -> float: - """Standard deviation is a measure of the amount of variation or dispersion of a set of values.""" + """Get Standard deviation that is a measure of the amount of variation or dispersion of a set of values.""" return std(data) def var_(data: Union[DataFrame, Series, ndarray]) -> float: - """Variance is a measure of the amount of variation or dispersion of a set of values.""" + """Get Variance that is a measure of the amount of variation or dispersion of a set of values.""" return var_np(data) diff --git a/openbb_platform/extensions/quantitative/openbb_quantitative/stats/stats_router.py b/openbb_platform/extensions/quantitative/openbb_quantitative/stats/stats_router.py index 68be4b675cfc..2b32123aaac3 100644 --- a/openbb_platform/extensions/quantitative/openbb_quantitative/stats/stats_router.py +++ b/openbb_platform/extensions/quantitative/openbb_quantitative/stats/stats_router.py @@ -101,8 +101,7 @@ def skew( ], ) def variance(data: List[Data], target: str) -> OBBject[List[Data]]: - """ - Calculate the variance of a target column. + """Calculate the variance of a target column. Variance measures the dispersion of a set of data points around their mean. It is a key metric for assessing the volatility and stability of financial returns or other time series data. @@ -150,8 +149,7 @@ def variance(data: List[Data], target: str) -> OBBject[List[Data]]: ], ) def stdev(data: List[Data], target: str) -> OBBject[List[Data]]: - """ - Calculate the rolling standard deviation of a target column. + """Calculate the rolling standard deviation of a target column. Standard deviation is a measure of the amount of variation or dispersion of a set of values. It is widely used to assess the risk and volatility of financial returns or other time series data @@ -200,8 +198,7 @@ def stdev(data: List[Data], target: str) -> OBBject[List[Data]]: ], ) def kurtosis(data: List[Data], target: str) -> OBBject[List[Data]]: - """ - Calculate the rolling kurtosis of a target column. + """Calculate the rolling kurtosis of a target column. Kurtosis measures the "tailedness" of the probability distribution of a real-valued random variable. High kurtosis indicates a distribution with heavy tails (outliers), suggesting a higher risk of extreme outcomes. @@ -255,8 +252,7 @@ def quantile( target: str, quantile_pct: NonNegativeFloat = 0.5, ) -> OBBject[List[Data]]: - """ - Calculate the quantile of a target column at a specified quantile percentage. + """Calculate the quantile of a target column at a specified quantile percentage. Quantiles are points dividing the range of a probability distribution into intervals with equal probabilities, or dividing the sample in the same way. @@ -312,8 +308,7 @@ def mean( data: List[Data], target: str, ) -> OBBject[List[Data]]: - """ - Calculate the mean (average) of a target column. + """Calculate the average of a target column. The rolling mean is a simple moving average that calculates the average of a target variable. This function is widely used in financial analysis to smooth short-term fluctuations and highlight longer-term trends diff --git a/openbb_platform/extensions/quantitative/tests/test_quantitative_helpers.py b/openbb_platform/extensions/quantitative/tests/test_quantitative_helpers.py index 82f6ae52b153..8a175957a0ad 100644 --- a/openbb_platform/extensions/quantitative/tests/test_quantitative_helpers.py +++ b/openbb_platform/extensions/quantitative/tests/test_quantitative_helpers.py @@ -7,6 +7,7 @@ def test_validate_window(): + """Test the validate_window function.""" input_data = pd.Series(range(1, 100)) validate_window( input_data=input_data, diff --git a/openbb_platform/extensions/quantitative/tests/test_statistics.py b/openbb_platform/extensions/quantitative/tests/test_statistics.py index 11c1ce2ec439..d1a34e30c8c9 100644 --- a/openbb_platform/extensions/quantitative/tests/test_statistics.py +++ b/openbb_platform/extensions/quantitative/tests/test_statistics.py @@ -1,3 +1,5 @@ +"""Tests for the statistics module.""" + import pandas as pd import pytest from openbb_quantitative.statistics import kurtosis_, mean_, skew_, std_dev_, var_ @@ -6,20 +8,25 @@ def test_kurtosis(): + """Test the kurtosis function.""" assert kurtosis_(test_data) == pytest.approx(-1.224, abs=1e-3) def test_skew(): + """Test the skewness function.""" assert skew_(test_data) == pytest.approx(0.0, abs=1e-3) def test_std_dev(): + """Test the standard deviation function.""" assert std_dev_(test_data) == pytest.approx(2.872, abs=1e-3) def test_mean(): + """Test the mean function.""" assert mean_(test_data) == pytest.approx(5.5, abs=1e-3) def test_var(): + """Test the variance function.""" assert var_(test_data) == pytest.approx(8.25, abs=1e-3) diff --git a/openbb_platform/extensions/regulators/integration/test_regulators_api.py b/openbb_platform/extensions/regulators/integration/test_regulators_api.py index 997ce2a2a707..0ea5fa5a8f2c 100644 --- a/openbb_platform/extensions/regulators/integration/test_regulators_api.py +++ b/openbb_platform/extensions/regulators/integration/test_regulators_api.py @@ -1,3 +1,5 @@ +"""Integration tests for the regulators API.""" + import base64 import pytest @@ -9,6 +11,7 @@ @pytest.fixture(scope="session") def headers(): + """Get the headers for the API request.""" userpass = f"{Env().API_USERNAME}:{Env().API_PASSWORD}" userpass_bytes = userpass.encode("ascii") base64_bytes = base64.b64encode(userpass_bytes) @@ -28,6 +31,7 @@ def headers(): ) @pytest.mark.integration def test_regulators_sec_cik_map(params, headers): + """Test the SEC CIK map endpoint.""" params = {p: v for p, v in params.items() if v} query_str = get_querystring(params, []) @@ -45,6 +49,7 @@ def test_regulators_sec_cik_map(params, headers): ) @pytest.mark.integration def test_regulators_sec_institutions_search(params, headers): + """Test the SEC institutions search endpoint.""" params = {p: v for p, v in params.items() if v} query_str = get_querystring(params, []) @@ -70,6 +75,7 @@ def test_regulators_sec_institutions_search(params, headers): ) @pytest.mark.integration def test_regulators_sec_schema_files(params, headers): + """Test the SEC schema files endpoint.""" params = {p: v for p, v in params.items() if v} query_str = get_querystring(params, []) @@ -88,6 +94,7 @@ def test_regulators_sec_schema_files(params, headers): ) @pytest.mark.integration def test_regulators_sec_symbol_map(params, headers): + """Test the SEC symbol map endpoint.""" params = {p: v for p, v in params.items() if v} query_str = get_querystring(params, []) @@ -103,6 +110,7 @@ def test_regulators_sec_symbol_map(params, headers): ) @pytest.mark.integration def test_regulators_sec_rss_litigation(params, headers): + """Test the SEC RSS litigation endpoint.""" params = {p: v for p, v in params.items() if v} query_str = get_querystring(params, []) @@ -118,6 +126,7 @@ def test_regulators_sec_rss_litigation(params, headers): ) @pytest.mark.integration def test_regulators_sec_sic_search(params, headers): + """Test the SEC SIC search endpoint.""" params = {p: v for p, v in params.items() if v} query_str = get_querystring(params, []) @@ -135,6 +144,7 @@ def test_regulators_sec_sic_search(params, headers): ) @pytest.mark.integration def test_regulators_cftc_cot_search(params, headers): + """Test the CFTC COT search endpoint.""" params = {p: v for p, v in params.items() if v} query_str = get_querystring(params, []) @@ -165,6 +175,7 @@ def test_regulators_cftc_cot_search(params, headers): ) @pytest.mark.integration def test_regulators_cftc_cot(params, headers): + """Test the CFTC COT endpoint.""" params = {p: v for p, v in params.items() if v} query_str = get_querystring(params, []) diff --git a/openbb_platform/extensions/regulators/integration/test_regulators_python.py b/openbb_platform/extensions/regulators/integration/test_regulators_python.py index 6e5ce8866863..77c2e811f537 100644 --- a/openbb_platform/extensions/regulators/integration/test_regulators_python.py +++ b/openbb_platform/extensions/regulators/integration/test_regulators_python.py @@ -28,6 +28,7 @@ def obb(pytestconfig): ) @pytest.mark.integration def test_regulators_sec_cik_map(params, obb): + """Test the SEC CIK map endpoint.""" result = obb.regulators.sec.cik_map(**params) assert result assert isinstance(result, OBBject) @@ -43,6 +44,7 @@ def test_regulators_sec_cik_map(params, obb): ) @pytest.mark.integration def test_regulators_sec_institutions_search(params, obb): + """Test the SEC institutions search endpoint.""" result = obb.regulators.sec.institutions_search(**params) assert result assert isinstance(result, OBBject) @@ -72,6 +74,7 @@ def test_regulators_sec_institutions_search(params, obb): ) @pytest.mark.integration def test_regulators_sec_schema_files(params, obb): + """Test the SEC schema files endpoint.""" result = obb.regulators.sec.schema_files(**params) assert result assert isinstance(result, OBBject) @@ -87,6 +90,7 @@ def test_regulators_sec_schema_files(params, obb): ) @pytest.mark.integration def test_regulators_sec_symbol_map(params, obb): + """Test the SEC symbol map endpoint.""" result = obb.regulators.sec.symbol_map(**params) assert result assert isinstance(result, OBBject) @@ -100,6 +104,7 @@ def test_regulators_sec_symbol_map(params, obb): ) @pytest.mark.integration def test_regulators_sec_rss_litigation(params, obb): + """Test the SEC RSS litigation endpoint.""" result = obb.regulators.sec.rss_litigation(**params) assert result assert isinstance(result, OBBject) @@ -112,6 +117,7 @@ def test_regulators_sec_rss_litigation(params, obb): ) @pytest.mark.integration def test_regulators_sec_sic_search(params, obb): + """Test the SEC SIC search endpoint.""" result = obb.regulators.sec.sic_search(**params) assert result assert isinstance(result, OBBject) @@ -126,6 +132,7 @@ def test_regulators_sec_sic_search(params, obb): ) @pytest.mark.integration def test_regulators_cftc_cot_search(params, obb): + """Test the CFTC COT search endpoint.""" result = obb.regulators.cftc.cot_search(**params) assert result assert isinstance(result, OBBject) @@ -153,6 +160,7 @@ def test_regulators_cftc_cot_search(params, obb): ) @pytest.mark.integration def test_regulators_cftc_cot(params, obb): + """Test the CFTC COT endpoint.""" result = obb.regulators.cftc.cot(**params) assert result assert isinstance(result, OBBject) diff --git a/openbb_platform/extensions/regulators/openbb_regulators/__init__.py b/openbb_platform/extensions/regulators/openbb_regulators/__init__.py index e69de29bb2d1..4167ad3a36f0 100644 --- a/openbb_platform/extensions/regulators/openbb_regulators/__init__.py +++ b/openbb_platform/extensions/regulators/openbb_regulators/__init__.py @@ -0,0 +1 @@ +"""OpenBB Regulators Extension.""" diff --git a/openbb_platform/extensions/regulators/openbb_regulators/cftc/cftc_router.py b/openbb_platform/extensions/regulators/openbb_regulators/cftc/cftc_router.py index eb5e1e642aae..b2a62a7ec42c 100644 --- a/openbb_platform/extensions/regulators/openbb_regulators/cftc/cftc_router.py +++ b/openbb_platform/extensions/regulators/openbb_regulators/cftc/cftc_router.py @@ -59,5 +59,5 @@ async def cot( standard_params: StandardParams, extra_params: ExtraParams, ) -> OBBject: - """Commitment of Traders Reports.""" + """Get Commitment of Traders Reports.""" return await OBBject.from_query(Query(**locals())) diff --git a/openbb_platform/extensions/regulators/openbb_regulators/sec/__init__.py b/openbb_platform/extensions/regulators/openbb_regulators/sec/__init__.py index e69de29bb2d1..4f3fc3a22e73 100644 --- a/openbb_platform/extensions/regulators/openbb_regulators/sec/__init__.py +++ b/openbb_platform/extensions/regulators/openbb_regulators/sec/__init__.py @@ -0,0 +1 @@ +"""Regulators for the SEC init.""" diff --git a/openbb_platform/extensions/regulators/openbb_regulators/sec/sec_router.py b/openbb_platform/extensions/regulators/openbb_regulators/sec/sec_router.py index df212ad35c72..6129d346c873 100644 --- a/openbb_platform/extensions/regulators/openbb_regulators/sec/sec_router.py +++ b/openbb_platform/extensions/regulators/openbb_regulators/sec/sec_router.py @@ -80,7 +80,7 @@ async def schema_files( standard_params: StandardParams, extra_params: ExtraParams, ) -> OBBject: - """A tool for navigating the directory of SEC XML schema files by year.""" + """Use tool for navigating the directory of SEC XML schema files by year.""" return await OBBject.from_query(Query(**locals())) @@ -108,7 +108,7 @@ async def rss_litigation( standard_params: StandardParams, extra_params: ExtraParams, ) -> OBBject: - """The RSS feed provides links to litigation releases concerning civil lawsuits brought by the Commission in federal court.""" # noqa: E501 pylint: disable=C0301 + """Get the RSS feed that provides links to litigation releases concerning civil lawsuits brought by the Commission in federal court.""" # noqa: E501 pylint: disable=C0301 return await OBBject.from_query(Query(**locals())) diff --git a/openbb_platform/extensions/technical/integration/test_technical_api.py b/openbb_platform/extensions/technical/integration/test_technical_api.py index 2fec3060fa0d..1ed903f85c4b 100644 --- a/openbb_platform/extensions/technical/integration/test_technical_api.py +++ b/openbb_platform/extensions/technical/integration/test_technical_api.py @@ -1,3 +1,5 @@ +"""Test technical api.""" + import base64 import json import random diff --git a/openbb_platform/extensions/technical/integration/test_technical_python.py b/openbb_platform/extensions/technical/integration/test_technical_python.py index ab51354904e9..afc0d60b9094 100644 --- a/openbb_platform/extensions/technical/integration/test_technical_python.py +++ b/openbb_platform/extensions/technical/integration/test_technical_python.py @@ -24,6 +24,7 @@ def obb(pytestconfig): def get_stocks_data(): + """Get stocks data.""" import openbb # pylint:disable=import-outside-toplevel if "stocks_data" in data: @@ -39,6 +40,7 @@ def get_stocks_data(): def get_crypto_data(): + """Get crypto data.""" import openbb # pylint:disable=import-outside-toplevel if "crypto_data" in data: @@ -55,6 +57,7 @@ def get_crypto_data(): def get_data(menu: Literal["stocks", "crypto"]): + """Get data.""" funcs = {"stocks": get_stocks_data, "crypto": get_crypto_data} return funcs[menu]() @@ -88,6 +91,7 @@ def get_data(menu: Literal["stocks", "crypto"]): ) @pytest.mark.integration def test_technical_atr(params, data_type, obb): + """Test atr.""" params = {p: v for p, v in params.items() if v} params["data"] = get_data(data_type) @@ -126,6 +130,7 @@ def test_technical_atr(params, data_type, obb): ) @pytest.mark.integration def test_technical_fib(params, data_type, obb): + """Test fib.""" params = {p: v for p, v in params.items() if v} params["data"] = get_data(data_type) @@ -144,6 +149,7 @@ def test_technical_fib(params, data_type, obb): ) @pytest.mark.integration def test_technical_obv(params, data_type, obb): + """Test obv.""" params = {p: v for p, v in params.items() if v} params["data"] = get_data(data_type) @@ -162,6 +168,7 @@ def test_technical_obv(params, data_type, obb): ) @pytest.mark.integration def test_technical_fisher(params, data_type, obb): + """Test fisher.""" params = {p: v for p, v in params.items() if v} params["data"] = get_data(data_type) @@ -198,6 +205,7 @@ def test_technical_fisher(params, data_type, obb): ) @pytest.mark.integration def test_technical_adosc(params, data_type, obb): + """Test adosc.""" params = {p: v for p, v in params.items() if v} params["data"] = get_data(data_type) @@ -238,6 +246,7 @@ def test_technical_adosc(params, data_type, obb): ) @pytest.mark.integration def test_technical_bbands(params, data_type, obb): + """Test bbands.""" params = {p: v for p, v in params.items() if v} params["data"] = get_data(data_type) @@ -274,6 +283,7 @@ def test_technical_bbands(params, data_type, obb): ) @pytest.mark.integration def test_technical_zlma(params, data_type, obb): + """Test zlma.""" params = {p: v for p, v in params.items() if v} params["data"] = get_data(data_type) @@ -300,6 +310,7 @@ def test_technical_zlma(params, data_type, obb): ) @pytest.mark.integration def test_technical_aroon(params, data_type, obb): + """Test aroon.""" params = {p: v for p, v in params.items() if v} params["data"] = get_data(data_type) @@ -336,6 +347,7 @@ def test_technical_aroon(params, data_type, obb): ) @pytest.mark.integration def test_technical_sma(params, data_type, obb): + """Test sma.""" params = {p: v for p, v in params.items() if v} params["data"] = get_data(data_type) @@ -374,6 +386,7 @@ def test_technical_sma(params, data_type, obb): ) @pytest.mark.integration def test_technical_demark(params, data_type, obb): + """Test demark.""" params = {p: v for p, v in params.items() if v} params["data"] = get_data(data_type) @@ -392,6 +405,7 @@ def test_technical_demark(params, data_type, obb): ) @pytest.mark.integration def test_technical_vwap(params, data_type, obb): + """Test vwap.""" params = {p: v for p, v in params.items() if v} params["data"] = get_data(data_type) @@ -430,6 +444,7 @@ def test_technical_vwap(params, data_type, obb): ) @pytest.mark.integration def test_technical_macd(params, data_type, obb): + """Test macd.""" params = {p: v for p, v in params.items() if v} params["data"] = get_data(data_type) @@ -466,6 +481,7 @@ def test_technical_macd(params, data_type, obb): ) @pytest.mark.integration def test_technical_hma(params, data_type, obb): + """Test hma.""" params = {p: v for p, v in params.items() if v} params["data"] = get_data(data_type) @@ -502,6 +518,7 @@ def test_technical_hma(params, data_type, obb): ) @pytest.mark.integration def test_technical_donchian(params, data_type, obb): + """Test donchian.""" params = {p: v for p, v in params.items() if v} params["data"] = get_data(data_type) @@ -542,6 +559,7 @@ def test_technical_donchian(params, data_type, obb): ) @pytest.mark.integration def test_technical_ichimoku(params, data_type, obb): + """Test ichimoku.""" params = {p: v for p, v in params.items() if v} params["data"] = get_data(data_type) @@ -568,6 +586,7 @@ def test_technical_ichimoku(params, data_type, obb): ) @pytest.mark.integration def test_technical_clenow(params, data_type, obb): + """Test clenow.""" params = {p: v for p, v in params.items() if v} params["data"] = get_data(data_type) @@ -604,6 +623,7 @@ def test_technical_clenow(params, data_type, obb): ) @pytest.mark.integration def test_technical_adx(params, data_type, obb): + """Test adx.""" params = {p: v for p, v in params.items() if v} params["data"] = get_data(data_type) @@ -622,6 +642,7 @@ def test_technical_adx(params, data_type, obb): ) @pytest.mark.integration def test_technical_ad(params, data_type, obb): + """Test ad.""" params = {p: v for p, v in params.items() if v} params["data"] = get_data(data_type) @@ -658,6 +679,7 @@ def test_technical_ad(params, data_type, obb): ) @pytest.mark.integration def test_technical_wma(params, data_type, obb): + """Test wma.""" params = {p: v for p, v in params.items() if v} params["data"] = get_data(data_type) @@ -684,6 +706,7 @@ def test_technical_wma(params, data_type, obb): ) @pytest.mark.integration def test_technical_cci(params, data_type, obb): + """Test cci.""" params = {p: v for p, v in params.items() if v} params["data"] = get_data(data_type) @@ -722,6 +745,7 @@ def test_technical_cci(params, data_type, obb): ) @pytest.mark.integration def test_technical_rsi(params, data_type, obb): + """Test rsi.""" params = {p: v for p, v in params.items() if v} params["data"] = get_data(data_type) @@ -758,6 +782,7 @@ def test_technical_rsi(params, data_type, obb): ) @pytest.mark.integration def test_technical_stoch(params, data_type, obb): + """Test stoch.""" params = {p: v for p, v in params.items() if v} params["data"] = get_data(data_type) @@ -796,6 +821,7 @@ def test_technical_stoch(params, data_type, obb): ) @pytest.mark.integration def test_technical_kc(params, data_type, obb): + """Test kc.""" params = {p: v for p, v in params.items() if v} params["data"] = get_data(data_type) @@ -814,6 +840,7 @@ def test_technical_kc(params, data_type, obb): ) @pytest.mark.integration def test_technical_cg(params, data_type, obb): + """Test cg.""" params = {p: v for p, v in params.items() if v} params["data"] = get_data(data_type) @@ -854,6 +881,7 @@ def test_technical_cg(params, data_type, obb): ) @pytest.mark.integration def test_technical_cones(params, data_type, obb): + """Test cones.""" params = {p: v for p, v in params.items() if v} params["data"] = get_data(data_type) @@ -890,6 +918,7 @@ def test_technical_cones(params, data_type, obb): ) @pytest.mark.integration def test_technical_ema(params, data_type, obb): + """Test ema.""" params = {p: v for p, v in params.items() if v} params["data"] = get_data(data_type) diff --git a/openbb_platform/extensions/technical/openbb_technical/helpers.py b/openbb_platform/extensions/technical/openbb_technical/helpers.py index 948a32fede3c..d4eca5d62019 100644 --- a/openbb_platform/extensions/technical/openbb_technical/helpers.py +++ b/openbb_platform/extensions/technical/openbb_technical/helpers.py @@ -82,7 +82,7 @@ def standard_deviation( is_crypto: bool = False, clean: bool = True, ) -> pd.DataFrame: - """Standard deviation. + """Calculate the Standard deviation. Measures how widely returns are dispersed from the average return. It is the most common (and biased) estimator of volatility. diff --git a/openbb_platform/extensions/technical/tests/test_technical_helpers.py b/openbb_platform/extensions/technical/tests/test_technical_helpers.py index 82ef6919fed9..9b4b7a9d1025 100644 --- a/openbb_platform/extensions/technical/tests/test_technical_helpers.py +++ b/openbb_platform/extensions/technical/tests/test_technical_helpers.py @@ -20,6 +20,7 @@ @pytest.fixture(scope="module") def mock_data(top_range: int = 100): + """Mock data for testing.""" _open = pd.Series(np.arange(1, top_range)) _high = pd.Series(np.arange(1, top_range)) _low = pd.Series(np.arange(1, top_range)) diff --git a/openbb_platform/extensions/tests/__init__.py b/openbb_platform/extensions/tests/__init__.py index e69de29bb2d1..d420712d8bbf 100644 --- a/openbb_platform/extensions/tests/__init__.py +++ b/openbb_platform/extensions/tests/__init__.py @@ -0,0 +1 @@ +"""Tests.""" diff --git a/openbb_platform/extensions/tests/conftest.py b/openbb_platform/extensions/tests/conftest.py index b8849169816a..c71c47faab52 100644 --- a/openbb_platform/extensions/tests/conftest.py +++ b/openbb_platform/extensions/tests/conftest.py @@ -14,7 +14,7 @@ def parametrize(argnames: str, argvalues: List, **kwargs): - """Custom parametrize decorator that filters test cases based on the environment.""" + """Apply a custom parametrize decorator that filters test cases based on the environment.""" routers, providers, obbject_ext = list_openbb_extensions() diff --git a/openbb_platform/extensions/tests/utils/__init__.py b/openbb_platform/extensions/tests/utils/__init__.py index e69de29bb2d1..479fdbbe1fba 100644 --- a/openbb_platform/extensions/tests/utils/__init__.py +++ b/openbb_platform/extensions/tests/utils/__init__.py @@ -0,0 +1 @@ +"""Testing utilities.""" diff --git a/openbb_platform/extensions/tests/utils/helpers.py b/openbb_platform/extensions/tests/utils/helpers.py index 8d35fced6711..2411a85484b4 100644 --- a/openbb_platform/extensions/tests/utils/helpers.py +++ b/openbb_platform/extensions/tests/utils/helpers.py @@ -242,7 +242,7 @@ def find_missing_router_function_models( def parse_example_string(example_string: str) -> Dict[str, Any]: - """Parses a string of examples into nested dictionaries. + """Parse a string of examples into nested dictionaries. This is capturing all instances of PythonEx and APIEx, including their "parameters", "code", and "description". """ diff --git a/openbb_platform/obbject_extensions/charting/integration/test_charting_api.py b/openbb_platform/obbject_extensions/charting/integration/test_charting_api.py index f89c1b318bf5..19a0e6c880fb 100644 --- a/openbb_platform/obbject_extensions/charting/integration/test_charting_api.py +++ b/openbb_platform/obbject_extensions/charting/integration/test_charting_api.py @@ -1,3 +1,5 @@ +"""Integration tests for charting API.""" + import base64 import json diff --git a/openbb_platform/obbject_extensions/charting/openbb_charting/__init__.py b/openbb_platform/obbject_extensions/charting/openbb_charting/__init__.py index ca03b8658b6c..5e14f028d6ff 100644 --- a/openbb_platform/obbject_extensions/charting/openbb_charting/__init__.py +++ b/openbb_platform/obbject_extensions/charting/openbb_charting/__init__.py @@ -58,16 +58,22 @@ def __init__(self, obbject): @classmethod def indicators(cls): - """Returns a list of the available indicators.""" + """Return a list of the available indicators.""" return ChartIndicators.get_available_indicators() @classmethod def functions(cls): - """Returns a list of the available functions.""" + """Return a list of the available functions.""" return get_charting_functions() - def _handle_backend(self) -> Backend: - """Handles backend initialization.""" + def _handle_backend(self): + """Create and start the backend.""" + # pylint: disable=import-outside-toplevel + from openbb_charting.core.backend import ( # pylint: disable=W0621, W0404 + create_backend, # noqa + get_backend, # noqa + ) + create_backend(self._charting_settings) backend = get_backend() backend.start(debug=self._charting_settings.debug_mode) @@ -149,8 +155,7 @@ def to_chart( render: bool = True, **kwargs, ): - """ - Creates a OpenBBFigure with user customizations (if any) and saves it to the OBBject. + """Create a OpenBBFigure with user customizations (if any) and saves it to the OBBject. This function is used so it can be called at the module level and used out of the box, which allows some more flexibility, ease of use and doesn't require the user to know @@ -198,7 +203,7 @@ def to_chart( > from openbb_charting import Charting > Charting.indicators() """ - data_as_df, has_data = self._prepare_data_as_df(data) + data_as_df, has_data = self._prepare_data_as_df(data) # type: ignore try: fig, content = to_chart( data_as_df, diff --git a/openbb_platform/obbject_extensions/charting/openbb_charting/core/__init__.py b/openbb_platform/obbject_extensions/charting/openbb_charting/core/__init__.py index e69de29bb2d1..91c890e79c2e 100644 --- a/openbb_platform/obbject_extensions/charting/openbb_charting/core/__init__.py +++ b/openbb_platform/obbject_extensions/charting/openbb_charting/core/__init__.py @@ -0,0 +1 @@ +"""OpenBB Charting core.""" diff --git a/openbb_platform/obbject_extensions/charting/openbb_charting/core/backend.py b/openbb_platform/obbject_extensions/charting/openbb_charting/core/backend.py index 2307f3993fcb..79d4c56e18b5 100644 --- a/openbb_platform/obbject_extensions/charting/openbb_charting/core/backend.py +++ b/openbb_platform/obbject_extensions/charting/openbb_charting/core/backend.py @@ -74,6 +74,7 @@ def __init__( max_retries: int = 30, proc_name: str = "OpenBB Terminal", ): + """Create a new instance of the backend.""" self.charting_settings = charting_settings has_version = hasattr(PyWry, "__version__") diff --git a/openbb_platform/obbject_extensions/charting/openbb_charting/core/config/__init__.py b/openbb_platform/obbject_extensions/charting/openbb_charting/core/config/__init__.py index e69de29bb2d1..9997eeed1a7c 100644 --- a/openbb_platform/obbject_extensions/charting/openbb_charting/core/config/__init__.py +++ b/openbb_platform/obbject_extensions/charting/openbb_charting/core/config/__init__.py @@ -0,0 +1 @@ +"""OpenBB Charting core configuration.""" diff --git a/openbb_platform/obbject_extensions/charting/openbb_charting/core/config/openbb_styles.py b/openbb_platform/obbject_extensions/charting/openbb_charting/core/config/openbb_styles.py index c3e60e665283..0c3532e016c6 100644 --- a/openbb_platform/obbject_extensions/charting/openbb_charting/core/config/openbb_styles.py +++ b/openbb_platform/obbject_extensions/charting/openbb_charting/core/config/openbb_styles.py @@ -1,3 +1,5 @@ +"""OpenBB Charting Styles.""" + from typing import Any, List, Optional import pandas as pd @@ -153,8 +155,9 @@ def de_increasing_color_list( increasing_color: str = PLT_STYLE_INCREASING, decreasing_color: str = PLT_STYLE_DECREASING, ) -> List[str]: - """Makes a colorlist for decrease/increase if value in df_column - contains "{contains_str}" default is "-" + """Make a colorlist for decrease/increase if value in df_column. + + Contains "{contains_str}" default is "-" Parameters ---------- diff --git a/openbb_platform/obbject_extensions/charting/openbb_charting/core/dummy_backend.py b/openbb_platform/obbject_extensions/charting/openbb_charting/core/dummy_backend.py index 2742185f7682..8b584bff6aa1 100644 --- a/openbb_platform/obbject_extensions/charting/openbb_charting/core/dummy_backend.py +++ b/openbb_platform/obbject_extensions/charting/openbb_charting/core/dummy_backend.py @@ -1,3 +1,5 @@ +"""Dummy backend for charting to avoid import errors.""" + import asyncio import warnings from queue import Queue @@ -52,7 +54,7 @@ def __new__(cls, *args, **kwargs): # pylint: disable=W0613 return cls.instance def __init__(self, daemon: bool = True, max_retries: int = 30): - """Dummy init to avoid import errors.""" + """Use cummy init to avoid import errors.""" self.daemon = daemon self.max_retries = max_retries try: @@ -66,14 +68,14 @@ def __init__(self, daemon: bool = True, max_retries: int = 30): dotenv.set_key(SETTINGS_ENV_FILE, "PLOT_ENABLE_PYWRY", "0") def close(self, reset: bool = False): # pylint: disable=W0613 - pass + """Close the backend.""" def start(self, debug: bool = False): # pylint: disable=W0613 - pass + """Start the backend.""" def send_outgoing(self, outgoing: dict): - pass + """Send outgoing data to the backend.""" async def check_backend(self): - """Dummy check backend method to avoid errors and revert to browser.""" + """Check backend method to avoid errors and revert to browser.""" raise Exception diff --git a/openbb_platform/obbject_extensions/charting/openbb_charting/core/openbb_figure.py b/openbb_platform/obbject_extensions/charting/openbb_charting/core/openbb_figure.py index 32e5876817f3..79fcae8d2e21 100644 --- a/openbb_platform/obbject_extensions/charting/openbb_charting/core/openbb_figure.py +++ b/openbb_platform/obbject_extensions/charting/openbb_charting/core/openbb_figure.py @@ -84,6 +84,7 @@ class OpenBBFigure(go.Figure): plotlyjs_path: Path = PLOTLYJS_PATH def __init__(self, fig: Optional[go.Figure] = None, **kwargs) -> None: + """Initialize the OpenBBFigure.""" super().__init__() if fig: self.__dict__ = fig.__dict__ @@ -238,8 +239,7 @@ def add_trend( secondary_y: bool = False, **kwargs, ): - """ - Add a trend line to the figure. + """Add a trend line to the figure. Parameters ---------- @@ -291,8 +291,7 @@ def add_histplot( # pylint: disable=too-many-arguments row: int = 1, col: int = 1, ) -> None: - """ - Add a histogram with a curve and rug plot if desired. + """Add a histogram with a curve and rug plot if desired. Parameters ---------- @@ -560,8 +559,7 @@ def add_hline_legend( legendrank: Optional[int] = None, **kwargs, ) -> None: - """ - Add a horizontal line with a legend label. + """Add a horizontal line with a legend label. Parameters ---------- @@ -598,8 +596,7 @@ def add_vline_legend( legendrank: Optional[int] = None, **kwargs, ) -> None: - """ - Add a vertical line with a legend label. + """Add a vertical line with a legend label. Parameters ---------- @@ -667,8 +664,7 @@ def horizontal_legend( # noqa: PLR0913 def chart_volume_scaling( df_volume: pd.DataFrame, volume_ticks_x: int = 7 ) -> Dict[str, list]: - """ - Takes df_volume and returns volume_ticks, tickvals for chart volume scaling. + """Take df_volume and returns volume_ticks, tickvals for chart volume scaling. Parameters ---------- @@ -716,8 +712,7 @@ def add_inchart_volume( # noqa: PLR0913 col: Optional[int] = 1, volume_ticks_x: int = 7, ) -> None: - """ - Add in-chart volume to a subplot. + """Add in-chart volume to a subplot. Parameters ---------- @@ -846,8 +841,7 @@ def show( # noqa: PLR0915 export_image: Optional[Union[Path, str]] = "", **kwargs, ) -> "OpenBBFigure": - """ - Show the figure. + """Show the figure. Parameters ---------- @@ -1234,8 +1228,7 @@ def to_html(self, *args, **kwargs) -> str: def to_plotly_json( self, ndarray: bool = False, np_nan: bool = False ) -> Dict[str, Any]: - """ - Convert figure to a JSON representation as a Python dict. + """Convert figure to a JSON representation as a Python dict. Parameters ---------- diff --git a/openbb_platform/obbject_extensions/charting/openbb_charting/core/plotly_ta/__init__.py b/openbb_platform/obbject_extensions/charting/openbb_charting/core/plotly_ta/__init__.py index e69de29bb2d1..4170e99482b0 100644 --- a/openbb_platform/obbject_extensions/charting/openbb_charting/core/plotly_ta/__init__.py +++ b/openbb_platform/obbject_extensions/charting/openbb_charting/core/plotly_ta/__init__.py @@ -0,0 +1 @@ +"""Plotly TA core package.""" diff --git a/openbb_platform/obbject_extensions/charting/openbb_charting/core/plotly_ta/base.py b/openbb_platform/obbject_extensions/charting/openbb_charting/core/plotly_ta/base.py index 1d0ec43eb51b..a5e7e0728e8a 100644 --- a/openbb_platform/obbject_extensions/charting/openbb_charting/core/plotly_ta/base.py +++ b/openbb_platform/obbject_extensions/charting/openbb_charting/core/plotly_ta/base.py @@ -23,6 +23,7 @@ def __init__( name: str = "", **attrs: Any, ) -> None: + """Initialize the indicator.""" self.func = func self.name = name self.attrs = attrs @@ -85,6 +86,7 @@ def __iter__(cls: Type["PluginMeta"]) -> Iterator[Indicator]: # type: ignore # pylint: disable=unused-argument def __init__(cls, *args: Any, **kwargs: Any) -> None: + """Initialize the class.""" super().__init__(*args, **kwargs) @@ -182,7 +184,7 @@ def __iter__(self) -> Iterator[Indicator]: return iter(self.__indicators__) def get_float_precision(self) -> str: - """Returns f-string precision format.""" + """Return f-string precision format.""" price = self.df_stock[self.close_column].tail(1).values[0] float_precision = ( ",.2f" if price > 1.10 else "" if len(str(price)) < 8 else ".6f" @@ -194,7 +196,7 @@ def indicator( name: str = "", **attrs: Any, ) -> Callable: - """Decorator for adding indicators to a plugin class.""" + """Use this decorator for adding indicators to a plugin class.""" attrs["name"] = name def decorator(func: Callable) -> Indicator: diff --git a/openbb_platform/obbject_extensions/charting/openbb_charting/core/plotly_ta/plugins/overlap_plugin.py b/openbb_platform/obbject_extensions/charting/openbb_charting/core/plotly_ta/plugins/overlap_plugin.py index b2a294162d49..be743e5ce003 100644 --- a/openbb_platform/obbject_extensions/charting/openbb_charting/core/plotly_ta/plugins/overlap_plugin.py +++ b/openbb_platform/obbject_extensions/charting/openbb_charting/core/plotly_ta/plugins/overlap_plugin.py @@ -1,3 +1,5 @@ +"""Overlap technical indicators plugin for Plotly TA.""" + import warnings import pandas as pd @@ -12,14 +14,14 @@ class Overlap(PltTA): - """Overlap technical indicators""" + """Overlap technical indicators.""" __inchart__ = ["vwap"] __ma_mode__ = ["sma", "ema", "wma", "hma", "zlma", "rma"] @indicator() def plot_ma(self, fig: OpenBBFigure, df_ta: pd.DataFrame, inchart_index: int): - """Adds moving average to plotly figure""" + """Add moving average to plotly figure.""" check_ma = [ma for ma in self.ma_mode if ma in self.indicators.get_active_ids()] if check_ma: for ma in check_ma: @@ -65,7 +67,7 @@ def plot_ma(self, fig: OpenBBFigure, df_ta: pd.DataFrame, inchart_index: int): @indicator() def plot_vwap(self, fig: OpenBBFigure, df_ta: pd.DataFrame, inchart_index: int): - """Adds vwap to plotly figure""" + """Add vwap to plotly figure.""" fig.add_scatter( name=columns_regex(df_ta, "VWAP_")[0], mode="lines", diff --git a/openbb_platform/obbject_extensions/charting/openbb_charting/core/plotly_ta/plugins/trend_indicators_plugin.py b/openbb_platform/obbject_extensions/charting/openbb_charting/core/plotly_ta/plugins/trend_indicators_plugin.py index bc30a499a243..bcb5637f551d 100644 --- a/openbb_platform/obbject_extensions/charting/openbb_charting/core/plotly_ta/plugins/trend_indicators_plugin.py +++ b/openbb_platform/obbject_extensions/charting/openbb_charting/core/plotly_ta/plugins/trend_indicators_plugin.py @@ -1,3 +1,5 @@ +"""Trend technical indicators.""" + import pandas as pd from openbb_charting.core.openbb_figure import OpenBBFigure from openbb_charting.core.plotly_ta.base import ( @@ -94,7 +96,7 @@ def plot_adx(self, fig: OpenBBFigure, df_ta: pd.DataFrame, subplot_row: int): @indicator() def plot_aroon(self, fig: OpenBBFigure, df_ta: pd.DataFrame, subplot_row: int): - """Adds aroon to plotly figure""" + """Add aroon to plotly figure.""" aroon_up_col = columns_regex(df_ta, "AROONU")[0] aroon_down_col = columns_regex(df_ta, "AROOND")[0] aroon_osc_col = columns_regex(df_ta, "AROONOSC")[0] diff --git a/openbb_platform/obbject_extensions/charting/openbb_charting/core/plotly_ta/plugins/volatility_plugin.py b/openbb_platform/obbject_extensions/charting/openbb_charting/core/plotly_ta/plugins/volatility_plugin.py index 3131df3edd25..c71186747c17 100644 --- a/openbb_platform/obbject_extensions/charting/openbb_charting/core/plotly_ta/plugins/volatility_plugin.py +++ b/openbb_platform/obbject_extensions/charting/openbb_charting/core/plotly_ta/plugins/volatility_plugin.py @@ -1,3 +1,5 @@ +"""Volatility technical indicators plugin for Plotly TA.""" + import pandas as pd from openbb_charting.core.openbb_figure import OpenBBFigure from openbb_charting.core.plotly_ta.base import ( @@ -10,15 +12,14 @@ class Volatility(PltTA): - """Volatility technical indicators""" + """Volatility technical indicators.""" __inchart__ = ["bbands", "donchian", "kc"] __subplots__ = ["atr"] @indicator() def plot_atr(self, fig: OpenBBFigure, df_ta: pd.DataFrame, subplot_row: int): - """Adds average true range to plotly figure""" - + """Add average true range to plotly figure.""" fig.add_scatter( name=f"{columns_regex(df_ta, 'ATR')[0]}", x=df_ta.index, @@ -47,8 +48,7 @@ def plot_atr(self, fig: OpenBBFigure, df_ta: pd.DataFrame, subplot_row: int): @indicator() def plot_bbands(self, fig: OpenBBFigure, df_ta: pd.DataFrame, inchart_index: int): - """Adds bollinger bands to plotly figure""" - + """Add bollinger bands to plotly figure.""" bbands_opacity = 0.8 if fig.theme.plt_style == "light" else 1 fig.add_scatter( @@ -107,8 +107,7 @@ def plot_bbands(self, fig: OpenBBFigure, df_ta: pd.DataFrame, inchart_index: int @indicator() def plot_donchian(self, fig: OpenBBFigure, df_ta: pd.DataFrame, inchart_index: int): - """Adds donchian channels to plotly figure""" - + """Add donchian channels to plotly figure.""" if fig.theme.plt_style == "light": fillcolor = "rgba(239, 103, 137, 0.05)" donchian_opacity = 0.4 @@ -166,7 +165,7 @@ def plot_donchian(self, fig: OpenBBFigure, df_ta: pd.DataFrame, inchart_index: i @indicator() def plot_kc(self, fig: OpenBBFigure, df_ta: pd.DataFrame, inchart_index: int): - """Adds Keltner channels to plotly figure""" + """Add Keltner channels to plotly figure.""" mamode = (self.params["kc"].get_argument_values("mamode") or "ema").lower() # type: ignore if fig.theme.plt_style == "light": diff --git a/openbb_platform/obbject_extensions/charting/openbb_charting/core/plotly_ta/plugins/volume_plugin.py b/openbb_platform/obbject_extensions/charting/openbb_charting/core/plotly_ta/plugins/volume_plugin.py index 671be2788a17..b71a419a5c75 100644 --- a/openbb_platform/obbject_extensions/charting/openbb_charting/core/plotly_ta/plugins/volume_plugin.py +++ b/openbb_platform/obbject_extensions/charting/openbb_charting/core/plotly_ta/plugins/volume_plugin.py @@ -1,3 +1,5 @@ +"""Volume technical indicators.""" + import pandas as pd from openbb_charting.core.openbb_figure import OpenBBFigure from openbb_charting.core.plotly_ta.base import ( @@ -20,7 +22,7 @@ class Volume(PltTA): @indicator() def plot_ad(self, fig: OpenBBFigure, df_ta: pd.DataFrame, subplot_row: int): - """Adds ad to plotly figure""" + """Add ad to plotly figure.""" ad_col = columns_regex(df_ta, "AD")[0] fig.add_scatter( name="AD", @@ -62,7 +64,7 @@ def plot_ad(self, fig: OpenBBFigure, df_ta: pd.DataFrame, subplot_row: int): @indicator() def plot_adosc(self, fig: OpenBBFigure, df_ta: pd.DataFrame, subplot_row: int): - """Adds adosc to plotly figure""" + """Add adosc to plotly figure.""" ad_col = columns_regex(df_ta, "ADOSC")[0] fig.add_scatter( name="ADOSC", @@ -92,7 +94,7 @@ def plot_adosc(self, fig: OpenBBFigure, df_ta: pd.DataFrame, subplot_row: int): @indicator() def plot_obv(self, fig: OpenBBFigure, df_ta: pd.DataFrame, subplot_row: int): - """Adds obv to plotly figure""" + """Add obv to plotly figure.""" obv_col = columns_regex(df_ta, "OBV")[0] fig.add_scatter( name="OBV", diff --git a/openbb_platform/obbject_extensions/charting/openbb_charting/core/plotly_ta/ta_class.py b/openbb_platform/obbject_extensions/charting/openbb_charting/core/plotly_ta/ta_class.py index 46b2af6cd6b5..970602c2172c 100644 --- a/openbb_platform/obbject_extensions/charting/openbb_charting/core/plotly_ta/ta_class.py +++ b/openbb_platform/obbject_extensions/charting/openbb_charting/core/plotly_ta/ta_class.py @@ -97,7 +97,10 @@ class PlotlyTA(PltTA): theme: Optional[ChartStyle] = None def __new__(cls, *args, **kwargs): - """Method is overridden to create a singleton instance of the class.""" + """Create a new instance of the class. + + Method is overridden to create a singleton instance of the class. + """ cls.charting_settings = kwargs.pop("charting_settings", cls.charting_settings) cls.theme = cls.setup_theme( chart_style=getattr(cls.charting_settings, "chart_style", ""), @@ -121,7 +124,10 @@ def __new__(cls, *args, **kwargs): return PLOTLY_TA def __init__(self, *args, **kwargs): - """Method is overridden to do nothing, except to clear the internal data structures.""" + """Initialize the class. + + Method is overridden to do nothing, except to clear the internal data structures. + """ if not args and not kwargs: self._clear_data() else: @@ -130,7 +136,7 @@ def __init__(self, *args, **kwargs): @staticmethod def setup_theme(chart_style, user_styles_directory) -> ChartStyle: - """Setup theme for charting.""" + """Set up theme for charting.""" return ChartStyle(chart_style, user_styles_directory) @property @@ -175,7 +181,10 @@ def __plot__( fig: Optional[OpenBBFigure] = None, volume_ticks_x: int = 7, ) -> OpenBBFigure: - """Method should not be called directly. Use the PlotlyTA.plot() static method instead.""" + """Do not call this directly. + + Use the PlotlyTA.plot() static method instead. + """ if isinstance(df_stock, pd.Series): df_stock = df_stock.to_frame() diff --git a/openbb_platform/obbject_extensions/charting/openbb_charting/core/plotly_ta/ta_helpers.py b/openbb_platform/obbject_extensions/charting/openbb_charting/core/plotly_ta/ta_helpers.py index 0c090a1cba09..17607ca054b3 100644 --- a/openbb_platform/obbject_extensions/charting/openbb_charting/core/plotly_ta/ta_helpers.py +++ b/openbb_platform/obbject_extensions/charting/openbb_charting/core/plotly_ta/ta_helpers.py @@ -1,3 +1,5 @@ +"""Helper functions for technical analysis indicators.""" + import re from typing import Optional @@ -7,7 +9,7 @@ def check_columns( data: pd.DataFrame, high: bool = True, low: bool = True, close: bool = True ) -> Optional[str]: - """Returns the close columns, or None if the dataframe does not have required columns + """Return the close columns, or None if the dataframe does not have required columns. Parameters ---------- @@ -24,7 +26,6 @@ def check_columns( ------- Optional[str] The name of the close column, none if df is invalid - """ close_regex = r"(Adj\sClose|adj_close|Close)" # pylint: disable=too-many-boolean-expressions diff --git a/openbb_platform/obbject_extensions/charting/openbb_charting/core/to_chart.py b/openbb_platform/obbject_extensions/charting/openbb_charting/core/to_chart.py index 3c84018c3e4c..affcde5929b6 100644 --- a/openbb_platform/obbject_extensions/charting/openbb_charting/core/to_chart.py +++ b/openbb_platform/obbject_extensions/charting/openbb_charting/core/to_chart.py @@ -18,8 +18,7 @@ def to_chart( prepost: bool = False, volume_ticks_x: int = 7, ) -> Tuple[OpenBBFigure, Dict[str, Any]]: - """ - Returns the plotly json representation of the chart. + """Return the plotly json representation of the chart. This function is used so it can be called at the module level and used out of the box, which allows some more flexibility, ease of use and doesn't require the user to know diff --git a/openbb_platform/obbject_extensions/charting/tests/__init__.py b/openbb_platform/obbject_extensions/charting/tests/__init__.py index e69de29bb2d1..6108752fdf4a 100644 --- a/openbb_platform/obbject_extensions/charting/tests/__init__.py +++ b/openbb_platform/obbject_extensions/charting/tests/__init__.py @@ -0,0 +1 @@ +"""OBBject Extensions Charting Tests Module.""" diff --git a/openbb_platform/obbject_extensions/charting/tests/test_charting.py b/openbb_platform/obbject_extensions/charting/tests/test_charting.py index 4e29544dd879..3c3adf5a68c0 100644 --- a/openbb_platform/obbject_extensions/charting/tests/test_charting.py +++ b/openbb_platform/obbject_extensions/charting/tests/test_charting.py @@ -1,3 +1,5 @@ +"""Test Charting class.""" + from unittest.mock import MagicMock, patch import pytest @@ -6,9 +8,14 @@ from openbb_core.app.model.user_settings import UserSettings from pydantic import BaseModel +# pylint: disable=redefined-outer-name, protected-access + class MockDataframe: + """Mock Dataframe.""" + def __init__(self): + """Mock Dataframe.""" self.columns = ["column1", "column2"] @@ -17,12 +24,19 @@ def __init__(self): @pytest.fixture() def obbject(): + """Mock OOBject.""" + class MockStdParams(BaseModel): + """Mock Standard Parameters.""" + param1: str param2: str class MockOOBject: + """Mock OOBject.""" + def __init__(self): + """Mock OOBject.""" self._user_settings = UserSettings() self._system_settings = SystemSettings() self._route = "mock/route" @@ -36,18 +50,21 @@ def __init__(self): self.warnings = "mock_warnings" def to_dataframe(self): + """Mock to_dataframe.""" return mock_dataframe return MockOOBject() def test_charting_settings(obbject): + """Test charting_settings.""" cm = Charting(obbject) assert isinstance(cm, Charting) @patch("openbb_charting.ChartIndicators.get_available_indicators") def test_indicators(mock_get_available_indicators, obbject): + """Test indicators method.""" # Arrange mock_get_available_indicators.return_value = [ "indicator1", @@ -66,6 +83,7 @@ def test_indicators(mock_get_available_indicators, obbject): @patch("openbb_charting.get_charting_functions") def test_functions(mock_get_charting_functions): + """Test functions method.""" # Arrange mock_get_charting_functions.return_value = ["function1", "function2", "function3"] @@ -80,6 +98,7 @@ def test_functions(mock_get_charting_functions): @patch("openbb_charting.core.backend.get_backend") @patch("openbb_charting.core.backend.create_backend") def test_handle_backend(mock_create_backend, mock_get_backend, obbject): + """Test _handle_backend method.""" # Act -> _handle backend is called in the constructor obj = Charting(obbject) @@ -90,6 +109,7 @@ def test_handle_backend(mock_create_backend, mock_get_backend, obbject): @patch("openbb_charting.charting_router") def test_get_chart_function(mock_charting_router): + """Test _get_chart_function method.""" # Arrange mock_function = MagicMock() mock_charting_router.some_function = mock_function @@ -104,6 +124,7 @@ def test_get_chart_function(mock_charting_router): @patch("openbb_charting.Charting._get_chart_function") def test_show(mock_get_chart_function, obbject): + """Test show method.""" # Arrange mock_function = MagicMock() mock_get_chart_function.return_value = mock_function @@ -122,6 +143,7 @@ def test_show(mock_get_chart_function, obbject): @patch("openbb_charting.to_chart") def test_to_chart(mock_to_chart, obbject): + """Test to_chart method.""" # Arrange mock_fig = MagicMock() mock_to_chart.return_value = (mock_fig, {"content": "mock_content"}) diff --git a/openbb_platform/providers/__init__.py b/openbb_platform/providers/__init__.py index e69de29bb2d1..e80dd09da706 100644 --- a/openbb_platform/providers/__init__.py +++ b/openbb_platform/providers/__init__.py @@ -0,0 +1 @@ +"""OpenBB Platform Providers.""" diff --git a/openbb_platform/providers/alpha_vantage/__init__.py b/openbb_platform/providers/alpha_vantage/__init__.py index e69de29bb2d1..cbf25829548a 100644 --- a/openbb_platform/providers/alpha_vantage/__init__.py +++ b/openbb_platform/providers/alpha_vantage/__init__.py @@ -0,0 +1 @@ +"""Alpha Vantage Provider.""" diff --git a/openbb_platform/providers/alpha_vantage/openbb_alpha_vantage/models/__init__.py b/openbb_platform/providers/alpha_vantage/openbb_alpha_vantage/models/__init__.py index e69de29bb2d1..77b12520b31e 100644 --- a/openbb_platform/providers/alpha_vantage/openbb_alpha_vantage/models/__init__.py +++ b/openbb_platform/providers/alpha_vantage/openbb_alpha_vantage/models/__init__.py @@ -0,0 +1 @@ +"""Alpha Vantage models.""" diff --git a/openbb_platform/providers/alpha_vantage/openbb_alpha_vantage/models/equity_historical.py b/openbb_platform/providers/alpha_vantage/openbb_alpha_vantage/models/equity_historical.py index 0ea55731e127..91e20c2d7268 100644 --- a/openbb_platform/providers/alpha_vantage/openbb_alpha_vantage/models/equity_historical.py +++ b/openbb_platform/providers/alpha_vantage/openbb_alpha_vantage/models/equity_historical.py @@ -157,7 +157,7 @@ async def aextract_data( results = [] async def callback(response, _): - """Callback function to process the response.""" + """Use callback function to process the response.""" try: result = await response.json() if "Information" in result: @@ -168,7 +168,7 @@ async def callback(response, _): return await response.read() async def intraday_callback(response, _): - """Callback function to process the intraday response.""" + """Use callback function to process the intraday response.""" symbol = response.url.query.get("symbol", None) data = await response.read() if data: @@ -189,7 +189,6 @@ async def intraday_callback(response, _): async def get_one(symbol, intraday: bool = False): """Get data for one symbol.""" - if intraday is True: adjusted = query.adjustment != "unadjusted" if query.adjustment == "splits_only": @@ -298,7 +297,6 @@ def transform_data( query: AVEquityHistoricalQueryParams, data: List[Dict], **kwargs: Any ) -> List[AVEquityHistoricalData]: """Transform the data to the standard format.""" - if data == []: return [] if "{" in data[0]: diff --git a/openbb_platform/providers/alpha_vantage/openbb_alpha_vantage/utils/__init__.py b/openbb_platform/providers/alpha_vantage/openbb_alpha_vantage/utils/__init__.py index e69de29bb2d1..37ed69b5ee1f 100644 --- a/openbb_platform/providers/alpha_vantage/openbb_alpha_vantage/utils/__init__.py +++ b/openbb_platform/providers/alpha_vantage/openbb_alpha_vantage/utils/__init__.py @@ -0,0 +1 @@ +"""Alpha Vantage utilities.""" diff --git a/openbb_platform/providers/alpha_vantage/openbb_alpha_vantage/utils/helpers.py b/openbb_platform/providers/alpha_vantage/openbb_alpha_vantage/utils/helpers.py index 88c6bffda35b..f16bd40fa0a2 100644 --- a/openbb_platform/providers/alpha_vantage/openbb_alpha_vantage/utils/helpers.py +++ b/openbb_platform/providers/alpha_vantage/openbb_alpha_vantage/utils/helpers.py @@ -48,10 +48,10 @@ def filter_by_dates( def calculate_adjusted_prices(df: pd.DataFrame, column: str, dividends: bool = False): - """Calculates the split-adjusted prices, or split and dividend adjusted prices. + """Calculate the split-adjusted prices, or split and dividend adjusted prices. Parameters - ------------ + ---------- df: pd.DataFrame DataFrame with unadjusted OHLCV values + split_factor + dividend column: str @@ -60,11 +60,10 @@ def calculate_adjusted_prices(df: pd.DataFrame, column: str, dividends: bool = F Whether to adjust for both splits and dividends. Default is split-adjusted only. Returns - -------- + ------- pd.DataFrame DataFrame with adjusted prices. """ - df = df.copy() adj_column = "adj_" + column diff --git a/openbb_platform/providers/alpha_vantage/tests/__init__.py b/openbb_platform/providers/alpha_vantage/tests/__init__.py index e69de29bb2d1..d12ab5730ed8 100644 --- a/openbb_platform/providers/alpha_vantage/tests/__init__.py +++ b/openbb_platform/providers/alpha_vantage/tests/__init__.py @@ -0,0 +1 @@ +"""Alpha Vantage tests.""" diff --git a/openbb_platform/providers/alpha_vantage/tests/test_alpha_vantage_fetchers.py b/openbb_platform/providers/alpha_vantage/tests/test_alpha_vantage_fetchers.py index 8cc9fb7ed66c..d14c8c47c554 100644 --- a/openbb_platform/providers/alpha_vantage/tests/test_alpha_vantage_fetchers.py +++ b/openbb_platform/providers/alpha_vantage/tests/test_alpha_vantage_fetchers.py @@ -1,3 +1,5 @@ +"""Test the Alpha Vantage fetchers.""" + from datetime import date import pytest @@ -12,6 +14,7 @@ @pytest.fixture(scope="module") def vcr_config(): + """VCR configuration.""" return { "filter_headers": [("User-Agent", None)], "filter_query_parameters": [ @@ -22,6 +25,7 @@ def vcr_config(): @pytest.mark.record_http def test_av_equity_historical_fetcher(credentials=test_credentials): + """Test the Alpha Vantage Equity Historical fetcher.""" params = { "symbol": "AAPL", "start_date": date(2023, 1, 1), @@ -36,6 +40,7 @@ def test_av_equity_historical_fetcher(credentials=test_credentials): @pytest.mark.record_http def test_av_historical_eps_fetcher(credentials=test_credentials): + """Test the Alpha Vantage Historical Earnings fetcher.""" params = {"symbol": "AAPL,MSFT", "period": "quarter", "limit": 4} fetcher = AVHistoricalEpsFetcher() diff --git a/openbb_platform/providers/benzinga/__init__.py b/openbb_platform/providers/benzinga/__init__.py index e69de29bb2d1..ae824bf16b42 100644 --- a/openbb_platform/providers/benzinga/__init__.py +++ b/openbb_platform/providers/benzinga/__init__.py @@ -0,0 +1 @@ +"""Benzinga Provider.""" diff --git a/openbb_platform/providers/benzinga/openbb_benzinga/models/__init__.py b/openbb_platform/providers/benzinga/openbb_benzinga/models/__init__.py index e69de29bb2d1..8b008a32eb48 100644 --- a/openbb_platform/providers/benzinga/openbb_benzinga/models/__init__.py +++ b/openbb_platform/providers/benzinga/openbb_benzinga/models/__init__.py @@ -0,0 +1 @@ +"""Benzinga Provider Models.""" diff --git a/openbb_platform/providers/benzinga/openbb_benzinga/models/analyst_search.py b/openbb_platform/providers/benzinga/openbb_benzinga/models/analyst_search.py index 90554c4decbe..27781df35eb2 100644 --- a/openbb_platform/providers/benzinga/openbb_benzinga/models/analyst_search.py +++ b/openbb_platform/providers/benzinga/openbb_benzinga/models/analyst_search.py @@ -293,6 +293,7 @@ class BenzingaAnalystSearchData(AnalystSearchData): @field_validator("last_updated", mode="before", check_fields=False) @classmethod def validate_date(cls, v): + """Validate date.""" if v: dt = datetime.fromtimestamp(v, UTC) return dt.date() if dt.time() == dt.min.time() else dt @@ -340,7 +341,6 @@ async def aextract_data( **kwargs: Any, ) -> List[Dict]: """Extract the raw data.""" - token = credentials.get("benzinga_api_key") if credentials else "" querystring = get_querystring(query.model_dump(), []) url = f"https://api.benzinga.com/api/v2.1/calendar/ratings/analysts?{querystring}&token={token}" diff --git a/openbb_platform/providers/benzinga/openbb_benzinga/utils/__init__.py b/openbb_platform/providers/benzinga/openbb_benzinga/utils/__init__.py index e69de29bb2d1..0209502ea388 100644 --- a/openbb_platform/providers/benzinga/openbb_benzinga/utils/__init__.py +++ b/openbb_platform/providers/benzinga/openbb_benzinga/utils/__init__.py @@ -0,0 +1 @@ +"""Benzinga Provider Utils.""" diff --git a/openbb_platform/providers/benzinga/tests/__init__.py b/openbb_platform/providers/benzinga/tests/__init__.py index e69de29bb2d1..e423bb412456 100644 --- a/openbb_platform/providers/benzinga/tests/__init__.py +++ b/openbb_platform/providers/benzinga/tests/__init__.py @@ -0,0 +1 @@ +"""Test Benzinga fetchers.""" diff --git a/openbb_platform/providers/benzinga/tests/test_benzinga_fetchers.py b/openbb_platform/providers/benzinga/tests/test_benzinga_fetchers.py index e33454139ca1..2902f09847cc 100644 --- a/openbb_platform/providers/benzinga/tests/test_benzinga_fetchers.py +++ b/openbb_platform/providers/benzinga/tests/test_benzinga_fetchers.py @@ -1,3 +1,5 @@ +"""Test the Benzinga fetchers.""" + import pytest from openbb_benzinga.models.analyst_search import BenzingaAnalystSearchFetcher from openbb_benzinga.models.company_news import BenzingaCompanyNewsFetcher @@ -12,6 +14,7 @@ @pytest.fixture(scope="module") def vcr_config(): + """VCR configuration.""" return { "filter_headers": [("User-Agent", None)], "filter_query_parameters": [ @@ -22,6 +25,7 @@ def vcr_config(): @pytest.mark.record_http def test_benzinga_world_news_fetcher(credentials=test_credentials): + """Test the world news fetcher.""" params = {"limit": 20} fetcher = BenzingaWorldNewsFetcher() @@ -31,6 +35,7 @@ def test_benzinga_world_news_fetcher(credentials=test_credentials): @pytest.mark.record_http def test_benzinga_company_news_fetcher(credentials=test_credentials): + """Test the company news fetcher.""" params = {"symbol": "AAPL,MSFT", "limit": 20} fetcher = BenzingaCompanyNewsFetcher() @@ -40,6 +45,7 @@ def test_benzinga_company_news_fetcher(credentials=test_credentials): @pytest.mark.record_http def test_benzinga_price_target_fetcher(credentials=test_credentials): + """Test the price target fetcher.""" params = {"symbol": "AAPL"} fetcher = BenzingaPriceTargetFetcher() @@ -49,6 +55,7 @@ def test_benzinga_price_target_fetcher(credentials=test_credentials): @pytest.mark.record_http def test_benzinga_analyst_search_fetcher(credentials=test_credentials): + """Test the analyst search fetcher.""" params = {"firm_name": "Barclays"} fetcher = BenzingaAnalystSearchFetcher() diff --git a/openbb_platform/providers/biztoc/__init__.py b/openbb_platform/providers/biztoc/__init__.py index e69de29bb2d1..028761078270 100644 --- a/openbb_platform/providers/biztoc/__init__.py +++ b/openbb_platform/providers/biztoc/__init__.py @@ -0,0 +1 @@ +"""Biztoc provider.""" diff --git a/openbb_platform/providers/biztoc/openbb_biztoc/models/__init__.py b/openbb_platform/providers/biztoc/openbb_biztoc/models/__init__.py index e69de29bb2d1..e716998b06ac 100644 --- a/openbb_platform/providers/biztoc/openbb_biztoc/models/__init__.py +++ b/openbb_platform/providers/biztoc/openbb_biztoc/models/__init__.py @@ -0,0 +1 @@ +"""Biztoc Provider models.""" diff --git a/openbb_platform/providers/biztoc/openbb_biztoc/utils/__init__.py b/openbb_platform/providers/biztoc/openbb_biztoc/utils/__init__.py index e69de29bb2d1..e46fb65077d6 100644 --- a/openbb_platform/providers/biztoc/openbb_biztoc/utils/__init__.py +++ b/openbb_platform/providers/biztoc/openbb_biztoc/utils/__init__.py @@ -0,0 +1 @@ +"""Biztoc utils.""" diff --git a/openbb_platform/providers/biztoc/openbb_biztoc/utils/helpers.py b/openbb_platform/providers/biztoc/openbb_biztoc/utils/helpers.py index d8d7ea8003fb..061271c8a5dd 100644 --- a/openbb_platform/providers/biztoc/openbb_biztoc/utils/helpers.py +++ b/openbb_platform/providers/biztoc/openbb_biztoc/utils/helpers.py @@ -1,4 +1,4 @@ -"""Biztoc Helpers""" +"""Biztoc Helpers.""" from datetime import timedelta from typing import Dict, List, Literal @@ -7,6 +7,8 @@ import requests_cache from openbb_core.app.utils import get_user_cache_directory +# pylint: disable=C0325 + cache_dir = get_user_cache_directory() biztoc_session_tags = requests_cache.CachedSession( @@ -18,8 +20,7 @@ def get_sources(api_key: str) -> List[Dict]: - """Valid sources for Biztoc queries.""" - + """Get valid sources for Biztoc queries.""" headers = { "X-RapidAPI-Key": f"{api_key}", "X-RapidAPI-Host": "biztoc.p.rapidapi.com", @@ -34,8 +35,7 @@ def get_sources(api_key: str) -> List[Dict]: def get_pages(api_key: str) -> List[str]: - """Valid pages for Biztoc queries.""" - + """Get valid pages for Biztoc queries.""" headers = { "X-RapidAPI-Key": f"{api_key}", "X-RapidAPI-Host": "biztoc.p.rapidapi.com", @@ -50,8 +50,7 @@ def get_pages(api_key: str) -> List[str]: def get_tags_by_page(page_id: str, api_key: str) -> List[str]: - """Valid tags required for Biztoc queries.""" - + """Get valid tags required for Biztoc queries.""" headers = { "X-RapidAPI-Key": f"{api_key}", "X-RapidAPI-Host": "biztoc.p.rapidapi.com", @@ -66,12 +65,13 @@ def get_tags_by_page(page_id: str, api_key: str) -> List[str]: def get_all_tags(api_key) -> Dict[str, List[str]]: + """Get all tags for all pages.""" tags: Dict[str, List[str]] = {} pages = get_pages(api_key) for page in pages: page_tags = get_tags_by_page(page, api_key) - tags.update({page: [x["tag"] for x in page_tags]}) + tags.update({page: [x["tag"] for x in page_tags]}) # type: ignore return tags @@ -85,8 +85,7 @@ def get_news( tag: str = "", term: str = "", ) -> List[Dict]: - """Calls the BizToc API and returns the data.""" - + """Call the BizToc API and returns the data.""" results = [] term = term.replace(" ", "%20") if term else "" _tags = get_all_tags(api_key) diff --git a/openbb_platform/providers/biztoc/tests/__init__.py b/openbb_platform/providers/biztoc/tests/__init__.py index e69de29bb2d1..f9f64a7d750b 100644 --- a/openbb_platform/providers/biztoc/tests/__init__.py +++ b/openbb_platform/providers/biztoc/tests/__init__.py @@ -0,0 +1 @@ +"""Biztoc Provider tests.""" diff --git a/openbb_platform/providers/biztoc/tests/test_biztoc_fetchers.py b/openbb_platform/providers/biztoc/tests/test_biztoc_fetchers.py index b56da94a9a85..e2a3c579573b 100644 --- a/openbb_platform/providers/biztoc/tests/test_biztoc_fetchers.py +++ b/openbb_platform/providers/biztoc/tests/test_biztoc_fetchers.py @@ -1,3 +1,5 @@ +"""Tests for the Biztoc fetchers.""" + import pytest from openbb_biztoc.models.world_news import BiztocWorldNewsFetcher from openbb_core.app.service.user_service import UserService @@ -7,6 +9,7 @@ @pytest.fixture(scope="module") def vcr_config(): + """VCR configuration.""" return { "filter_headers": [("User-Agent", None), ("X-RapidAPI-Key", "MOCK_API_KEY")], "filter_query_parameters": [ @@ -17,6 +20,7 @@ def vcr_config(): @pytest.mark.record_http def test_biztoc_world_news_fetcher(credentials=test_credentials): + """Test the Biztoc World News fetcher.""" params = {"term": "earnings"} fetcher = BiztocWorldNewsFetcher() diff --git a/openbb_platform/providers/cboe/__init__.py b/openbb_platform/providers/cboe/__init__.py index e69de29bb2d1..635774cce049 100644 --- a/openbb_platform/providers/cboe/__init__.py +++ b/openbb_platform/providers/cboe/__init__.py @@ -0,0 +1 @@ +"""CBOE provider.""" diff --git a/openbb_platform/providers/cboe/openbb_cboe/models/futures_curve.py b/openbb_platform/providers/cboe/openbb_cboe/models/futures_curve.py index 44970f62b89c..fee62fb339a7 100644 --- a/openbb_platform/providers/cboe/openbb_cboe/models/futures_curve.py +++ b/openbb_platform/providers/cboe/openbb_cboe/models/futures_curve.py @@ -36,6 +36,7 @@ class CboeFuturesCurveFetcher( @staticmethod def transform_query(params: Dict[str, Any]) -> CboeFuturesCurveQueryParams: + """Transform the query.""" return CboeFuturesCurveQueryParams(**params) @staticmethod @@ -45,7 +46,6 @@ async def aextract_data( **kwargs: Any, ) -> List[Dict]: """Return the raw data from the CBOE endpoint.""" - symbol = query.symbol.upper().split(",")[0] FUTURES = await get_settlement_prices(**kwargs) if len(FUTURES) == 0: @@ -68,4 +68,5 @@ def transform_data( data: List[Dict], **kwargs: Any, ) -> List[CboeFuturesCurveData]: + """Transform data.""" return [CboeFuturesCurveData.model_validate(d) for d in data] diff --git a/openbb_platform/providers/cboe/openbb_cboe/utils/helpers.py b/openbb_platform/providers/cboe/openbb_cboe/utils/helpers.py index 74b7ca608cf3..e49361b1549b 100644 --- a/openbb_platform/providers/cboe/openbb_cboe/utils/helpers.py +++ b/openbb_platform/providers/cboe/openbb_cboe/utils/helpers.py @@ -1,4 +1,4 @@ -"""Cboe Helpers""" +"""Cboe Helpers.""" # pylint: disable=expression-not-assigned, unused-argument @@ -81,7 +81,7 @@ async def response_callback(response: ClientResponse, _: Any): - """Callback for HTTP Client Response.""" + """Use callback for HTTP Client Response.""" content_type = response.headers.get("Content-Type", "") if "application/json" in content_type: return await response.json() @@ -91,7 +91,7 @@ async def response_callback(response: ClientResponse, _: Any): async def get_cboe_data(url, use_cache: bool = True, **kwargs) -> Any: - """Generic Cboe HTTP request.""" + """Use the generic Cboe HTTP request.""" if use_cache is True: async with CachedSession(cache=backend) as cached_session: try: @@ -106,15 +106,14 @@ async def get_cboe_data(url, use_cache: bool = True, **kwargs) -> Any: async def get_company_directory(use_cache: bool = True, **kwargs) -> DataFrame: - """ - Get the US Company Directory for Cboe options. If use_cache is True, - the data will be cached for 24 hours. + """Get the US Company Directory for Cboe options. + + If use_cache is True, the data will be cached for 24 hours. Returns ------- DataFrame: Pandas DataFrame of the Cboe listings directory """ - url = "https://www.cboe.com/us/options/symboldir/equity_index_options/?download=csv" results = await get_cboe_data(url, use_cache) @@ -136,15 +135,14 @@ async def get_company_directory(use_cache: bool = True, **kwargs) -> DataFrame: async def get_index_directory(use_cache: bool = True, **kwargs) -> DataFrame: - """ - Get the Cboe Index Directory. If use_cache is True, - the data will be cached for 24 hours. + """Get the Cboe Index Directory. + + If use_cache is True, the data will be cached for 24 hours. Returns - -------- + ------- List[Dict]: A list of dictionaries containing the index information. """ - url = "https://cdn.cboe.com/api/global/us_indices/definitions/all_indices.json" results = await get_cboe_data(url, use_cache=use_cache) @@ -162,11 +160,10 @@ async def list_futures(**kwargs) -> List[dict]: """List of CBOE futures and their underlying symbols. Returns - -------- + ------- pd.DataFrame Pandas DataFrame with results. """ - r = await get_cboe_data( "https://cdn.cboe.com/api/global/delayed_quotes/symbol_book/futures-roots.json" ) @@ -183,10 +180,10 @@ async def get_settlement_prices( final_settlement: bool = False, **kwargs, ) -> DataFrame: - """Gets the settlement prices of CBOE futures. + """Get the settlement prices of CBOE futures. Parameters - ----------- + ---------- settlement_date: Optional[date] The settlement date. Only valid for active contracts. [YYYY-MM-DD] options: bool diff --git a/openbb_platform/providers/cboe/tests/__init__.py b/openbb_platform/providers/cboe/tests/__init__.py index e69de29bb2d1..41685dac0a57 100644 --- a/openbb_platform/providers/cboe/tests/__init__.py +++ b/openbb_platform/providers/cboe/tests/__init__.py @@ -0,0 +1 @@ +"""CBOE tests.""" diff --git a/openbb_platform/providers/cboe/tests/test_cboe_fetchers.py b/openbb_platform/providers/cboe/tests/test_cboe_fetchers.py index 9f380286c003..1545a87a00d3 100644 --- a/openbb_platform/providers/cboe/tests/test_cboe_fetchers.py +++ b/openbb_platform/providers/cboe/tests/test_cboe_fetchers.py @@ -34,6 +34,7 @@ @pytest.fixture(scope="module") def vcr_config(): + """VCR configuration.""" return { "filter_headers": [("User-Agent", None)], "filter_query_parameters": [ @@ -44,6 +45,7 @@ def vcr_config(): @pytest.mark.record_http def test_cboe_index_historical_fetcher(credentials=test_credentials): + """Test Cboe index historical fetcher.""" params = {"symbol": "AAVE10RP", "use_cache": False} fetcher = CboeIndexHistoricalFetcher() @@ -53,6 +55,7 @@ def test_cboe_index_historical_fetcher(credentials=test_credentials): @pytest.mark.record_http def test_cboe_index_constituents_fetcher(credentials=test_credentials): + """Test Cboe index constituents fetcher.""" params = {"symbol": "BUK100P"} fetcher = CboeIndexConstituentsFetcher() @@ -62,6 +65,7 @@ def test_cboe_index_constituents_fetcher(credentials=test_credentials): @pytest.mark.record_http def test_cboe_index_search_fetcher(credentials=test_credentials): + """Test Cboe index search fetcher.""" params = {"query": "uk", "use_cache": False} fetcher = CboeIndexSearchFetcher() @@ -71,6 +75,7 @@ def test_cboe_index_search_fetcher(credentials=test_credentials): @pytest.mark.record_http def test_cboe_equity_historical_fetcher(credentials=test_credentials): + """Test Cboe equity historical fetcher.""" params = { "symbol": "AAPL", "start_date": date(2023, 1, 1), @@ -86,6 +91,7 @@ def test_cboe_equity_historical_fetcher(credentials=test_credentials): @pytest.mark.record_http def test_cboe_available_indices_fetcher(credentials=test_credentials): + """Test Cboe available indices fetcher.""" params = {"use_cache": False} fetcher = CboeAvailableIndicesFetcher() @@ -95,6 +101,7 @@ def test_cboe_available_indices_fetcher(credentials=test_credentials): @pytest.mark.record_http def test_cboe_options_chains_fetcher(credentials=test_credentials): + """Test Cboe options chains fetcher.""" params = {"symbol": "AAPL", "use_cache": False} fetcher = CboeOptionsChainsFetcher() @@ -104,6 +111,7 @@ def test_cboe_options_chains_fetcher(credentials=test_credentials): @pytest.mark.record_http def test_cboe_equity_search_fetcher(credentials=test_credentials): + """Test Cboe equity search fetcher.""" params = {"query": "ETF", "use_cache": False} fetcher = CboeEquitySearchFetcher() @@ -113,6 +121,7 @@ def test_cboe_equity_search_fetcher(credentials=test_credentials): @pytest.mark.record_http def test_cboe_equity_quote_fetcher(credentials=test_credentials): + """Test Cboe equity quote fetcher.""" params = {"symbol": "AAPL", "use_cache": False} fetcher = CboeEquityQuoteFetcher() @@ -122,6 +131,7 @@ def test_cboe_equity_quote_fetcher(credentials=test_credentials): @pytest.mark.record_http def test_cboe_futures_curve_fetcher(credentials=test_credentials): + """Test Cboe futures curve fetcher.""" params = {"symbol": "VX"} fetcher = CboeFuturesCurveFetcher() @@ -131,6 +141,7 @@ def test_cboe_futures_curve_fetcher(credentials=test_credentials): @pytest.mark.record_http def test_cboe_index_snapshots_fetcher(credentials=test_credentials): + """Test Cboe index snapshots fetcher.""" params = {"region": "eu"} fetcher = CboeIndexSnapshotsFetcher() diff --git a/openbb_platform/providers/ecb/openbb_ecb/models/__init__.py b/openbb_platform/providers/ecb/openbb_ecb/models/__init__.py index e69de29bb2d1..de03eacd4a6e 100644 --- a/openbb_platform/providers/ecb/openbb_ecb/models/__init__.py +++ b/openbb_platform/providers/ecb/openbb_ecb/models/__init__.py @@ -0,0 +1 @@ +"""ECB Provider Models.""" diff --git a/openbb_platform/providers/ecb/openbb_ecb/utils/__init__.py b/openbb_platform/providers/ecb/openbb_ecb/utils/__init__.py index e69de29bb2d1..c703f4399bd3 100644 --- a/openbb_platform/providers/ecb/openbb_ecb/utils/__init__.py +++ b/openbb_platform/providers/ecb/openbb_ecb/utils/__init__.py @@ -0,0 +1 @@ +"""ECB utils module.""" diff --git a/openbb_platform/providers/federal_reserve/__init__.py b/openbb_platform/providers/federal_reserve/__init__.py index e69de29bb2d1..e06814d70310 100644 --- a/openbb_platform/providers/federal_reserve/__init__.py +++ b/openbb_platform/providers/federal_reserve/__init__.py @@ -0,0 +1 @@ +"""Federal Reserve provider for OpenBB Platform.""" diff --git a/openbb_platform/providers/federal_reserve/tests/test_federal_reserve_fetchers.py b/openbb_platform/providers/federal_reserve/tests/test_federal_reserve_fetchers.py index 97e9fe5ac734..40e5bab1f15e 100644 --- a/openbb_platform/providers/federal_reserve/tests/test_federal_reserve_fetchers.py +++ b/openbb_platform/providers/federal_reserve/tests/test_federal_reserve_fetchers.py @@ -1,3 +1,5 @@ +"""Tests for the Federal Reserve fetchers.""" + from datetime import date import pytest @@ -17,6 +19,7 @@ @pytest.mark.record_http def test_federal_reserve_treasury_rates_fetcher(credentials=test_credentials): + """Test the Federal Reserve Treasury Rates fetcher.""" params = {"start_date": date(2023, 1, 1), "end_date": date(2023, 5, 10)} fetcher = FederalReserveTreasuryRatesFetcher() @@ -26,6 +29,7 @@ def test_federal_reserve_treasury_rates_fetcher(credentials=test_credentials): @pytest.mark.record_http def test_federal_reserve_money_measures_fetcher(credentials=test_credentials): + """Test the Federal Reserve Money Measures fetcher.""" params = {"start_date": date(2023, 1, 1), "end_date": date(2023, 5, 10)} fetcher = FederalReserveMoneyMeasuresFetcher() @@ -35,6 +39,7 @@ def test_federal_reserve_money_measures_fetcher(credentials=test_credentials): @pytest.mark.record_http def test_federal_reserve_fed_fetcher(credentials=test_credentials): + """Test the Federal Reserve FED fetcher.""" params = {"start_date": date(2023, 1, 1), "end_date": date(2023, 6, 6)} fetcher = FederalReserveFEDFetcher() diff --git a/openbb_platform/providers/finra/__init__.py b/openbb_platform/providers/finra/__init__.py index e69de29bb2d1..35f7b384ac05 100644 --- a/openbb_platform/providers/finra/__init__.py +++ b/openbb_platform/providers/finra/__init__.py @@ -0,0 +1 @@ +"""FINRA provider for OpenBB Platform.""" diff --git a/openbb_platform/providers/finra/openbb_finra/utils/helpers.py b/openbb_platform/providers/finra/openbb_finra/utils/helpers.py index 4468004ebd0a..364f3fde743e 100644 --- a/openbb_platform/providers/finra/openbb_finra/utils/helpers.py +++ b/openbb_platform/providers/finra/openbb_finra/utils/helpers.py @@ -1,12 +1,15 @@ -# Helper functions for FINRA API +"""Helper functions for FINRA API.""" + import datetime from typing import List import requests +# pylint: disable=W0621 + def get_finra_weeks(tier: str = "T1", is_ats: bool = True): - """Fetches the available weeks from FINRA that can be used.""" + """Fetch the available weeks from FINRA that can be used.""" request_header = {"Accept": "application/json", "Content-Type": "application/json"} request_data = { @@ -40,6 +43,7 @@ def get_finra_weeks(tier: str = "T1", is_ats: bool = True): def get_finra_data(symbol, week_start, tier: str = "T1", is_ats: bool = True): + """Get the data for a symbol from FINRA.""" req_hdr = { "Accept": "application/json", "Content-Type": "application/json", @@ -93,6 +97,7 @@ def get_finra_data(symbol, week_start, tier: str = "T1", is_ats: bool = True): def get_full_data(symbol, tier: str = "T1", is_ats: bool = True): + """Get the full data for a symbol from FINRA.""" weeks = [week["weekStartDate"] for week in get_finra_weeks(tier, is_ats)] data = [] @@ -106,6 +111,7 @@ def get_full_data(symbol, tier: str = "T1", is_ats: bool = True): def get_adjusted_date(year, month, day): + """Find the closest date if the date falls on a weekend.""" # Get the date date = datetime.date(year, month, day) @@ -120,13 +126,14 @@ def get_adjusted_date(year, month, day): def get_short_interest_dates() -> List[str]: - """ - Get a list of dates for which the short interest data is available. It is reported on the 15th and the - last day of each month,but if the date falls on a weekend, the date is adjusted to the closest friday. + """Get a list of dates for which the short interest data is available. + + It is reported on the 15th and the last day of each month,but if the date falls on a weekend, + the date is adjusted to the closest friday. """ def get_adjusted_date(year, month, day): - """If the date falls on a weekend, find the closest date""" + """Find the closest date if the date falls on a weekend.""" # Get the date date = datetime.date(year, month, day) diff --git a/openbb_platform/providers/finra/tests/test_finra_fetchers.py b/openbb_platform/providers/finra/tests/test_finra_fetchers.py index 212fb4317c0e..19f8f2929633 100644 --- a/openbb_platform/providers/finra/tests/test_finra_fetchers.py +++ b/openbb_platform/providers/finra/tests/test_finra_fetchers.py @@ -1,3 +1,5 @@ +"""Tests for the Finra fetchers.""" + import pytest from openbb_core.app.service.user_service import UserService from openbb_finra.models.equity_short_interest import FinraShortInterestFetcher @@ -10,6 +12,7 @@ @pytest.fixture(scope="module") def vcr_config(): + """VCR configuration.""" return { "filter_headers": [("User-Agent", None)], "filter_query_parameters": [ @@ -20,6 +23,7 @@ def vcr_config(): @pytest.mark.record_http def test_finra_otc_aggregate_fetcher(credentials=test_credentials): + """Test the Finra OTC Aggregate fetcher.""" params = {"symbol": "AAPL", "tier": "T1", "is_ats": True} fetcher = FinraOTCAggregateFetcher() @@ -30,6 +34,7 @@ def test_finra_otc_aggregate_fetcher(credentials=test_credentials): @pytest.mark.freeze_time("2021-10-21") @pytest.mark.record_http def test_finra_short_interest_fetcher(credentials=test_credentials): + """Test the Finra Short Interest fetcher.""" params = {"symbol": "AAPL"} fetcher = FinraShortInterestFetcher() diff --git a/openbb_platform/providers/finviz/__init__.py b/openbb_platform/providers/finviz/__init__.py index e69de29bb2d1..c89b671ab793 100644 --- a/openbb_platform/providers/finviz/__init__.py +++ b/openbb_platform/providers/finviz/__init__.py @@ -0,0 +1 @@ +"""Finviz provider.""" diff --git a/openbb_platform/providers/finviz/openbb_finviz/models/__init__.py b/openbb_platform/providers/finviz/openbb_finviz/models/__init__.py index e69de29bb2d1..3370d9d3dc30 100644 --- a/openbb_platform/providers/finviz/openbb_finviz/models/__init__.py +++ b/openbb_platform/providers/finviz/openbb_finviz/models/__init__.py @@ -0,0 +1 @@ +"""Finviz Provider models.""" diff --git a/openbb_platform/providers/finviz/openbb_finviz/models/compare_groups.py b/openbb_platform/providers/finviz/openbb_finviz/models/compare_groups.py index a360a4126479..4c53fde9cf29 100644 --- a/openbb_platform/providers/finviz/openbb_finviz/models/compare_groups.py +++ b/openbb_platform/providers/finviz/openbb_finviz/models/compare_groups.py @@ -191,7 +191,7 @@ def validate_percent_values(cls, v): @field_validator("market_cap", "volume", mode="before", check_fields=False) @classmethod def validate_abbreviated_numbers(cls, v): - """Checks for abbreviated string values.""" + """Check for abbreviated string values.""" if v is not None and isinstance(v, str): v = ( v.replace("M", "e+6") diff --git a/openbb_platform/providers/finviz/openbb_finviz/utils/__init__.py b/openbb_platform/providers/finviz/openbb_finviz/utils/__init__.py index e69de29bb2d1..e5a38b98d21e 100644 --- a/openbb_platform/providers/finviz/openbb_finviz/utils/__init__.py +++ b/openbb_platform/providers/finviz/openbb_finviz/utils/__init__.py @@ -0,0 +1 @@ +"""Finviz provider utils.""" diff --git a/openbb_platform/providers/finviz/tests/__init__.py b/openbb_platform/providers/finviz/tests/__init__.py index e69de29bb2d1..05531f1aa144 100644 --- a/openbb_platform/providers/finviz/tests/__init__.py +++ b/openbb_platform/providers/finviz/tests/__init__.py @@ -0,0 +1 @@ +"""Finviz provider tests.""" diff --git a/openbb_platform/providers/finviz/tests/test_finviz_fetchers.py b/openbb_platform/providers/finviz/tests/test_finviz_fetchers.py index 70c33e716a12..02b935c9c3a9 100644 --- a/openbb_platform/providers/finviz/tests/test_finviz_fetchers.py +++ b/openbb_platform/providers/finviz/tests/test_finviz_fetchers.py @@ -15,6 +15,7 @@ @pytest.fixture(scope="module") def vcr_config(): + """VCR configuration.""" return { "filter_headers": [ ("User-Agent", None), @@ -30,6 +31,7 @@ def vcr_config(): @pytest.mark.record_http def test_finviz_price_target_fetcher(credentials=test_credentials): + """Test Finviz Price Target Fetcher.""" params = {"symbol": "AAPL"} fetcher = FinvizPriceTargetFetcher() @@ -39,6 +41,7 @@ def test_finviz_price_target_fetcher(credentials=test_credentials): @pytest.mark.record_http def test_finviz_price_performance_fetcher(credentials=test_credentials): + """Test Finviz Price Performance Fetcher.""" params = {"symbol": "AAPL"} fetcher = FinvizPricePerformanceFetcher() @@ -48,6 +51,7 @@ def test_finviz_price_performance_fetcher(credentials=test_credentials): @pytest.mark.record_http def test_finviz_key_metrics_fetcher(credentials=test_credentials): + """Test Finviz Key Metrics Fetcher.""" params = {"symbol": "AAPL"} fetcher = FinvizKeyMetricsFetcher() @@ -57,6 +61,7 @@ def test_finviz_key_metrics_fetcher(credentials=test_credentials): @pytest.mark.record_http def test_finviz_equity_profile_fetcher(credentials=test_credentials): + """Test Finviz Equity Profile Fetcher.""" params = {"symbol": "AAPL"} fetcher = FinvizEquityProfileFetcher() @@ -66,6 +71,7 @@ def test_finviz_equity_profile_fetcher(credentials=test_credentials): @pytest.mark.record_http def test_finviz_compare_groups_fetcher(credentials=test_credentials): + """Test Finviz Compare Groups Fetcher.""" params = {"group": "country", "metric": "performance"} fetcher = FinvizCompareGroupsFetcher() diff --git a/openbb_platform/providers/fmp/__init__.py b/openbb_platform/providers/fmp/__init__.py index e69de29bb2d1..a49b8af83211 100644 --- a/openbb_platform/providers/fmp/__init__.py +++ b/openbb_platform/providers/fmp/__init__.py @@ -0,0 +1 @@ +"""FMP Provider.""" diff --git a/openbb_platform/providers/fmp/openbb_fmp/utils/__init__.py b/openbb_platform/providers/fmp/openbb_fmp/utils/__init__.py index e69de29bb2d1..9d4fc004b59c 100644 --- a/openbb_platform/providers/fmp/openbb_fmp/utils/__init__.py +++ b/openbb_platform/providers/fmp/openbb_fmp/utils/__init__.py @@ -0,0 +1 @@ +"""FMP utils.""" diff --git a/openbb_platform/providers/fmp/openbb_fmp/utils/helpers.py b/openbb_platform/providers/fmp/openbb_fmp/utils/helpers.py index 26d59ac562c0..c37c5718cdc6 100644 --- a/openbb_platform/providers/fmp/openbb_fmp/utils/helpers.py +++ b/openbb_platform/providers/fmp/openbb_fmp/utils/helpers.py @@ -17,8 +17,7 @@ async def response_callback( response: ClientResponse, _: ClientSession ) -> Union[Dict, List[Dict]]: - """Callback for make_request.""" - + """Use callback for make_request.""" data = await response.json() if isinstance(data, dict) and "Error Message" in data: raise RuntimeError(f"FMP Error Message -> {data['Error Message']}") diff --git a/openbb_platform/providers/fmp/tests/__init__.py b/openbb_platform/providers/fmp/tests/__init__.py index e69de29bb2d1..78e9c51c609e 100644 --- a/openbb_platform/providers/fmp/tests/__init__.py +++ b/openbb_platform/providers/fmp/tests/__init__.py @@ -0,0 +1 @@ +"""FMP tests.""" diff --git a/openbb_platform/providers/fmp/tests/test_fmp_fetchers.py b/openbb_platform/providers/fmp/tests/test_fmp_fetchers.py index 46aee30de484..187d6d479001 100644 --- a/openbb_platform/providers/fmp/tests/test_fmp_fetchers.py +++ b/openbb_platform/providers/fmp/tests/test_fmp_fetchers.py @@ -77,6 +77,7 @@ def response_filter(response): + """Filter the response.""" if "Location" in response["headers"]: response["headers"]["Location"] = [ re.sub(r"apikey=[^&]+", "apikey=MOCK_API_KEY", x) @@ -87,6 +88,7 @@ def response_filter(response): @pytest.fixture(scope="module") def vcr_config(): + """VCR configuration.""" return { "filter_headers": [("User-Agent", None)], "filter_query_parameters": [ @@ -98,6 +100,7 @@ def vcr_config(): @pytest.mark.record_http def test_fmp_company_filings_fetcher(credentials=test_credentials): + """Test FMP company filings fetcher.""" params = {"symbol": "AAPL", "form_type": "10-K", "limit": 100} fetcher = FMPCompanyFilingsFetcher() @@ -107,6 +110,7 @@ def test_fmp_company_filings_fetcher(credentials=test_credentials): @pytest.mark.record_http def test_fmp_crypto_historical_fetcher(credentials=test_credentials): + """Test FMP crypto historical fetcher.""" params = { "symbol": "BTCUSD", "start_date": date(2023, 1, 1), @@ -120,6 +124,7 @@ def test_fmp_crypto_historical_fetcher(credentials=test_credentials): @pytest.mark.record_http def test_fmp_currency_historical_fetcher(credentials=test_credentials): + """Test FMP currency historical fetcher.""" params = { "symbol": "EURUSD", "start_date": date(2023, 1, 1), @@ -133,6 +138,7 @@ def test_fmp_currency_historical_fetcher(credentials=test_credentials): @pytest.mark.record_http def test_fmp_market_indices_fetcher(credentials=test_credentials): + """Test FMP market indices fetcher.""" params = { "symbol": "^DJI", "start_date": date(2023, 1, 1), @@ -146,6 +152,7 @@ def test_fmp_market_indices_fetcher(credentials=test_credentials): @pytest.mark.record_http def test_fmp_index_historical_fetcher(credentials=test_credentials): + """Test FMP index historical fetcher.""" params = { "symbol": "^DJI", "start_date": date(2023, 1, 1), @@ -159,6 +166,7 @@ def test_fmp_index_historical_fetcher(credentials=test_credentials): @pytest.mark.record_http def test_fmp_equity_historical_fetcher(credentials=test_credentials): + """Test FMP equity historical fetcher.""" params = { "symbol": "AAPL", "start_date": date(2023, 1, 1), @@ -173,6 +181,7 @@ def test_fmp_equity_historical_fetcher(credentials=test_credentials): @pytest.mark.record_http def test_fmp_company_news_fetcher(credentials=test_credentials): + """Test FMP company news fetcher.""" params = {"symbol": "AAPL,MSFT"} fetcher = FMPCompanyNewsFetcher() @@ -182,6 +191,7 @@ def test_fmp_company_news_fetcher(credentials=test_credentials): @pytest.mark.record_http def test_fmp_balance_sheet_fetcher(credentials=test_credentials): + """Test FMP balance sheet fetcher.""" params = {"symbol": "AAPL"} fetcher = FMPBalanceSheetFetcher() @@ -191,6 +201,7 @@ def test_fmp_balance_sheet_fetcher(credentials=test_credentials): @pytest.mark.record_http def test_fmp_cash_flow_statement_fetcher(credentials=test_credentials): + """Test FMP cash flow statement fetcher.""" params = {"symbol": "AAPL"} fetcher = FMPCashFlowStatementFetcher() @@ -200,6 +211,7 @@ def test_fmp_cash_flow_statement_fetcher(credentials=test_credentials): @pytest.mark.record_http def test_fmp_income_statement_fetcher(credentials=test_credentials): + """Test FMP income statement fetcher.""" params = {"symbol": "AAPL"} fetcher = FMPIncomeStatementFetcher() @@ -209,6 +221,7 @@ def test_fmp_income_statement_fetcher(credentials=test_credentials): @pytest.mark.record_http def test_fmp_available_indices_fetcher(credentials=test_credentials): + """Test FMP available indices fetcher.""" params = {} fetcher = FMPAvailableIndicesFetcher() @@ -218,6 +231,7 @@ def test_fmp_available_indices_fetcher(credentials=test_credentials): @pytest.mark.record_http def test_fmp_key_executives_fetcher(credentials=test_credentials): + """Test FMP key executives fetcher.""" params = {"symbol": "AAPL"} fetcher = FMPKeyExecutivesFetcher() @@ -227,6 +241,7 @@ def test_fmp_key_executives_fetcher(credentials=test_credentials): @pytest.mark.record_http def test_fmp_world_news_fetcher(credentials=test_credentials): + """Test FMP world news fetcher.""" params = {} fetcher = FMPWorldNewsFetcher() @@ -236,6 +251,7 @@ def test_fmp_world_news_fetcher(credentials=test_credentials): @pytest.mark.record_http def test_fmp_income_statement_growth_fetcher(credentials=test_credentials): + """Test FMP income statement growth fetcher.""" params = {"symbol": "AAPL"} fetcher = FMPIncomeStatementGrowthFetcher() @@ -245,6 +261,7 @@ def test_fmp_income_statement_growth_fetcher(credentials=test_credentials): @pytest.mark.record_http def test_fmp_balance_sheet_growth_fetcher(credentials=test_credentials): + """Test FMP balance sheet growth fetcher.""" params = {"symbol": "AAPL"} fetcher = FMPBalanceSheetGrowthFetcher() @@ -254,6 +271,7 @@ def test_fmp_balance_sheet_growth_fetcher(credentials=test_credentials): @pytest.mark.record_http def test_fmp_cash_flow_statement_growth_fetcher(credentials=test_credentials): + """Test FMP cash flow statement growth fetcher.""" params = {"symbol": "AAPL"} fetcher = FMPCashFlowStatementGrowthFetcher() @@ -263,6 +281,7 @@ def test_fmp_cash_flow_statement_growth_fetcher(credentials=test_credentials): @pytest.mark.record_http def test_fmp_share_statistics_fetcher(credentials=test_credentials): + """Test FMP share statistics fetcher.""" params = {"symbol": "AAPL"} fetcher = FMPShareStatisticsFetcher() @@ -272,6 +291,7 @@ def test_fmp_share_statistics_fetcher(credentials=test_credentials): @pytest.mark.record_http def test_fmp_revenue_geographic_fetcher(credentials=test_credentials): + """Test FMP revenue geographic fetcher.""" params = {"symbol": "AAPL"} fetcher = FMPRevenueGeographicFetcher() @@ -281,6 +301,7 @@ def test_fmp_revenue_geographic_fetcher(credentials=test_credentials): @pytest.mark.record_http def test_fmp_revenue_business_line_fetcher(credentials=test_credentials): + """Test FMP revenue business line fetcher.""" params = {"symbol": "AAPL"} fetcher = FMPRevenueBusinessLineFetcher() @@ -290,6 +311,7 @@ def test_fmp_revenue_business_line_fetcher(credentials=test_credentials): @pytest.mark.record_http def test_fmp_institutional_ownership_fetcher(credentials=test_credentials): + """Test FMP institutional ownership fetcher.""" params = {"symbol": "AAPL"} fetcher = FMPInstitutionalOwnershipFetcher() @@ -299,6 +321,7 @@ def test_fmp_institutional_ownership_fetcher(credentials=test_credentials): @pytest.mark.record_http def test_fmp_company_overview_fetcher(credentials=test_credentials): + """Test FMP company overview fetcher.""" params = {"symbol": "AAPL"} fetcher = FMPCompanyOverviewFetcher() @@ -308,6 +331,7 @@ def test_fmp_company_overview_fetcher(credentials=test_credentials): @pytest.mark.record_http def test_fmp_insider_trading_fetcher(credentials=test_credentials): + """Test FMP insider trading fetcher.""" params = {"symbol": "AAPL"} fetcher = FMPInsiderTradingFetcher() @@ -317,6 +341,7 @@ def test_fmp_insider_trading_fetcher(credentials=test_credentials): @pytest.mark.record_http def test_fmp_equity_ownership_fetcher(credentials=test_credentials): + """Test FMP equity ownership fetcher.""" params = {"symbol": "AAPL", "date": date(2022, 12, 31)} fetcher = FMPEquityOwnershipFetcher() @@ -326,6 +351,7 @@ def test_fmp_equity_ownership_fetcher(credentials=test_credentials): @pytest.mark.record_http def test_fmp_price_target_consensus_fetcher(credentials=test_credentials): + """Test FMP price target consensus fetcher.""" params = {"symbol": "AAPL"} fetcher = FMPPriceTargetConsensusFetcher() @@ -335,6 +361,7 @@ def test_fmp_price_target_consensus_fetcher(credentials=test_credentials): @pytest.mark.record_http def test_fmp_price_target_fetcher(credentials=test_credentials): + """Test FMP price target fetcher.""" params = {"symbol": "AAPL"} fetcher = FMPPriceTargetFetcher() @@ -344,6 +371,7 @@ def test_fmp_price_target_fetcher(credentials=test_credentials): @pytest.mark.record_http def test_fmp_analyst_estimates_fetcher(credentials=test_credentials): + """Test FMP analyst estimates fetcher.""" params = {"symbol": "AAPL", "limit": 30} fetcher = FMPAnalystEstimatesFetcher() @@ -353,6 +381,7 @@ def test_fmp_analyst_estimates_fetcher(credentials=test_credentials): @pytest.mark.record_http def test_fmp_historical_eps_fetcher(credentials=test_credentials): + """Test FMP historical EPS fetcher.""" params = {"symbol": "AAPL"} fetcher = FMPHistoricalEpsFetcher() @@ -362,6 +391,7 @@ def test_fmp_historical_eps_fetcher(credentials=test_credentials): @pytest.mark.record_http def test_fmp_earnings_call_transcript_fetcher(credentials=test_credentials): + """Test FMP earnings call transcript fetcher.""" params = {"symbol": "AAPL", "year": 2020} fetcher = FMPEarningsCallTranscriptFetcher() @@ -371,6 +401,7 @@ def test_fmp_earnings_call_transcript_fetcher(credentials=test_credentials): @pytest.mark.record_http def test_fmp_historical_splits_fetcher(credentials=test_credentials): + """Test FMP historical splits fetcher.""" params = {"symbol": "AAPL"} fetcher = FMPHistoricalSplitsFetcher() @@ -380,6 +411,7 @@ def test_fmp_historical_splits_fetcher(credentials=test_credentials): @pytest.mark.record_http def test_fmp_calendar_splits_fetcher(credentials=test_credentials): + """Test FMP calendar splits fetcher.""" params = {"start_date": date(2023, 1, 1), "end_date": date(2023, 1, 10)} fetcher = FMPCalendarSplitsFetcher() @@ -389,6 +421,7 @@ def test_fmp_calendar_splits_fetcher(credentials=test_credentials): @pytest.mark.record_http def test_fmp_historical_dividends_fetcher(credentials=test_credentials): + """Test FMP historical dividends fetcher.""" params = {"symbol": "AAPL"} fetcher = FMPHistoricalDividendsFetcher() @@ -398,6 +431,7 @@ def test_fmp_historical_dividends_fetcher(credentials=test_credentials): @pytest.mark.record_http def test_fmp_key_metrics_fetcher(credentials=test_credentials): + """Test FMP key metrics fetcher.""" params = {"symbol": "AAPL"} fetcher = FMPKeyMetricsFetcher() @@ -407,6 +441,7 @@ def test_fmp_key_metrics_fetcher(credentials=test_credentials): @pytest.mark.record_http def test_fmp_treasury_rates_fetcher(credentials=test_credentials): + """Test FMP treasury rates fetcher.""" params = {"start_date": date(2023, 1, 1), "end_date": date(2023, 5, 10)} fetcher = FMPTreasuryRatesFetcher() @@ -416,6 +451,7 @@ def test_fmp_treasury_rates_fetcher(credentials=test_credentials): @pytest.mark.record_http def test_fmp_executive_compensation_fetcher(credentials=test_credentials): + """Test FMP executive compensation fetcher.""" params = {"symbol": "AAPL"} fetcher = FMPExecutiveCompensationFetcher() @@ -425,6 +461,7 @@ def test_fmp_executive_compensation_fetcher(credentials=test_credentials): @pytest.mark.record_http def test_fmp_currency_pairs_fetcher(credentials=test_credentials): + """Test FMP currency pairs fetcher.""" params = {} fetcher = FMPCurrencyPairsFetcher() @@ -434,6 +471,7 @@ def test_fmp_currency_pairs_fetcher(credentials=test_credentials): @pytest.mark.record_http def test_fmp_equity_peers_fetcher(credentials=test_credentials): + """Test FMP equity peers fetcher.""" params = {"symbol": "AAPL"} fetcher = FMPEquityPeersFetcher() @@ -443,6 +481,7 @@ def test_fmp_equity_peers_fetcher(credentials=test_credentials): @pytest.mark.record_http def test_fmp_equity_valuation_multiples_fetcher(credentials=test_credentials): + """Test FMP equity valuation multiples fetcher.""" params = {"symbol": "AAPL"} fetcher = FMPEquityValuationMultiplesFetcher() @@ -452,6 +491,7 @@ def test_fmp_equity_valuation_multiples_fetcher(credentials=test_credentials): @pytest.mark.record_http def test_fmp_historical_employees_fetcher(credentials=test_credentials): + """Test FMP historical employees fetcher.""" params = {"symbol": "AAPL"} fetcher = FMPHistoricalEmployeesFetcher() @@ -461,6 +501,7 @@ def test_fmp_historical_employees_fetcher(credentials=test_credentials): @pytest.mark.record_http def test_fmp_risk_premium_fetcher(credentials=test_credentials): + """Test FMP risk premium fetcher.""" params = {} fetcher = FMPRiskPremiumFetcher() @@ -470,6 +511,7 @@ def test_fmp_risk_premium_fetcher(credentials=test_credentials): @pytest.mark.record_http def test_fmp_index_constituents_fetcher(credentials=test_credentials): + """Test FMP index constituents fetcher.""" params = {} fetcher = FMPIndexConstituentsFetcher() @@ -479,6 +521,7 @@ def test_fmp_index_constituents_fetcher(credentials=test_credentials): @pytest.mark.record_http def test_fmp_calendar_dividend_fetcher(credentials=test_credentials): + """Test FMP calendar dividend fetcher.""" params = {"start_date": date(2023, 11, 6), "end_date": date(2023, 11, 10)} fetcher = FMPCalendarDividendFetcher() @@ -488,6 +531,7 @@ def test_fmp_calendar_dividend_fetcher(credentials=test_credentials): @pytest.mark.record_http def test_fmp_equity_quote_fetcher(credentials=test_credentials): + """Test FMP equity quote fetcher.""" params = {"symbol": "AAPL"} fetcher = FMPEquityQuoteFetcher() @@ -497,6 +541,7 @@ def test_fmp_equity_quote_fetcher(credentials=test_credentials): @pytest.mark.record_http def test_fmp_equity_screener_fetcher(credentials=test_credentials): + """Test FMP equity screener fetcher.""" params = {"query": "midstream", "sector": "Energy", "beta_max": 0.5} fetcher = FMPEquityScreenerFetcher() @@ -506,6 +551,7 @@ def test_fmp_equity_screener_fetcher(credentials=test_credentials): @pytest.mark.record_http def test_fmp_financial_ratios_fetcher(credentials=test_credentials): + """Test FMP financial ratios fetcher.""" params = {"symbol": "AAPL"} fetcher = FMPFinancialRatiosFetcher() @@ -515,6 +561,7 @@ def test_fmp_financial_ratios_fetcher(credentials=test_credentials): @pytest.mark.record_http def test_fmp_economic_calendar_fetcher(credentials=test_credentials): + """Test FMP economic calendar fetcher.""" params = {} fetcher = FMPEconomicCalendarFetcher() @@ -524,6 +571,7 @@ def test_fmp_economic_calendar_fetcher(credentials=test_credentials): @pytest.mark.record_http def test_fmp_market_snapshots_fetcher(credentials=test_credentials): + """Test FMP market snapshots fetcher.""" params = {"market": "lse"} fetcher = FMPMarketSnapshotsFetcher() @@ -533,6 +581,7 @@ def test_fmp_market_snapshots_fetcher(credentials=test_credentials): @pytest.mark.record_http def test_fmp_etf_search_fetcher(credentials=test_credentials): + """Test FMP ETF search fetcher.""" params = {"query": "India"} fetcher = FMPEtfSearchFetcher() @@ -542,6 +591,7 @@ def test_fmp_etf_search_fetcher(credentials=test_credentials): @pytest.mark.record_http def test_fmp_etf_info_fetcher(credentials=test_credentials): + """Test FMP ETF info fetcher.""" params = {"symbol": "IOO"} fetcher = FMPEtfInfoFetcher() @@ -551,6 +601,7 @@ def test_fmp_etf_info_fetcher(credentials=test_credentials): @pytest.mark.record_http def test_fmp_etf_sectors_fetcher(credentials=test_credentials): + """Test FMP ETF sectors fetcher.""" params = {"symbol": "IOO"} fetcher = FMPEtfSectorsFetcher() @@ -560,6 +611,7 @@ def test_fmp_etf_sectors_fetcher(credentials=test_credentials): @pytest.mark.record_http def test_fmp_etf_holdings_fetcher(credentials=test_credentials): + """Test FMP ETF holdings fetcher.""" params = {"symbol": "IOO", "date": date(2022, 12, 31)} fetcher = FMPEtfHoldingsFetcher() @@ -569,6 +621,7 @@ def test_fmp_etf_holdings_fetcher(credentials=test_credentials): @pytest.mark.record_http def test_fmp_etf_holdings_date_fetcher(credentials=test_credentials): + """Test FMP ETF holdings date fetcher.""" params = {"symbol": "IOO"} fetcher = FMPEtfHoldingsDateFetcher() @@ -578,6 +631,7 @@ def test_fmp_etf_holdings_date_fetcher(credentials=test_credentials): @pytest.mark.record_http def test_fmp_price_performance_fetcher(credentials=test_credentials): + """Test FMP price performance fetcher.""" params = {"symbol": "AAPL,SPY,QQQ,MSFT,AMZN,GOOG"} fetcher = FMPPricePerformanceFetcher() @@ -587,6 +641,7 @@ def test_fmp_price_performance_fetcher(credentials=test_credentials): @pytest.mark.record_http def test_fmp_etf_countries_fetcher(credentials=test_credentials): + """Test FMP ETF countries fetcher.""" params = {"symbol": "VTI,QQQ,VOO,IWM"} fetcher = FMPEtfCountriesFetcher() @@ -596,6 +651,7 @@ def test_fmp_etf_countries_fetcher(credentials=test_credentials): @pytest.mark.record_http def test_fmp_etf_holdings_performance_fetcher(credentials=test_credentials): + """Test FMP ETF holdings performance fetcher.""" params = {"symbol": "SILJ"} fetcher = FMPEtfHoldingsPerformanceFetcher() @@ -605,6 +661,7 @@ def test_fmp_etf_holdings_performance_fetcher(credentials=test_credentials): @pytest.mark.record_http def test_fmp_discovery_filings_fetcher(credentials=test_credentials): + """Test FMP discovery filings fetcher.""" params = { "start_date": None, "end_date": None, @@ -620,6 +677,7 @@ def test_fmp_discovery_filings_fetcher(credentials=test_credentials): @pytest.mark.record_http def test_fmp_crypto_search_fetcher(credentials=test_credentials): + """Test FMP crypto search fetcher.""" params = {"query": "asd"} fetcher = FMPCryptoSearchFetcher() @@ -629,6 +687,7 @@ def test_fmp_crypto_search_fetcher(credentials=test_credentials): @pytest.mark.record_http def test_fmp_calendar_earnings_fetcher(credentials=test_credentials): + """Test FMP calendar earnings fetcher.""" params = {"symbol": "AAPL"} params = { @@ -642,6 +701,7 @@ def test_fmp_calendar_earnings_fetcher(credentials=test_credentials): @pytest.mark.record_http def test_fmp_equity_profile_fetcher(credentials=test_credentials): + """Test FMP equity profile fetcher.""" params = {"symbol": "AAPL"} fetcher = FMPEquityProfileFetcher() @@ -651,6 +711,7 @@ def test_fmp_equity_profile_fetcher(credentials=test_credentials): @pytest.mark.record_http def test_fmp_etf_equity_exposure_fetcher(credentials=test_credentials): + """Test FMP ETF equity exposure fetcher.""" params = {"symbol": "AAPL,MSFT"} fetcher = FMPEtfEquityExposureFetcher() @@ -660,6 +721,7 @@ def test_fmp_etf_equity_exposure_fetcher(credentials=test_credentials): @pytest.mark.record_http def test_fmp_currency_snapshots_fetcher(credentials=test_credentials): + """Test FMP currency snapshots fetcher.""" params = { "base": "XAU", "quote_type": "indirect", @@ -673,6 +735,7 @@ def test_fmp_currency_snapshots_fetcher(credentials=test_credentials): @pytest.mark.record_http def test_fmp_equity_forward_eps_fetcher(credentials=test_credentials): + """Test FMP forward EPS estimates fetcher.""" params = { "symbol": "MSFT,AAPL", "fiscal_period": "annual", diff --git a/openbb_platform/providers/government_us/__init__.py b/openbb_platform/providers/government_us/__init__.py index e69de29bb2d1..da089bdfadf2 100644 --- a/openbb_platform/providers/government_us/__init__.py +++ b/openbb_platform/providers/government_us/__init__.py @@ -0,0 +1 @@ +"""Government US provider.""" diff --git a/openbb_platform/providers/government_us/openbb_government_us/models/treasury_prices.py b/openbb_platform/providers/government_us/openbb_government_us/models/treasury_prices.py index 15e7e1bb0d01..a4fcc6efcca9 100644 --- a/openbb_platform/providers/government_us/openbb_government_us/models/treasury_prices.py +++ b/openbb_platform/providers/government_us/openbb_government_us/models/treasury_prices.py @@ -1,4 +1,4 @@ -"""US Government Treasury Prices""" +"""US Government Treasury Prices.""" # pylint: disable=unused-argument import asyncio @@ -38,12 +38,13 @@ class GovernmentUSTreasuryPricesFetcher( List[GovernmentUSTreasuryPricesData], ] ): + """US Government Treasury Prices Fetcher.""" + @staticmethod def transform_query( params: Dict[str, Any] ) -> GovernmentUSTreasuryPricesQueryParams: """Transform query params.""" - if params.get("date") is None: _date = datetime.now().date() else: @@ -66,7 +67,6 @@ async def aextract_data( **kwargs: Any, ) -> str: """Extract the raw data from US Treasury website.""" - url = "https://treasurydirect.gov/GA-FI/FedInvest/securityPriceDetail" HEADERS = { @@ -110,7 +110,6 @@ def transform_data( **kwargs: Any, ) -> List[GovernmentUSTreasuryPricesData]: """Transform the data.""" - try: if not data: raise EmptyDataError("Data not found") diff --git a/openbb_platform/providers/government_us/openbb_government_us/utils/__init__.py b/openbb_platform/providers/government_us/openbb_government_us/utils/__init__.py index e69de29bb2d1..7267bae0adee 100644 --- a/openbb_platform/providers/government_us/openbb_government_us/utils/__init__.py +++ b/openbb_platform/providers/government_us/openbb_government_us/utils/__init__.py @@ -0,0 +1 @@ +"""OpenBB Government US utils.""" diff --git a/openbb_platform/providers/government_us/tests/__init__.py b/openbb_platform/providers/government_us/tests/__init__.py index e69de29bb2d1..6af19936d320 100644 --- a/openbb_platform/providers/government_us/tests/__init__.py +++ b/openbb_platform/providers/government_us/tests/__init__.py @@ -0,0 +1 @@ +"""Government US tests.""" diff --git a/openbb_platform/providers/intrinio/__init__.py b/openbb_platform/providers/intrinio/__init__.py index e69de29bb2d1..a87030559a5a 100644 --- a/openbb_platform/providers/intrinio/__init__.py +++ b/openbb_platform/providers/intrinio/__init__.py @@ -0,0 +1 @@ +"""Intrinio provider.""" diff --git a/openbb_platform/providers/intrinio/openbb_intrinio/models/equity_info.py b/openbb_platform/providers/intrinio/openbb_intrinio/models/equity_info.py index 6488dbd70253..21c8d7d44aff 100644 --- a/openbb_platform/providers/intrinio/openbb_intrinio/models/equity_info.py +++ b/openbb_platform/providers/intrinio/openbb_intrinio/models/equity_info.py @@ -74,5 +74,5 @@ def transform_data( data: List[Dict], **kwargs: Any, ) -> List[IntrinioEquityInfoData]: - """Transforms the data.""" + """Transform the data.""" return [IntrinioEquityInfoData.model_validate(d) for d in data] diff --git a/openbb_platform/providers/intrinio/openbb_intrinio/models/forward_eps_estimates.py b/openbb_platform/providers/intrinio/openbb_intrinio/models/forward_eps_estimates.py index 9166f490f799..294428c3055f 100644 --- a/openbb_platform/providers/intrinio/openbb_intrinio/models/forward_eps_estimates.py +++ b/openbb_platform/providers/intrinio/openbb_intrinio/models/forward_eps_estimates.py @@ -162,7 +162,7 @@ async def get_one(symbol): return results async def fetch_callback(response, session): - """Callback for pagination.""" + """Use callback for pagination.""" data = await response.json() messages = data.get("messages", None) if messages: @@ -196,7 +196,6 @@ def transform_data( **kwargs: Any, ) -> List[IntrinioForwardEpsEstimatesData]: """Transform the raw data into the standard format.""" - symbols = query.symbol.split(",") if query.symbol else [] results: List[IntrinioForwardEpsEstimatesData] = [] for item in sorted( diff --git a/openbb_platform/providers/intrinio/openbb_intrinio/models/forward_sales_estimates.py b/openbb_platform/providers/intrinio/openbb_intrinio/models/forward_sales_estimates.py index 42444f494f53..c57ad52cfcb5 100644 --- a/openbb_platform/providers/intrinio/openbb_intrinio/models/forward_sales_estimates.py +++ b/openbb_platform/providers/intrinio/openbb_intrinio/models/forward_sales_estimates.py @@ -181,7 +181,7 @@ async def get_one(symbol): return results async def fetch_callback(response, session): - """Callback for pagination.""" + """Use callback for pagination.""" data = await response.json() messages = data.get("messages") if messages: @@ -215,7 +215,6 @@ def transform_data( **kwargs: Any, ) -> List[IntrinioForwardSalesEstimatesData]: """Transform the raw data into the standard format.""" - symbols = query.symbol.split(",") if query.symbol else [] results: List[IntrinioForwardSalesEstimatesData] = [] for item in sorted( diff --git a/openbb_platform/providers/intrinio/openbb_intrinio/models/historical_attributes.py b/openbb_platform/providers/intrinio/openbb_intrinio/models/historical_attributes.py index 47ce69831088..7c83c3b8d999 100644 --- a/openbb_platform/providers/intrinio/openbb_intrinio/models/historical_attributes.py +++ b/openbb_platform/providers/intrinio/openbb_intrinio/models/historical_attributes.py @@ -1,5 +1,7 @@ """Intrinio Historical Attributes Model.""" +# pylint: disable = unused-argument + import warnings from datetime import datetime from typing import Any, Dict, List, Optional @@ -62,7 +64,7 @@ def transform_query( @staticmethod async def aextract_data( - query: IntrinioHistoricalAttributesQueryParams, # pylint: disable=unused-argument + query: IntrinioHistoricalAttributesQueryParams, credentials: Optional[Dict[str, str]], **kwargs: Any, ) -> List[Dict]: @@ -73,7 +75,7 @@ async def aextract_data( query_str = get_querystring(query.model_dump(by_alias=True), ["symbol", "tag"]) def generate_url(symbol: str, tag: str) -> str: - """Returns the url for the given symbol and tag.""" + """Return the url for the given symbol and tag.""" url_params = f"{symbol}/{tag}?{query_str}&api_key={api_key}" url = f"{base_url}/historical_data/{url_params}" return url @@ -84,37 +86,43 @@ async def callback( """Return the response.""" init_response = await response.json() - if message := init_response.get("error") or init_response.get("message"): - warnings.warn(message=message, category=OpenBBWarning) + if message := init_response.get( # type: ignore + "error" + ) or init_response.get( # type: ignore + "message" + ): + warnings.warn(message=str(message), category=OpenBBWarning) return [] - symbol = response.url.parts[-2] - tag = response.url.parts[-1] + symbol = response.url.parts[-2] # type: ignore + tag = response.url.parts[-1] # type: ignore - all_data: list = init_response.get("historical_data", []) + all_data: List = init_response.get("historical_data", []) # type: ignore all_data = [{**item, "symbol": symbol, "tag": tag} for item in all_data] - next_page = init_response.get("next_page", None) + next_page = init_response.get("next_page", None) # type: ignore while next_page: - url = response.url.update_query(next_page=next_page).human_repr() + url = response.url.update_query( # type: ignore + next_page=next_page + ).human_repr() response_data = await session.get_json(url) - if message := response_data.get("error") or response_data.get( + if message := response_data.get("error") or response_data.get( # type: ignore "message" ): warnings.warn(message=message, category=OpenBBWarning) return [] - symbol = response.url.parts[-2] - tag = response_data.url.parts[-1] + symbol = response.url.parts[-2] # type: ignore + tag = response_data.url.parts[-1] # type: ignore - response_data = response_data.get("historical_data", []) + response_data = response_data.get("historical_data", []) # type: ignore response_data = [ {**item, "symbol": symbol, "tag": tag} for item in response_data ] all_data.extend(response_data) - next_page = response_data.get("next_page", None) + next_page = response_data.get("next_page", None) # type: ignore return all_data @@ -128,7 +136,7 @@ async def callback( @staticmethod def transform_data( - query: IntrinioHistoricalAttributesQueryParams, # pylint: disable=unused-argument + query: IntrinioHistoricalAttributesQueryParams, data: List[Dict], **kwargs: Any, ) -> List[IntrinioHistoricalAttributesData]: diff --git a/openbb_platform/providers/intrinio/openbb_intrinio/models/latest_attributes.py b/openbb_platform/providers/intrinio/openbb_intrinio/models/latest_attributes.py index ca635744259a..55cf7bc685db 100644 --- a/openbb_platform/providers/intrinio/openbb_intrinio/models/latest_attributes.py +++ b/openbb_platform/providers/intrinio/openbb_intrinio/models/latest_attributes.py @@ -57,7 +57,7 @@ async def aextract_data( base_url = "https://api-v2.intrinio.com/companies" def generate_url(symbol: str, tag: str) -> str: - """Returns the url for the given symbol and tag.""" + """Return the url for the given symbol and tag.""" return f"{base_url}/{symbol}/data_point/{tag}?api_key={api_key}" async def callback(response: ClientResponse, _: Any) -> Dict: @@ -68,7 +68,8 @@ async def callback(response: ClientResponse, _: Any) -> Dict: "error" in response_data or "message" in response_data ): warnings.warn( - message=response_data.get("error") or response_data.get("message"), + message=str(response_data.get("error")) + or str(response_data.get("message")), category=OpenBBWarning, ) return {} diff --git a/openbb_platform/providers/intrinio/openbb_intrinio/models/price_target_consensus.py b/openbb_platform/providers/intrinio/openbb_intrinio/models/price_target_consensus.py index a82695dc0961..fcf1a99c4a47 100644 --- a/openbb_platform/providers/intrinio/openbb_intrinio/models/price_target_consensus.py +++ b/openbb_platform/providers/intrinio/openbb_intrinio/models/price_target_consensus.py @@ -128,7 +128,7 @@ async def get_one(symbol): return results async def fetch_callback(response, session): - """Callback for pagination.""" + """Use callback for pagination.""" data = await response.json() messages = data.get("messages") if messages: @@ -162,7 +162,6 @@ def transform_data( **kwargs: Any, ) -> List[IntrinioPriceTargetConsensusData]: """Transform the raw data into the standard format.""" - symbols = query.symbol.split(",") if query.symbol else [] results: List[IntrinioPriceTargetConsensusData] = [] for item in sorted( # type: ignore diff --git a/openbb_platform/providers/intrinio/openbb_intrinio/utils/helpers.py b/openbb_platform/providers/intrinio/openbb_intrinio/utils/helpers.py index 83126a65809a..572a0ce63931 100644 --- a/openbb_platform/providers/intrinio/openbb_intrinio/utils/helpers.py +++ b/openbb_platform/providers/intrinio/openbb_intrinio/utils/helpers.py @@ -59,7 +59,7 @@ def request(url: str) -> BasicResponse: async def response_callback( response: ClientResponse, _: ClientSession ) -> Union[dict, List[dict]]: - """Callback for async_request.""" + """Use callback for async_request.""" data = await response.json() if isinstance(data, dict) and response.status != 200: diff --git a/openbb_platform/providers/intrinio/tests/__init__.py b/openbb_platform/providers/intrinio/tests/__init__.py index e69de29bb2d1..36c3ae93b8f5 100644 --- a/openbb_platform/providers/intrinio/tests/__init__.py +++ b/openbb_platform/providers/intrinio/tests/__init__.py @@ -0,0 +1 @@ +"""Intrinio tests.""" diff --git a/openbb_platform/providers/intrinio/tests/test_intrinio_fetchers.py b/openbb_platform/providers/intrinio/tests/test_intrinio_fetchers.py index 2aaacba666b3..8ec7382d8674 100644 --- a/openbb_platform/providers/intrinio/tests/test_intrinio_fetchers.py +++ b/openbb_platform/providers/intrinio/tests/test_intrinio_fetchers.py @@ -1,3 +1,5 @@ +"""Test Intrinio fetchers.""" + from datetime import date from unittest import mock @@ -63,6 +65,7 @@ @pytest.fixture(scope="module") def vcr_config(): + """VCR configuration.""" return { "filter_headers": [("User-Agent", None)], "filter_query_parameters": [ @@ -79,6 +82,7 @@ def vcr_config(): @pytest.fixture(autouse=True, scope="module") def mock_cpu_count(): + """Mock the cpu_count function so recording works.""" with mock.patch( "os.cpu_count" ) as mock_cpu_count: # pylint: disable=redefined-outer-name @@ -88,6 +92,7 @@ def mock_cpu_count(): @pytest.mark.record_http def test_intrinio_equity_historical_fetcher(credentials=test_credentials): + """Test equity historical fetcher.""" params = { "symbol": "AAPL", "start_date": date(2023, 1, 1), @@ -102,6 +107,7 @@ def test_intrinio_equity_historical_fetcher(credentials=test_credentials): @pytest.mark.record_http def test_intrinio_currency_pairs_fetcher(credentials=test_credentials): + """Test currency pairs fetcher.""" params = {} fetcher = IntrinioCurrencyPairsFetcher() @@ -111,6 +117,7 @@ def test_intrinio_currency_pairs_fetcher(credentials=test_credentials): @pytest.mark.record_http def test_intrinio_company_news_fetcher(credentials=test_credentials): + """Test company news fetcher.""" params = {"symbol": "AAPL"} fetcher = IntrinioCompanyNewsFetcher() @@ -120,6 +127,7 @@ def test_intrinio_company_news_fetcher(credentials=test_credentials): @pytest.mark.record_http def test_intrinio_world_news_fetcher(credentials=test_credentials): + """Test world news fetcher.""" params = {} fetcher = IntrinioWorldNewsFetcher() @@ -129,6 +137,7 @@ def test_intrinio_world_news_fetcher(credentials=test_credentials): @pytest.mark.record_http def test_intrinio_equity_quote_fetcher(credentials=test_credentials): + """Test equity quote fetcher.""" params = {"symbol": "AAPL"} fetcher = IntrinioEquityQuoteFetcher() @@ -138,6 +147,7 @@ def test_intrinio_equity_quote_fetcher(credentials=test_credentials): @pytest.mark.record_http def test_intrinio_options_chains_fetcher(credentials=test_credentials): + """Test options chains fetcher.""" params = {"symbol": "AAPL", "date": date(2023, 9, 15)} fetcher = IntrinioOptionsChainsFetcher() @@ -147,6 +157,7 @@ def test_intrinio_options_chains_fetcher(credentials=test_credentials): @pytest.mark.record_http def test_intrinio_options_unusual_fetcher(credentials=test_credentials): + """Test options unusual fetcher.""" params = { "source": "delayed", "trade_type": "block", @@ -162,6 +173,7 @@ def test_intrinio_options_unusual_fetcher(credentials=test_credentials): @pytest.mark.record_http def test_intrinio_balance_sheet_fetcher(credentials=test_credentials): + """Test balance sheet fetcher.""" params = {"symbol": "AAPL"} fetcher = IntrinioBalanceSheetFetcher() @@ -171,6 +183,7 @@ def test_intrinio_balance_sheet_fetcher(credentials=test_credentials): @pytest.mark.record_http def test_intrinio_cash_flow_statement_fetcher(credentials=test_credentials): + """Test cash flow statement fetcher.""" params = {"symbol": "AAPL"} fetcher = IntrinioCashFlowStatementFetcher() result = fetcher.test(params, credentials) @@ -179,6 +192,7 @@ def test_intrinio_cash_flow_statement_fetcher(credentials=test_credentials): @pytest.mark.record_http def test_intrinio_income_statement_fetcher(credentials=test_credentials): + """Test income statement fetcher.""" params = {"symbol": "AAPL"} fetcher = IntrinioIncomeStatementFetcher() @@ -188,6 +202,7 @@ def test_intrinio_income_statement_fetcher(credentials=test_credentials): @pytest.mark.record_http def test_intrinio_fred_series_fetcher(credentials=test_credentials): + """Test fred series fetcher.""" params = { "symbol": "$GDP", "start_date": date(2022, 9, 20), @@ -201,6 +216,7 @@ def test_intrinio_fred_series_fetcher(credentials=test_credentials): @pytest.mark.record_http def test_intrinio_calendar_ipo_fetcher(credentials=test_credentials): + """Test calendar IPO fetcher.""" params = {"status": "upcoming"} fetcher = IntrinioCalendarIpoFetcher() @@ -210,6 +226,7 @@ def test_intrinio_calendar_ipo_fetcher(credentials=test_credentials): @pytest.mark.record_http def test_intrinio_search_attributes(credentials=test_credentials): + """Test search attributes fetcher.""" params = {"query": "ebit"} fetcher = IntrinioSearchAttributesFetcher() @@ -219,6 +236,7 @@ def test_intrinio_search_attributes(credentials=test_credentials): @pytest.mark.record_http def test_intrinio_historical_attributes(credentials=test_credentials): + """Test historical attributes fetcher.""" params = { "provider": "intrinio", "symbol": "AAPL,MSFT", @@ -238,6 +256,7 @@ def test_intrinio_historical_attributes(credentials=test_credentials): @pytest.mark.record_http def test_intrinio_latest_attributes(credentials=test_credentials): + """Test latest attributes fetcher.""" params = { "provider": "intrinio", "symbol": "AAPL,MSFT", @@ -251,6 +270,7 @@ def test_intrinio_latest_attributes(credentials=test_credentials): @pytest.mark.record_http def test_intrinio_equity_info_fetcher(credentials=test_credentials): + """Test equity info fetcher.""" params = {"symbol": "AAPL"} fetcher = IntrinioEquityInfoFetcher() @@ -260,6 +280,7 @@ def test_intrinio_equity_info_fetcher(credentials=test_credentials): @pytest.mark.record_http def test_intrinio_market_indices_fetcher(credentials=test_credentials): + """Test market indices fetcher.""" params = { "symbol": "$DJI", "tag": "level", @@ -274,6 +295,7 @@ def test_intrinio_market_indices_fetcher(credentials=test_credentials): @pytest.mark.record_http def test_intrinio_index_historical_fetcher(credentials=test_credentials): + """Test index historical fetcher.""" params = { "symbol": "DJI", "start_date": date(2024, 1, 1), @@ -287,6 +309,7 @@ def test_intrinio_index_historical_fetcher(credentials=test_credentials): @pytest.mark.record_http def test_intrinio_historical_dividends_fetcher(credentials=test_credentials): + """Test historical dividends fetcher.""" params = { "symbol": "AAPL", "start_date": date(2023, 1, 1), @@ -300,6 +323,7 @@ def test_intrinio_historical_dividends_fetcher(credentials=test_credentials): @pytest.mark.record_http def test_intrinio_company_filings_fetcher(credentials=test_credentials): + """Test company filings fetcher.""" params = { "symbol": "AAPL", "form_type": None, @@ -315,6 +339,7 @@ def test_intrinio_company_filings_fetcher(credentials=test_credentials): @pytest.mark.record_http def test_intrinio_insider_trading_fetcher(credentials=test_credentials): + """Test insider trading fetcher.""" params = { "symbol": "AAPL", "start_date": date(2023, 1, 1), @@ -338,6 +363,7 @@ def test_intrinio_insider_trading_fetcher(credentials=test_credentials): @pytest.mark.record_http def test_intrinio_key_metrics_fetcher(credentials=test_credentials): + """Test key metrics fetcher.""" params = {"symbol": "AAPL"} fetcher = IntrinioKeyMetricsFetcher() @@ -347,6 +373,7 @@ def test_intrinio_key_metrics_fetcher(credentials=test_credentials): @pytest.mark.record_http def test_intrinio_share_statistics_fetcher(credentials=test_credentials): + """Test share statistics fetcher.""" params = {"symbol": "AAPL"} fetcher = IntrinioShareStatisticsFetcher() @@ -356,6 +383,7 @@ def test_intrinio_share_statistics_fetcher(credentials=test_credentials): @pytest.mark.record_http def test_intrinio_equity_search_fetcher(credentials=test_credentials): + """Test equity search fetcher.""" params = {"query": "gold", "limit": 100} fetcher = IntrinioEquitySearchFetcher() @@ -365,6 +393,7 @@ def test_intrinio_equity_search_fetcher(credentials=test_credentials): @pytest.mark.record_http def test_intrinio_financial_ratios_fetcher(credentials=test_credentials): + """Test financial ratios fetcher.""" params = {"symbol": "AAPL", "period": "annual", "limit": 2, "use_cache": False} fetcher = IntrinioFinancialRatiosFetcher() @@ -374,6 +403,7 @@ def test_intrinio_financial_ratios_fetcher(credentials=test_credentials): @pytest.mark.record_http def test_intrinio_reported_financials_fetcher(credentials=test_credentials): + """Test reported financials fetcher.""" params = { "symbol": "AAPL", "statement_type": "cash", @@ -388,6 +418,7 @@ def test_intrinio_reported_financials_fetcher(credentials=test_credentials): @pytest.mark.record_http def test_intrinio_etf_search_fetcher(credentials=test_credentials): + """Test etf search fetcher.""" params = {"query": "factor", "exchange": "bats"} fetcher = IntrinioEtfSearchFetcher() @@ -397,6 +428,7 @@ def test_intrinio_etf_search_fetcher(credentials=test_credentials): @pytest.mark.record_http def test_intrinio_etf_info_fetcher(credentials=test_credentials): + """Test etf info fetcher.""" params = {"symbol": "DJIA,SPY,GOVT"} fetcher = IntrinioEtfInfoFetcher() @@ -406,6 +438,7 @@ def test_intrinio_etf_info_fetcher(credentials=test_credentials): @pytest.mark.record_http def test_intrinio_etf_holdings_fetcher(credentials=test_credentials): + """Test etf holdings fetcher.""" params = {"symbol": "DJIA"} fetcher = IntrinioEtfHoldingsFetcher() @@ -415,6 +448,7 @@ def test_intrinio_etf_holdings_fetcher(credentials=test_credentials): @pytest.mark.record_http def test_intrinio_etf_price_performance_fetcher(credentials=test_credentials): + """Test etf price performance fetcher.""" params = {"symbol": "SPY:US"} fetcher = IntrinioEtfPricePerformanceFetcher() @@ -424,6 +458,7 @@ def test_intrinio_etf_price_performance_fetcher(credentials=test_credentials): @pytest.mark.record_http def test_intrinio_market_snapshots_fetcher(credentials=test_credentials): + """Test market snapshots fetcher.""" params = {"date": date(2022, 6, 30)} fetcher = IntrinioMarketSnapshotsFetcher() @@ -433,6 +468,7 @@ def test_intrinio_market_snapshots_fetcher(credentials=test_credentials): @pytest.mark.record_http def test_intrinio_forward_eps_estimates_fetcher(credentials=test_credentials): + """Test forward EPS estimates fetcher.""" params = {"symbol": "AAPL"} fetcher = IntrinioForwardEpsEstimatesFetcher() @@ -442,6 +478,7 @@ def test_intrinio_forward_eps_estimates_fetcher(credentials=test_credentials): @pytest.mark.record_http def test_intrinio_forward_sales_estimates_fetcher(credentials=test_credentials): + """Test forward sales estimates fetcher.""" params = {"symbol": "AAPL"} fetcher = IntrinioForwardSalesEstimatesFetcher() @@ -451,6 +488,7 @@ def test_intrinio_forward_sales_estimates_fetcher(credentials=test_credentials): @pytest.mark.record_http def test_intrinio_price_target_consensus_fetcher(credentials=test_credentials): + """Test price target consensus fetcher.""" params = {"symbol": "AAPL"} fetcher = IntrinioPriceTargetConsensusFetcher() diff --git a/openbb_platform/providers/nasdaq/__init__.py b/openbb_platform/providers/nasdaq/__init__.py index e69de29bb2d1..32980449cbc3 100644 --- a/openbb_platform/providers/nasdaq/__init__.py +++ b/openbb_platform/providers/nasdaq/__init__.py @@ -0,0 +1 @@ +"""NASDAQ provider.""" diff --git a/openbb_platform/providers/nasdaq/openbb_nasdaq/models/__init__.py b/openbb_platform/providers/nasdaq/openbb_nasdaq/models/__init__.py index e69de29bb2d1..cb477918ea66 100644 --- a/openbb_platform/providers/nasdaq/openbb_nasdaq/models/__init__.py +++ b/openbb_platform/providers/nasdaq/openbb_nasdaq/models/__init__.py @@ -0,0 +1 @@ +"""NASDAQ provider data models.""" diff --git a/openbb_platform/providers/nasdaq/openbb_nasdaq/models/calendar_dividend.py b/openbb_platform/providers/nasdaq/openbb_nasdaq/models/calendar_dividend.py index 1e96673b9d28..201e55714f84 100644 --- a/openbb_platform/providers/nasdaq/openbb_nasdaq/models/calendar_dividend.py +++ b/openbb_platform/providers/nasdaq/openbb_nasdaq/models/calendar_dividend.py @@ -50,6 +50,7 @@ class NasdaqCalendarDividendData(CalendarDividendData): ) @classmethod def validate_date(cls, v: str): + """Validate the date.""" v = v.replace("N/A", "") return datetime.strptime(v, "%m/%d/%Y").date() if v else None diff --git a/openbb_platform/providers/nasdaq/openbb_nasdaq/models/cot.py b/openbb_platform/providers/nasdaq/openbb_nasdaq/models/cot.py index f0ee0b72f1c4..7fbaa956b5c5 100644 --- a/openbb_platform/providers/nasdaq/openbb_nasdaq/models/cot.py +++ b/openbb_platform/providers/nasdaq/openbb_nasdaq/models/cot.py @@ -85,8 +85,7 @@ class NasdaqCotData(COTData): @field_validator("date", mode="before", check_fields=False) def date_validate(cls, v): # pylint: disable=E0213 - """Return the datetime object from the date string""" - + """Return the datetime object from the date string.""" return datetime.strptime(v, "%Y-%m-%d").date() @@ -95,6 +94,7 @@ class NasdaqCotFetcher(Fetcher[NasdaqCotQueryParams, List[NasdaqCotData]]): @staticmethod def transform_query(params: Dict[str, Any]) -> NasdaqCotQueryParams: + """Transform the query parameters.""" return NasdaqCotQueryParams(**params) @staticmethod @@ -103,6 +103,7 @@ def extract_data( credentials: Optional[Dict[str, str]], **kwargs: Any, ) -> List[Dict]: + """Extract the data from the Nasdaq Data Link API.""" api_key = credentials.get("nasdaq_api_key") if credentials else "" # The "code" can be an exact name, a symbol, or a CFTC series code. @@ -174,4 +175,5 @@ def transform_data( data: List[Dict], **kwargs: Any, ) -> List[NasdaqCotData]: + """Transform the data.""" return [NasdaqCotData.model_validate(d) for d in data] diff --git a/openbb_platform/providers/nasdaq/openbb_nasdaq/models/cot_search.py b/openbb_platform/providers/nasdaq/openbb_nasdaq/models/cot_search.py index 820a86eb55e4..a642a3c34396 100644 --- a/openbb_platform/providers/nasdaq/openbb_nasdaq/models/cot_search.py +++ b/openbb_platform/providers/nasdaq/openbb_nasdaq/models/cot_search.py @@ -10,6 +10,8 @@ ) from openbb_nasdaq.utils.series_ids import CFTC +# pylint: disable=W0613 + class NasdaqCotSearchQueryParams(CotSearchQueryParams): """Nasdaq CFTC Commitment of Traders Reports Search Query. @@ -31,6 +33,7 @@ class NasdaqCotSearchFetcher( @staticmethod def transform_query(params: Dict[str, Any]) -> NasdaqCotSearchQueryParams: + """Transform the query params.""" return NasdaqCotSearchQueryParams(**params) @staticmethod @@ -60,4 +63,5 @@ def transform_data( data: List[Dict], **kwargs: Any, ) -> List[NasdaqCotSearchData]: + """Transform the data.""" return [NasdaqCotSearchData.model_validate(d) for d in data] diff --git a/openbb_platform/providers/nasdaq/openbb_nasdaq/utils/__init__.py b/openbb_platform/providers/nasdaq/openbb_nasdaq/utils/__init__.py index e69de29bb2d1..25cbd0e00fae 100644 --- a/openbb_platform/providers/nasdaq/openbb_nasdaq/utils/__init__.py +++ b/openbb_platform/providers/nasdaq/openbb_nasdaq/utils/__init__.py @@ -0,0 +1 @@ +"""NASDAQ provider utils.""" diff --git a/openbb_platform/providers/nasdaq/tests/__init__.py b/openbb_platform/providers/nasdaq/tests/__init__.py index e69de29bb2d1..60bd86abf47d 100644 --- a/openbb_platform/providers/nasdaq/tests/__init__.py +++ b/openbb_platform/providers/nasdaq/tests/__init__.py @@ -0,0 +1 @@ +"""NASDAQ provider tests.""" diff --git a/openbb_platform/providers/nasdaq/tests/test_nasdaq_fetchers.py b/openbb_platform/providers/nasdaq/tests/test_nasdaq_fetchers.py index 095763d5015e..9a3adc506b8c 100644 --- a/openbb_platform/providers/nasdaq/tests/test_nasdaq_fetchers.py +++ b/openbb_platform/providers/nasdaq/tests/test_nasdaq_fetchers.py @@ -1,3 +1,5 @@ +"""Tests for the Nasdaq fetchers.""" + import datetime import pytest @@ -21,6 +23,7 @@ @pytest.fixture(scope="module") def vcr_config(): + """VCR configuration.""" return { "filter_headers": [ ("User-Agent", None), @@ -36,6 +39,7 @@ def vcr_config(): @pytest.mark.record_http def test_nasdaq_equity_search_fetcher(credentials=test_credentials): + """Test the Nasdaq Equity Search fetcher.""" params = {"query": "", "is_etf": True, "use_cache": False} fetcher = NasdaqEquitySearchFetcher() @@ -45,6 +49,7 @@ def test_nasdaq_equity_search_fetcher(credentials=test_credentials): @pytest.mark.record_http def test_nasdaq_economic_calendar_fetcher(credentials=test_credentials): + """Test the Nasdaq Economic Calendar fetcher.""" params = { "start_date": datetime.date(2023, 11, 3), "end_date": datetime.date(2023, 11, 3), @@ -57,6 +62,7 @@ def test_nasdaq_economic_calendar_fetcher(credentials=test_credentials): @pytest.mark.record_http def test_nasdaq_calendar_dividend_fetcher(credentials=test_credentials): + """Test the Nasdaq Calendar Dividend fetcher.""" params = { "start_date": datetime.date(2023, 11, 6), "end_date": datetime.date(2023, 11, 6), @@ -69,6 +75,7 @@ def test_nasdaq_calendar_dividend_fetcher(credentials=test_credentials): @pytest.mark.record_http def test_nasdaq_calendar_ipo_fetcher(credentials=test_credentials): + """Test the Nasdaq Calendar IPO fetcher.""" params = { "start_date": datetime.date(2023, 11, 1), "end_date": datetime.date(2023, 11, 30), @@ -82,6 +89,7 @@ def test_nasdaq_calendar_ipo_fetcher(credentials=test_credentials): @pytest.mark.record_http def test_nasdaq_top_retail_fetcher(credentials=test_credentials): + """Test the Nasdaq Top Retail fetcher.""" params = {} fetcher = NasdaqTopRetailFetcher() @@ -91,6 +99,7 @@ def test_nasdaq_top_retail_fetcher(credentials=test_credentials): @pytest.mark.record_http def test_nasdaq_sp500_multiples_fetcher(credentials=test_credentials): + """Test the Nasdaq SP500 Multiples fetcher.""" params = {} fetcher = NasdaqSP500MultiplesFetcher() @@ -100,6 +109,7 @@ def test_nasdaq_sp500_multiples_fetcher(credentials=test_credentials): @pytest.mark.record_http def test_nasdaq_cot_fetcher(credentials=test_credentials): + """Test the Nasdaq COT fetcher.""" params = {} fetcher = NasdaqCotFetcher() @@ -108,6 +118,7 @@ def test_nasdaq_cot_fetcher(credentials=test_credentials): def test_nasdaq_cot_search_fetcher(credentials=test_credentials): + """Test the Nasdaq COT Search fetcher.""" params = {} fetcher = NasdaqCotSearchFetcher() @@ -117,6 +128,7 @@ def test_nasdaq_cot_search_fetcher(credentials=test_credentials): @pytest.mark.record_http def test_nasdaq_calendar_earnings_fetcher(credentials=test_credentials): + """Test the Nasdaq Calendar Earnings fetcher.""" params = { "start_date": datetime.date(2023, 11, 1), "end_date": datetime.date(2023, 11, 30), @@ -129,6 +141,7 @@ def test_nasdaq_calendar_earnings_fetcher(credentials=test_credentials): @pytest.mark.record_http def test_nasdaq_historical_dividends_fetcher(credentials=test_credentials): + """Test the Nasdaq Historical Dividends fetcher.""" params = {"symbol": "AAPL"} fetcher = NasdaqHistoricalDividendsFetcher() @@ -138,6 +151,7 @@ def test_nasdaq_historical_dividends_fetcher(credentials=test_credentials): @pytest.mark.record_http def test_nasdaq_lbma_fixing_fetcher(credentials=test_credentials): + """Test the Nasdaq LBMA Fixing fetcher.""" params = {"asset": "gold"} fetcher = NasdaqLbmaFixingFetcher() diff --git a/openbb_platform/providers/oecd/__init__.py b/openbb_platform/providers/oecd/__init__.py index e69de29bb2d1..782328221349 100644 --- a/openbb_platform/providers/oecd/__init__.py +++ b/openbb_platform/providers/oecd/__init__.py @@ -0,0 +1 @@ +"""OECD Provider for OpenBB Platform.""" diff --git a/openbb_platform/providers/oecd/openbb_oecd/utils/helpers.py b/openbb_platform/providers/oecd/openbb_oecd/utils/helpers.py index 61e5475137d4..3e11609ef3ec 100644 --- a/openbb_platform/providers/oecd/openbb_oecd/utils/helpers.py +++ b/openbb_platform/providers/oecd/openbb_oecd/utils/helpers.py @@ -1,3 +1,5 @@ +"""OECD helper functions.""" + import ssl from datetime import date from io import StringIO @@ -20,14 +22,16 @@ class CustomHttpAdapter(requests.adapters.HTTPAdapter): - # "Transport adapter" that allows us to use custom ssl_context. + """Transport adapter" that allows us to use custom ssl_context.""" def __init__(self, ssl_context=None, **kwargs): + """Initialize the adapter with a custom ssl_context.""" self.ssl_context = ssl_context super().__init__(**kwargs) # pylint: disable=arguments-differ def init_poolmanager(self, connections, maxsize, block=False): + """Initialize the poolmanager with a custom ssl_context.""" self.poolmanager = urllib3.poolmanager.PoolManager( # pylint: disable=attribute-defined-outside-init num_pools=connections, maxsize=maxsize, @@ -40,7 +44,7 @@ def init_poolmanager(self, connections, maxsize, block=False): def get_legacy_session(): - """Stackoverflow code to create a custom session.""" + """Create a custom session.""" ctx = ssl.create_default_context(ssl.Purpose.SERVER_AUTH) ctx.options |= 0x4 # OP_LEGACY_SERVER_CONNECT session = requests.Session() @@ -64,9 +68,9 @@ def fetch_data(url: str, csv_kwargs: Optional[Dict] = None, **kwargs: Any) -> Da def oecd_xml_to_df(xml_string: str) -> DataFrame: - """Helper function to parse the OECD XML and return a dataframe. + """Parse the OECD XML and return a dataframe. - Parameters + Parameters ---------- xml_string : str A string containing the OECD XML data. @@ -108,7 +112,7 @@ def oecd_xml_to_df(xml_string: str) -> DataFrame: def parse_url(url: str) -> DataFrame: - """Helper function to parse the SDMX url and return a dataframe. + """Parse the SDMX url and return a dataframe. Parameters ---------- @@ -193,7 +197,7 @@ def write_to_cache(cache_str: str, data: DataFrame, cache_method: str) -> None: def query_dict_to_path(query_dict: dict) -> str: - """Convert the query dict into something usable for writing file""" + """Convert the query dict into something usable for writing file.""" items = sorted(query_dict.items()) key_parts = [f"{key}_{value}" for key, value in items] return "-".join(key_parts).replace("/", "_").replace(" ", "_") @@ -206,8 +210,7 @@ def get_possibly_cached_data( cache_method: str = "csv", skip_cache: bool = False, ) -> DataFrame: - """ - Retrieve data from a given URL or from the cache if available and valid. + """Retrieve data from a given URL or from the cache if available and valid. Parameters ---------- @@ -225,8 +228,9 @@ def get_possibly_cached_data( DataFrame A Pandas DataFrame containing the fetched or cached data. """ - - base_cache = f"{cache}/{function}_{query_dict_to_path(query_dict)}" + base_cache = ( + f"{cache}/{function}_{query_dict_to_path(query_dict if query_dict else {})}" + ) if cache_method == "parquet": cache_path = base_cache + ".parquet" elif cache_method == "csv": @@ -248,7 +252,7 @@ def get_possibly_cached_data( def oecd_date_to_python_date(input_date: Union[str, int]) -> date: - """Darrens good idea to make the dates filterable""" + """Use Darrens good idea to make the dates filterable.""" input_date = str(input_date) if "Q" in input_date: return to_datetime(input_date).to_period("Q").to_timestamp("Q").date() diff --git a/openbb_platform/providers/oecd/tests/test_oecd_fetchers.py b/openbb_platform/providers/oecd/tests/test_oecd_fetchers.py index 2bfd968f7c1a..c1e0dc618ea7 100644 --- a/openbb_platform/providers/oecd/tests/test_oecd_fetchers.py +++ b/openbb_platform/providers/oecd/tests/test_oecd_fetchers.py @@ -1,3 +1,5 @@ +"""Test the OECD fetchers.""" + import datetime import pytest @@ -17,6 +19,7 @@ @pytest.fixture(scope="module") def vcr_config(): + """VCR configuration.""" return { "filter_headers": [("User-Agent", None)], "filter_query_parameters": [ @@ -27,6 +30,7 @@ def vcr_config(): @pytest.mark.record_http def test_oecd_nominal_gdp_fetcher(credentials=test_credentials): + """Test the OECD Nominal GDP fetcher.""" params = { "start_date": datetime.date(2020, 1, 1), "end_date": datetime.date(2023, 6, 6), @@ -39,6 +43,7 @@ def test_oecd_nominal_gdp_fetcher(credentials=test_credentials): @pytest.mark.record_http def test_oecd_real_gdp_fetcher(credentials=test_credentials): + """Test the OECD Real GDP fetcher.""" params = { "start_date": datetime.date(2020, 1, 1), "end_date": datetime.date(2023, 6, 6), @@ -50,6 +55,7 @@ def test_oecd_real_gdp_fetcher(credentials=test_credentials): @pytest.mark.record_http def test_oecd_forecast_gdp_fetcher(credentials=test_credentials): + """Test the OECD GDP Forecast fetcher.""" params = { "start_date": datetime.date(2020, 1, 1), "end_date": datetime.date(2023, 6, 6), @@ -62,6 +68,7 @@ def test_oecd_forecast_gdp_fetcher(credentials=test_credentials): @pytest.mark.record_http def test_oecd_unemployment_fetcher(credentials=test_credentials): + """Test the OECD Unemployment Rate fetcher.""" params = { "start_date": datetime.date(2023, 1, 1), "end_date": datetime.date(2023, 6, 6), @@ -74,6 +81,7 @@ def test_oecd_unemployment_fetcher(credentials=test_credentials): @pytest.mark.record_http def test_oecdcli_fetcher(credentials=test_credentials): + """Test the OECD Composite Leading Indicator fetcher.""" params = { "start_date": datetime.date(2023, 1, 1), "end_date": datetime.date(2023, 6, 6), @@ -86,6 +94,7 @@ def test_oecdcli_fetcher(credentials=test_credentials): @pytest.mark.record_http def test_oecdstir_fetcher(credentials=test_credentials): + """Test the OECD Short Term Interest Rate fetcher.""" params = { "start_date": datetime.date(2023, 1, 1), "end_date": datetime.date(2023, 6, 6), @@ -98,6 +107,7 @@ def test_oecdstir_fetcher(credentials=test_credentials): @pytest.mark.record_http def test_oecdltir_fetcher(credentials=test_credentials): + """Test the OECD Long Term Interest Rate fetcher.""" params = { "start_date": datetime.date(2023, 1, 1), "end_date": datetime.date(2023, 6, 6), diff --git a/openbb_platform/providers/polygon/__init__.py b/openbb_platform/providers/polygon/__init__.py index e69de29bb2d1..058a541bd210 100644 --- a/openbb_platform/providers/polygon/__init__.py +++ b/openbb_platform/providers/polygon/__init__.py @@ -0,0 +1 @@ +"""Polygon Provider init.""" diff --git a/openbb_platform/providers/polygon/openbb_polygon/models/__init__.py b/openbb_platform/providers/polygon/openbb_polygon/models/__init__.py index e69de29bb2d1..8062aa0a1f18 100644 --- a/openbb_platform/providers/polygon/openbb_polygon/models/__init__.py +++ b/openbb_platform/providers/polygon/openbb_polygon/models/__init__.py @@ -0,0 +1 @@ +"""OpenBB Polygon provider data models.""" diff --git a/openbb_platform/providers/polygon/openbb_polygon/utils/__init__.py b/openbb_platform/providers/polygon/openbb_polygon/utils/__init__.py index e69de29bb2d1..23bbc3b80cba 100644 --- a/openbb_platform/providers/polygon/openbb_polygon/utils/__init__.py +++ b/openbb_platform/providers/polygon/openbb_polygon/utils/__init__.py @@ -0,0 +1 @@ +"""OpenBB Polygon utils.""" diff --git a/openbb_platform/providers/polygon/openbb_polygon/utils/helpers.py b/openbb_platform/providers/polygon/openbb_polygon/utils/helpers.py index bc7f160f1823..c2e4b3a0a205 100644 --- a/openbb_platform/providers/polygon/openbb_polygon/utils/helpers.py +++ b/openbb_platform/providers/polygon/openbb_polygon/utils/helpers.py @@ -2,7 +2,7 @@ import json from io import StringIO -from typing import Any, List, Optional, Tuple, TypeVar, Union +from typing import Any, Dict, List, Optional, Tuple, TypeVar, Union from openbb_core.provider.utils.errors import EmptyDataError from openbb_core.provider.utils.helpers import ( @@ -31,16 +31,17 @@ def json(self) -> dict: def request(url: str) -> BasicResponse: - """ - Request function for PyScript. Pass in Method and make sure to await. + """Request function for PyScript. + + Pass in Method and make sure to await. - Parameters: - ----------- + Parameters + ---------- url: str URL to make request to - Return: - ------- + Return + ------ response: BasicRequest BasicRequest object with status_code and text attributes """ @@ -54,8 +55,8 @@ def request(url: str) -> BasicResponse: async def response_callback( response: ClientResponse, _: ClientSession ) -> Union[dict, List[dict]]: - """Callback for make_request.""" - data: dict = await response.json() + """Use callback for make_request.""" + data: Dict = await response.json() # type: ignore if response.status != 200: message = data.get("error", None) or data.get("message", None) @@ -79,15 +80,15 @@ async def get_data_many( ) -> List[dict]: """Get data from Polygon endpoint and convert to list of schemas. - Parameters: - ----------- + Parameters + ---------- url: str The URL to get the data from. sub_dict: Optional[str] The sub-dictionary to use. - Returns: - -------- + Returns + ------- List[dict] Dictionary of data. """ diff --git a/openbb_platform/providers/polygon/tests/test_polygon_fetchers.py b/openbb_platform/providers/polygon/tests/test_polygon_fetchers.py index ebc51911a319..034334f21953 100644 --- a/openbb_platform/providers/polygon/tests/test_polygon_fetchers.py +++ b/openbb_platform/providers/polygon/tests/test_polygon_fetchers.py @@ -1,3 +1,5 @@ +"""Test the Polygon fetchers.""" + from datetime import date import pytest @@ -26,6 +28,7 @@ @pytest.fixture(scope="module") def vcr_config(): + """VCR configuration.""" return { "filter_headers": [("User-Agent", None)], "filter_query_parameters": [ @@ -36,6 +39,7 @@ def vcr_config(): @pytest.mark.record_http def test_polygon_equity_historical_fetcher(credentials=test_credentials): + """Test the Polygon Equity Historical fetcher.""" params = { "symbol": "AAPL", "start_date": date(2023, 1, 1), @@ -50,6 +54,7 @@ def test_polygon_equity_historical_fetcher(credentials=test_credentials): @pytest.mark.record_http def test_polygon_market_indices_fetcher(credentials=test_credentials): + """Test the Polygon Market Indices fetcher.""" params = { "symbol": "NDX", "start_date": date(2023, 1, 1), @@ -63,6 +68,7 @@ def test_polygon_market_indices_fetcher(credentials=test_credentials): @pytest.mark.record_http def test_polygon_index_historical_fetcher(credentials=test_credentials): + """Test the Polygon Index Historical fetcher.""" params = { "symbol": "NDX", "start_date": date(2023, 1, 1), @@ -76,6 +82,7 @@ def test_polygon_index_historical_fetcher(credentials=test_credentials): @pytest.mark.record_http def test_polygon_company_news_fetcher(credentials=test_credentials): + """Test the Polygon Company News fetcher.""" params = {"symbol": "AAPL"} fetcher = PolygonCompanyNewsFetcher() @@ -85,6 +92,7 @@ def test_polygon_company_news_fetcher(credentials=test_credentials): @pytest.mark.record_http def test_polygon_balance_sheet_fetcher(credentials=test_credentials): + """Test the Polygon Balance Sheet fetcher.""" params = {"symbol": "AAPL"} fetcher = PolygonBalanceSheetFetcher() @@ -94,6 +102,7 @@ def test_polygon_balance_sheet_fetcher(credentials=test_credentials): @pytest.mark.record_http def test_polygon_income_statement_fetcher(credentials=test_credentials): + """Test the Polygon Income Statement fetcher.""" params = {"symbol": "AAPL"} fetcher = PolygonIncomeStatementFetcher() @@ -103,6 +112,7 @@ def test_polygon_income_statement_fetcher(credentials=test_credentials): @pytest.mark.record_http def test_polygon_cash_flow_statement_fetcher(credentials=test_credentials): + """Test the Polygon Cash Flow Statement fetcher.""" params = {"symbol": "AAPL"} fetcher = PolygonCashFlowStatementFetcher() @@ -112,6 +122,7 @@ def test_polygon_cash_flow_statement_fetcher(credentials=test_credentials): @pytest.mark.record_http def test_polygon_crypto_historical_fetcher(credentials=test_credentials): + """Test the Polygon Crypto Historical fetcher.""" params = { "symbol": "BTCUSD", "start_date": date(2023, 1, 1), @@ -125,6 +136,7 @@ def test_polygon_crypto_historical_fetcher(credentials=test_credentials): @pytest.mark.record_http def test_polygon_currency_historical_fetcher(credentials=test_credentials): + """Test the Polygon Currency Historical fetcher.""" params = { "symbol": "EURUSD", "start_date": date(2023, 1, 1), @@ -138,6 +150,7 @@ def test_polygon_currency_historical_fetcher(credentials=test_credentials): @pytest.mark.record_http def test_polygon_currency_pairs_fetcher(credentials=test_credentials): + """Test the Polygon Currency Pairs fetcher.""" params = {"date": date(2023, 1, 1)} fetcher = PolygonCurrencyPairsFetcher() @@ -147,6 +160,7 @@ def test_polygon_currency_pairs_fetcher(credentials=test_credentials): @pytest.mark.record_http def test_polygon_equity_nbbo_fetcher(credentials=test_credentials): + """Test the Polygon Equity NBBO fetcher.""" params = {"symbol": "SPY", "limit": 1000} fetcher = PolygonEquityNBBOFetcher() @@ -156,6 +170,7 @@ def test_polygon_equity_nbbo_fetcher(credentials=test_credentials): @pytest.mark.record_http def test_polygon_market_snapshots_fetcher(credentials=test_credentials): + """Test the Polygon Market Snapshots fetcher.""" params = {} fetcher = PolygonMarketSnapshotsFetcher() diff --git a/openbb_platform/providers/sec/__init__.py b/openbb_platform/providers/sec/__init__.py index e69de29bb2d1..58f6e5aeaa49 100644 --- a/openbb_platform/providers/sec/__init__.py +++ b/openbb_platform/providers/sec/__init__.py @@ -0,0 +1 @@ +"""SEC Provider.""" diff --git a/openbb_platform/providers/sec/openbb_sec/models/__init__.py b/openbb_platform/providers/sec/openbb_sec/models/__init__.py index e69de29bb2d1..a2faa26a3ad2 100644 --- a/openbb_platform/providers/sec/openbb_sec/models/__init__.py +++ b/openbb_platform/providers/sec/openbb_sec/models/__init__.py @@ -0,0 +1 @@ +"""SEC Provider Models.""" diff --git a/openbb_platform/providers/sec/openbb_sec/models/company_filings.py b/openbb_platform/providers/sec/openbb_sec/models/company_filings.py index 1108ad19419d..85d98ff1b0c4 100644 --- a/openbb_platform/providers/sec/openbb_sec/models/company_filings.py +++ b/openbb_platform/providers/sec/openbb_sec/models/company_filings.py @@ -145,7 +145,7 @@ def extract_data( credentials: Optional[Dict[str, str]], **kwargs: Any, ) -> List[Dict]: - """Extracts the data from the SEC endpoint.""" + """Extract the data from the SEC endpoint.""" filings = pd.DataFrame() if query.symbol and not query.cik: @@ -156,12 +156,12 @@ def extract_data( return [] # The leading 0s need to be inserted but are typically removed from the data to store as an integer. - if len(query.cik) != 10: + if len(query.cik) != 10: # type: ignore cik_: str = "" - temp = 10 - len(query.cik) + temp = 10 - len(query.cik) # type: ignore for i in range(temp): cik_ = cik_ + "0" - query.cik = cik_ + query.cik + query.cik = cik_ + str(query.cik) # type: ignore url = f"https://data.sec.gov/submissions/CIK{query.cik}.json" r = ( @@ -236,5 +236,5 @@ def extract_data( def transform_data( query: SecCompanyFilingsQueryParams, data: List[Dict], **kwargs: Any ) -> List[SecCompanyFilingsData]: - """Transforms the data.""" + """Transform the data.""" return [SecCompanyFilingsData.model_validate(d) for d in data] diff --git a/openbb_platform/providers/sec/openbb_sec/models/equity_ftd.py b/openbb_platform/providers/sec/openbb_sec/models/equity_ftd.py index ad8039bbc91a..097a73d3a4d6 100644 --- a/openbb_platform/providers/sec/openbb_sec/models/equity_ftd.py +++ b/openbb_platform/providers/sec/openbb_sec/models/equity_ftd.py @@ -56,7 +56,7 @@ def extract_data( credentials: Optional[Dict[str, str]], **kwargs: Any, ) -> List[Dict]: - """Extracts the data from the SEC website.""" + """Extract the data from the SEC website.""" results = [] limit = query.limit if query.limit is not None and query.limit > 0 else 0 symbol = query.symbol.upper() @@ -83,5 +83,5 @@ def extract_data( def transform_data( query: SecEquityFtdQueryParams, data: List[Dict], **kwargs: Any ) -> List[SecEquityFtdData]: - """Transforms the data to the standard format.""" + """Transform the data to the standard format.""" return [SecEquityFtdData.model_validate(d) for d in data] diff --git a/openbb_platform/providers/sec/openbb_sec/utils/__init__.py b/openbb_platform/providers/sec/openbb_sec/utils/__init__.py index e69de29bb2d1..e63a6cc9ef44 100644 --- a/openbb_platform/providers/sec/openbb_sec/utils/__init__.py +++ b/openbb_platform/providers/sec/openbb_sec/utils/__init__.py @@ -0,0 +1 @@ +"""SEC Utils.""" diff --git a/openbb_platform/providers/sec/openbb_sec/utils/helpers.py b/openbb_platform/providers/sec/openbb_sec/utils/helpers.py index 1b150ddd95be..e8622aac7f5f 100644 --- a/openbb_platform/providers/sec/openbb_sec/utils/helpers.py +++ b/openbb_platform/providers/sec/openbb_sec/utils/helpers.py @@ -1,4 +1,4 @@ -"""SEC Helpers module""" +"""SEC Helpers module.""" # pylint: skip-file from datetime import timedelta @@ -30,7 +30,8 @@ def get_all_companies(use_cache: bool = True) -> pd.DataFrame: - """Gets all company names, tickers, and CIK numbers registered with the SEC. + """Get all company names, tickers, and CIK numbers registered with the SEC. + Companies are sorted by market cap. Returns @@ -41,7 +42,6 @@ def get_all_companies(use_cache: bool = True) -> pd.DataFrame: ------- >>> tickers = get_all_companies() """ - url = "https://www.sec.gov/files/company_tickers.json" r = ( @@ -56,8 +56,7 @@ def get_all_companies(use_cache: bool = True) -> pd.DataFrame: def get_all_ciks(use_cache: bool = True) -> pd.DataFrame: - """Gets a list of entity names and their CIK number.""" - + """Get a list of entity names and their CIK number.""" HEADERS = { "User-Agent": "my real company name definitelynot@fakecompany.com", "Accept-Encoding": "gzip, deflate", @@ -86,8 +85,7 @@ def get_all_ciks(use_cache: bool = True) -> pd.DataFrame: def get_mf_and_etf_map(use_cache: bool = True) -> pd.DataFrame: - """Returns the CIK number of a ticker symbol for querying the SEC API.""" - + """Return the CIK number of a ticker symbol for querying the SEC API.""" symbols = pd.DataFrame() url = "https://www.sec.gov/files/company_tickers_mf.json" @@ -110,8 +108,7 @@ def search_institutions(keyword: str, use_cache: bool = True) -> pd.DataFrame: def symbol_map(symbol: str, use_cache: bool = True) -> str: - """Returns the CIK number of a ticker symbol for querying the SEC API.""" - + """Return the CIK number of a ticker symbol for querying the SEC API.""" symbol = symbol.upper().replace(".", "-") symbols = get_all_companies(use_cache=use_cache) @@ -130,8 +127,7 @@ def symbol_map(symbol: str, use_cache: bool = True) -> str: def cik_map(cik: int, use_cache: bool = True) -> str: - """ - Converts a CIK number to a ticker symbol. Enter CIK as an integer with no leading zeros. + """Convert a CIK number to a ticker symbol. Enter CIK as an integer with no leading zeros. Function is not meant for funds. @@ -164,7 +160,8 @@ def get_frame( instantaneous: bool = False, use_cache: bool = True, ) -> Dict: - """ + """Get a frame of data for a given fact. + The xbrl/frames API aggregates one fact for each reporting entity that is last filed that most closely fits the calendrical period requested. @@ -197,7 +194,6 @@ def get_frame( Facts where units are, "shares": WeightedAverageNumberOfDilutedSharesOutstanding """ - if fact in ["WeightedAverageNumberOfDilutedSharesOutstanding"]: units = "shares" @@ -237,6 +233,7 @@ def get_frame( def get_schema_filelist(query: str = "", url: str = "") -> List: + """Get a list of schema files from the SEC website.""" results: List = [] url = url if url else f"https://xbrl.fasb.org/us-gaap/{query}" _url = url @@ -300,7 +297,6 @@ def download_zip_file(url, symbol: Optional[str] = None) -> List[Dict]: def get_ftd_urls() -> Dict: """Get Fails-to-Deliver Data URLs.""" - results = {} position = None key = "title" @@ -330,8 +326,8 @@ def get_ftd_urls() -> Dict: def get_series_id( symbol: Optional[str] = None, cik: Optional[str] = None, use_cache: bool = True ): - """ - This function maps the fund to the series and class IDs for validating the correct filing. + """Map the fund to the series and class IDs for validating the correct filing. + For an exact match, use a symbol. """ symbol = symbol if symbol else "" @@ -359,8 +355,7 @@ def get_series_id( def get_nport_candidates(symbol: str, use_cache: bool = True) -> List[Dict]: - """Gets a list of all NPORT-P filings for a given fund's symbol.""" - + """Get a list of all NPORT-P filings for a given fund's symbol.""" results = [] _series_id = get_series_id(symbol, use_cache=use_cache) try: diff --git a/openbb_platform/providers/sec/openbb_sec/utils/parse_13f.py b/openbb_platform/providers/sec/openbb_sec/utils/parse_13f.py index eda060c17bc6..5fedbaf3858d 100644 --- a/openbb_platform/providers/sec/openbb_sec/utils/parse_13f.py +++ b/openbb_platform/providers/sec/openbb_sec/utils/parse_13f.py @@ -1,6 +1,6 @@ """Utility functions for parsing SEC Form 13F-HR.""" -from typing import Dict, Optional +from typing import Any, Dict, Optional import xmltodict from bs4 import BeautifulSoup @@ -22,7 +22,7 @@ def date_to_quarter_end(date: str) -> str: def get_13f_candidates(symbol: Optional[str] = None, cik: Optional[str] = None): """Get the 13F-HR filings for a given symbol or CIK.""" fetcher = SecCompanyFilingsFetcher() - params = {} + params: Dict[str, Any] = {} if cik is not None: params["cik"] = str(cik) if symbol is not None: @@ -46,7 +46,7 @@ def get_13f_candidates(symbol: Optional[str] = None, cik: Optional[str] = None): async def complete_submission_callback(response, _): - """Callback function for processing the response object.""" + """Use callback function for processing the response object.""" if response.status == 200: return await response.text() raise RuntimeError(f"Request failed with status code {response.status}") @@ -106,7 +106,7 @@ def get_period_ending(filing_str: str): async def parse_13f_hr(filing: str): - """Parses a 13F-HR filing from the Complete Submission TXT file string.""" + """Parse a 13F-HR filing from the Complete Submission TXT file string.""" data = DataFrame() # Check if the input string is a URL diff --git a/openbb_platform/providers/sec/tests/__init__.py b/openbb_platform/providers/sec/tests/__init__.py index e69de29bb2d1..9c38549cbb39 100644 --- a/openbb_platform/providers/sec/tests/__init__.py +++ b/openbb_platform/providers/sec/tests/__init__.py @@ -0,0 +1 @@ +"""SEC tests.""" diff --git a/openbb_platform/providers/sec/tests/test_sec_fetchers.py b/openbb_platform/providers/sec/tests/test_sec_fetchers.py index e7f7f2df02c5..60db05d26d3a 100644 --- a/openbb_platform/providers/sec/tests/test_sec_fetchers.py +++ b/openbb_platform/providers/sec/tests/test_sec_fetchers.py @@ -1,3 +1,5 @@ +"""Tests for the SEC fetchers.""" + import pytest from openbb_core.app.service.user_service import UserService from openbb_sec.models.cik_map import SecCikMapFetcher @@ -17,6 +19,7 @@ @pytest.fixture(scope="module") def vcr_config(): + """VCR configuration.""" return { "filter_headers": [("User-Agent", None)], "filter_query_parameters": [ @@ -27,6 +30,7 @@ def vcr_config(): @pytest.mark.record_http def test_sec_etf_holdings_fetcher(credentials=test_credentials): + """Test the SEC ETF Holdings fetcher.""" params = {"symbol": "TQQQ", "use_cache": False} fetcher = SecEtfHoldingsFetcher() @@ -36,6 +40,7 @@ def test_sec_etf_holdings_fetcher(credentials=test_credentials): @pytest.mark.record_http def test_sec_sic_search_fetcher(credentials=test_credentials): + """Test the SEC SIC Search fetcher.""" params = {"query": "oil", "use_cache": False} fetcher = SecSicSearchFetcher() @@ -45,6 +50,7 @@ def test_sec_sic_search_fetcher(credentials=test_credentials): @pytest.mark.record_http def test_sec_symbol_map_fetcher(credentials=test_credentials): + """Test the SEC Symbol Map fetcher.""" params = {"query": "0000909832"} fetcher = SecSymbolMapFetcher() @@ -54,6 +60,7 @@ def test_sec_symbol_map_fetcher(credentials=test_credentials): @pytest.mark.record_http def test_sec_equity_ftd_fetcher(credentials=test_credentials): + """Test the SEC Equity FTD fetcher.""" params = {"symbol": "AAPL", "limit": 1} fetcher = SecEquityFtdFetcher() @@ -63,6 +70,7 @@ def test_sec_equity_ftd_fetcher(credentials=test_credentials): @pytest.mark.record_http def test_sec_equity_search_fetcher(credentials=test_credentials): + """Test the SEC Equity Search fetcher.""" params = {"query": "trust", "use_cache": False} fetcher = SecEquitySearchFetcher() @@ -72,6 +80,7 @@ def test_sec_equity_search_fetcher(credentials=test_credentials): @pytest.mark.record_http def test_sec_company_filings_fetcher(credentials=test_credentials): + """Test the SEC Company Filings fetcher.""" params = {"symbol": "AAPL", "type": "10-K", "use_cache": False} fetcher = SecCompanyFilingsFetcher() @@ -81,6 +90,7 @@ def test_sec_company_filings_fetcher(credentials=test_credentials): @pytest.mark.record_http def test_sec_institutions_search_fetcher(credentials=test_credentials): + """Test the SEC Institutions Search fetcher.""" params = {"query": "Investment Trust", "use_cache": False} fetcher = SecInstitutionsSearchFetcher() @@ -90,6 +100,7 @@ def test_sec_institutions_search_fetcher(credentials=test_credentials): @pytest.mark.record_http def test_sec_schema_files_fetcher(credentials=test_credentials): + """Test the SEC Schema Files fetcher.""" params = {"query": "2022"} fetcher = SecSchemaFilesFetcher() @@ -99,6 +110,7 @@ def test_sec_schema_files_fetcher(credentials=test_credentials): @pytest.mark.record_http def test_sec_rss_litigation_fetcher(credentials=test_credentials): + """Test the SEC RSS Litigation fetcher.""" params = {} fetcher = SecRssLitigationFetcher() @@ -108,6 +120,7 @@ def test_sec_rss_litigation_fetcher(credentials=test_credentials): @pytest.mark.record_http def test_sec_cik_map_fetcher(credentials=test_credentials): + """Test the SEC CIK map fetcher.""" params = {"symbol": "OXY"} fetcher = SecCikMapFetcher() @@ -117,6 +130,7 @@ def test_sec_cik_map_fetcher(credentials=test_credentials): @pytest.mark.record_http def test_sec_form_13FHR_fetcher(credentials=test_credentials): + """Test the SEC Form 13FHR fetcher.""" params = {"symbol": "NVDA"} fetcher = SecForm13FHRFetcher() diff --git a/openbb_platform/providers/seeking_alpha/tests/__init__.py b/openbb_platform/providers/seeking_alpha/tests/__init__.py index e69de29bb2d1..47cf47b762cb 100644 --- a/openbb_platform/providers/seeking_alpha/tests/__init__.py +++ b/openbb_platform/providers/seeking_alpha/tests/__init__.py @@ -0,0 +1 @@ +"""Seeking Alpha provider tests.""" diff --git a/openbb_platform/providers/seeking_alpha/tests/test_seeking_alpha_fetchers.py b/openbb_platform/providers/seeking_alpha/tests/test_seeking_alpha_fetchers.py index fb89a5e02992..e279c044e00c 100644 --- a/openbb_platform/providers/seeking_alpha/tests/test_seeking_alpha_fetchers.py +++ b/openbb_platform/providers/seeking_alpha/tests/test_seeking_alpha_fetchers.py @@ -1,3 +1,5 @@ +"""Tests for the Seeking Alpha fetchers.""" + import pytest from openbb_core.app.service.user_service import UserService from openbb_seeking_alpha.models.upcoming_release_days import ( @@ -11,6 +13,7 @@ @pytest.fixture(scope="module") def vcr_config(): + """VCR configuration.""" return { "filter_headers": [("User-Agent", None)], "filter_query_parameters": [ @@ -21,6 +24,7 @@ def vcr_config(): @pytest.mark.record_http def test_sa_upcoming_release_days_fetcher(credentials=test_credentials): + """Test the Seeking Alpha Upcoming Release Days fetcher.""" params = {"limit": 5} fetcher = SAUpcomingReleaseDaysFetcher() diff --git a/openbb_platform/providers/stockgrid/__init__.py b/openbb_platform/providers/stockgrid/__init__.py index e69de29bb2d1..61d62436f153 100644 --- a/openbb_platform/providers/stockgrid/__init__.py +++ b/openbb_platform/providers/stockgrid/__init__.py @@ -0,0 +1 @@ +"""Stockgrid provider.""" diff --git a/openbb_platform/providers/stockgrid/tests/test_stockgrid_fetchers.py b/openbb_platform/providers/stockgrid/tests/test_stockgrid_fetchers.py index cdc591c080de..a06c0e619ea1 100644 --- a/openbb_platform/providers/stockgrid/tests/test_stockgrid_fetchers.py +++ b/openbb_platform/providers/stockgrid/tests/test_stockgrid_fetchers.py @@ -1,3 +1,5 @@ +"""Test stockgrid fetchers.""" + import pytest from openbb_core.app.service.user_service import UserService from openbb_stockgrid.models.short_volume import StockgridShortVolumeFetcher @@ -9,6 +11,7 @@ @pytest.fixture(scope="module") def vcr_config(): + """VCR configuration.""" return { "filter_headers": [("User-Agent", None)], "filter_query_parameters": [ @@ -20,6 +23,7 @@ def vcr_config(): @pytest.mark.freeze_time("2023-11-08") @pytest.mark.record_http def test_stockgrid_short_volume_fetcher(credentials=test_credentials): + """Test short volume fetcher.""" params = {"symbol": "AAPL"} fetcher = StockgridShortVolumeFetcher() diff --git a/openbb_platform/providers/tests/__init__.py b/openbb_platform/providers/tests/__init__.py index e69de29bb2d1..bf8046d32a1c 100644 --- a/openbb_platform/providers/tests/__init__.py +++ b/openbb_platform/providers/tests/__init__.py @@ -0,0 +1 @@ +"""OpenBB Provider tests.""" diff --git a/openbb_platform/providers/tests/utils/__init__.py b/openbb_platform/providers/tests/utils/__init__.py index e69de29bb2d1..83831219db37 100644 --- a/openbb_platform/providers/tests/utils/__init__.py +++ b/openbb_platform/providers/tests/utils/__init__.py @@ -0,0 +1 @@ +"""Provider test utils.""" diff --git a/openbb_platform/providers/tiingo/__init__.py b/openbb_platform/providers/tiingo/__init__.py index e69de29bb2d1..da05810f5e9d 100644 --- a/openbb_platform/providers/tiingo/__init__.py +++ b/openbb_platform/providers/tiingo/__init__.py @@ -0,0 +1 @@ +"""Tiingo provider.""" diff --git a/openbb_platform/providers/tiingo/tests/test_tiingo_fetchers.py b/openbb_platform/providers/tiingo/tests/test_tiingo_fetchers.py index 24357f9e02e7..26dcddaf1df6 100644 --- a/openbb_platform/providers/tiingo/tests/test_tiingo_fetchers.py +++ b/openbb_platform/providers/tiingo/tests/test_tiingo_fetchers.py @@ -1,3 +1,5 @@ +"""Test Tiingo fetchers.""" + from datetime import date import pytest @@ -16,6 +18,7 @@ @pytest.fixture(scope="module") def vcr_config(): + """VCR configuration.""" return { "filter_headers": [("User-Agent", None)], "filter_query_parameters": [ @@ -26,6 +29,7 @@ def vcr_config(): @pytest.mark.record_http def test_tiingo_equity_historical_fetcher(credentials=test_credentials): + """Test Tiingo equity historical fetcher.""" params = { "symbol": "AAPL", "start_date": date(2023, 1, 1), @@ -39,6 +43,7 @@ def test_tiingo_equity_historical_fetcher(credentials=test_credentials): @pytest.mark.record_http def test_tiingo_company_news_fetcher(credentials=test_credentials): + """Test Tiingo company news fetcher.""" params = {"symbol": "AAPL,MSFT"} fetcher = TiingoCompanyNewsFetcher() @@ -48,6 +53,7 @@ def test_tiingo_company_news_fetcher(credentials=test_credentials): @pytest.mark.record_http def test_tiingo_world_news_fetcher(credentials=test_credentials): + """Test Tiingo world news fetcher.""" params = {"limit": 20} fetcher = TiingoWorldNewsFetcher() @@ -57,6 +63,7 @@ def test_tiingo_world_news_fetcher(credentials=test_credentials): @pytest.mark.record_http def test_tiingo_crypto_historical_fetcher(credentials=test_credentials): + """Test Tiingo crypto historical fetcher.""" params = { "symbol": "BTCUSD", "start_date": date(2023, 1, 1), @@ -70,6 +77,7 @@ def test_tiingo_crypto_historical_fetcher(credentials=test_credentials): @pytest.mark.record_http def test_tiingo_currency_historical_fetcher(credentials=test_credentials): + """Test Tiingo currency historical fetcher.""" params = { "symbol": "EURUSD", "start_date": date(2023, 1, 1), @@ -83,6 +91,7 @@ def test_tiingo_currency_historical_fetcher(credentials=test_credentials): @pytest.mark.record_http def test_tiingo_trailing_div_yield_fetcher(credentials=test_credentials): + """Test Tiingo trailing dividend yield fetcher.""" params = {"symbol": "SCHD"} fetcher = TiingoTrailingDivYieldFetcher() diff --git a/openbb_platform/providers/tmx/__init__.py b/openbb_platform/providers/tmx/__init__.py index e69de29bb2d1..ecfc13312a4d 100644 --- a/openbb_platform/providers/tmx/__init__.py +++ b/openbb_platform/providers/tmx/__init__.py @@ -0,0 +1 @@ +"""TMX Provider.""" diff --git a/openbb_platform/providers/tmx/openbb_tmx/models/__init__.py b/openbb_platform/providers/tmx/openbb_tmx/models/__init__.py index e69de29bb2d1..8810abcee396 100644 --- a/openbb_platform/providers/tmx/openbb_tmx/models/__init__.py +++ b/openbb_platform/providers/tmx/openbb_tmx/models/__init__.py @@ -0,0 +1 @@ +"""TMX Provider Models.""" diff --git a/openbb_platform/providers/tmx/openbb_tmx/models/calendar_earnings.py b/openbb_platform/providers/tmx/openbb_tmx/models/calendar_earnings.py index 0494f09d08bd..87082ce61300 100644 --- a/openbb_platform/providers/tmx/openbb_tmx/models/calendar_earnings.py +++ b/openbb_platform/providers/tmx/openbb_tmx/models/calendar_earnings.py @@ -1,4 +1,4 @@ -"""TMX Earnings Calendar Model""" +"""TMX Earnings Calendar Model.""" # pylint: disable=unused-argument import asyncio @@ -85,14 +85,12 @@ async def aextract_data( **kwargs: Any, ) -> List[Dict]: """Return the raw data from the TMX endpoint.""" - - results = [] - dates = [] + results: List[Dict] = [] user_agent = get_random_agent() dates = date_range(query.start_date, end=query.end_date) async def create_task(date, results): - """Creates a task for a single date in the range.""" + """Create a task for a single date in the range.""" data = [] date = date.strftime("%Y-%m-%d") payload = gql.get_earnings_date_payload.copy() diff --git a/openbb_platform/providers/tmx/openbb_tmx/models/company_news.py b/openbb_platform/providers/tmx/openbb_tmx/models/company_news.py index 4c8269ac2413..cc8fd504cdc4 100644 --- a/openbb_platform/providers/tmx/openbb_tmx/models/company_news.py +++ b/openbb_platform/providers/tmx/openbb_tmx/models/company_news.py @@ -26,9 +26,17 @@ class TmxCompanyNewsQueryParams(CompanyNewsQueryParams): default=1, description="The page number to start from. Use with limit." ) + @field_validator("symbol", mode="before") + @classmethod + def symbols_validate(cls, v): + """Validate the symbols.""" + if v is None: + raise ValueError("Symbol is a required field for TMX.") + return v + class TmxCompanyNewsData(CompanyNewsData): - """TMX Stock News Data""" + """TMX Stock News Data.""" __alias_dict__ = { "date": "datetime", @@ -63,12 +71,11 @@ async def aextract_data( ) -> List[Dict]: """Return the raw data from the TMX endpoint.""" user_agent = get_random_agent() - symbols = query.symbol.split(",") - results = [] + symbols = query.symbol.split(",") # type: ignore + results: List[Dict] = [] async def create_task(symbol, results): - """Makes a POST request to the TMX GraphQL endpoint for a single symbol.""" - + """Make a POST request to the TMX GraphQL endpoint for a single symbol.""" symbol = ( symbol.upper().replace(".TO", "").replace(".TSX", "").replace("-", ".") ) @@ -78,7 +85,7 @@ async def create_task(symbol, results): payload["variables"]["limit"] = query.limit payload["variables"]["locale"] = "en" url = "https://app-money.tmx.com/graphql" - data = {} + data: Dict = {} response = await get_data_from_gql( method="POST", url=url, diff --git a/openbb_platform/providers/tmx/openbb_tmx/models/equity_historical.py b/openbb_platform/providers/tmx/openbb_tmx/models/equity_historical.py index acc66c794496..f81c10e06f93 100644 --- a/openbb_platform/providers/tmx/openbb_tmx/models/equity_historical.py +++ b/openbb_platform/providers/tmx/openbb_tmx/models/equity_historical.py @@ -48,7 +48,7 @@ class TmxEquityHistoricalQueryParams(EquityHistoricalQueryParams): interval: Union[ Literal["1m", "2m", "5m", "15m", "30m", "60m", "1h", "1d", "1W", "1M"], str, int - ] = Field( + ] = Field( # type: ignore description=QUERY_DESCRIPTIONS.get("interval", "") + " Or, any integer (entered as a string) representing the number of minutes." + " Default is daily data." @@ -146,12 +146,11 @@ async def aextract_data( **kwargs: Any, ) -> List[Dict]: """Return the raw data from the TMX endpoint.""" - results: List[Dict] = [] symbols = query.symbol.split(",") async def create_task(symbol, results): - """Makes a POST request to the TMX GraphQL endpoint for a single ticker.""" + """Make a POST request to the TMX GraphQL endpoint for a single ticker.""" data: List[Dict] = [] # A different request is used for each type of interval. if query.interval == "day": @@ -199,7 +198,6 @@ def transform_data( **kwargs: Any, ) -> List[TmxEquityHistoricalData]: """Return the transformed data.""" - results = DataFrame(data) if results.empty or len(results) == 0: raise EmptyDataError() diff --git a/openbb_platform/providers/tmx/openbb_tmx/models/equity_profile.py b/openbb_platform/providers/tmx/openbb_tmx/models/equity_profile.py index 9627e25b7c66..ddce1445ef71 100644 --- a/openbb_platform/providers/tmx/openbb_tmx/models/equity_profile.py +++ b/openbb_platform/providers/tmx/openbb_tmx/models/equity_profile.py @@ -1,4 +1,4 @@ -"""TMX Equity Profile fetcher""" +"""TMX Equity Profile fetcher.""" # pylint: disable=unused-argument import asyncio @@ -84,18 +84,16 @@ async def aextract_data( **kwargs: Any, ) -> List[Dict]: """Return the raw data from the TMX endpoint.""" - symbols = query.symbol.split(",") # The list where the results will be stored and appended to. - results = [] + results: List[Dict] = [] user_agent = get_random_agent() url = "https://app-money.tmx.com/graphql" async def create_task(symbol: str, results) -> None: - """Makes a POST request to the TMX GraphQL endpoint for a single symbol.""" - + """Make a POST request to the TMX GraphQL endpoint for a single symbol.""" symbol = ( symbol.upper().replace("-", ".").replace(".TO", "").replace(".TSX", "") ) @@ -133,7 +131,6 @@ def transform_data( **kwargs: Any, ) -> List[TmxEquityProfileData]: """Return the transformed data.""" - # Get only the items associated with `equity.profile()`. items_list = [ "shortDescription", diff --git a/openbb_platform/providers/tmx/openbb_tmx/models/equity_quote.py b/openbb_platform/providers/tmx/openbb_tmx/models/equity_quote.py index 8edd26c60999..a97659e5f7a6 100644 --- a/openbb_platform/providers/tmx/openbb_tmx/models/equity_quote.py +++ b/openbb_platform/providers/tmx/openbb_tmx/models/equity_quote.py @@ -1,4 +1,4 @@ -"""TMX Equity Profile fetcher""" +"""TMX Equity Profile fetcher.""" # pylint: disable=unused-argument @@ -237,7 +237,7 @@ class TmxEquityQuoteData(EquityQuoteData): ) @classmethod def date_validate(cls, v): # pylint: disable=E0213 - """Return the datetime object from the date string""" + """Return the datetime object from the date string.""" if v: try: return datetime.strptime(v, "%Y-%m-%d").date() @@ -281,18 +281,16 @@ async def aextract_data( **kwargs: Any, ) -> List[Dict]: """Return the raw data from the TMX endpoint.""" - symbols = query.symbol.split(",") # The list where the results will be stored and appended to. - results = [] + results: List[Dict] = [] user_agent = get_random_agent() url = "https://app-money.tmx.com/graphql" async def create_task(symbol: str, results) -> None: - """Makes a POST request to the TMX GraphQL endpoint for a single symbol.""" - + """Make a POST request to the TMX GraphQL endpoint for a single symbol.""" symbol = ( symbol.upper().replace("-", ".").replace(".TO", "").replace(".TSX", "") ) @@ -332,7 +330,6 @@ def transform_data( **kwargs: Any, ) -> List[TmxEquityQuoteData]: """Return the transformed data.""" - # Remove the items associated with `equity.profile()`. items_list = [ "shortDescription", diff --git a/openbb_platform/providers/tmx/openbb_tmx/models/gainers.py b/openbb_platform/providers/tmx/openbb_tmx/models/gainers.py index 169a737201b0..461be6775afd 100644 --- a/openbb_platform/providers/tmx/openbb_tmx/models/gainers.py +++ b/openbb_platform/providers/tmx/openbb_tmx/models/gainers.py @@ -76,6 +76,7 @@ def normalize_percent(cls, v): @model_validator(mode="before") @classmethod def check_metric(cls, values): + """Check for missing metrics.""" for k, v in values.items(): if v is None or v == "-": values[k] = 0 @@ -104,7 +105,6 @@ async def aextract_data( **kwargs: Any, ) -> List[TmxGainersData]: """Return the raw data from the TMX endpoint.""" - user_agent = get_random_agent() payload = gql.get_stock_list_payload.copy() payload["variables"]["stockListId"] = STOCK_LISTS_DICT[query.category] diff --git a/openbb_platform/providers/tmx/openbb_tmx/models/index_constituents.py b/openbb_platform/providers/tmx/openbb_tmx/models/index_constituents.py index 915ebe03005f..9d299d3fa241 100644 --- a/openbb_platform/providers/tmx/openbb_tmx/models/index_constituents.py +++ b/openbb_platform/providers/tmx/openbb_tmx/models/index_constituents.py @@ -1,4 +1,4 @@ -"""TMX Index Constituents Model""" +"""TMX Index Constituents Model.""" # pylint: disable=unused-argument from typing import Any, Dict, List, Optional @@ -49,6 +49,8 @@ class TmxIndexConstituentsFetcher( List[TmxIndexConstituentsData], ] ): + """TMX Index Constituents Fetcher.""" + @staticmethod def transform_query(params: Dict[str, Any]) -> TmxIndexConstituentsQueryParams: """Transform the query.""" @@ -61,7 +63,6 @@ async def aextract_data( **kwargs: Any, ) -> Dict: """Return the raw data from the TMX endpoint.""" - url = "https://tmxinfoservices.com/files/indices/sptsx-indices.json" data = await get_data_from_url( diff --git a/openbb_platform/providers/tmx/openbb_tmx/models/index_snapshots.py b/openbb_platform/providers/tmx/openbb_tmx/models/index_snapshots.py index a57e030155ba..2052991fff7d 100644 --- a/openbb_platform/providers/tmx/openbb_tmx/models/index_snapshots.py +++ b/openbb_platform/providers/tmx/openbb_tmx/models/index_snapshots.py @@ -1,4 +1,4 @@ -"""TMX Index Snapshots Model""" +"""TMX Index Snapshots Model.""" # pylint: disable=unused-argument import json @@ -24,7 +24,7 @@ class TmxIndexSnapshotsQueryParams(IndexSnapshotsQueryParams): """TMX Index Snapshots Query Params.""" - region: Literal[None, "ca", "us"] = Field(default="ca") + region: Literal[None, "ca", "us"] = Field(default="ca") # type: ignore use_cache: bool = Field( default=True, description="Whether to use a cached request." @@ -151,6 +151,8 @@ class TmxIndexSnapshotsFetcher( List[TmxIndexSnapshotsData], ] ): + """TMX Index Snapshots Fetcher.""" + @staticmethod def transform_query(params: Dict[str, Any]) -> TmxIndexSnapshotsQueryParams: """Transform the query.""" diff --git a/openbb_platform/providers/tmx/openbb_tmx/models/insider_trading.py b/openbb_platform/providers/tmx/openbb_tmx/models/insider_trading.py index 831ae1107716..4764e5310c33 100644 --- a/openbb_platform/providers/tmx/openbb_tmx/models/insider_trading.py +++ b/openbb_platform/providers/tmx/openbb_tmx/models/insider_trading.py @@ -1,4 +1,4 @@ -"""TMX Insider Trading Model""" +"""TMX Insider Trading Model.""" # pylint: disable=unused-argument import json @@ -17,7 +17,7 @@ class TmxInsiderTradingQueryParams(InsiderTradingQueryParams): - """TMX Insider Trading Query Params""" + """TMX Insider Trading Query Params.""" summary: bool = Field( default=False, @@ -26,7 +26,7 @@ class TmxInsiderTradingQueryParams(InsiderTradingQueryParams): class TmxInsiderTradingData(InsiderTradingData): - """TMX Insider Trading Data""" + """TMX Insider Trading Data.""" period: str = Field( description="The period of the activity. Bucketed by three, six, and twelve months." @@ -66,6 +66,7 @@ class TmxInsiderTradingData(InsiderTradingData): @field_validator("period", mode="before", check_fields=False) @classmethod def period_to_snake_case(cls, v): + """Convert the period to snake case.""" return to_snake_case(v) if v else None @@ -89,7 +90,6 @@ async def aextract_data( **kwargs: Any, ) -> List[Dict]: """Return the raw data from the TMX endpoint.""" - results = [] user_agent = get_random_agent() symbol = ( diff --git a/openbb_platform/providers/tmx/openbb_tmx/utils/__init__.py b/openbb_platform/providers/tmx/openbb_tmx/utils/__init__.py index e69de29bb2d1..75323e86bd90 100644 --- a/openbb_platform/providers/tmx/openbb_tmx/utils/__init__.py +++ b/openbb_platform/providers/tmx/openbb_tmx/utils/__init__.py @@ -0,0 +1 @@ +"""TMX Provider Utils.""" diff --git a/openbb_platform/providers/tmx/openbb_tmx/utils/helpers.py b/openbb_platform/providers/tmx/openbb_tmx/utils/helpers.py index 6f31263e82f7..2ed84d0abb01 100644 --- a/openbb_platform/providers/tmx/openbb_tmx/utils/helpers.py +++ b/openbb_platform/providers/tmx/openbb_tmx/utils/helpers.py @@ -12,7 +12,7 @@ timedelta, ) from io import StringIO -from typing import Any, Dict, List, Literal, Optional +from typing import Any, Dict, List, Literal, Optional, Union import exchange_calendars as xcals import pandas as pd @@ -265,7 +265,7 @@ def get_random_agent() -> str: async def response_callback(response, _: Any): - """Callback for HTTP Client Response.""" + """Use callback for HTTP Client Response.""" content_type = response.headers.get("Content-Type", "") if "application/json" in content_type: return await response.json() @@ -296,7 +296,6 @@ async def get_data_from_url( async def get_data_from_gql(url: str, headers, data, **kwargs: Any) -> Any: """Make an asynchronous GraphQL request.""" - response = await amake_request( url=url, method="POST", @@ -310,7 +309,7 @@ async def get_data_from_gql(url: str, headers, data, **kwargs: Any) -> Any: def replace_values_in_list_of_dicts(data): - """Helper function to replace "NA" and "-" with None in a list of dictionaries.""" + """Replace "NA" and "-" with None in a list of dictionaries.""" for d in data: for k, v in d.items(): if isinstance(v, dict): @@ -329,7 +328,7 @@ def replace_values_in_list_of_dicts(data): def check_weekday(date) -> str: - """Helper function to check if the input date is a weekday, and if not, returns the next weekday. + """Check if the input date is a weekday, and if not, returns the next weekday. Parameters ---------- @@ -341,32 +340,27 @@ def check_weekday(date) -> str: str Date in YYYY-MM-DD format. If the date is a weekend, returns the date of the next weekday. """ - if pd.to_datetime(date).weekday() > 4: return next_workday(pd.to_datetime(date)).strftime("%Y-%m-%d") return date async def get_all_etfs(use_cache: bool = True) -> List[Dict]: - """ - Gets a summary of the TMX ETF universe. + """Get a summary of the TMX ETF universe. Returns ------- Dict Dictionary with all TMX-listed ETFs. """ - url = "https://dgr53wu9i7rmp.cloudfront.net/etfs/etfs.json" response = await get_data_from_url( url, use_cache=use_cache, backend=tmx_etfs_backend ) - if response is None: - raise RuntimeError( - f"There was a problem with the request. Could not get ETFs. -> {response.status_code}" - ) + if not response or response is None: + raise RuntimeError("There was a problem with the request. Could not get ETFs.") response = replace_values_in_list_of_dicts(response) @@ -403,8 +397,7 @@ async def get_all_etfs(use_cache: bool = True) -> List[Dict]: async def get_tmx_tickers( exchange: Literal["tsx", "tsxv"] = "tsx", use_cache: bool = True ) -> Dict: - """Gets a dictionary of either TSX or TSX-V symbols and names.""" - + """Get a dictionary of either TSX or TSX-V symbols and names.""" tsx_json_url = "https://www.tsx.com/json/company-directory/search" url = f"{tsx_json_url}/{exchange}/*" response = await get_data_from_url( @@ -420,7 +413,7 @@ async def get_tmx_tickers( async def get_all_tmx_companies(use_cache: bool = True) -> Dict: - """Merges TSX and TSX-V listings into a single dictionary.""" + """Merge TSX and TSX-V listings into a single dictionary.""" all_tmx = {} tsx_tickers = await get_tmx_tickers(use_cache=use_cache) tsxv_tickers = await get_tmx_tickers("tsxv", use_cache=use_cache) @@ -430,14 +423,13 @@ async def get_all_tmx_companies(use_cache: bool = True) -> Dict: async def get_all_options_tickers(use_cache: bool = True) -> pd.DataFrame: - """Returns a DataFrame with all valid ticker symbols.""" - + """Return a DataFrame with all valid ticker symbols.""" url = "https://www.m-x.ca/en/trading/data/options-list" r = await get_data_from_url(url, use_cache=use_cache, backend=tmx_companies_backend) - if r is None: - raise RuntimeError(f"Error with the request: {r.status_code}") + if r is None or r == []: + raise RuntimeError("Error with the request") # mypy: ignore options_listings = pd.read_html(StringIO(r)) listings = pd.concat(options_listings) @@ -456,8 +448,7 @@ async def get_all_options_tickers(use_cache: bool = True) -> pd.DataFrame: async def get_current_options(symbol: str, use_cache: bool = True) -> pd.DataFrame: - """Gets the current quotes for the complete options chain.""" - + """Get the current quotes for the complete options chain.""" SYMBOLS = await get_all_options_tickers(use_cache=use_cache) data = pd.DataFrame() symbol = symbol.upper() @@ -558,8 +549,7 @@ async def get_current_options(symbol: str, use_cache: bool = True) -> pd.DataFra async def download_eod_chains( symbol: str, date: Optional[dateType] = None, use_cache: bool = False ) -> pd.DataFrame: - """Downloads EOD chains data for a given symbol and date.""" - + """Download EOD chains data for a given symbol and date.""" symbol = symbol.upper() SYMBOLS = await get_all_options_tickers(use_cache=False) # Remove echange identifiers from the symbol. @@ -582,10 +572,10 @@ async def download_eod_chains( EOD_URL = BASE_URL + f"{symbol}" "&dnld=1#quotes" if date is not None: date = check_weekday(date) # type: ignore - if cal.is_session(date) is False: + if cal.is_session(date) is False: # type: ignore date = (pd.to_datetime(date) + timedelta(days=1)).strftime("%Y-%m-%d") # type: ignore date = check_weekday(date) # type: ignore - if cal.is_session(date=date) is False: + if cal.is_session(date=date) is False: # type: ignore date = (pd.to_datetime(date) + timedelta(days=1)).strftime("%Y-%m-%d") # type: ignore EOD_URL = ( @@ -717,8 +707,8 @@ async def get_company_filings( async def get_daily_price_history( symbol: str, - start_date: Optional[dateType] = None, - end_date: Optional[dateType] = None, + start_date: Optional[Union[str, dateType]] = None, + end_date: Optional[Union[str, dateType]] = None, adjustment: Literal[ "splits_only", "unadjusted", "splits_and_dividends" ] = "splits_only", @@ -834,21 +824,23 @@ async def try_again(): async def get_weekly_or_monthly_price_history( symbol: str, - start_date: Optional[dateType] = None, - end_date: Optional[dateType] = None, + start_date: Optional[Union[str, dateType]] = None, + end_date: Optional[Union[str, dateType]] = None, interval: Literal["month", "week"] = "month", ): """Get historical price data.""" - start_date = ( - datetime.strptime(start_date, "%Y-%m-%d") - if isinstance(start_date, str) - else start_date - ) - end_date = ( - datetime.strptime(end_date, "%Y-%m-%d") - if isinstance(end_date, str) - else end_date - ) + if start_date: + start_date = ( + datetime.strptime(start_date, "%Y-%m-%d") + if isinstance(start_date, str) + else start_date + ) + if end_date: + end_date = ( + datetime.strptime(end_date, "%Y-%m-%d") + if isinstance(end_date, str) + else end_date + ) user_agent = get_random_agent() results: List[Dict] = [] symbol = symbol.upper().replace("-", ".").replace(".TO", "").replace(".TSX", "") @@ -868,8 +860,14 @@ async def get_weekly_or_monthly_price_history( payload["variables"].pop("endDateTime") payload["variables"]["symbol"] = symbol payload["variables"]["freq"] = interval - payload["variables"]["end"] = end_date.strftime("%Y-%m-%d") - payload["variables"]["start"] = start_date.strftime("%Y-%m-%d") + payload["variables"]["end"] = ( + end_date.strftime("%Y-%m-%d") if isinstance(end_date, dateType) else end_date + ) + payload["variables"]["start"] = ( + start_date.strftime("%Y-%m-%d") + if isinstance(start_date, dateType) + else start_date + ) url = "https://app-money.tmx.com/graphql" data = await get_data_from_gql( method="POST", @@ -914,21 +912,23 @@ async def try_again(): async def get_intraday_price_history( symbol: str, - start_date: Optional[dateType] = None, - end_date: Optional[dateType] = None, + start_date: Optional[Union[str, dateType]] = None, + end_date: Optional[Union[str, dateType]] = None, interval: Optional[int] = 1, ): """Get historical price data.""" - start_date = ( - datetime.strptime(start_date, "%Y-%m-%d") - if isinstance(start_date, str) - else start_date - ) - end_date = ( - datetime.strptime(end_date, "%Y-%m-%d") - if isinstance(end_date, str) - else end_date - ) + if start_date: + start_date = ( + datetime.strptime(start_date, "%Y-%m-%d") + if isinstance(start_date, str) + else start_date + ) + if end_date: + end_date = ( + datetime.strptime(end_date, "%Y-%m-%d") + if isinstance(end_date, str) + else end_date + ) user_agent = get_random_agent() results: List[Dict] = [] symbol = symbol.upper().replace("-", ".").replace(".TO", "").replace(".TSX", "") @@ -941,11 +941,11 @@ async def get_intraday_price_history( # This is the first date of available intraday data. date_check = datetime(2022, 4, 12).date() start_date = max(start_date, date_check) - if end_date < date_check: + if end_date < date_check: # type: ignore end_date = datetime.now().date() # Generate a list of dates from start_date to end_date with a frequency of 3 weeks dates = list( - rrule.rrule(rrule.WEEKLY, interval=4, dtstart=start_date, until=end_date) + rrule.rrule(rrule.WEEKLY, interval=4, dtstart=start_date, until=end_date) # type: ignore ) if dates[-1] != end_date: @@ -1039,8 +1039,10 @@ async def try_again(): async def get_all_bonds(use_cache: bool = True) -> pd.DataFrame: - """Gets all bonds reference data published by CIRO. The complete list is approximately 70-100K securities.""" + """Get all bonds reference data published by CIRO. + The complete list is approximately 70-100K securities. + """ url = "https://bondtradedata.iiroc.ca/debtip/designatedbonds/list" response = await get_data_from_url( url, use_cache=use_cache, timeout=30, backend=tmx_bonds_backend diff --git a/openbb_platform/providers/tmx/tests/__init__.py b/openbb_platform/providers/tmx/tests/__init__.py index 8b137891791f..82c47774efc4 100644 --- a/openbb_platform/providers/tmx/tests/__init__.py +++ b/openbb_platform/providers/tmx/tests/__init__.py @@ -1 +1 @@ - +"""TMX Tests.""" diff --git a/openbb_platform/providers/tmx/tests/test_tmx_fetchers.py b/openbb_platform/providers/tmx/tests/test_tmx_fetchers.py index 652b0159defb..685da00dad2b 100644 --- a/openbb_platform/providers/tmx/tests/test_tmx_fetchers.py +++ b/openbb_platform/providers/tmx/tests/test_tmx_fetchers.py @@ -33,6 +33,7 @@ @pytest.fixture(scope="module") def vcr_config(): + """VCR configuration.""" return { "filter_headers": [("User-Agent", None)], "filter_query_parameters": [ @@ -43,6 +44,7 @@ def vcr_config(): @pytest.mark.record_http def test_tmx_equity_profile_fetcher(credentials=test_credentials): + """Test equity profile fetcher.""" params = {"symbol": "RY,NTR"} fetcher = TmxEquityProfileFetcher() @@ -52,6 +54,7 @@ def test_tmx_equity_profile_fetcher(credentials=test_credentials): @pytest.mark.record_http def test_tmx_equity_search_fetcher(credentials=test_credentials): + """Test equity search fetcher.""" params = {"query": "gold", "use_cache": False} fetcher = TmxEquitySearchFetcher() @@ -61,6 +64,7 @@ def test_tmx_equity_search_fetcher(credentials=test_credentials): @pytest.mark.record_http def test_tmx_available_indices_fetcher(credentials=test_credentials): + """Test available indices fetcher.""" params = {"use_cache": False} fetcher = TmxAvailableIndicesFetcher() @@ -70,6 +74,7 @@ def test_tmx_available_indices_fetcher(credentials=test_credentials): @pytest.mark.record_http def test_tmx_calendar_earnings_fetcher(credentials=test_credentials): + """Test calendar earnings fetcher.""" params = {"start_date": date(2023, 1, 2), "end_date": date(2023, 1, 31)} fetcher = TmxCalendarEarningsFetcher() @@ -79,6 +84,7 @@ def test_tmx_calendar_earnings_fetcher(credentials=test_credentials): @pytest.mark.record_http def test_tmx_company_filings_fetcher(credentials=test_credentials): + """Test company filings fetcher.""" params = { "symbol": "SHOP", "start_date": date(2023, 6, 30), @@ -92,6 +98,7 @@ def test_tmx_company_filings_fetcher(credentials=test_credentials): @pytest.mark.record_http def test_tmx_company_news_fetcher(credentials=test_credentials): + """Test company news fetcher.""" params = {"symbol": "SHOP", "limit": 5} fetcher = TmxCompanyNewsFetcher() @@ -101,6 +108,7 @@ def test_tmx_company_news_fetcher(credentials=test_credentials): @pytest.mark.record_http def test_tmx_equity_historical_fetcher(credentials=test_credentials): + """Test equity historical fetcher.""" params = { "symbol": "SHOP", "start_date": date(2022, 1, 1), @@ -114,6 +122,7 @@ def test_tmx_equity_historical_fetcher(credentials=test_credentials): @pytest.mark.record_http def test_tmx_equity_quote_fetcher(credentials=test_credentials): + """Test equity quote fetcher.""" params = {"symbol": "SHOP"} fetcher = TmxEquityQuoteFetcher() @@ -123,6 +132,7 @@ def test_tmx_equity_quote_fetcher(credentials=test_credentials): @pytest.mark.record_http def test_tmx_etf_countries_fetcher(credentials=test_credentials): + """Test ETF countries fetcher.""" params = {"symbol": "HXX", "use_cache": False} fetcher = TmxEtfCountriesFetcher() @@ -132,6 +142,7 @@ def test_tmx_etf_countries_fetcher(credentials=test_credentials): @pytest.mark.record_http def test_tmx_etf_holdings_fetcher(credentials=test_credentials): + """Test ETF holdings fetcher.""" params = {"symbol": "XIU", "use_cache": False} fetcher = TmxEtfHoldingsFetcher() @@ -141,6 +152,7 @@ def test_tmx_etf_holdings_fetcher(credentials=test_credentials): @pytest.mark.record_http def test_tmx_etf_info_fetcher(credentials=test_credentials): + """Test ETF info fetcher.""" params = {"symbol": "XIU", "use_cache": False} fetcher = TmxEtfInfoFetcher() @@ -150,6 +162,7 @@ def test_tmx_etf_info_fetcher(credentials=test_credentials): @pytest.mark.record_http def test_tmx_etf_search_fetcher(credentials=test_credentials): + """Test ETF search fetcher.""" params = {"query": "sector", "use_cache": False} fetcher = TmxEtfSearchFetcher() @@ -159,6 +172,7 @@ def test_tmx_etf_search_fetcher(credentials=test_credentials): @pytest.mark.record_http def test_tmx_etf_sectors_fetcher(credentials=test_credentials): + """Test ETF sectors fetcher.""" params = {"symbol": "XIU", "use_cache": False} fetcher = TmxEtfSectorsFetcher() @@ -168,6 +182,7 @@ def test_tmx_etf_sectors_fetcher(credentials=test_credentials): @pytest.mark.record_http def test_tmx_gainers_fetcher(credentials=test_credentials): + """Test gainers fetcher.""" params = {} fetcher = TmxGainersFetcher() @@ -177,6 +192,7 @@ def test_tmx_gainers_fetcher(credentials=test_credentials): @pytest.mark.record_http def test_tmx_historical_dividends_fetcher(credentials=test_credentials): + """Test historical dividends fetcher.""" params = {"symbol": "TD"} fetcher = TmxHistoricalDividendsFetcher() @@ -186,6 +202,7 @@ def test_tmx_historical_dividends_fetcher(credentials=test_credentials): @pytest.mark.record_http def test_tmx_index_constituents_fetcher(credentials=test_credentials): + """Test index constituents fetcher.""" params = {"symbol": "^TX60", "use_cache": False} fetcher = TmxIndexConstituentsFetcher() @@ -195,6 +212,7 @@ def test_tmx_index_constituents_fetcher(credentials=test_credentials): @pytest.mark.record_http def test_tmx_index_sectors_fetcher(credentials=test_credentials): + """Test index sectors fetcher.""" params = {"symbol": "^TSX", "use_cache": False} fetcher = TmxIndexSectorsFetcher() @@ -204,6 +222,7 @@ def test_tmx_index_sectors_fetcher(credentials=test_credentials): @pytest.mark.record_http def test_tmx_index_snapshots_fetcher(credentials=test_credentials): + """Test index snapshots fetcher.""" params = {"use_cache": False} fetcher = TmxIndexSnapshotsFetcher() @@ -213,6 +232,7 @@ def test_tmx_index_snapshots_fetcher(credentials=test_credentials): @pytest.mark.record_http def test_tmx_insider_trading_fetcher(credentials=test_credentials): + """Test insider trading fetcher.""" params = {"symbol": "SHOP", "summary": False} fetcher = TmxInsiderTradingFetcher() @@ -222,6 +242,7 @@ def test_tmx_insider_trading_fetcher(credentials=test_credentials): @pytest.mark.record_http def test_tmx_options_chains_fetcher(credentials=test_credentials): + """Test options chains fetcher.""" params = {"symbol": "SHOP", "use_cache": False} fetcher = TmxOptionsChainsFetcher() @@ -231,6 +252,7 @@ def test_tmx_options_chains_fetcher(credentials=test_credentials): @pytest.mark.record_http def test_tmx_price_target_consensus_fetcher(credentials=test_credentials): + """Test price target consensus fetcher.""" params = {"symbol": "SHOP"} fetcher = TmxPriceTargetConsensusFetcher() @@ -240,6 +262,7 @@ def test_tmx_price_target_consensus_fetcher(credentials=test_credentials): @pytest.mark.record_http def test_tmx_treasury_prices_fetcher(credentials=test_credentials): + """Test treasury prices fetcher.""" params = {"govt_type": "federal", "use_cache": False} fetcher = TmxTreasuryPricesFetcher() @@ -249,6 +272,7 @@ def test_tmx_treasury_prices_fetcher(credentials=test_credentials): @pytest.mark.record_http def test_tmx_bond_prices_fetcher(credentials=test_credentials): + """Test bond prices fetcher.""" params = {"use_cache": False, "coupon_rate_min": 4} fetcher = TmxBondPricesFetcher() diff --git a/openbb_platform/providers/tradier/__init__.py b/openbb_platform/providers/tradier/__init__.py index e69de29bb2d1..192b3be92d78 100644 --- a/openbb_platform/providers/tradier/__init__.py +++ b/openbb_platform/providers/tradier/__init__.py @@ -0,0 +1 @@ +"""Tradier provider.""" diff --git a/openbb_platform/providers/tradier/openbb_tradier/models/__init__.py b/openbb_platform/providers/tradier/openbb_tradier/models/__init__.py index e69de29bb2d1..7c35443f7b5d 100644 --- a/openbb_platform/providers/tradier/openbb_tradier/models/__init__.py +++ b/openbb_platform/providers/tradier/openbb_tradier/models/__init__.py @@ -0,0 +1 @@ +"""Tradier provider models.""" diff --git a/openbb_platform/providers/tradier/openbb_tradier/models/options_chains.py b/openbb_platform/providers/tradier/openbb_tradier/models/options_chains.py index ba4f728dda85..edbfbe7557c6 100644 --- a/openbb_platform/providers/tradier/openbb_tradier/models/options_chains.py +++ b/openbb_platform/providers/tradier/openbb_tradier/models/options_chains.py @@ -1,4 +1,4 @@ -"""Tradier Options Chains Model""" +"""Tradier Options Chains Model.""" # pylint: disable = unused-argument @@ -20,8 +20,7 @@ class TradierOptionsChainsQueryParams(OptionsChainsQueryParams): - """ - Tradier Options Chains Query. + """Tradier Options Chains Query. Source: https://documentation.tradier.com/brokerage-api/markets/get-options-chains @@ -31,7 +30,7 @@ class TradierOptionsChainsQueryParams(OptionsChainsQueryParams): class TradierOptionsChainsData(OptionsChainsData): - """Tradier Options Chains Data""" + """Tradier Options Chains Data.""" __alias_dict__ = { "expiration": "expiration_date", @@ -177,6 +176,7 @@ class TradierOptionsChainsFetcher( @staticmethod def transform_query(params: Dict[str, Any]) -> TradierOptionsChainsQueryParams: + """Transform the query parameters.""" return TradierOptionsChainsQueryParams(**params) @staticmethod @@ -185,8 +185,7 @@ async def aextract_data( credentials: Optional[Dict[str, str]], **kwargs: Any, ) -> List[Dict]: - """Return the raw data from the Tradier endpoint""" - + """Return the raw data from the Tradier endpoint.""" api_key = credentials.get("tradier_api_key") if credentials else "" sandbox = True @@ -216,7 +215,6 @@ async def aextract_data( # Get the expiration dates for the symbol so we can gather the chains data. async def get_expirations(symbol): """Get the expiration dates for the given symbol.""" - url = ( f"{BASE_URL}expirations?symbol={symbol}&includeAllRoots=true" "&strikes=false&contractSize=false&expirationType=false" diff --git a/openbb_platform/providers/tradier/openbb_tradier/utils/__init__.py b/openbb_platform/providers/tradier/openbb_tradier/utils/__init__.py index e69de29bb2d1..5b37a7ad2040 100644 --- a/openbb_platform/providers/tradier/openbb_tradier/utils/__init__.py +++ b/openbb_platform/providers/tradier/openbb_tradier/utils/__init__.py @@ -0,0 +1 @@ +"""Tradier provider utils.""" diff --git a/openbb_platform/providers/tradier/tests/__init__.py b/openbb_platform/providers/tradier/tests/__init__.py index e69de29bb2d1..f070d287ac6f 100644 --- a/openbb_platform/providers/tradier/tests/__init__.py +++ b/openbb_platform/providers/tradier/tests/__init__.py @@ -0,0 +1 @@ +"""Tradier provider tests.""" diff --git a/openbb_platform/providers/tradier/tests/test_tradier_fetchers.py b/openbb_platform/providers/tradier/tests/test_tradier_fetchers.py index 56a954db0be9..7eba9625148a 100644 --- a/openbb_platform/providers/tradier/tests/test_tradier_fetchers.py +++ b/openbb_platform/providers/tradier/tests/test_tradier_fetchers.py @@ -16,6 +16,7 @@ @pytest.fixture(scope="module") def vcr_config(): + """VCR configuration.""" return { "filter_headers": [ ("User-Agent", None), @@ -27,6 +28,7 @@ def vcr_config(): @pytest.mark.record_http def test_tradier_equity_historical_fetcher(credentials=test_credentials): + """Test the Tradier Equity Historical fetcher.""" params = { "start_date": datetime(2024, 2, 1).date(), "end_date": datetime(2024, 2, 29).date(), @@ -41,6 +43,7 @@ def test_tradier_equity_historical_fetcher(credentials=test_credentials): @pytest.mark.record_http def test_tradier_equity_search_fetcher(credentials=test_credentials): + """Test the Tradier Equity Search fetcher.""" params = { "query": "brookfield", "is_symbol": False, @@ -53,6 +56,7 @@ def test_tradier_equity_search_fetcher(credentials=test_credentials): @pytest.mark.record_http def test_tradier_equity_quote_fetcher(credentials=test_credentials): + """Test the Tradier Equity Quote fetcher.""" params = {"symbol": "SPY,SPY251219P00450000"} fetcher = TradierEquityQuoteFetcher() @@ -62,6 +66,7 @@ def test_tradier_equity_quote_fetcher(credentials=test_credentials): @pytest.mark.record_http def test_tradier_derivatives_options_chains_fetcher(credentials=test_credentials): + """Test the Tradier Derivatives Options Chains fetcher.""" params = {"symbol": "PLTR"} fetcher = TradierOptionsChainsFetcher() diff --git a/openbb_platform/providers/tradingeconomics/__init__.py b/openbb_platform/providers/tradingeconomics/__init__.py index e69de29bb2d1..7a4238e74bbc 100644 --- a/openbb_platform/providers/tradingeconomics/__init__.py +++ b/openbb_platform/providers/tradingeconomics/__init__.py @@ -0,0 +1 @@ +"""OpenBB Trading Economics Provider.""" diff --git a/openbb_platform/providers/tradingeconomics/openbb_tradingeconomics/models/economic_calendar.py b/openbb_platform/providers/tradingeconomics/openbb_tradingeconomics/models/economic_calendar.py index c0a14d17818b..97e1056633b8 100644 --- a/openbb_platform/providers/tradingeconomics/openbb_tradingeconomics/models/economic_calendar.py +++ b/openbb_platform/providers/tradingeconomics/openbb_tradingeconomics/models/economic_calendar.py @@ -62,6 +62,7 @@ def validate_country(cls, c: str): # pylint: disable=E0213 @field_validator("importance") @classmethod def importance_to_number(cls, v): + """Convert importance to number.""" string_to_value = {"Low": 1, "Medium": 2, "High": 3} return string_to_value.get(v, None) @@ -93,6 +94,7 @@ class TEEconomicCalendarData(EconomicCalendarData): @field_validator("date", mode="before") @classmethod def validate_date(cls, v: str) -> datetime: + """Validate the date.""" return to_datetime(v, utc=True) diff --git a/openbb_platform/providers/tradingeconomics/openbb_tradingeconomics/utils/countries.py b/openbb_platform/providers/tradingeconomics/openbb_tradingeconomics/utils/countries.py index c604b77e9c43..ab31a2be5791 100644 --- a/openbb_platform/providers/tradingeconomics/openbb_tradingeconomics/utils/countries.py +++ b/openbb_platform/providers/tradingeconomics/openbb_tradingeconomics/utils/countries.py @@ -1,3 +1,5 @@ +"""Countries list for Trading Economics API.""" + country_dict = { "G20": [ "United States", diff --git a/openbb_platform/providers/tradingeconomics/openbb_tradingeconomics/utils/url_generator.py b/openbb_platform/providers/tradingeconomics/openbb_tradingeconomics/utils/url_generator.py index 0bcb2a460056..f9063ecd2594 100644 --- a/openbb_platform/providers/tradingeconomics/openbb_tradingeconomics/utils/url_generator.py +++ b/openbb_platform/providers/tradingeconomics/openbb_tradingeconomics/utils/url_generator.py @@ -6,6 +6,7 @@ def check_args(query_args: Dict, to_include: List[str]): + """Check if all fields in to_include are present in query_args.""" available_args = ["country", "start_date", "end_date", "importance", "group"] # Check if all fields in to_include are present in query_args @@ -16,9 +17,10 @@ def check_args(query_args: Dict, to_include: List[str]): def generate_url(in_query): - """ - Generate the url for trading economimcs. There is not a single api endpoint to hit so these are - generated based on the combinations. There are also some combinations that return no data so that will return "" + """Generate the url for trading economimcs. + + There is not a single api endpoint to hit so these are generated based on the combinations. + There are also some combinations that return no data so that will return an empty string. """ # Converting the input query to a dict of params that are not None query = {k: v for k, v in in_query.dict().items() if v is not None} diff --git a/openbb_platform/providers/tradingeconomics/tests/test_tradingeconomics_fetchers.py b/openbb_platform/providers/tradingeconomics/tests/test_tradingeconomics_fetchers.py index 5feba458012b..35d5088fd05f 100644 --- a/openbb_platform/providers/tradingeconomics/tests/test_tradingeconomics_fetchers.py +++ b/openbb_platform/providers/tradingeconomics/tests/test_tradingeconomics_fetchers.py @@ -1,3 +1,5 @@ +"""Test the Trading Economics fetchers.""" + from datetime import date import pytest @@ -11,6 +13,7 @@ @pytest.fixture(scope="module") def vcr_config(): + """VCR configuration.""" return { "filter_headers": [("User-Agent", None)], "filter_query_parameters": [ @@ -21,6 +24,7 @@ def vcr_config(): @pytest.mark.record_http def test_tradingeconomics_economic_calendar_fetcher(credentials=test_credentials): + """Test the Trading Economics economic calendar fetcher.""" params = { "start_date": date(2023, 1, 1), "end_date": date(2023, 6, 6), diff --git a/openbb_platform/providers/tradingeconomics/tests/test_url_generator.py b/openbb_platform/providers/tradingeconomics/tests/test_url_generator.py index 566282ba09a0..70b49140c58d 100644 --- a/openbb_platform/providers/tradingeconomics/tests/test_url_generator.py +++ b/openbb_platform/providers/tradingeconomics/tests/test_url_generator.py @@ -9,30 +9,35 @@ def test_check_args_valid(): + """Test check_args with valid args.""" query_args = {"country": "US", "start_date": "2023-01-01", "end_date": "2023-01-31"} to_include = ["country", "start_date", "end_date"] assert check_args(query_args, to_include) def test_check_args_invalid(): + """Test check_args with missing args.""" query_args = {"country": "US"} to_include = ["start_date", "end_date"] assert not check_args(query_args, to_include) def create_query_mock(query_dict): + """Create a query mock.""" query_mock = Mock() query_mock.dict.return_value = query_dict return query_mock def test_generate_url_country_only(): + """Test generate_url with country.""" query_mock = create_query_mock({"country": "US"}) expected_url = "https://api.tradingeconomics.com/calendar/country/US?c=" assert generate_url(query_mock) == expected_url def test_generate_url_country_and_dates(): + """Test generate_url with country and dates.""" query_mock = create_query_mock( {"country": "US", "start_date": "2023-01-01", "end_date": "2023-01-31"} ) @@ -43,24 +48,28 @@ def test_generate_url_country_and_dates(): def test_generate_url_importance_only(): + """Test generate_url with importance.""" query_mock = create_query_mock({"importance": "High"}) expected_url = "https://api.tradingeconomics.com/calendar?importance=High&c=" assert generate_url(query_mock) == expected_url def test_generate_url_no_data(): + """Test generate_url with no data.""" query_mock = create_query_mock({}) expected_url = "https://api.tradingeconomics.com/calendar?c=" assert generate_url(query_mock) == expected_url def test_generate_url_group_only(): + """Test generate_url with group.""" query_mock = create_query_mock({"group": "G20"}) expected_url = "https://api.tradingeconomics.com/calendar/group/G20?c=" assert generate_url(query_mock) == expected_url def test_generate_url_country_group_and_dates(): + """Test generate_url with country, group, and dates.""" query_mock = create_query_mock( { "country": "US", diff --git a/openbb_platform/providers/wsj/__init__.py b/openbb_platform/providers/wsj/__init__.py index e69de29bb2d1..41291b5e0142 100644 --- a/openbb_platform/providers/wsj/__init__.py +++ b/openbb_platform/providers/wsj/__init__.py @@ -0,0 +1 @@ +"""WSJ provider.""" diff --git a/openbb_platform/providers/wsj/tests/test_wsj_fetchers.py b/openbb_platform/providers/wsj/tests/test_wsj_fetchers.py index 1390cdd57d6c..30f1eb80eae9 100644 --- a/openbb_platform/providers/wsj/tests/test_wsj_fetchers.py +++ b/openbb_platform/providers/wsj/tests/test_wsj_fetchers.py @@ -1,3 +1,5 @@ +"""Tests for the WSJ fetchers.""" + import pytest from openbb_core.app.service.user_service import UserService from openbb_wsj.models.active import WSJActiveFetcher @@ -11,6 +13,7 @@ @pytest.fixture(scope="module") def vcr_config(): + """VCR configuration.""" return { "filter_headers": [("User-Agent", None)], "filter_query_parameters": [ @@ -21,6 +24,7 @@ def vcr_config(): @pytest.mark.record_http def test_wsj_gainers_fetcher(credentials=test_credentials): + """Test the WSJ Gainers fetcher.""" params = {} fetcher = WSJGainersFetcher() @@ -30,6 +34,7 @@ def test_wsj_gainers_fetcher(credentials=test_credentials): @pytest.mark.record_http def test_wsj_losers_fetcher(credentials=test_credentials): + """Test the WSJ Losers fetcher.""" params = {} fetcher = WSJLosersFetcher() @@ -39,6 +44,7 @@ def test_wsj_losers_fetcher(credentials=test_credentials): @pytest.mark.record_http def test_wsj_active_fetcher(credentials=test_credentials): + """Test the WSJ Active fetcher.""" params = {} fetcher = WSJActiveFetcher() diff --git a/openbb_platform/providers/yfinance/__init__.py b/openbb_platform/providers/yfinance/__init__.py index e69de29bb2d1..2b56bab46097 100644 --- a/openbb_platform/providers/yfinance/__init__.py +++ b/openbb_platform/providers/yfinance/__init__.py @@ -0,0 +1 @@ +"""YFinance provider.""" diff --git a/openbb_platform/providers/yfinance/openbb_yfinance/models/available_indices.py b/openbb_platform/providers/yfinance/openbb_yfinance/models/available_indices.py index cb5eda90a15c..cfddf9359690 100644 --- a/openbb_platform/providers/yfinance/openbb_yfinance/models/available_indices.py +++ b/openbb_platform/providers/yfinance/openbb_yfinance/models/available_indices.py @@ -43,10 +43,10 @@ def transform_query(params: Dict[str, Any]) -> YFinanceAvailableIndicesQueryPara @staticmethod def extract_data( - query: YFinanceAvailableIndicesQueryParams, + query: YFinanceAvailableIndicesQueryParams, # pylint disable=unused-argument credentials: Optional[Dict[str, str]], - **kwargs: Any, ) -> List[Dict]: + """Extract the data.""" indices = pd.DataFrame(INDICES).transpose().reset_index() indices.columns = ["code", "name", "ticker"] diff --git a/openbb_platform/providers/yfinance/tests/__init__.py b/openbb_platform/providers/yfinance/tests/__init__.py index e69de29bb2d1..e59458f440ec 100644 --- a/openbb_platform/providers/yfinance/tests/__init__.py +++ b/openbb_platform/providers/yfinance/tests/__init__.py @@ -0,0 +1 @@ +"""YFinance tests.""" diff --git a/openbb_platform/providers/yfinance/tests/test_yfinance_fetchers.py b/openbb_platform/providers/yfinance/tests/test_yfinance_fetchers.py index 7fe29e3c429f..1dd0c1671a6a 100644 --- a/openbb_platform/providers/yfinance/tests/test_yfinance_fetchers.py +++ b/openbb_platform/providers/yfinance/tests/test_yfinance_fetchers.py @@ -1,3 +1,5 @@ +"""Tests for YFinance fetchers.""" + from datetime import date import pytest @@ -48,6 +50,7 @@ @pytest.fixture(scope="module") def vcr_config(): + """VCR configuration.""" return { "filter_headers": [ ("User-Agent", None), @@ -64,6 +67,7 @@ def vcr_config(): @pytest.mark.record_http def test_y_finance_crypto_historical_fetcher(credentials=test_credentials): + """Test YFinanceCryptoHistoricalFetcher.""" params = { "symbol": "BTCUSD", "start_date": date(2023, 1, 1), @@ -78,6 +82,7 @@ def test_y_finance_crypto_historical_fetcher(credentials=test_credentials): @pytest.mark.record_http def test_y_finance_currency_historical_fetcher(credentials=test_credentials): + """Test YFinanceCurrencyHistoricalFetcher.""" params = { "symbol": "EURUSD", "start_date": date(2023, 1, 1), @@ -91,6 +96,7 @@ def test_y_finance_currency_historical_fetcher(credentials=test_credentials): @pytest.mark.record_http def test_y_finance_index_historical_fetcher(credentials=test_credentials): + """Test YFinanceIndexHistoricalFetcher.""" params = { "symbol": "^GSPC", "start_date": date(2023, 1, 1), @@ -104,6 +110,7 @@ def test_y_finance_index_historical_fetcher(credentials=test_credentials): @pytest.mark.record_http def test_y_finance_equity_historical_fetcher(credentials=test_credentials): + """Test YFinanceEquityHistoricalFetcher.""" params = { "symbol": "AAPL", "start_date": date(2023, 1, 1), @@ -118,6 +125,7 @@ def test_y_finance_equity_historical_fetcher(credentials=test_credentials): @pytest.mark.record_http def test_y_finance_historical_dividends_fetcher(credentials=test_credentials): + """Test YFinanceHistoricalDividendsFetcher.""" params = {"symbol": "IBM"} fetcher = YFinanceHistoricalDividendsFetcher() @@ -127,6 +135,7 @@ def test_y_finance_historical_dividends_fetcher(credentials=test_credentials): @pytest.mark.record_http def test_y_finance_market_indices_fetcher(credentials=test_credentials): + """Test YFinanceMarketIndicesFetcher.""" params = { "symbol": "^GSPC", "start_date": date(2023, 1, 1), @@ -140,6 +149,7 @@ def test_y_finance_market_indices_fetcher(credentials=test_credentials): @pytest.mark.record_http def test_y_finance_futures_historical_fetcher(credentials=test_credentials): + """Test YFinanceFuturesHistoricalFetcher.""" params = { "symbol": "ES=F", "start_date": date(2023, 1, 1), @@ -154,6 +164,7 @@ def test_y_finance_futures_historical_fetcher(credentials=test_credentials): @pytest.mark.skip("Unreliable amount of data while recording test.") @pytest.mark.record_http def test_y_finance_futures_curve_fetcher(credentials=test_credentials): + """Test YFinanceFuturesCurveFetcher.""" params = {"symbol": "ES"} fetcher = YFinanceFuturesCurveFetcher() @@ -163,6 +174,7 @@ def test_y_finance_futures_curve_fetcher(credentials=test_credentials): @pytest.mark.record_http def test_y_finance_company_news_fetcher(credentials=test_credentials): + """Test YFinanceCompanyNewsFetcher.""" params = {"symbol": "AAPL,MSFT"} fetcher = YFinanceCompanyNewsFetcher() @@ -172,6 +184,7 @@ def test_y_finance_company_news_fetcher(credentials=test_credentials): @pytest.mark.record_http def test_y_finance_balance_sheet_fetcher(credentials=test_credentials): + """Test YFinanceBalanceSheetFetcher.""" params = {"symbol": "AAPL"} fetcher = YFinanceBalanceSheetFetcher() @@ -181,6 +194,7 @@ def test_y_finance_balance_sheet_fetcher(credentials=test_credentials): @pytest.mark.record_http def test_y_finance_cash_flow_statement_fetcher(credentials=test_credentials): + """Test YFinanceCashFlowStatementFetcher.""" params = {"symbol": "AAPL"} fetcher = YFinanceCashFlowStatementFetcher() @@ -190,6 +204,7 @@ def test_y_finance_cash_flow_statement_fetcher(credentials=test_credentials): @pytest.mark.record_http def test_y_finance_income_statement_fetcher(credentials=test_credentials): + """Test YFinanceIncomeStatementFetcher.""" params = {"symbol": "AAPL"} fetcher = YFinanceIncomeStatementFetcher() @@ -198,6 +213,7 @@ def test_y_finance_income_statement_fetcher(credentials=test_credentials): def test_y_finance_available_fetcher(credentials=test_credentials): + """Test YFinanceAvailableIndicesFetcher.""" params = {} fetcher = YFinanceAvailableIndicesFetcher() @@ -207,6 +223,7 @@ def test_y_finance_available_fetcher(credentials=test_credentials): @pytest.mark.record_http def test_y_finance_etf_historical_fetcher(credentials=test_credentials): + """Test YFinanceEtfHistoricalFetcher.""" params = { "symbol": "SPY", "start_date": date(2023, 1, 1), @@ -220,6 +237,7 @@ def test_y_finance_etf_historical_fetcher(credentials=test_credentials): @pytest.mark.record_http def test_y_finance_active_fetcher(credentials=test_credentials): + """Test YFActiveFetcher.""" params = {} fetcher = YFActiveFetcher() @@ -229,6 +247,7 @@ def test_y_finance_active_fetcher(credentials=test_credentials): @pytest.mark.record_http def test_y_finance_gainers_fetcher(credentials=test_credentials): + """Test YFGainersFetcher.""" params = {} fetcher = YFGainersFetcher() @@ -238,6 +257,7 @@ def test_y_finance_gainers_fetcher(credentials=test_credentials): @pytest.mark.record_http def test_y_finance_losers_fetcher(credentials=test_credentials): + """Test YFLosersFetcher.""" params = {} fetcher = YFLosersFetcher() @@ -247,6 +267,7 @@ def test_y_finance_losers_fetcher(credentials=test_credentials): @pytest.mark.record_http def test_y_finance_undervalued_large_caps_fetcher(credentials=test_credentials): + """Test YFUndervaluedLargeCapsFetcher.""" params = {} fetcher = YFUndervaluedLargeCapsFetcher() @@ -256,6 +277,7 @@ def test_y_finance_undervalued_large_caps_fetcher(credentials=test_credentials): @pytest.mark.record_http def test_y_finance_undervalued_growth_equities_fetcher(credentials=test_credentials): + """Test YFUndervaluedGrowthEquitiesFetcher.""" params = {} fetcher = YFUndervaluedGrowthEquitiesFetcher() @@ -265,6 +287,7 @@ def test_y_finance_undervalued_growth_equities_fetcher(credentials=test_credenti @pytest.mark.record_http def test_y_finance_aggressive_small_caps_fetcher(credentials=test_credentials): + """Test YFAggressiveSmallCapsFetcher.""" params = {} fetcher = YFAggressiveSmallCapsFetcher() @@ -274,6 +297,7 @@ def test_y_finance_aggressive_small_caps_fetcher(credentials=test_credentials): @pytest.mark.record_http def test_y_finance_growth_tech_equities_fetcher(credentials=test_credentials): + """Test YFGrowthTechEquitiesFetcher.""" params = {} fetcher = YFGrowthTechEquitiesFetcher() @@ -283,6 +307,7 @@ def test_y_finance_growth_tech_equities_fetcher(credentials=test_credentials): @pytest.mark.record_http def test_y_finance_equity_profile_fetcher(credentials=test_credentials): + """Test YFinanceEquityProfileFetcher.""" params = {"symbol": "AAPL"} fetcher = YFinanceEquityProfileFetcher() @@ -292,6 +317,7 @@ def test_y_finance_equity_profile_fetcher(credentials=test_credentials): @pytest.mark.record_http def test_y_finance_equity_quote_fetcher(credentials=test_credentials): + """Test YFinanceEquityQuoteFetcher.""" params = {"symbol": "AAPL"} fetcher = YFinanceEquityQuoteFetcher() @@ -301,6 +327,7 @@ def test_y_finance_equity_quote_fetcher(credentials=test_credentials): @pytest.mark.record_http def test_y_finance_price_target_consensus_fetcher(credentials=test_credentials): + """Test YFinancePriceTargetConsensusFetcher.""" params = {"symbol": "AAPL"} fetcher = YFinancePriceTargetConsensusFetcher() @@ -310,6 +337,7 @@ def test_y_finance_price_target_consensus_fetcher(credentials=test_credentials): @pytest.mark.record_http def test_y_finance_share_statistics_fetcher(credentials=test_credentials): + """Test YFinanceShareStatisticsFetcher.""" params = {"symbol": "AAPL"} fetcher = YFinanceShareStatisticsFetcher() @@ -319,6 +347,7 @@ def test_y_finance_share_statistics_fetcher(credentials=test_credentials): @pytest.mark.record_http def test_y_finance_key_executives_fetcher(credentials=test_credentials): + """Test YFinanceKeyExecutivesFetcher.""" params = {"symbol": "AAPL"} fetcher = YFinanceKeyExecutivesFetcher() @@ -328,6 +357,7 @@ def test_y_finance_key_executives_fetcher(credentials=test_credentials): @pytest.mark.record_http def test_y_finance_key_metrics_fetcher(credentials=test_credentials): + """Test YFinanceKeyMetricsFetcher.""" params = {"symbol": "AAPL"} fetcher = YFinanceKeyMetricsFetcher() @@ -337,6 +367,7 @@ def test_y_finance_key_metrics_fetcher(credentials=test_credentials): @pytest.mark.record_http def test_y_finance_etf_info_fetcher(credentials=test_credentials): + """Test YFinanceEtfInfoFetcher.""" params = {"symbol": "QQQ"} fetcher = YFinanceEtfInfoFetcher() diff --git a/openbb_platform/providers/yfinance/tests/test_yfinance_helpers.py b/openbb_platform/providers/yfinance/tests/test_yfinance_helpers.py index 9c8b13bca67d..7c3817cbc369 100644 --- a/openbb_platform/providers/yfinance/tests/test_yfinance_helpers.py +++ b/openbb_platform/providers/yfinance/tests/test_yfinance_helpers.py @@ -20,12 +20,14 @@ def mock_futures_csv(monkeypatch): def test_get_futures_data(mock_futures_csv): + """Test get_futures_data.""" df = get_futures_data() assert not df.empty assert df.equals(MOCK_FUTURES_DATA) def test_df_transform_numbers(): + """Test df_transform_numbers.""" data = pd.DataFrame( {"Value": ["1M", "2.5B", "3T"], "% Change": ["1%", "-2%", "3.5%"]} ) diff --git a/openbb_platform/tests/conftest.py b/openbb_platform/tests/conftest.py index 5348bc9d3090..0c35960fb620 100644 --- a/openbb_platform/tests/conftest.py +++ b/openbb_platform/tests/conftest.py @@ -1,3 +1,5 @@ +"""Configuration for pytest.""" + # TODO: See if we can dynamically import the test modules under the openbb_platform # TODO: Add global fixture for headers here @@ -6,4 +8,5 @@ def pytest_configure(): + """Set environment variables for testing.""" os.environ["OPENBB_AUTO_BUILD"] = "false" diff --git a/openbb_platform/tests/test_auto_build.py b/openbb_platform/tests/test_auto_build.py index c1aa5314cac4..bd6acd65fd62 100644 --- a/openbb_platform/tests/test_auto_build.py +++ b/openbb_platform/tests/test_auto_build.py @@ -11,6 +11,7 @@ @pytest.fixture(autouse=True) def setup_mocks(): + """Set up mocks for the test.""" with patch( "openbb_core.app.static.package_builder.PackageBuilder.auto_build" ) as mock_auto_build: @@ -20,6 +21,7 @@ def setup_mocks(): @pytest.fixture def openbb_module(setup_mocks): + """Reload the openbb module.""" if "openbb" in sys.modules: importlib.reload(sys.modules["openbb"]) else: @@ -29,7 +31,5 @@ def openbb_module(setup_mocks): @pytest.mark.integration def test_autobuild_called(openbb_module): - """ - Test that auto_build is called upon importing openbb. - """ + """Test that auto_build is called upon importing openbb.""" openbb_module.assert_called_once() diff --git a/openbb_platform/tests/test_extension_map.py b/openbb_platform/tests/test_extension_map.py index 0a7a879ec184..b3a4c742b362 100644 --- a/openbb_platform/tests/test_extension_map.py +++ b/openbb_platform/tests/test_extension_map.py @@ -1,3 +1,5 @@ +"""Test the extension map.""" + import json from pathlib import Path from typing import Dict