mirror of
https://github.com/OpenBB-finance/OpenBB.git
synced 2026-10-28 13:01:38 +00:00
* Added github actions for gitflow * Minor changes * Fix plot look when using eval and add query to choices (#3881) (#3898) * convert index to datetime and update choices * uncomment economy integration test * fix treasury concat bug * fix datasets concat on duplciates Co-authored-by: montezdesousa <79287829+montezdesousa@users.noreply.github.com> * Testing Gitflow (#3899) * testing gitflow * Name changes * Testing python changes * Added Checkout to Base test * Feature/gitflow (#3900) * Fix plot look when using eval and add query to choices (#3881) (#3901) * convert index to datetime and update choices * uncomment economy integration test * fix treasury concat bug * fix datasets concat on duplciates Co-authored-by: montezdesousa <79287829+montezdesousa@users.noreply.github.com> * Gitflow Implementations (#3902) * testing gitflow * Name changes * Testing python changes * Added Checkout to Base test * More minor fixes for merge * Minor fix * Added nightly build * Gitflow Implementations (#3904) * testing gitflow * Name changes * Testing python changes * Added Checkout to Base test * More minor fixes for merge * Minor fix * Added nightly build * Testing Merge * Main --> develop (#3906) * Fix plot look when using eval and add query to choices (#3881) * convert index to datetime and update choices * uncomment economy integration test * fix treasury concat bug * fix datasets concat on duplciates * Lock ruff version so that new lints dont break our CI (#3905) * Lock ruff version so that new lints dont break our CI * Bumped pre-commit ruff version Co-authored-by: montezdesousa <79287829+montezdesousa@users.noreply.github.com> Co-authored-by: Colin Delahunty <72827203+colin99d@users.noreply.github.com> * GItflow Implementations (#3909) * testing gitflow * Name changes * Testing python changes * Added Checkout to Base test * More minor fixes for merge * Minor fix * Added nightly build * Testing Merge * Merge error fix * Feature/gitflow (#3911) * testing gitflow * Name changes * Testing python changes * Added Checkout to Base test * More minor fixes for merge * Minor fix * Added nightly build * Testing Merge * Merge error fix * Merge fix * merge fix * Merge fix * Merge fix * Merge fix * merge fix * Update develop (#3913) * Fix plot look when using eval and add query to choices (#3881) * convert index to datetime and update choices * uncomment economy integration test * fix treasury concat bug * fix datasets concat on duplciates * Lock ruff version so that new lints dont break our CI (#3905) * Lock ruff version so that new lints dont break our CI * Bumped pre-commit ruff version Co-authored-by: montezdesousa <79287829+montezdesousa@users.noreply.github.com> Co-authored-by: Colin Delahunty <72827203+colin99d@users.noreply.github.com> * Feature/gitflow (#3914) * testing gitflow * Name changes * Testing python changes * Added Checkout to Base test * More minor fixes for merge * Minor fix * Added nightly build * Testing Merge * Merge error fix * Merge fix * merge fix * Merge fix * Merge fix * Merge fix * merge fix * [Gitflow] - Minor fix * Feature/gitflow (#3921) * testing gitflow * Name changes * Testing python changes * Added Checkout to Base test * More minor fixes for merge * Minor fix * Added nightly build * Testing Merge * Merge error fix * Merge fix * merge fix * Merge fix * Merge fix * Merge fix * merge fix * [Gitflow] - Minor fix * Feature/gitflow (#3914) (#3915) * testing gitflow * Name changes * Testing python changes * Added Checkout to Base test * More minor fixes for merge * Minor fix * Added nightly build * Testing Merge * Merge error fix * Merge fix * merge fix * Merge fix * Merge fix * Merge fix * merge fix * [Gitflow] - Minor fix * Nightly build feature * Added branch name docs * poetry add ccxt@latest (#3920) * Fix plot look when using eval and add query to choices (#3881) * convert index to datetime and update choices * uncomment economy integration test * fix treasury concat bug * fix datasets concat on duplciates * Lock ruff version so that new lints dont break our CI (#3905) * Lock ruff version so that new lints dont break our CI * Bumped pre-commit ruff version * poetry add ccxt@latest Co-authored-by: montezdesousa <79287829+montezdesousa@users.noreply.github.com> Co-authored-by: Colin Delahunty <72827203+colin99d@users.noreply.github.com> * Add crypto dd functions to sdk (#3888) * Fix plot look when using eval and add query to choices (#3881) * convert index to datetime and update choices * uncomment economy integration test * fix treasury concat bug * fix datasets concat on duplciates * Add crypto dd functions to sdk * Lock ruff version so that new lints dont break our CI (#3905) * Lock ruff version so that new lints dont break our CI * Bumped pre-commit ruff version * Fixes currency and trailmap Co-authored-by: montezdesousa <79287829+montezdesousa@users.noreply.github.com> Co-authored-by: Colin Delahunty <72827203+colin99d@users.noreply.github.com> * Integration tests refactor (#3781) * generate integration tests report * new console report * simple run_scripts * move tests script to folder * add skipping * always display skips * func name * allow running from relative path * rename some vars and time * typo * change portfolio supress and warning * uncomment economy test * rename test controller * multiprocessing * display test progress and available * rename func * mypy * should not be here * small changes * type hinting and docstrings * new subprocesses default * forget context and chunksize * clean len skipt * small comment * fix subproc default with v * minor change * fix path * better this way * make output visible * allow only sequential run with verbose mode * change message * detail * include andrew idea * limit multiprocessing to clone version * fix for package application * must be up here * allow verbose with multiprocessing but warn * update readme * move tests to core * Update README.md * Update README.md * move readme outside * Update README.md * Update README.md * Update README.md * Update README.md * Update README.md * Update README.md * Update README.md * Update README.md * Update README.md * parse subproc arg * Update README.md * Fix plot look when using eval and add query to choices (#3881) * convert index to datetime and update choices * uncomment economy integration test * fix treasury concat bug * fix datasets concat on duplciates * Lock ruff version so that new lints dont break our CI (#3905) * Lock ruff version so that new lints dont break our CI * Bumped pre-commit ruff version * Delete glossary base command * move scripts * ruff * update pyproject.toml * update yfinance * fix futures and economy test, rewrite * rewrite stocks test yfinance dependent * refactor sia to yfinance 0.2... * fix last failing sia tests * black * update reqs Co-authored-by: James Maslek <jmaslek11@gmail.com> Co-authored-by: Colin Delahunty <72827203+colin99d@users.noreply.github.com> Co-authored-by: Chavithra PARANA <chavithra@gmail.com> * Gitflow - Autodoc (#3922) * Hotfix/dots sources (#3928) * fix: wordwrap * Fix plot look when using eval and add query to choices (#3881) * convert index to datetime and update choices * uncomment economy integration test * fix treasury concat bug * fix datasets concat on duplciates * Lock ruff version so that new lints dont break our CI (#3905) * Lock ruff version so that new lints dont break our CI * Bumped pre-commit ruff version * fix: str Co-authored-by: montezdesousa <79287829+montezdesousa@users.noreply.github.com> Co-authored-by: Colin Delahunty <72827203+colin99d@users.noreply.github.com> * Update dependency: grpcio (#3937) * Update grpcio * Revert "Update grpcio" This reverts commit 676c50a2bdde5ca64614bddd3eaebbccd68c5994. * Update dependencies * Rebase develop? (#3935) * Fix plot look when using eval and add query to choices (#3881) * convert index to datetime and update choices * uncomment economy integration test * fix treasury concat bug * fix datasets concat on duplciates * Lock ruff version so that new lints dont break our CI (#3905) * Lock ruff version so that new lints dont break our CI * Bumped pre-commit ruff version Co-authored-by: montezdesousa <79287829+montezdesousa@users.noreply.github.com> Co-authored-by: Colin Delahunty <72827203+colin99d@users.noreply.github.com> * Update installation guides with videos (#3903) * Fix plot look when using eval and add query to choices (#3881) * convert index to datetime and update choices * uncomment economy integration test * fix treasury concat bug * fix datasets concat on duplciates * Update installation guides with videos * Add fix for Ruff crashing * Me no longer do what James said * Lock ruff version so that new lints dont break our CI (#3905) * Lock ruff version so that new lints dont break our CI * Bumped pre-commit ruff version Co-authored-by: montezdesousa <79287829+montezdesousa@users.noreply.github.com> Co-authored-by: Jeroen Bouma <jeroenbouma@Jeroens-MacBook-Pro.local> Co-authored-by: Colin Delahunty <72827203+colin99d@users.noreply.github.com> Co-authored-by: James Maslek <jmaslek11@gmail.com> * broken link (#3889) * Fix plot look when using eval and add query to choices (#3881) * convert index to datetime and update choices * uncomment economy integration test * fix treasury concat bug * fix datasets concat on duplciates * broken link due to quandl.com redirecting to nasdaq.com, for the link to work and get the appropiate API key you need to remove the period at the end of this link... Co-authored-by: montezdesousa <79287829+montezdesousa@users.noreply.github.com> Co-authored-by: james <jmaslek11@gmail.com> * Issue #3882 Fixed (#3885) * Fix plot look when using eval and add query to choices (#3881) * convert index to datetime and update choices * uncomment economy integration test * fix treasury concat bug * fix datasets concat on duplciates * Issue #3882 Fixed * 2 files reformatted by black * tests added * Lock ruff version so that new lints dont break our CI (#3905) * Lock ruff version so that new lints dont break our CI * Bumped pre-commit ruff version * fixed mypy errors Co-authored-by: montezdesousa <79287829+montezdesousa@users.noreply.github.com> Co-authored-by: Colin Delahunty <72827203+colin99d@users.noreply.github.com> Co-authored-by: James Maslek <jmaslek11@gmail.com> * GitFlow - improve check for changes (#3948) Gitflow Implementation * Rewrite and skip yfinance tests (#3953) * economy * fix futures * fix stocks tests * skip unfixable tests * fix ark * Fixed failing badge not used anymore (#3932) Co-authored-by: James Maslek <jmaslek11@gmail.com> * Fix portfolio returns (#3931) * fix inception bug and clean some useless attributes * reorder attributes * add returns and cumulative returns * fix cumulative returns * fix cumulative returns * remove cumulative ret * add some doc and encapsule methods * order detail * add more details on docstrings * wrong docstring * add commnet * Update portfolio_engine.py * fix bug with unsupported type * Fix plot look when using eval and add query to choices (#3881) * convert index to datetime and update choices * uncomment economy integration test * fix treasury concat bug * fix datasets concat on duplciates * Lock ruff version so that new lints dont break our CI (#3905) * Lock ruff version so that new lints dont break our CI * Bumped pre-commit ruff version * fix table header * fix portfolio integration test * ruff * fix tests * rewrite yfinance call * fix test_draw * test_stocks_helper * bt model * fix comp analysis * fix ftd * fix dd * fix screener Co-authored-by: James Maslek <jmaslek11@gmail.com> Co-authored-by: Colin Delahunty <72827203+colin99d@users.noreply.github.com> Co-authored-by: hjoaquim <h.joaquim@campus.fct.unl.pt> * Put yf.info behind an exchange flag on `load` (#3951) * Put yf.info behind an exchange flag * Guides Co-authored-by: montezdesousa <79287829+montezdesousa@users.noreply.github.com> * Last Price Bug into Previous Close #3865 (#3949) Co-authored-by: James Maslek <jmaslek11@gmail.com> * Add multiple countries option to events (#3938) * allow multiple countries in events cmd * fix test * fix last test * black Co-authored-by: James Maslek <jmaslek11@gmail.com> * Minor Fix for branch name check (#3979) * Gitflow - Added manual trigger to Linting (#3981) * Minor Fix for branch name check * added manual trigger to linting * Linting fix (#3984) Linting fix * Feature/macro convert (#3924) * Fix plot look when using eval and add query to choices (#3881) * convert index to datetime and update choices * uncomment economy integration test * fix treasury concat bug * fix datasets concat on duplciates * Issue #3882 Fixed * 2 files reformatted by black * tests added * Lock ruff version so that new lints dont break our CI (#3905) * Lock ruff version so that new lints dont break our CI * Bumped pre-commit ruff version * fixed mypy errors * Fixed parser options for currency conversion Co-authored-by: montezdesousa <79287829+montezdesousa@users.noreply.github.com> Co-authored-by: Colin Delahunty <72827203+colin99d@users.noreply.github.com> Co-authored-by: James Maslek <jmaslek11@gmail.com> * Update sma.md (#3956) * Fix plot look when using eval and add query to choices (#3881) * convert index to datetime and update choices * uncomment economy integration test * fix treasury concat bug * fix datasets concat on duplciates * Lock ruff version so that new lints dont break our CI (#3905) * Lock ruff version so that new lints dont break our CI * Bumped pre-commit ruff version * Update sma.md Co-authored-by: montezdesousa <79287829+montezdesousa@users.noreply.github.com> Co-authored-by: Colin Delahunty <72827203+colin99d@users.noreply.github.com> Co-authored-by: James Maslek <jmaslek11@gmail.com> * Update overlap_model.py (#3955) * Fix plot look when using eval and add query to choices (#3881) * convert index to datetime and update choices * uncomment economy integration test * fix treasury concat bug * fix datasets concat on duplciates * Lock ruff version so that new lints dont break our CI (#3905) * Lock ruff version so that new lints dont break our CI * Bumped pre-commit ruff version * Update overlap_model.py Co-authored-by: montezdesousa <79287829+montezdesousa@users.noreply.github.com> Co-authored-by: Colin Delahunty <72827203+colin99d@users.noreply.github.com> Co-authored-by: James Maslek <jmaslek11@gmail.com> * Update vwap.md (#3971) Co-authored-by: James Maslek <jmaslek11@gmail.com> * Update overlap_model.py - wrong typehint (#3970) * Fix plot look when using eval and add query to choices (#3881) * convert index to datetime and update choices * uncomment economy integration test * fix treasury concat bug * fix datasets concat on duplciates * Lock ruff version so that new lints dont break our CI (#3905) * Lock ruff version so that new lints dont break our CI * Bumped pre-commit ruff version * Update overlap_model.py Co-authored-by: montezdesousa <79287829+montezdesousa@users.noreply.github.com> Co-authored-by: Colin Delahunty <72827203+colin99d@users.noreply.github.com> Co-authored-by: James Maslek <jmaslek11@gmail.com> * Bump yfinance to 0.2.4 and fix tests (#3977) * upgrade yfinance to 0.2.4 * fix some tests failing bc yfinance new date format * fix remaining tests * fix tests * rewrite failing test * black * rerecord test * fix get_1y_sp500 test * missing import here Co-authored-by: Henrique Joaquim <h.joaquim@campus.fct.unl.pt> Co-authored-by: James Maslek <jmaslek11@gmail.com> * Add extra error handling for yf in etf (#3985) * Fix the news command and making it more stable (#3965) Co-authored-by: James Maslek <jmaslek11@gmail.com> * Hotfix/bug #3945 (#3963) * Add exception to http requests made by ftd * Formatting Co-authored-by: montezdesousa <79287829+montezdesousa@users.noreply.github.com> Co-authored-by: James Maslek <jmaslek11@gmail.com> * Fix #3787 (#3966) Make the get_equal_weights handle portfolio's with stock's filtered out, due to the stocks having to many NaNs. Co-authored-by: James Maslek <jmaslek11@gmail.com> * Add ticker to the load export file (#3997) * bump * Change export name to have the ticker * revert yaml * Feature/release branch gitflow (#3998) * release branch gitflow implentation * Fix integration tests bugs (#3993) * fix tk * fix newsletters * fix lt * exception on pir * fix attrib bug and remove warning * fix earnings * fix ins, lt, whatif * fillna * fix vis Co-authored-by: James Maslek <jmaslek11@gmail.com> * change .env loading priority (#4005) * [FIX] Pytorch-lightning trainer conflict with TQDM progress bar (#4002) * fix for tqdm progress bar conflict * fix tests Co-authored-by: James Maslek <jmaslek11@gmail.com> * bump * Update release branch * revert conda yaml * logging hash * Fix historical futures plot axes (#4006) * change start date to model * rewrite test * ruff * add end date * move futures and update test * return if wrong dates * fix controller test * record mode rewrite model and view Co-authored-by: James Maslek <jmaslek11@gmail.com> * Update version number * Added scipy to intel * Fix M1 build (#4010) * Fix plot look when using eval and add query to choices (#3881) * convert index to datetime and update choices * uncomment economy integration test * fix treasury concat bug * fix datasets concat on duplciates * Lock ruff version so that new lints dont break our CI (#3905) * Lock ruff version so that new lints dont break our CI * Bumped pre-commit ruff version * adding xgboost explicitly * testing juan sugestion * removing unncessary stuff that the hook deals with Co-authored-by: montezdesousa <79287829+montezdesousa@users.noreply.github.com> Co-authored-by: Colin Delahunty <72827203+colin99d@users.noreply.github.com> * Add xgboost to intel * add scipy libs to windows only * add scipy sparse * update scipy and pywin * update tests * UPdate installation.md to reflect 2.2 * fix yf unit tests * Try to get futures tests working * Ignore tz in yf download * Found another end date needed * delelte yf cache Co-authored-by: luqazino@gmail.com <luqazino@gmail.com> Co-authored-by: montezdesousa <79287829+montezdesousa@users.noreply.github.com> Co-authored-by: Colin Delahunty <72827203+colin99d@users.noreply.github.com> Co-authored-by: Chavithra PARANA <chavithra@gmail.com> Co-authored-by: jose-donato <43375532+jose-donato@users.noreply.github.com> Co-authored-by: Jeroen Bouma <jer.bouma@gmail.com> Co-authored-by: Jeroen Bouma <jeroenbouma@Jeroens-MacBook-Pro.local> Co-authored-by: Rob-Rychs <Robrychel@gmail.com> Co-authored-by: Mert Nuhuz <mail@mertnuhuz.com> Co-authored-by: hjoaquim <h.joaquim@campus.fct.unl.pt> Co-authored-by: Bongani Bendile <58882596+Bonganibendi@users.noreply.github.com> Co-authored-by: Sergio A. S <sergio-abu@proton.me> Co-authored-by: northern-64bit <75195383+northern-64bit@users.noreply.github.com> Co-authored-by: martinb-bb <105685594+martinb-bb@users.noreply.github.com>
375 lines
12 KiB
Python
375 lines
12 KiB
Python
# pylint: disable=unused-argument
|
|
import argparse
|
|
import inspect
|
|
from datetime import datetime, timedelta
|
|
from importlib.util import module_from_spec, spec_from_file_location
|
|
from inspect import FullArgSpec, getmembers, isclass
|
|
from pathlib import Path
|
|
from types import FunctionType, ModuleType
|
|
from typing import Any, Dict, List, Optional
|
|
from unittest.mock import patch
|
|
|
|
import pandas as pd
|
|
from pandas.tseries.holiday import USFederalHolidayCalendar
|
|
|
|
import openbb_terminal
|
|
from openbb_terminal.decorators import disable_check_api
|
|
from openbb_terminal.parent_classes import BaseController, CryptoBaseController
|
|
|
|
disable_check_api()
|
|
|
|
DF_STOCK = pd.DataFrame.from_dict(
|
|
data={
|
|
pd.Timestamp("2020-11-30 00:00:00"): {
|
|
"Open": 75.69999694824219,
|
|
"High": 76.08999633789062,
|
|
"Low": 75.41999816894531,
|
|
"Close": 75.75,
|
|
"Adj Close": 71.90919494628906,
|
|
"Volume": 5539100,
|
|
"date_id": 1,
|
|
"OC_High": 75.75,
|
|
"OC_Low": 75.69999694824219,
|
|
},
|
|
pd.Timestamp("2020-12-01 00:00:00"): {
|
|
"Open": 76.0199966430664,
|
|
"High": 77.12999725341797,
|
|
"Low": 75.69000244140625,
|
|
"Close": 77.02999877929688,
|
|
"Adj Close": 73.1242904663086,
|
|
"Volume": 6791700,
|
|
"date_id": 2,
|
|
"OC_High": 77.02999877929688,
|
|
"OC_Low": 76.0199966430664,
|
|
},
|
|
},
|
|
orient="index",
|
|
)
|
|
|
|
sub_folders_abbr = {
|
|
"discovery": "disc",
|
|
"due_diligence": "dd",
|
|
"overview": "ov",
|
|
"alternative": "alt",
|
|
"cryptocurrency": "crypto",
|
|
"behavioural_analysis": "ba",
|
|
"comparison_analysis": "ca",
|
|
"dark_pool_shorts": "dps",
|
|
"portfolio_optimization": "po",
|
|
"quantitative_analysis": "qa",
|
|
"sector_industry_analysis": "sia",
|
|
"technical_analysis": "ta",
|
|
"tradinghours": "th",
|
|
"fundamental_analysis": "fa",
|
|
"mutual_funds": "funds",
|
|
"government": "gov",
|
|
"insider": "ins",
|
|
}
|
|
|
|
sub_names_full = {
|
|
"alt": "Alternative",
|
|
"ba": "Behavioural Analysis",
|
|
"ca": "Comparison Analysis",
|
|
"crypto": "Cryptocurrency",
|
|
"dd": "Due Diligence",
|
|
"defi": "DeFi",
|
|
"disc": "Discovery",
|
|
"dps": "Darkpool Shorts",
|
|
"etf": "ETFs",
|
|
"fa": "Fundamental Analysis",
|
|
"forecast": "Forecasting",
|
|
"funds": "Mutual Funds",
|
|
"gov": "Government",
|
|
"ins": "Insiders",
|
|
"keys": "Keys",
|
|
"nft": "NFTs",
|
|
"onchain": "OnChain",
|
|
"ov": "Overview",
|
|
"po": "Portfolio Optimization",
|
|
"qa": "Quantitative Analysis",
|
|
"screener": "Screener",
|
|
"sia": "Sector Industry Analysis",
|
|
"ta": "Technical Analysis",
|
|
"th": "Trading Hours",
|
|
}
|
|
|
|
|
|
def get_expiration_date():
|
|
"""Gets the next expiration date for dummy data"""
|
|
dt = datetime.now()
|
|
bdays_indx = pd.bdate_range(
|
|
dt.strftime("%Y-%m-%d"),
|
|
(dt + timedelta(days=20)).strftime("%Y-%m-%d"),
|
|
freq=pd.offsets.CustomBusinessDay(calendar=USFederalHolidayCalendar()),
|
|
).tolist()
|
|
expiration = [x.strftime("%Y-%m-%d") for x in bdays_indx if x.weekday() == 4][0]
|
|
return expiration
|
|
|
|
|
|
param_name_to_value = {
|
|
"expiration": get_expiration_date(),
|
|
"start_date": "2022-01-01",
|
|
"start": "2022-01-01",
|
|
"end_date": "2022-08-01",
|
|
"end": "2022-08-01",
|
|
"vs": "USDT",
|
|
}
|
|
param_type_to_value = {
|
|
pd.DataFrame: DF_STOCK,
|
|
(dict, Dict): {"AAPL": DF_STOCK},
|
|
list: [],
|
|
str: "",
|
|
int: 0,
|
|
float: 0.0,
|
|
bool: False,
|
|
}
|
|
|
|
|
|
def get_parameters(controller_cls: BaseController) -> Dict[str, Any]:
|
|
"""Gets the parameters of a controller's `__init__` signature. If required parameters are missing,
|
|
we get the type and create a dummy value for it.
|
|
|
|
Parameters
|
|
----------
|
|
controller_class: Type[BaseController]
|
|
The controller class
|
|
|
|
Returns
|
|
-------
|
|
dict[str, Any]
|
|
The dummy parameters for the controller init
|
|
"""
|
|
signature = inspect.signature(controller_cls)
|
|
kwargs: Dict[str, Any] = {}
|
|
for param in signature.parameters.values():
|
|
if param.name in ("ticker", "symbol"):
|
|
kwargs[param.name] = (
|
|
"AAPL"
|
|
if not issubclass(controller_cls, CryptoBaseController)
|
|
else "BTC"
|
|
)
|
|
elif (
|
|
param.default is inspect.Parameter.empty
|
|
and param.kind is not inspect.Parameter.VAR_KEYWORD
|
|
):
|
|
for param_name, value in param_name_to_value.items():
|
|
if param.name == param_name:
|
|
kwargs[param.name] = value
|
|
break
|
|
if param.name not in kwargs:
|
|
for param_type, value in param_type_to_value.items():
|
|
if isinstance(param_type, tuple):
|
|
if param.annotation in param_type:
|
|
kwargs[param.name] = value
|
|
break
|
|
elif param.annotation is param_type:
|
|
kwargs[param.name] = value
|
|
break
|
|
|
|
return kwargs
|
|
|
|
|
|
class ControllerDoc:
|
|
"""Class that retrieves the ArgumentParser for each command of the Controller and stores it in a dictionary
|
|
for use in auto-generating the documentation.
|
|
|
|
Parameters
|
|
----------
|
|
controller: BaseController
|
|
The controller to get the commands from
|
|
|
|
Attributes
|
|
----------
|
|
controller: BaseController
|
|
The controller to get the commands from
|
|
cmd_parsers: Dict[str, argparse.ArgumentParser]
|
|
A dictionary of the command name and the ArgumentParser for that command
|
|
cmd_funcs: Dict[str, FunctionType]
|
|
A dictionary of the command name and the function for that command
|
|
cmd_fullspec: Dict[str, FullArgSpec]
|
|
A dictionary of the command name and the full argument spec for that command
|
|
ignore: List[str]
|
|
A list of commands to ignore
|
|
commands: List[str]
|
|
A list of commands to document
|
|
|
|
Methods
|
|
-------
|
|
get_commands()
|
|
Get commands
|
|
get_command_parser(command: str)
|
|
Get the parser for a command
|
|
get_all_command_parsers()
|
|
Get all command parsers
|
|
has_commands()
|
|
Checks if controller has commands to document
|
|
"""
|
|
|
|
def __init__(self, controller: BaseController, trailmap: str):
|
|
|
|
self.controller = controller(**get_parameters(controller))
|
|
self.trailmap = trailmap
|
|
self.name = trailmap.split(".")[-1]
|
|
self.cmd_parsers: Dict[str, argparse.ArgumentParser] = {}
|
|
self.cmd_funcs: Dict[str, FunctionType] = {}
|
|
self.cmd_fullspec: Dict[str, FullArgSpec] = {}
|
|
self.ignore = [
|
|
"call_help",
|
|
"call_exit",
|
|
"call_clear",
|
|
"call_cls",
|
|
"call_quit",
|
|
"call_about",
|
|
"call_reset",
|
|
"call_support",
|
|
"call_wiki",
|
|
"call_record",
|
|
"call_stop",
|
|
"call_screenshot",
|
|
]
|
|
self.commands: List[str] = self.get_commands()
|
|
self.get_all_command_parsers()
|
|
|
|
def get_commands(self) -> List[str]:
|
|
"""Get commands"""
|
|
commands = []
|
|
for name, _ in getmembers(self.controller, predicate=inspect.ismethod):
|
|
|
|
if name.startswith("call_") and name not in self.ignore:
|
|
func = getattr(self.controller, name)
|
|
|
|
if hasattr(func, "__wrapped__"):
|
|
func = func.__wrapped__
|
|
if hasattr(func, "__wrapped__"):
|
|
func = func.__wrapped__
|
|
|
|
self.cmd_funcs[name] = func
|
|
self.cmd_fullspec[name] = inspect.getfullargspec(func)
|
|
|
|
if "_" not in self.cmd_fullspec[
|
|
name
|
|
].args and "from openbb_terminal." not in inspect.getsource(func):
|
|
commands.append(name)
|
|
|
|
return commands
|
|
|
|
def get_command_parser(self, command: str) -> Optional[argparse.ArgumentParser]:
|
|
"""Get command parser"""
|
|
if command not in self.cmd_parsers:
|
|
self._get_parser(command)
|
|
|
|
if command in self.cmd_parsers:
|
|
return self.cmd_parsers[command]
|
|
|
|
return None
|
|
|
|
def _get_parser(self, command: str) -> None:
|
|
"""Get parser information from source"""
|
|
|
|
def mock_func(fparser: argparse.ArgumentParser, *args, **kwargs):
|
|
self.cmd_parsers[command] = fparser
|
|
return
|
|
|
|
try:
|
|
with patch.object(
|
|
self.controller, "parse_known_args_and_warn", new=mock_func
|
|
) as _:
|
|
args = {}
|
|
|
|
fullspec = self.cmd_fullspec[command]
|
|
if "_" in fullspec.args:
|
|
return
|
|
|
|
if len(fullspec.args) > 2:
|
|
args.update({arg: ["1234"] for arg in fullspec.args[2:]})
|
|
with patch("openbb_terminal.rich_config.console.print"):
|
|
try:
|
|
_ = getattr(self.controller, command)(["--help"], **args)
|
|
except SystemExit:
|
|
pass
|
|
except Exception as e:
|
|
print(e)
|
|
|
|
def get_all_command_parsers(self) -> None:
|
|
"""Get all command parsers"""
|
|
for command in self.commands:
|
|
self.get_command_parser(command)
|
|
|
|
def has_commands(self) -> bool:
|
|
"""Checks if controller has commands"""
|
|
return len(self.commands) > 0
|
|
|
|
|
|
class LoadControllersDoc:
|
|
"""Class that loads all controllers and creates a ControllerDoc class instance for each one
|
|
|
|
|
|
Attributes
|
|
----------
|
|
controller_docs: Dict[str, ControllerDoc]
|
|
A dictionary of the controller name and the ControllerDoc class instance for that controller
|
|
|
|
Methods
|
|
-------
|
|
get_controllers()
|
|
Gets all controllers to create a ControllerDoc class instance for
|
|
get_controller_doc(controller: str)
|
|
Gets the ControllerDoc class instance for a controller
|
|
available_controllers()
|
|
Gets a list of available controllers names
|
|
"""
|
|
|
|
def __init__(self) -> None:
|
|
self.controller_docs: Dict[str, ControllerDoc] = {}
|
|
self.get_controllers()
|
|
|
|
def get_controllers(self) -> None:
|
|
"""Gets all controllers"""
|
|
for trailmap, module in self._get_modules().items():
|
|
for name, obj in getmembers(module):
|
|
if name != "TerminalController" and "BaseController" not in name:
|
|
if isclass(obj) and issubclass(obj, BaseController):
|
|
if trailmap not in self.controller_docs:
|
|
ctrl = ControllerDoc(obj, trailmap)
|
|
if ctrl.has_commands():
|
|
self.controller_docs[trailmap] = ctrl
|
|
|
|
def _get_modules(self) -> Dict[str, ModuleType]:
|
|
"""Gets all controllers modules"""
|
|
modules = {}
|
|
terminal_path = Path(openbb_terminal.__file__).parent
|
|
|
|
for file in terminal_path.glob("**/*controller.py"):
|
|
spec = spec_from_file_location(file.stem, file)
|
|
if spec is not None and spec.loader is not None:
|
|
module = module_from_spec(spec)
|
|
spec.loader.exec_module(module)
|
|
|
|
ctrl_path = (
|
|
str(file)
|
|
.replace(str(terminal_path), "")
|
|
.replace("\\", "/")
|
|
.split("/")[1:]
|
|
)
|
|
for sub_name, abbr in sub_folders_abbr.items():
|
|
ctrl_path = [
|
|
path.lower().replace(sub_name, abbr) for path in ctrl_path
|
|
]
|
|
|
|
trailmap = ".".join(ctrl_path[:-1])
|
|
if trailmap not in modules:
|
|
modules[trailmap] = module
|
|
|
|
return modules
|
|
|
|
def get_controller_doc(self, controller_name: str) -> ControllerDoc:
|
|
"""Get the ControllerDoc instance for a controller"""
|
|
if controller_name not in self.controller_docs:
|
|
raise KeyError(f"Controller {controller_name} not found")
|
|
|
|
return self.controller_docs[controller_name]
|
|
|
|
def available_controllers(self) -> List[str]:
|
|
"""Get available controllers"""
|
|
return [ctrl for ctrl in self.controller_docs if ctrl != ""]
|