Files
OpenBB/openbb_terminal/portfolio/portfolio_optimization/optimizer_helper.py
Jeroen Bouma 6421be3d8e Cleanse functionality from relying on yfinance (#4176)
* Cleanse PO from Yahoo Finance

* I removed equal but then moved it back in

* Update tests

* Get rid of sust command

* Get rid of quote since broken

* Added in export capability for quote

* Remove pir and summary, fix news and change source for weights

* Update stuff

* Add sources

* Update portfolio to not be dependend on Yahoo Finance

* Update all tests

* Update SDK

* Details

* Fix integration scripts

* I think I had to rewrite these

* Update more tests

* oopsie

* Fix 1

* Fix Sort

* and fix test

---------

Co-authored-by: james <jmaslek11@gmail.com>
2023-02-09 16:57:26 -05:00

93 lines
2.0 KiB
Python

"""Optimization helpers"""
__docformat__ = "numpy"
from typing import Any
import pandas as pd
from openbb_terminal.portfolio.portfolio_optimization.statics import (
OPTIMIZATION_PARAMETERS,
RISK_CHOICES,
TERMINAL_TEMPLATE_MAP,
)
from openbb_terminal.rich_config import console
def dict_to_df(d: dict) -> pd.DataFrame:
"""Convert a dictionary to a DataFrame
Parameters
----------
d : dict
Dictionary to convert
Returns
-------
pd.DataFrame
DataFrame with dictionary
"""
if not d:
return pd.DataFrame()
df = pd.DataFrame.from_dict(data=d, orient="index", columns=["value"])
return df
def validate_risk_measure(risk_measure: str, warning: bool = True) -> str:
"""Check that the risk measure selected is valid
Parameters
----------
risk_measure : str
Risk measure to check
Returns
-------
str
Validated risk measure
"""
if risk_measure.lower() in RISK_CHOICES:
return RISK_CHOICES[risk_measure.lower()]
if warning:
console.print("[yellow]Risk measure not found. Using 'MV'.[/yellow]")
return "MV"
def get_kwarg(key: str, kwargs: dict, default: Any = None) -> Any:
"""Get a key from kwargs
If key is in kwargs, returns it.
Otherwise, if default provided, returns it.
Otherwise, if key is in OPTIMIZATION_PARAMETERS, returns it.
Parameters
----------
key : str
The key to be searched
kwargs : dict
The kwargs to be searched
default : Any
The default value to be returned if the key is not found
Returns
-------
Any
The value of the key if it exists, else None
"""
if key in kwargs:
return kwargs[key]
if default:
return default
# TODO: Remove this line when mapping between template and terminal is not needed
template_key = TERMINAL_TEMPLATE_MAP.get(key, key)
PARAMETER = OPTIMIZATION_PARAMETERS.get(template_key)
if PARAMETER is None:
return default
return PARAMETER.default