This commit is contained in:
Igor Radovanovic
2023-08-31 12:14:41 +02:00
parent e1d971c754
commit bc28dff7cc
18 changed files with 132 additions and 110 deletions

View File

@@ -22,7 +22,7 @@ from reportlab.graphics import renderPDF
try:
from pywry import PyWry
except ImportError as e:
print(f"\033[91m{e}\033[0m")
print(f"\033[91m{e}\033[0m") # noqa: T201
# pylint: disable=C0412
from .dummy_backend import DummyBackend
@@ -241,10 +241,12 @@ class Backend(PyWry):
if self.charting_settings.plot_open_export:
if sys.platform == "win32":
os.startfile(export_image) # nosec: B606
os.startfile(export_image) # nosec: B606 # noqa: S606
else:
opener = "open" if sys.platform == "darwin" else "xdg-open"
subprocess.check_call([opener, export_image]) # nosec: B603
subprocess.check_call(
[opener, export_image] # nosec: B603 # noqa: S603
)
def send_table(
self,
@@ -489,7 +491,7 @@ async def download_plotly_js():
file.unlink(missing_ok=True)
except Exception as err: # pylint: disable=W0703
print(f"Error downloading plotly.js: {err}")
warnings.warn(f"Error downloading plotly.js: {err}")
# To avoid having plotly.js in the repo, we download it if it's not present

View File

@@ -54,7 +54,7 @@ class PluginMeta(type):
is_static_method = isinstance(value, staticmethod)
if is_static_method:
value = value.__func__
value = value.__func__ # noqa: PLW2901
if isinstance(value, Indicator):
if is_static_method:
raise TypeError(

View File

@@ -55,10 +55,10 @@ def estr(
extra_params: ExtraParams,
) -> OBBject[BaseModel]: # type: ignore
"""
The euro short-term rate (€STR) reflects the wholesale euro unsecured overnight borrowing costs of banks located in the euro area.
The €STR is published on each TARGET2 business day based on transactions conducted and settled on the previous TARGET2 business
day (the reporting date “T”) with a maturity date of T+1 which are deemed to have been executed at arm’s length and thus reflect
market rates in an unbiased way."""
The euro short-term rate (€STR) reflects the wholesale euro unsecured overnight borrowing costs of banks located in
the euro area. The €STR is published on each TARGET2 business day based on transactions conducted and settled on
the previous TARGET2 business day (the reporting date “T”) with a maturity date of T+1 which are deemed to have been
executed at arm’s length and thus reflect market rates in an unbiased way."""
return OBBject(results=Query(**locals()).execute())
@@ -70,9 +70,9 @@ def sonia(
extra_params: ExtraParams,
) -> OBBject[BaseModel]: # type: ignore
"""
SONIA (Sterling Overnight Index Average) is an important interest rate benchmark. SONIA is based on actual transactions and
reflects the average of the interest rates that banks pay to borrow sterling overnight from other financial institutions and other
institutional investors."""
SONIA (Sterling Overnight Index Average) is an important interest rate benchmark. SONIA is based on actual
transactions and reflects the average of the interest rates that banks pay to borrow sterling overnight from other
financial institutions and other institutional investors."""
return OBBject(results=Query(**locals()).execute())
@@ -84,9 +84,9 @@ def ameribor(
extra_params: ExtraParams,
) -> OBBject[BaseModel]: # type: ignore
"""
Ameribor (short for the American interbank offered rate) is a benchmark interest rate that reflects the true cost of short-term
interbank borrowing. This rate is based on transactions in overnight unsecured loans conducted on the American Financial Exchange
(AFX)."""
Ameribor (short for the American interbank offered rate) is a benchmark interest rate that reflects the true cost of
short-term interbank borrowing. This rate is based on transactions in overnight unsecured loans conducted on the
American Financial Exchange (AFX)."""
return OBBject(results=Query(**locals()).execute())
@@ -98,9 +98,10 @@ def fed(
extra_params: ExtraParams,
) -> OBBject[BaseModel]: # type: ignore
"""
Get Effective Federal Funds Rate data. A bank rate is the interest rate a nation's central bank charges to its domestic banks to
borrow money. The rates central banks charge are set to stabilize the economy. In the United States, the Federal Reserve System's
Board of Governors set the bank rate, also known as the discount rate."""
Get Effective Federal Funds Rate data. A bank rate is the interest rate a nation's central bank charges to its
domestic banks to borrow money. The rates central banks charge are set to stabilize the economy. In the
United States, the Federal Reserve System's Board of Governors set the bank rate, also known as the discount rate.
"""
return OBBject(results=Query(**locals()).execute())
@@ -112,9 +113,10 @@ def projections(
extra_params: ExtraParams,
) -> OBBject[BaseModel]: # type: ignore
"""
Get Effective Federal Funds Rate data. A bank rate is the interest rate a nation's central bank charges to its domestic banks to
borrow money. The rates central banks charge are set to stabilize the economy. In the United States, the Federal Reserve System's
Board of Governors set the bank rate, also known as the discount rate."""
Get Effective Federal Funds Rate data. A bank rate is the interest rate a nation's central bank charges to its
domestic banks to borrow money. The rates central banks charge are set to stabilize the economy. In the
United States, the Federal Reserve System's Board of Governors set the bank rate, also known as the discount rate.
"""
return OBBject(results=Query(**locals()).execute())
@@ -126,7 +128,8 @@ def iorb(
extra_params: ExtraParams,
) -> OBBject[BaseModel]: # type: ignore
"""
Get Interest Rate on Reserve Balances data A bank rate is the interest rate a nation's central bank charges to its domestic banks
to borrow money. The rates central banks charge are set to stabilize the economy. In the United States, the Federal Reserve
System's Board of Governors set the bank rate, also known as the discount rate."""
Get Interest Rate on Reserve Balances data A bank rate is the interest rate a nation's central bank charges to its
domestic banks to borrow money. The rates central banks charge are set to stabilize the economy. In the
United States, the Federal Reserve System's Board of Governors set the bank rate, also known as the discount rate.
"""
return OBBject(results=Query(**locals()).execute())

View File

@@ -9,14 +9,14 @@ import pandas as pd
# ruff: ignore=S310
def get_fama_raw(start_date: str, end_date: str) -> pd.DataFrame:
"""Gets base Fama French data to calculate risk
"""Get base Fama French data to calculate risk.
Returns
-------
pd.DataFrame
A data with fama french model information
"""
with urlopen( # nosec # noqa: S310
with urlopen( # nosec # noqa: S310 SIM117
"https://mba.tuck.dartmouth.edu/pages/faculty/ken.french/ftp/F-F_Research_Data_Factors_CSV.zip"
) as url:
# Download Zipfile and create pandas DataFrame

View File

@@ -47,9 +47,9 @@ class CLASS_fixedincome(Container):
**kwargs
) -> OBBject[List]:
"""
Ameribor (short for the American interbank offered rate) is a benchmark interest rate that reflects the true cost of short-term
interbank borrowing. This rate is based on transactions in overnight unsecured loans conducted on the American Financial Exchange
(AFX).
Ameribor (short for the American interbank offered rate) is a benchmark interest rate that reflects the true cost of
short-term interbank borrowing. This rate is based on transactions in overnight unsecured loans conducted on the
American Financial Exchange (AFX).
Parameters
----------
@@ -124,10 +124,10 @@ class CLASS_fixedincome(Container):
**kwargs
) -> OBBject[List]:
"""
The euro short-term rate (€STR) reflects the wholesale euro unsecured overnight borrowing costs of banks located in the euro area.
The €STR is published on each TARGET2 business day based on transactions conducted and settled on the previous TARGET2 business
day (the reporting date “T”) with a maturity date of T+1 which are deemed to have been executed at arm’s length and thus reflect
market rates in an unbiased way.
The euro short-term rate (€STR) reflects the wholesale euro unsecured overnight borrowing costs of banks located in
the euro area. The €STR is published on each TARGET2 business day based on transactions conducted and settled on
the previous TARGET2 business day (the reporting date “T”) with a maturity date of T+1 which are deemed to have been
executed at arm’s length and thus reflect market rates in an unbiased way.
Parameters
----------
@@ -202,9 +202,10 @@ class CLASS_fixedincome(Container):
**kwargs
) -> OBBject[List]:
"""
Get Effective Federal Funds Rate data. A bank rate is the interest rate a nation's central bank charges to its domestic banks to
borrow money. The rates central banks charge are set to stabilize the economy. In the United States, the Federal Reserve System's
Board of Governors set the bank rate, also known as the discount rate.
Get Effective Federal Funds Rate data. A bank rate is the interest rate a nation's central bank charges to its
domestic banks to borrow money. The rates central banks charge are set to stabilize the economy. In the
United States, the Federal Reserve System's Board of Governors set the bank rate, also known as the discount rate.
Parameters
----------
@@ -279,9 +280,10 @@ class CLASS_fixedincome(Container):
**kwargs
) -> OBBject[List]:
"""
Get Interest Rate on Reserve Balances data A bank rate is the interest rate a nation's central bank charges to its domestic banks
to borrow money. The rates central banks charge are set to stabilize the economy. In the United States, the Federal Reserve
System's Board of Governors set the bank rate, also known as the discount rate.
Get Interest Rate on Reserve Balances data A bank rate is the interest rate a nation's central bank charges to its
domestic banks to borrow money. The rates central banks charge are set to stabilize the economy. In the
United States, the Federal Reserve System's Board of Governors set the bank rate, also known as the discount rate.
Parameters
----------
@@ -339,9 +341,10 @@ class CLASS_fixedincome(Container):
self, chart: bool = False, provider: Optional[Literal["fred"]] = None, **kwargs
) -> OBBject[List]:
"""
Get Effective Federal Funds Rate data. A bank rate is the interest rate a nation's central bank charges to its domestic banks to
borrow money. The rates central banks charge are set to stabilize the economy. In the United States, the Federal Reserve System's
Board of Governors set the bank rate, also known as the discount rate.
Get Effective Federal Funds Rate data. A bank rate is the interest rate a nation's central bank charges to its
domestic banks to borrow money. The rates central banks charge are set to stabilize the economy. In the
United States, the Federal Reserve System's Board of Governors set the bank rate, also known as the discount rate.
Parameters
----------
@@ -495,9 +498,9 @@ class CLASS_fixedincome(Container):
**kwargs
) -> OBBject[List]:
"""
SONIA (Sterling Overnight Index Average) is an important interest rate benchmark. SONIA is based on actual transactions and
reflects the average of the interest rates that banks pay to borrow sterling overnight from other financial institutions and other
institutional investors.
SONIA (Sterling Overnight Index Average) is an important interest rate benchmark. SONIA is based on actual
transactions and reflects the average of the interest rates that banks pay to borrow sterling overnight from other
financial institutions and other institutional investors.
Parameters
----------

