Files
OpenBB/openbb_terminal/common/common_model.py
James Maslek 707ae7e317 Release 2.5.0 (#4355)
* Rename SDK folder

* Fixing all the tests I hope

* Depreciate the sia menu

* Fix routine script

* Update SDK generation scripts

* This needed fixing anyways

* Regenerate SDK files

* Update paths in sdk helpers

* Regenerate the remains of the SDK

* Fix candle not working with symbol via the sdk

* Fix pydocstyle errors

* deps

* Add in Docstrings

* Push to website since I need to upload images

* typos

* Add in Fixed Income Guide

* Tests : fix cassette

* changes to layout and adding more content

* trailmap

* poetry

* updates to requirements files

* add `_try_to_login` to sdk generation, fix `_chart` in `about()` url

* sentiment analysis

* refactor

* changing to base model default

* rounding

* renewing poetry

* fixed poetry

* spacing

* black

* adds selectable models for realized volatility calculations

* fixes line too long

* Add intro guides to Fixed Income

* Fix some missing docstrings

* Fix website not working

* missed a few

* fix /economy/test_yfinance_view tests

* fix etf/test_stockanalysis_model.py

* fix etf/test_stockanalysis_view.py

* fix test_stocks_controller

* deprecating non used function

* update financedatabase to 2.0.4

* Delete SIA from OpenBB Docs and SDK

* Searching was not done properly for short name and index

* changes the default data source for crypto.load

* Fix tests I broke

* Little fixy fix to remove duplicates

* Fix tests

* typo

* adds check for empty dataframe

* Patch Equity Report

* Update so that image links to website

* linting v2

* silly imports

* adding tempfile

* add imap unordered

* reordering imports

* Adding databento as a source (#4293)

* First commit

* Baby steps

* Keys and sdk

* Fix import for api key

* Add SDK endpoints

* Test + api checks

* tests

* roque print of api key

* Changes

* minor

* custom timeout

* improve timeouts

---------

Co-authored-by: hjoaquim <h.joaquim@campus.fct.unl.pt>

* Tests

* Integration test

* frozendict remove

* update spec

* rename sdk faq to troubleshooting

* add hidden import

* add hidden imports

* imports again

* valid url check

* new lines and prompt

* split imports

* more spec

* adds cones to the crypto-ta menu

* Fix tests

* Update code to reflect new changes to FinanceDatabase

* Small bugfix for DCF if you have no ticker loaded

* remove yfinance from news

* add reverse fx choices

* black

* ruff

* Add options greeks to the SDK

* Linting

* Delete rogue file and update test and add fixedincome to en.yml

* fix for options screener

* ruff

* updates tests for options screener

* reqs

* updates more test files

* rewrite for test_github_model

* rewrite test for test_syncretism_view

* removes test_view_available_presets[]

* black

* coverage

* adds option screener preset

* Update directories.py

* len & set

* set all list

* adds unit testing for cones

* ruff

* pylint

* adds options screener endpoint to SDK

* test markers

* Testing draft PR mode

* Update package to v2.0.7

* Remove etf/screener and tests

* Updated

* Merge reqs

* Updated readme

* hook test for pyinstaller

* Little fixy fix

* Remove etf/scr from SDK

* Update tests

* Update hook-whisper.py

* oops lol

* Update sdk

* update

* Etf

* removed old trailmap csv's

* Update fixedincome text

* add greeks to trail

* rouge file

* merge killed it

* fix test

* fix build failure

* catch for error message

* fix for frozendict

* caching search and prompting on hub

* whisper model prompts

* Fix long/short issue and fix transform issue

* separates volatility models from cones function

* Introduce CPI functionality

* improves error handling for volatility models when window length is too small

* ur welcome <3

* additional sanity check for volatility_view

* updates volatility_model test

* black

* Fix linting

* Make cpi a little bit more robust

* Add in missing value

* sdk updates

* update dep files

* Update trail_map_forecasting.csv

* import ordering pylint?

* fix trailing comma

* sorted trailmaps

* remove one test artifact

* rewrite test

* Adds the missing pieces.

* adds clickable URL in keys + Databento

* adds databento images

* adds images for Databento

* update deps

* req files

* swap order in databento

* ruff

* mypy

* lint

* sdk

* makes requested changes

* ruff v2..

* replaces screenshot.

* Removed because it shouldn't have been in this PR.

* ruff v3

* Minor edit, move installation to position 2 instead of last

* util linting changes

* linting for controller

* fix test

* test

* Revert some tests

* Guess not

* see if this sticks

* fixes

* Fix linters.  Add --video if not provided

* Checkout develop tests for keys

* Release time

* Revert papermill and update gh pages action

* Fix shortname (#4356)

* uninstall brotli on conda test

* Fix issue 4316 (#4357)

* Fix issue 4316

* Updating polygon_model + options_controller

* Tests : FRED

* ruff

---------

Co-authored-by: Theodore Aptekarev <aptekarev@gmail.com>
Co-authored-by: Jeroen Bouma <jer.bouma@gmail.com>
Co-authored-by: Danglewood <85772166+deeleeramone@users.noreply.github.com>
Co-authored-by: hjoaquim <h.joaquim@campus.fct.unl.pt>
Co-authored-by: Chavithra PARANA <chavithra@gmail.com>
Co-authored-by: teh_coderer <me@tehcoderer.com>
Co-authored-by: martinb-bb <105685594+martinb-bb@users.noreply.github.com>
Co-authored-by: Diogo Sousa <montezdesousa@gmail.com>
Co-authored-by: northern-64bit <75195383+northern-64bit@users.noreply.github.com>
Co-authored-by: luqazino@gmail.com <luqazino@gmail.com>
Co-authored-by: colin99d <colin99delahunty@gmail.com>
Co-authored-by: montezdesousa <79287829+montezdesousa@users.noreply.github.com>
Co-authored-by: andrewkenreich <andrew.kenreich@gmail.com>
2023-03-01 08:47:12 -05:00

113 lines
3.7 KiB
Python
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

"""Common Model"""
__docformat__ = "numpy"
import logging
from pathlib import Path
from typing import Any, Dict, Optional
import pandas as pd
import statsmodels.api as sm
from linearmodels.datasets import wage_panel
from pandas import errors
from openbb_terminal.decorators import log_start_end
from openbb_terminal.rich_config import console
logger = logging.getLogger(__name__)
DATA_EXAMPLES: Dict[str, str] = {
"anes96": "American National Election Survey 1996",
"cancer": "Breast Cancer Data",
"ccard": "Bill Greene’s credit scoring data.",
"cancer_china": "Smoking and lung cancer in eight cities in China.",
"co2": "Mauna Loa Weekly Atmospheric CO2 Data",
"committee": "First 100 days of the US House of Representatives 1995",
"copper": "World Copper Market 1951-1975 Dataset",
"cpunish": "US Capital Punishment dataset.",
"danish_data": "Danish Money Demand Data",
"elnino": "El Nino - Sea Surface Temperatures",
"engel": "Engel (1857) food expenditure data",
"fair": "Affairs dataset",
"fertility": "World Bank Fertility Data",
"grunfeld": "Grunfeld (1950) Investment Data",
"heart": "Transplant Survival Data",
"interest_inflation": "(West) German interest and inflation rate 1972-1998",
"longley": "Longley dataset",
"macrodata": "United States Macroeconomic data",
"modechoice": "Travel Mode Choice",
"nile": "Nile River flows at Ashwan 1871-1970",
"randhie": "RAND Health Insurance Experiment Data",
"scotland": "Taxation Powers Vote for the Scottish Parliament 1997",
"spector": "Spector and Mazzeo (1980) - Program Effectiveness Data",
"stackloss": "Stack loss data",
"star98": "Star98 Educational Dataset",
"statecrim": "Statewide Crime Data 2009",
"strikes": "U.S. Strike Duration Data",
"sunspots": "Yearly sunspots data 1700-2008",
"wage_panel": "Veila and M. Verbeek (1998): Whose Wages Do Unions Raise?",
}
file_types = ["xlsx", "csv"]
@log_start_end(log=logger)
def load(
file: str,
data_files: Optional[Dict[Any, Any]] = None,
data_examples: Optional[Dict[Any, Any]] = None,
) -> pd.DataFrame:
"""Load custom file into dataframe.
Parameters
----------
file: str
Path to file
data_files: dict
Contains all available data files within the Export folder
data_examples: dict
Contains all available examples from Statsmodels
Returns
-------
pd.DataFrame
Dataframe with custom data
"""
if data_files is None:
data_files = {}
if data_examples is None:
data_examples = DATA_EXAMPLES
if file in data_examples:
if file == "wage_panel":
return wage_panel.load()
return getattr(sm.datasets, file).load_pandas().data
full_file = data_files[file] if file in data_files else file
if not Path(full_file).exists():
console.print(f"[red]Cannot find the file {full_file}[/red]\n")
return pd.DataFrame()
file_type = Path(full_file).suffix
try:
if file_type == ".xlsx":
data = pd.read_excel(full_file)
elif file_type == ".csv":
data = pd.read_csv(full_file)
else:
console.print(
f"The file type {file_type} is not supported. Use .xlsx or .csv."
)
return pd.DataFrame()
except errors.ParserError:
console.print("[red]The given file is not properly formatted.[/red]\b")
return pd.DataFrame()
except errors.EmptyDataError:
console.print("[red]The given file is empty.[/red]\b")
return pd.DataFrame()
if data is None:
return pd.DataFrame()
if not data.empty:
data.columns = [x.replace("/", "_") for x in data.columns]
return data