summaryrefslogtreecommitdiffstats
diff options
context:
space:
mode:
authorDiogo Sousa <montezdesousa@gmail.com>2024-06-05 15:50:28 +0100
committerDiogo Sousa <montezdesousa@gmail.com>2024-06-05 15:50:28 +0100
commite6cb4eafa332a4cd51a6383826b28305f54208c7 (patch)
tree60a678a8f58913c1bbf01fb29f45f779cf82b33e
parente0be8cdacfdd2e95b58ee545bfcf258ddff6750c (diff)
fix: comply w/ possibly used before assignment
-rw-r--r--cli/openbb_cli/argparse_translator/utils.py9
-rw-r--r--cli/openbb_cli/controllers/base_platform_controller.py3
-rw-r--r--cli/openbb_cli/controllers/choices.py1
-rw-r--r--cli/openbb_cli/controllers/cli_controller.py7
-rw-r--r--cli/openbb_cli/controllers/utils.py5
-rw-r--r--cli/openbb_cli/session.py5
-rw-r--r--openbb_platform/extensions/tests/utils/helpers.py6
-rw-r--r--openbb_platform/extensions/tests/utils/integration_tests_testers.py2
-rw-r--r--openbb_platform/extensions/tests/utils/router_testers.py2
-rw-r--r--openbb_platform/obbject_extensions/charting/openbb_charting/charting_router.py5
-rw-r--r--openbb_platform/obbject_extensions/charting/openbb_charting/core/plotly_ta/base.py1
-rw-r--r--openbb_platform/providers/ecb/openbb_ecb/models/yield_curve.py5
-rw-r--r--openbb_platform/providers/fred/openbb_fred/models/regional.py5
-rw-r--r--openbb_platform/providers/intrinio/openbb_intrinio/models/cash_flow.py5
-rw-r--r--openbb_platform/providers/intrinio/openbb_intrinio/models/financial_ratios.py5
-rw-r--r--openbb_platform/providers/intrinio/openbb_intrinio/models/income_statement.py5
-rw-r--r--openbb_platform/providers/oecd/openbb_oecd/utils/helpers.py10
-rw-r--r--openbb_platform/providers/tmx/openbb_tmx/utils/helpers.py2
-rw-r--r--openbb_platform/providers/tradingeconomics/openbb_tradingeconomics/utils/url_generator.py2
-rw-r--r--openbb_platform/providers/yfinance/openbb_yfinance/models/company_news.py1
-rw-r--r--openbb_platform/providers/yfinance/openbb_yfinance/models/crypto_historical.py8
-rw-r--r--openbb_platform/providers/yfinance/openbb_yfinance/models/futures_historical.py8
22 files changed, 51 insertions, 51 deletions
diff --git a/cli/openbb_cli/argparse_translator/utils.py b/cli/openbb_cli/argparse_translator/utils.py
index 20b2de27178..d9ab81c5327 100644
--- a/cli/openbb_cli/argparse_translator/utils.py
+++ b/cli/openbb_cli/argparse_translator/utils.py
@@ -59,9 +59,12 @@ def get_argument_optional_choices(parser: ArgumentParser, argument_name: str) ->
"""Get the optional_choices attribute of an argument from an ArgumentParser."""
for action in parser._actions: # pylint: disable=protected-access
opts = action.option_strings
- if (opts and opts[0] == argument_name) or action.dest == argument_name:
- if hasattr(action, "optional_choices"):
- return action.optional_choices
+ if (
+ (opts and opts[0] == argument_name)
+ or action.dest == argument_name
+ and hasattr(action, "optional_choices")
+ ):
+ return action.optional_choices
return False
diff --git a/cli/openbb_cli/controllers/base_platform_controller.py b/cli/openbb_cli/controllers/base_platform_controller.py
index 33cc4700849..acbec34d165 100644
--- a/cli/openbb_cli/controllers/base_platform_controller.py
+++ b/cli/openbb_cli/controllers/base_platform_controller.py
@@ -6,7 +6,6 @@ from types import MethodType
from typing import Dict, List, Optional
import pandas as pd
-from openbb import obb
from openbb_charting.core.openbb_figure import OpenBBFigure
from openbb_cli.argparse_translator.argparse_class_processor import (
ArgparseClassProcessor,
@@ -17,6 +16,8 @@ from openbb_cli.controllers.utils import export_data, print_rich_table
from openbb_cli.session import Session
from openbb_core.app.model.obbject import OBBject
+from openbb import obb
+
session = Session()
diff --git a/cli/openbb_cli/controllers/choices.py b/cli/openbb_cli/controllers/choices.py
index 5ed38bb8ba3..338a3fed185 100644
--- a/cli/openbb_cli/controllers/choices.py
+++ b/cli/openbb_cli/controllers/choices.py
@@ -274,6 +274,7 @@ def _get_argument_parser(
" - parse_known_args_and_warn\n"
)
+ # pylint: disable=possibly-used-before-assignment
return argument_parser
diff --git a/cli/openbb_cli/controllers/cli_controller.py b/cli/openbb_cli/controllers/cli_controller.py
index ccd54ae9114..31d32499659 100644
--- a/cli/openbb_cli/controllers/cli_controller.py
+++ b/cli/openbb_cli/controllers/cli_controller.py
@@ -18,7 +18,6 @@ from typing import Any, Dict, List, Optional
import pandas as pd
import requests
-from openbb import obb
from openbb_cli.config import constants
from openbb_cli.config.constants import (
ASSETS_DIRECTORY,
@@ -48,6 +47,8 @@ from prompt_toolkit.formatted_text import HTML
from prompt_toolkit.styles import Style
from pydantic import BaseModel
+from openbb import obb
+
PLATFORM_ROUTERS = {
d: "menu" if not isinstance(getattr(obb, d), BaseModel) else "command"
for d in dir(obb)
@@ -291,7 +292,7 @@ class CLIController(BaseController):
: session.settings.N_TO_DISPLAY_OBBJECT_REGISTRY
]:
mt.add_raw(
- f"[yellow]OBB{key}[/yellow]: {value['command']}",
+ f"[yellow]OBB{key}[/yellow]: {value['command']}", # type: ignore[index]
left_spacing=True,
)
@@ -769,7 +770,6 @@ def replace_dynamic(match: re.Match, special_arguments: Dict[str, str]) -> str:
str
The new string
"""
-
cleaned = match[0].replace("{", "").replace("}", "").replace("$", "")
key, default = cleaned.split("=")
dict_value = special_arguments.get(key, default)
@@ -939,7 +939,6 @@ def launch(
debug: bool = False, dev: bool = False, queue: Optional[List[str]] = None
) -> None:
"""Launch CLI."""
-
if queue:
main(debug, dev, queue, module="")
else:
diff --git a/cli/openbb_cli/controllers/utils.py b/cli/openbb_cli/controllers/utils.py
index 7c92a5880ae..a77c93eb683 100644
--- a/cli/openbb_cli/controllers/utils.py
+++ b/cli/openbb_cli/controllers/utils.py
@@ -16,7 +16,6 @@ from typing import TYPE_CHECKING, Dict, List, Optional, Tuple, Union
import numpy as np
import pandas as pd
import requests
-from openbb import obb
from openbb_charting.core.backend import create_backend, get_backend
from openbb_cli.config.constants import AVAILABLE_FLAIRS, ENV_FILE_SETTINGS
from openbb_cli.session import Session
@@ -24,6 +23,8 @@ from openbb_core.app.model.charts.charting_settings import ChartingSettings
from pytz import all_timezones, timezone
from rich.table import Table
+from openbb import obb
+
if TYPE_CHECKING:
from openbb_charting.core.openbb_figure import OpenBBFigure
@@ -680,7 +681,6 @@ def remove_timezone_from_dataframe(df: pd.DataFrame) -> pd.DataFrame:
pd.DataFrame
The dataframe with timezone information removed
"""
-
date_cols = []
index_is_date = False
@@ -844,7 +844,6 @@ def export_data(
margin : bool
Automatically adjust subplot parameters to give specified padding.
"""
-
if export_type:
saved_path = compose_export_path(func_name, dir_path).resolve()
saved_path.parent.mkdir(parents=True, exist_ok=True)
diff --git a/cli/openbb_cli/session.py b/cli/openbb_cli/session.py
index 49da650bf8c..1c5dcdc3c4d 100644
--- a/cli/openbb_cli/session.py
+++ b/cli/openbb_cli/session.py
@@ -4,11 +4,11 @@ import sys
from pathlib import Path
from typing import Optional
-from openbb import obb
from openbb_core.app.model.abstract.singleton import SingletonMeta
from openbb_core.app.model.user_settings import UserSettings as User
from prompt_toolkit import PromptSession
+from openbb import obb
from openbb_cli.argparse_translator.obbject_registry import Registry
from openbb_cli.config.completer import CustomFileHistory
from openbb_cli.config.console import Console
@@ -82,9 +82,6 @@ class Session(metaclass=SingletonMeta):
"""Check if user is local."""
return not bool(self.user.profile.hub_session)
- def reset(self) -> None:
- pass
-
def max_obbjects_exceeded(self) -> bool:
"""Check if max obbjects exceeded."""
return (
diff --git a/openbb_platform/extensions/tests/utils/helpers.py b/openbb_platform/extensions/tests/utils/helpers.py
index 2411a85484b..35f73ca8b69 100644
--- a/openbb_platform/extensions/tests/utils/helpers.py
+++ b/openbb_platform/extensions/tests/utils/helpers.py
@@ -187,7 +187,7 @@ class Decorator:
kwargs: Optional[dict] = None
-def get_decorator_details(function) -> Decorator:
+def get_decorator_details(function) -> Optional[Decorator]:
"""Extract decorators and their arguments from a function."""
source = inspect.getsource(function)
parsed_source = parse(source)
@@ -207,8 +207,8 @@ def get_decorator_details(function) -> Decorator:
name = (
decorator.id if isinstance(decorator, Name) else unparse(decorator)
)
-
- return Decorator(name, args, kwargs)
+ return Decorator(name, args, kwargs)
+ return None
def find_missing_router_function_models(
diff --git a/openbb_platform/extensions/tests/utils/integration_tests_testers.py b/openbb_platform/extensions/tests/utils/integration_tests_testers.py
index fc1ff20edd0..afb0d95e9f1 100644
--- a/openbb_platform/extensions/tests/utils/integration_tests_testers.py
+++ b/openbb_platform/extensions/tests/utils/integration_tests_testers.py
@@ -34,6 +34,8 @@ def get_integration_tests(
file_end = "_python.py"
elif test_type == "api":
file_end = "_api.py"
+ else:
+ raise ValueError(f"test_type '{test_type}' not valid")
for extension in find_extensions(filter_charting_ext):
integration_folder = os.path.join(extension, "integration")
diff --git a/openbb_platform/extensions/tests/utils/router_testers.py b/openbb_platform/extensions/tests/utils/router_testers.py
index bb6304dd6e8..f1523afb696 100644
--- a/openbb_platform/extensions/tests/utils/router_testers.py
+++ b/openbb_platform/extensions/tests/utils/router_testers.py
@@ -137,7 +137,7 @@ def check_router_command_examples() -> List[str]:
)
if decorator:
decorator_details = get_decorator_details(function)
- if decorator_details.name == "router.command":
+ if decorator_details and decorator_details.name == "router.command":
keywords = decorator_details.kwargs or {}
examples = keywords.get("examples", [])
# General checks
diff --git a/openbb_platform/obbject_extensions/charting/openbb_charting/charting_router.py b/openbb_platform/obbject_extensions/charting/openbb_charting/charting_router.py
index 94dcb63ca45..26b31d6289c 100644
--- a/openbb_platform/obbject_extensions/charting/openbb_charting/charting_router.py
+++ b/openbb_platform/obbject_extensions/charting/openbb_charting/charting_router.py
@@ -1235,13 +1235,12 @@ def technical_relative_rotation(
fig = relative_rotation.create_rrg_with_tails(
ratios_df, momentum_df, study, benchmark_symbol, tail_periods, tail_interval # type: ignore
)
-
- if show_tails is False:
+ else:
fig = relative_rotation.create_rrg_without_tails(
ratios_df, momentum_df, benchmark_symbol, study, date # type: ignore
)
- figure = OpenBBFigure(fig) # pylint: disable=E0606
+ figure = OpenBBFigure(fig)
font_color = "black" if ChartStyle().plt_style == "light" else "white"
figure.update_layout(
paper_bgcolor="rgba(0,0,0,0)",
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 a5e7e0728e8..e77a36a08b6 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
@@ -203,6 +203,7 @@ def indicator(
if not attrs.pop("name", ""):
name = func.__name__
+ # pylint: disable=possibly-used-before-assignment
return Indicator(func, name, **attrs)
return decorator
diff --git a/openbb_platform/providers/ecb/openbb_ecb/models/yield_curve.py b/openbb_platform/providers/ecb/openbb_ecb/models/yield_curve.py
index acae4b4706a..97799d57ab4 100644
--- a/openbb_platform/providers/ecb/openbb_ecb/models/yield_curve.py
+++ b/openbb_platform/providers/ecb/openbb_ecb/models/yield_curve.py
@@ -72,7 +72,6 @@ class ECBYieldCurveFetcher(
**kwargs: Any,
) -> List[Dict]:
"""Extract data."""
-
results: List = []
IDS = get_yield_curve_ids(
@@ -100,9 +99,9 @@ class ECBYieldCurveFetcher(
await session.close()
else:
response = await amake_request(url=url)
- if not response: # pylint: disable=E0606
+ if not response:
raise RuntimeError("Error: No data was returned.")
- if isinstance(response, List): # pylint: disable=E0606
+ if isinstance(response, List):
for item in response:
d = {
"date": item.get("PERIOD"),
diff --git a/openbb_platform/providers/fred/openbb_fred/models/regional.py b/openbb_platform/providers/fred/openbb_fred/models/regional.py
index 64d8b12cc6f..d3254294483 100644
--- a/openbb_platform/providers/fred/openbb_fred/models/regional.py
+++ b/openbb_platform/providers/fred/openbb_fred/models/regional.py
@@ -210,7 +210,7 @@ class FredRegionalDataFetcher(
) -> Dict:
"""Extract the raw data."""
api_key = credentials.get("fred_api_key") if credentials else ""
- if query.is_series_group is True:
+ if query.is_series_group:
base_url = "https://api.stlouisfed.org/geofred/regional/data?"
url = (
base_url
@@ -219,7 +219,7 @@ class FredRegionalDataFetcher(
)
+ f"&file_type=json&api_key={api_key}"
)
- if query.is_series_group is False:
+ else:
base_url = "https://api.stlouisfed.org/geofred/series/data?"
url = (
base_url
@@ -246,7 +246,6 @@ class FredRegionalDataFetcher(
**kwargs,
) -> List[FredRegionalData]:
"""Flatten the response object and validate the model."""
-
results: List[FredRegionalData] = []
if data.get("meta") is None:
raise EmptyDataError()
diff --git a/openbb_platform/providers/intrinio/openbb_intrinio/models/cash_flow.py b/openbb_platform/providers/intrinio/openbb_intrinio/models/cash_flow.py
index 3441983152d..10939045643 100644
--- a/openbb_platform/providers/intrinio/openbb_intrinio/models/cash_flow.py
+++ b/openbb_platform/providers/intrinio/openbb_intrinio/models/cash_flow.py
@@ -251,13 +251,14 @@ class IntrinioCashFlowStatementFetcher(
**kwargs: Any,
) -> List[Dict]:
"""Return the raw data from the Intrinio endpoint."""
-
api_key = credentials.get("intrinio_api_key") if credentials else ""
statement_code = "cash_flow_statement"
if query.period in ["quarter", "annual"]:
period_type = "FY" if query.period == "annual" else "QTR"
- if query.period in ["ttm", "ytd"]:
+ elif query.period in ["ttm", "ytd"]:
period_type = query.period.upper()
+ else:
+ raise ValueError(f"Period '{query.period}' not supported.")
base_url = "https://api-v2.intrinio.com"
fundamentals_url = (
diff --git a/openbb_platform/providers/intrinio/openbb_intrinio/models/financial_ratios.py b/openbb_platform/providers/intrinio/openbb_intrinio/models/financial_ratios.py
index 28cba446a2e..4945f8cff14 100644
--- a/openbb_platform/providers/intrinio/openbb_intrinio/models/financial_ratios.py
+++ b/openbb_platform/providers/intrinio/openbb_intrinio/models/financial_ratios.py
@@ -153,13 +153,14 @@ class IntrinioFinancialRatiosFetcher(
**kwargs: Any,
) -> List[Dict]:
"""Return the raw data from the Intrinio endpoint."""
-
api_key = credentials.get("intrinio_api_key") if credentials else ""
statement_code = "calculations"
if query.period in ["quarter", "annual"]:
period_type = "FY" if query.period == "annual" else "QTR"
- if query.period in ["ttm", "ytd"]:
+ elif query.period in ["ttm", "ytd"]:
period_type = query.period.upper()
+ else:
+ raise ValueError(f"Period '{query.period}' not supported.")
fundamentals_data: Dict = {}
diff --git a/openbb_platform/providers/intrinio/openbb_intrinio/models/income_statement.py b/openbb_platform/providers/intrinio/openbb_intrinio/models/income_statement.py
index 04e9d7fa8fd..876135e4131 100644
--- a/openbb_platform/providers/intrinio/openbb_intrinio/models/income_statement.py
+++ b/openbb_platform/providers/intrinio/openbb_intrinio/models/income_statement.py
@@ -402,8 +402,11 @@ class IntrinioIncomeStatementFetcher(
statement_code = "income_statement"
if query.period in ["quarter", "annual"]:
period_type = "FY" if query.period == "annual" else "QTR"
- if query.period in ["ttm", "ytd"]:
+ elif query.period in ["ttm", "ytd"]:
period_type = query.period.upper()
+ else:
+ raise ValueError(f"Period '{query.period}' not supported.")
+
data_tags = [
"ebit",
"ebitda",
diff --git a/openbb_platform/providers/oecd/openbb_oecd/utils/helpers.py b/openbb_platform/providers/oecd/openbb_oecd/utils/helpers.py
index b2bbaf439f4..a501e63fd8c 100644
--- a/openbb_platform/providers/oecd/openbb_oecd/utils/helpers.py
+++ b/openbb_platform/providers/oecd/openbb_oecd/utils/helpers.py
@@ -4,7 +4,7 @@ import ssl
from datetime import date
from io import StringIO
from pathlib import Path
-from typing import Any, Dict, Optional, Union
+from typing import Any, Dict, Literal, Optional, Union
import requests
import urllib3
@@ -207,7 +207,7 @@ def get_possibly_cached_data(
url: str,
function: Optional[str] = None,
query_dict: Optional[dict] = None,
- cache_method: str = "csv",
+ cache_method: Literal["csv", "parquet"] = "csv",
skip_cache: bool = False,
) -> DataFrame:
"""Retrieve data from a given URL or from the cache if available and valid.
@@ -231,15 +231,11 @@ def get_possibly_cached_data(
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":
- cache_path = base_cache + ".csv"
-
use_cache = check_cache_exists_and_valid(
cache_str=base_cache, cache_method=cache_method
)
if use_cache and not skip_cache:
+ cache_path = f"{base_cache}.{cache_method}"
if cache_method == "csv":
data = read_csv(cache_path)
elif cache_method == "parquet":
diff --git a/openbb_platform/providers/tmx/openbb_tmx/utils/helpers.py b/openbb_platform/providers/tmx/openbb_tmx/utils/helpers.py
index 04e769c8b4c..4e3c01369ee 100644
--- a/openbb_platform/providers/tmx/openbb_tmx/utils/helpers.py
+++ b/openbb_platform/providers/tmx/openbb_tmx/utils/helpers.py
@@ -571,7 +571,7 @@ async def download_eod_chains(
if date is None:
EOD_URL = BASE_URL + f"{symbol}" "&dnld=1#quotes"
- if date is not None:
+ else:
date = check_weekday(date) # type: ignore
if cal.is_session(date) is False: # type: ignore
date = (pd.to_datetime(date) + timedelta(days=1)).strftime("%Y-%m-%d") # type: ignore
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 7ec2bb20105..c878fe614d7 100644
--- a/openbb_platform/providers/tradingeconomics/openbb_tradingeconomics/utils/url_generator.py
+++ b/openbb_platform/providers/tradingeconomics/openbb_tradingeconomics/utils/url_generator.py
@@ -48,6 +48,7 @@ def generate_url(in_query):
# Construct URL based on query parameters
# Country Only
if check_args(query, ["country"]):
+ # pylint: disable=possibly-used-before-assignment
url = f"{base_url}/country/{country}?c="
# Country + Date
elif check_args(query, ["country", "start_date", "end_date"]):
@@ -59,6 +60,7 @@ def generate_url(in_query):
url = f"{base_url}/country/{country}?{urlencode(query)}&c="
# Country + Group
elif check_args(query, ["country", "group"]):
+ # pylint: disable=possibly-used-before-assignment
url = f"{base_url}/country/{country}/group/{group}?c="
# Country + Group + Date
elif check_args(query, ["country", "group", "start_date", "end_date"]):
diff --git a/openbb_platform/providers/yfinance/openbb_yfinance/models/company_news.py b/openbb_platform/providers/yfinance/openbb_yfinance/models/company_news.py
index a313f63ff31..afdbc894dd2 100644
--- a/openbb_platform/providers/yfinance/openbb_yfinance/models/company_news.py
+++ b/openbb_platform/providers/yfinance/openbb_yfinance/models/company_news.py
@@ -70,6 +70,7 @@ class YFinanceCompanyNewsFetcher(
async def get_one(symbol):
data = Ticker(symbol).get_news()
for d in data:
+ images = None
if d.get("thumbnail"):
images = d["thumbnail"].get("resolutions")
_ = d.pop("uuid")
diff --git a/openbb_platform/providers/yfinance/openbb_yfinance/models/crypto_historical.py b/openbb_platform/providers/yfinance/openbb_yfinance/models/crypto_historical.py
index 00ca5fd7b0e..332748648c7 100644
--- a/openbb_platform/providers/yfinance/openbb_yfinance/models/crypto_historical.py
+++ b/openbb_platform/providers/yfinance/openbb_yfinance/models/crypto_historical.py
@@ -81,14 +81,12 @@ class YFinanceCryptoHistoricalFetcher(
**kwargs: Any,
) -> List[Dict]:
"""Return the raw data from the Yahoo Finance endpoint."""
-
tickers = query.symbol.split(",")
new_tickers = []
for ticker in tickers:
- if "-" not in ticker:
- new_ticker = ticker[:-3] + "-" + ticker[-3:]
- if "-" in ticker:
- new_ticker = ticker
+ new_ticker = (
+ ticker[:-3] + "-" + ticker[-3:] if "-" not in ticker else ticker
+ )
new_tickers.append(new_ticker)
symbols = ",".join(new_tickers)
diff --git a/openbb_platform/providers/yfinance/openbb_yfinance/models/futures_historical.py b/openbb_platform/providers/yfinance/openbb_yfinance/models/futures_historical.py
index f7715d2dcd6..ce30fa2194f 100644
--- a/openbb_platform/providers/yfinance/openbb_yfinance/models/futures_historical.py
+++ b/openbb_platform/providers/yfinance/openbb_yfinance/models/futures_historical.py
@@ -85,11 +85,9 @@ class YFinanceFuturesHistoricalFetcher(
exchange = futures_data[futures_data["Ticker"] == symbol][
"Exchange"
].values[0]
- new_symbol = (
- f"{symbol}{MONTHS[expiry_date.month]}{str(expiry_date.year)[-2:]}.{exchange}"