View File

@@ -1,6 +1,7 @@
"""CBOE Helpers Module"""
"""CBOE Helpers Module."""
import os
import warnings
from datetime import date, datetime, timedelta
from io import StringIO
from pathlib import Path
@@ -202,7 +203,7 @@ def stock_search(query: str, ticker: bool = False) -> dict:
if len(result) > 0:
data.update({"results": result})
return data
print(f"No results found for: {query}. Try another search query.")
warnings.warn(f"No results found for: {query}. Try another search query.")
return pd.DataFrame()
@@ -230,14 +231,13 @@ def get_ticker_info(symbol: str) -> Tuple[pd.DataFrame, List[str]]:
try:
if symbol in TICKER_EXCEPTIONS:
new_ticker = "^" + symbol
else:
if symbol not in INDEXES:
new_ticker = symbol
elif symbol not in INDEXES:
new_ticker = symbol
elif symbol in INDEXES:
new_ticker = "^" + symbol
elif symbol in INDEXES:
new_ticker = "^" + symbol
# Get the data to return, and if none returns empty Tuple #
# Get the data to return, and if none returns empty Tuple #
symbol_info_url = (
"https://www.cboe.com/education/tools/trade-optimizer/symbol-info/?symbol="
@@ -250,7 +250,7 @@ def get_ticker_info(symbol: str) -> Tuple[pd.DataFrame, List[str]]:
if symbol_info_json.success is False:
ticker_details = pd.DataFrame()
ticker_expirations = []
print("No data found for the symbol: " f"{symbol}" "")
warnings.warn("No data found for the symbol: " f"{symbol}" "")
else:
symbol_details = pd.Series(symbol_info_json["details"])
symbol_details = pd.DataFrame(symbol_details).transpose()
@@ -352,7 +352,7 @@ def get_ticker_info(symbol: str) -> Tuple[pd.DataFrame, List[str]]:
).rename(columns={f"{new_ticker}": f"{symbol}"})
except requests.HTTPError:
print("There was an error with the request'\n")
warnings.warn("There was an error with the request'\n")
ticker_details = pd.DataFrame()
ticker_expirations = list()
return ticker_details, ticker_expirations
@@ -382,24 +382,23 @@ def get_ticker_iv(symbol: str) -> pd.DataFrame:
f"{symbol}"
".json"
)
else:
if symbol not in INDEXES:
quotes_iv_url = (
"https://cdn.cboe.com/api/global/delayed_quotes/historical_data/"
f"{symbol}"
".json"
)
elif symbol not in INDEXES:
quotes_iv_url = (
"https://cdn.cboe.com/api/global/delayed_quotes/historical_data/"
f"{symbol}"
".json"
)
elif symbol in INDEXES:
quotes_iv_url = (
"https://cdn.cboe.com/api/global/delayed_quotes/historical_data/_"
f"{symbol}"
".json"
)
elif symbol in INDEXES:
quotes_iv_url = (
"https://cdn.cboe.com/api/global/delayed_quotes/historical_data/_"
f"{symbol}"
".json"
)
h_iv = request(quotes_iv_url)
if h_iv.status_code != 200:
print("No data found for the symbol: " f"{symbol}" "")
warnings.warn("No data found for the symbol: " f"{symbol}" "")
return pd.DataFrame()
data = h_iv.json()
@@ -439,7 +438,7 @@ def get_ticker_iv(symbol: str) -> pd.DataFrame:
ticker_iv = pd.DataFrame(h_data).transpose()
except requests.HTTPError:
print("There was an error with the request'\n")
warnings.warn("There was an error with the request'\n")
return pd.DataFrame(ticker_iv, columns=iv_order).transpose()
@@ -483,7 +482,7 @@ def get_chains(symbol: str) -> pd.DataFrame:
result = request(quotes_url)
if result.status_code != 200:
print("No data found for the symbol: " f"{symbol}" "")
warnings.warn("No data found for the symbol: " f"{symbol}" "")
return pd.DataFrame()
r_json = result.json()
@@ -552,7 +551,7 @@ def get_chains(symbol: str) -> pd.DataFrame:
quotes["changePercent"] = round(quotes["changePercent"], 2)
except requests.HTTPError:
print("There was an error with the request'\n")
warnings.warn("There was an error with the request'\n")
return pd.DataFrame()
return quotes.reset_index()
@@ -566,7 +565,7 @@ def __generate_historical_prices_url(
url: str = ""
if data_type not in ["historical", "intraday"]:
print(
warnings.warn(
"Invalid data_type. Must be either 'historical' or 'intraday'. Defaulting to 'historical'."
)
data_type = "historical"
@@ -577,20 +576,19 @@ def __generate_historical_prices_url(
f"{symbol}"
".json"
)
else:
if symbol not in INDEXES:
url = (
f"https://cdn.cboe.com/api/global/delayed_quotes/charts/{data_type}/"
f"{symbol}"
".json"
)
elif symbol not in INDEXES:
url = (
f"https://cdn.cboe.com/api/global/delayed_quotes/charts/{data_type}/"
f"{symbol}"
".json"
)
elif symbol in INDEXES:
url = (
f"https://cdn.cboe.com/api/global/delayed_quotes/charts/{data_type}/_"
f"{symbol}"
".json"
)
elif symbol in INDEXES:
url = (
f"https://cdn.cboe.com/api/global/delayed_quotes/charts/{data_type}/_"
f"{symbol}"
".json"
)
return url
@@ -618,7 +616,9 @@ def get_eod_prices(
symbol = symbol.upper()
if symbol == ("NDX", "^NDX"):
print("NDX time series data is not currently supported by the CBOE provider.")
warnings.warn(
"NDX time series data is not currently supported by the CBOE provider."
)
return pd.DataFrame()
if "^" in symbol:
symbol = symbol.replace("^", "")
@@ -626,14 +626,16 @@ def get_eod_prices(
start_date = start_date if start_date else now - timedelta(days=50000)
end_date = end_date if end_date else now
if symbol not in SYMBOLS.index:
print("The symbol, " f"{symbol}" ", was not found in the CBOE directory.")
warnings.warn(
"The symbol, " f"{symbol}" ", was not found in the CBOE directory."
)
return pd.DataFrame()
url = __generate_historical_prices_url(symbol)
result = request(url)
if result.status_code != 200:
print(f"Error: {result.status_code}")
warnings.warn(f"Error: {result.status_code}")
return pd.DataFrame()
data = (

View File

@@ -73,7 +73,6 @@ def get_futures_curve(symbol: str, date: Optional[dateType]) -> pd.DataFrame:
return pd.DataFrame({"date": [], "Last Price": []})
if historical_curve:
print(historical_curve)
return pd.DataFrame(
{"Last Price": historical_curve, "expiration": futures_index}
)

View File

@@ -11,6 +11,7 @@ from openbb_core.app.service.user_service import UserService
from passlib.context import CryptContext
from typing_extensions import Annotated
# ruff: noqa: S105
SECRET_KEY = "a0657288545d1d2e991195841782ae2a22574a22954081db0c2888c5f5ddbecc" # nosec # pragma: allowlist secret
ALGORITHM = "HS256"
ACCESS_TOKEN_EXPIRE_MINUTES = 1440
@@ -78,7 +79,7 @@ def create_jwt_token(
async def get_user_service() -> UserService:
"""Get user service."""
global __user_service # pylint: disable=global-statement
global __user_service # pylint: disable=global-statement # noqa: PLW0603
if __user_service is None:
__user_service = UserService()

View File

@@ -50,7 +50,7 @@ async def login_for_access_token(
sub=user_settings.id,
)
jwt_token = create_jwt_token(access_token=access_token)
return TokenResponse(access_token=jwt_token, token_type="bearer")
return TokenResponse(access_token=jwt_token, token_type="bearer") # noqa: S106
@router.put("/push")

View File

@@ -141,7 +141,8 @@ class ParametersBuilder:
command_coverage: Dict[str, List[str]],
route_default: Optional[str],
) -> Optional[str]:
"""Get the default provider for the given route. Either pick it from the user defaults or from the command coverage."""
"""Get the default provider for the given route.
Either pick it from the user defaults or from the command coverage."""
cmd_cov_given_route = command_coverage.get(route, None)
command_cov_provider = (
cmd_cov_given_route[0] if cmd_cov_given_route else None

View File

@@ -1,6 +1,7 @@
# IMPORT STANDARD
import time
import uuid
import warnings
from pathlib import Path, PosixPath
# IMPORT THIRD-PARTY
@@ -14,14 +15,13 @@ def get_session_id() -> str:
def get_app_id(contextual_user_data_directory: str) -> str:
"""UUID of the current installation."""
"""Get UUID of the current installation."""
try:
app_id = get_log_dir(contextual_user_data_directory).stem
except OSError as e:
if e.errno == 30:
print("Please move the application into a writable location.")
print(
warnings.warn("Please move the application into a writable location.")
warnings.warn(
"Note for macOS users: copy `OpenBB Terminal` folder outside the DMG."
)
raise e
@@ -33,7 +33,6 @@ def get_app_id(contextual_user_data_directory: str) -> str:
def get_log_dir(contextual_user_data_directory: str) -> PosixPath:
"""Retrieve application's log directory."""
log_dir = create_log_dir_if_not_exists(contextual_user_data_directory)
logging_uuid = create_log_uuid_if_not_exists(log_dir)
uuid_log_dir = create_uuid_dir_if_not_exists(log_dir, logging_uuid)

View File

@@ -32,6 +32,8 @@ from openbb_core.app.model.custom_parameter import OpenBBCustomParameter
from openbb_core.app.provider_interface import ProviderInterface
from openbb_core.app.router import RouterLoader
# ruff: noqa: T201
class PackageBuilder:
"""Build the extension package for the SDK."""
@@ -318,21 +320,19 @@ class DocstringGenerator:
type_ = p_type.__name__ if inspect.isclass(p_type) else p_type
meta = param._annotation.__metadata__
description = getattr(meta[0], "description", "") if meta else ""
else:
elif param_name == "provider":
# pylint: disable=W0212
if param_name == "provider":
# pylint: disable=W0212
type_ = param._annotation
default = param._annotation.__args__[0].__args__[0]
description = f"""The provider to use for the query, by default None.
type_ = param._annotation
default = param._annotation.__args__[0].__args__[0]
description = f"""The provider to use for the query, by default None.
If None, the provider specified in defaults is selected or '{default}' if there is
no default."""
elif param_name == "chart":
type_ = "bool"
description = "Whether to create a chart or not, by default False."
else:
type_ = ""
description = ""
elif param_name == "chart":
type_ = "bool"
description = "Whether to create a chart or not, by default False."
else:
type_ = ""
description = ""
docstring += f"{param_name} : {type_}\n"
docstring += f" {description}\n"

View File

@@ -14,6 +14,8 @@ from openbb_core.api.dependency.user import (
verify_password,
)
# ruff: noqa: S105 S106
def test_password_functions():
"""Test password functions."""

View File

@@ -6,6 +6,8 @@ from openbb_core.api.router.user import patch_user_credentials, read_users_setti
from openbb_core.app.model.credentials import Credentials
from openbb_core.app.model.user_settings import UserSettings
# ruff: noqa: S106
def test_read_users_settings():
"""Test read users settings."""

View File

@@ -7,6 +7,8 @@ from openbb_core.app.logs.logging_manager import LoggingManager
from openbb_core.app.model.abstract.error import OpenBBError
from pydantic import BaseModel
# ruff: noqa: S106
class MockLoggingSettings:
def __init__(self, system_settings, user_settings):

View File

@@ -1,5 +1,7 @@
from openbb_core.app.model.hub.features_keys import FeaturesKeys
# ruff: noqa: S105 S106
def test_features_keys():
fk = FeaturesKeys(API_BITQUERY_KEY="test", API_BIZTOC_TOKEN="test2")

View File

@@ -1,5 +1,7 @@
from openbb_core.app.model.hub.hub_session import HubSession
# ruff: noqa: S105 S106
def test_hub_session():
session = HubSession(

View File

@@ -1,5 +1,7 @@
"""Test the hub_service.py module."""
# pylint: disable=W0212
# ruff: noqa: S105 S106
from unittest.mock import MagicMock, patch