Skip to content

Commit

Permalink
Merge branch 'hotfix/update-api-endpoint' of github.com:davidtran001/…
Browse files Browse the repository at this point in the history
…OpenBBTerminal into hotfix/update-api-endpoint
  • Loading branch information
davidtran001 committed Dec 5, 2023
2 parents 6ccd76b + a0085cd commit c852b02
Show file tree
Hide file tree
Showing 27 changed files with 226 additions and 224 deletions.
10 changes: 5 additions & 5 deletions CONTRIBUTING.md
Original file line number Diff line number Diff line change
Expand Up @@ -135,7 +135,7 @@ def get_price_targets(cls, symbol: str) -> pd.DataFrame:
url = f"https://financialmodelingprep.com/api/v4/price-target?symbol={symbol}&apikey={current_user.credentials.API_KEY_FINANCIALMODELINGPREP}"
response = request(url)

# Check if response is valid
# Check if the response is valid
if response.status_code != 200 or "Error Message" in response.json():
message = f"Error, Status Code: {response.status_code}."
message = (
Expand Down Expand Up @@ -345,7 +345,7 @@ Now that we have the model and views, it is time to add to the controller.
- Call the function contained in a `_view.py` file with the arguments parsed by argparse.

Note that the function self.parse_known_args_and_warn() has some additional options we can add. If the function is showing a chart, but we want the option to show raw data, we can add the `raw=True` keyword and the resulting namespace will have the `raw` attribute.
Same with limit, we can pass limit=10 to add the `-l` flag with default=10. Here we also specify the export, and whether it is data only, plots only or anything. This function also adds the `source` attribute to the namespace. In our example, this is important because we added an additional source.
Same with limit, we can pass limit=10 to add the `-l` flag with default=10. Here we also specify the export, and whether it is data only, plots only or anything else. This function also adds the `source` attribute to the namespace. In our example, this is important because we added an additional source.

Our new function will be:

Expand Down Expand Up @@ -511,15 +511,15 @@ In order to add a command to the SDK, follow these steps:

### Add OpenBB Platform endpoint (V4)

Refer to the documentation [here](openbb_platform\CONTRIBUTING.md).
Refer to the documentation [here](https://docs.openbb.co/platform/development).

### Add Unit Tests

This is a vital part of the contribution process. We have a set of unit tests that are run on every Pull Request. These tests are located in the `tests` folder.

Unit tests minimize errors in code and quickly find errors when they do arise. Integration tests are standard usage examples, which are also used to identify errors.

A thorough introduction on the usage of unit tests and integration tests in OpenBBTerminal can be found on the following page respectively:
A thorough introduction on the usage of unit tests and integration tests in OpenBBTerminal can be found on the following page:

[Unit Test README](tests/README.md)

Expand Down Expand Up @@ -578,7 +578,7 @@ CLI :computer: → `_controller.py` :robot: → `_view.py` :art:  &nbs
| **File                           ** | **Role** | **Description** |
| :------------------------- | :------------- | :----------------------------------------------------- |
| **_controller.py** :robot: | The router/input validator | The controller file should hold the least amount of logic possible. Its role is to be a stupid (no logic) router and redirect the command correctly while checking the input with argparser. |
| **_view.py** :art: | The artist | The view file should only output or visualise the data it gets from the `_model` file! The `_view` can limit the data coming from the `_model`, otherwise the data object should be identical in the `_view` and the `_model` files. |
| **_view.py** :art: | The artist | The view file should only output or visualize the data it gets from the `_model` file! The `_view` can limit the data coming from the `_model`, otherwise the data object should be identical in the `_view` and the `_model` files. |
| **_model.py** 🧠 |The brain | The model file is where everything fun happens. The data is gathered (external APIs), processed and returned here. |
| **sdk.py** 🏭 |The SDK Factory | The SDK file is where the callable functions are created for the SDK. There is only one SDK file in the openbb_terminal folder. |

Expand Down
6 changes: 3 additions & 3 deletions build/README.md
Original file line number Diff line number Diff line change
@@ -1,11 +1,11 @@
# Building Installers
This guide serves to assist developers construct OpenBB Terminal installers on MacOs and Windows.
This guide serves to assist developers construct OpenBB Terminal installers on macOS and Windows.

## Overview
Building an installer takes source code as input and produces deployable software as an output. For MacOS the output is a DMG while for windows it is an EXE. This process utilizes two major modules: Pyinstaller & Create-dmg. Windows additionally recruits the service of NSIS. There are two ways to build an installer: locally or through Github.
Building an installer takes source code as input and produces deployable software as an output. For MacOS the output is a DMG while for Windows it is an EXE. This process utilizes two major modules: Pyinstaller & Create-dmg. Windows additionally recruits the service of NSIS. There are two ways to build an installer: locally or through Github.

## Local
In this section we detail the steps necessary to construct an installer locally on a windows machine and mac machine. These steps can be performed on either one of these operating systems so long as they have the OpenBBTerminal repository codebase. This process assumes you already have a working conda environment. Building locally usually takes anywhere from 10-20 minutes.
In this section we detail the steps necessary to construct an installer locally on a Windows machine and Mac machine. These steps can be performed on either one of these operating systems so long as they have the OpenBBTerminal repository codebase. This process assumes you already have a working conda environment. Building locally usually takes anywhere from 10-20 minutes.

### MacOS Steps
1. `brew install create-dmg`
Expand Down
2 changes: 1 addition & 1 deletion build/pyinstaller/macOS/darwin/Resources/conclusion.html
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,7 @@
<h3>WSO2 API Manager</h3>
<p style="color: #020202; font-size: 11px;">Thank you for installing WSO2 API MAnager.</p>
<h5>Run API Manager</h5>
<p style="color: #020202; font-size: 11px;">Open a new terminal and run the following command to get start with APIM server:</p>
<p style="color: #020202; font-size: 11px;">Open a new terminal and run the following command to get started with APIM server:</p>
<code style="color: #c6a72b; font-size: 11px;">&nbsp; $ <span style="color: #abb0b0">wso2am-2.6.0 [command]</span></code>
</div>
<div style="font-family: Helvetica; padding-left: 10px;" align="left">
Expand Down
2 changes: 1 addition & 1 deletion build/pyinstaller/macOS/darwin/Resources/uninstall.sh
Original file line number Diff line number Diff line change
Expand Up @@ -42,7 +42,7 @@ VERSION=__VERSION__
PRODUCT=__PRODUCT__

echo "Application uninstalling process started"
# remove link to shorcut file
# remove link to shortcut file
find "/usr/local/bin/" -name "__PRODUCT__-__VERSION__" | xargs rm
if [ $? -eq 0 ]
then
Expand Down
4 changes: 2 additions & 2 deletions examples/v3/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -29,7 +29,7 @@ This notebook explains how to calculate and plot the Copper-to-Gold ratio.

### realizedVolatilityModels

This notebook demonstrates the six, realized volatility models with in the Technical Analysis module.
This notebook demonstrates the six, realized volatility models within the Technical Analysis module.

- Explore differences between:
- Standard Deviation
Expand Down Expand Up @@ -70,7 +70,7 @@ This notebook demonstrates how to install the OpenBB SDK within Google Colab.

### volumeAtPrice

Volume-at-price is a chart used by technical analysts as a visual gauge to where the trading levels are concentrated, relative to price and volume. In short, it is the sum of volume at different price levels. This notebook utilizes individual components of the OpenBB SDK and combines them to build a new view.
Volume-at-price is a chart used by technical analysts as a visual gauge of where the trading levels are concentrated, relative to price and volume. In short, it is the sum of volume at different price levels. This notebook utilizes individual components of the OpenBB SDK and combines them to build a new view.

- Price
- Volume
Expand Down
2 changes: 1 addition & 1 deletion openbb_platform/CONTRIBUTING.md
Original file line number Diff line number Diff line change
Expand Up @@ -870,7 +870,7 @@ To create a PR to the OpenBB Platform, you'll need to fork the repository and cr
`git add openbb_platform/platform/core/openbb_core/app/constants.py`.
Note: **DON'T** add any files with personal information.
4. Write a concise commit message under 50 characters, e.g. `git commit -m "meaningful commit message"`. If your PR
solves an issue raised by a user, you may specify such issue by adding #ISSUE_NUMBER to the commit message, so that
solves an issue raised by a user, you may specify such an issue by adding #ISSUE_NUMBER to the commit message, so that
these get linked. Note: If you installed pre-commit hooks and one of the formatters re-formats your code, you'll need
to go back to step 3 to add these.

Expand Down
2 changes: 1 addition & 1 deletion openbb_platform/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -42,7 +42,7 @@ This will install the following data providers:
To install extensions that expand the core functionalities specify the extension name or use `all` to install all.

```bash
# Install single extension, e.g. openbb-charting and yahoo finance
# Install a single extension, e.g. openbb-charting and yahoo finance
pip install openbb[charting]
pip install openbb-yfinance
```
Expand Down
4 changes: 2 additions & 2 deletions openbb_platform/core/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@

## Overview

The Core extension serves as the foundational component of the OpenBB Platform. It encapsulates essential functionalities and serves as a infrastructural base for other extensions. This extension is vital for maintaining the integrity and standardization of the platform.
The Core extension serves as the foundational component of the OpenBB Platform. It encapsulates essential functionalities and serves as an infrastructural base for other extensions. This extension is vital for maintaining the integrity and standardization of the platform.

## Key Features

Expand All @@ -27,7 +27,7 @@ Installing through pip:
pip install openbb-core
```

> Note that, the openbb-core is a infrastructural component of the OpenBB Platform. It is not intended to be used as a standalone package.
> Note that, the openbb-core is an infrastructural component of the OpenBB Platform. It is not intended to be used as a standalone package.
### Usage

Expand Down
2 changes: 1 addition & 1 deletion openbb_platform/core/openbb_core/api/rest_api.py
Original file line number Diff line number Diff line change
Expand Up @@ -61,7 +61,7 @@ async def startup():
banner = rf"""
███╗
█████████████████╔══█████████████████╗ OpenBB Platform {system.version}
█████████████████╔══█████████████████╗ OpenBB Platform v{system.version}
███╔══════════███║ ███╔══════════███║
█████████████████║ █████████████████║ Authentication: {auth}
╚═════════════███║ ███╔═════════════╝
Expand Down
14 changes: 6 additions & 8 deletions openbb_platform/core/openbb_core/app/static/account.py
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
"""Account service."""
"""Account."""
# pylint: disable=W0212:protected-access
import json
from functools import wraps
Expand All @@ -18,13 +18,11 @@


class Account:
"""The account service handles the following commands.
/account
login
logout
save
refresh
"""/account
login
logout
save
refresh
"""

SESSION_FILE = ".hub_session.json"
Expand Down
15 changes: 8 additions & 7 deletions openbb_platform/core/openbb_core/app/static/app_factory.py
Original file line number Diff line number Diff line change
@@ -1,3 +1,4 @@
"""App factory."""
from typing import Optional, Type, TypeVar

from openbb_core.app.command_runner import CommandRunner
Expand All @@ -6,21 +7,21 @@
from openbb_core.app.static.account import Account
from openbb_core.app.static.container import Container
from openbb_core.app.static.coverage import Coverage
from openbb_core.app.version import VERSION

E = TypeVar("E", bound=Type[Container])


class BaseApp:
# fmt: off
"""OpenBB Platform
BASE_DOC = f"""OpenBB Platform v{VERSION}
Utilities:
/account
/user
/system
/coverage
"""
# fmt: on


class BaseApp:
"""Base app."""

def __init__(self, command_runner: CommandRunner):
self._command_runner = command_runner
Expand Down Expand Up @@ -58,6 +59,6 @@ class App(BaseApp, extensions or EmptyClass): # type: ignore
def __repr__(self) -> str:
# pylint: disable=E1101
ext_doc = extensions.__doc__ if extensions else ""
return (super().__doc__ or "") + (ext_doc or "")
return BASE_DOC + (ext_doc or "")

return App(command_runner=CommandRunner())
Original file line number Diff line number Diff line change
Expand Up @@ -29,25 +29,11 @@ class BalanceSheetQueryParams(QueryParams):
default=5, description=QUERY_DESCRIPTIONS.get("limit", "")
)

# pylint: disable=inconsistent-return-statements
@field_validator("symbol", mode="before", check_fields=False)
@classmethod
def upper_symbol(cls, v: Union[str, List[str], Set[str]]):
"""Convert symbol to uppercase."""
if isinstance(v, str):
if v.isdigit() or v.isalpha():
return v.upper()
raise ValueError(f"Invalid symbol: {v}. Must be either a ticker or CIK.")
if isinstance(v, List):
symbols = []
for symbol in v:
if symbol.isdigit() or symbol.isalpha():
symbols.append(symbol.upper())
else:
raise ValueError(
f"Invalid symbol: {symbol}. Must be either a ticker or CIK."
)
return ",".join(symbols)
return v.split(",")[0].upper() if "," in v else v.upper()


class BalanceSheetData(Data):
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -26,25 +26,11 @@ class CashFlowStatementQueryParams(QueryParams):
default=5, description=QUERY_DESCRIPTIONS.get("limit", "")
)

# pylint: disable=inconsistent-return-statements
@field_validator("symbol", mode="before", check_fields=False)
@classmethod
def upper_symbol(cls, v: Union[str, List[str], Set[str]]):
"""Convert symbol to uppercase."""
if isinstance(v, str):
if v.isdigit() or v.isalpha():
return v.upper()
raise ValueError(f"Invalid symbol: {v}. Must be either a ticker or CIK.")
if isinstance(v, List):
symbols = []
for symbol in v:
if symbol.isdigit() or symbol.isalpha():
symbols.append(symbol.upper())
else:
raise ValueError(
f"Invalid symbol: {symbol}. Must be either a ticker or CIK."
)
return ",".join(symbols)
return v.split(",")[0].upper() if "," in v else v.upper()


class CashFlowStatementData(Data):
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -80,9 +80,11 @@ class ConsumerPriceIndexQueryParams(QueryParams):
description=QUERY_DESCRIPTIONS.get("units", "")
+ """
Options:
- `growth_previous`: growth from the previous period
- `growth_same`: growth from the same period in the previous year
- `index_2015`: index with base year 2015.""",
- `growth_previous`: Percent growth from the previous period.
If monthly data, this is month-over-month, etc
- `growth_same`: Percent growth from the same period in the previous year.
If looking at monthly data, this would be year-over-year, etc.
- `index_2015`: Rescaled index value, such that the value in 2015 is 100.""",
)
frequency: CPI_FREQUENCY = Field(
default="monthly",
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -26,25 +26,11 @@ class IncomeStatementQueryParams(QueryParams):
default=5, description=QUERY_DESCRIPTIONS.get("limit", "")
)

# pylint: disable=inconsistent-return-statements
@field_validator("symbol", mode="before", check_fields=False)
@classmethod
def upper_symbol(cls, v: Union[str, List[str], Set[str]]):
"""Convert symbol to uppercase."""
if isinstance(v, str):
if v.isdigit() or v.isalpha():
return v.upper()
raise ValueError(f"Invalid symbol: {v}. Must be either a ticker or CIK.")
if isinstance(v, List):
symbols = []
for symbol in v:
if symbol.isdigit() or symbol.isalpha():
symbols.append(symbol.upper())
else:
raise ValueError(
f"Invalid symbol: {symbol}. Must be either a ticker or CIK."
)
return ",".join(symbols)
return v.split(",")[0].upper() if "," in v else v.upper()


class IncomeStatementData(Data):
Expand Down
2 changes: 1 addition & 1 deletion openbb_platform/extensions/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -4,4 +4,4 @@ In this folder you can find the extensions that were created or are supported by

## Available Extensions

See full list of available providers in the [EXTENSIONS file](../EXTENSIONS.md)
See the full list of available providers in the [EXTENSIONS file](../EXTENSIONS.md)
4 changes: 2 additions & 2 deletions openbb_platform/extensions/charting/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -18,7 +18,7 @@ pip install openbb-charting

## PyWry dependency on Linux

The PyWry dependency handles display of interactive charts and tables in a separate window. It is installed automatically with the OpenBB Charting extension.
The PyWry dependency handles the display of interactive charts and tables in a separate window. It is installed automatically with the OpenBB Charting extension.

When using Linux distributions, the PyWry dependency requires certain dependencies to be installed first.

Expand All @@ -35,7 +35,7 @@ When using Linux distributions, the PyWry dependency requires certain dependenci

To use the extension, run any of the OpenBB Platform endpoints with the `chart` argument set to `True`.

Here's an example how it would look like in a python interface:
Here's an example of how it would look like in a python interface:

```python
from openbb import obb
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -36,7 +36,7 @@ async def cpi(
standard_params: StandardParams,
extra_params: ExtraParams,
) -> OBBject[BaseModel]:
"""Consumer Price Index (CPI) Data."""
"""Consumer Price Index (CPI). Returns either the rescaled index value, or a rate of change (inflation)."""
return await OBBject.from_query(Query(**locals()))


Expand Down Expand Up @@ -70,7 +70,7 @@ async def fred_search(
extra_params: ExtraParams,
) -> OBBject[BaseModel]:
"""
Search for FRED series or economic releases by ID or fuzzy query.
Search for FRED series or economic releases by ID or string.
This does not return the observation values, only the metadata.
Use this function to find series IDs for `fred_series()`.
"""
Expand Down
13 changes: 13 additions & 0 deletions openbb_platform/extensions/news/integration/test_news_api.py
Original file line number Diff line number Diff line change
Expand Up @@ -157,3 +157,16 @@ def test_news_company(params, headers):
result = requests.get(url, headers=headers, timeout=10)
assert isinstance(result, requests.Response)
assert result.status_code == 200


@pytest.mark.skip(reason="No providers implement this yet.")
@pytest.mark.parametrize("params", [])
@pytest.mark.integration
def test_news_sector(params, headers):
params = {p: v for p, v in params.items() if v}

query_str = get_querystring(params, [])
url = f"http://0.0.0.0:8000/api/v1/news/sector?{query_str}"
result = requests.get(url, headers=headers, timeout=10)
assert isinstance(result, requests.Response)
assert result.status_code == 200
12 changes: 12 additions & 0 deletions openbb_platform/extensions/news/integration/test_news_python.py
Original file line number Diff line number Diff line change
Expand Up @@ -150,3 +150,15 @@ def test_news_company(params, obb):
assert result
assert isinstance(result, OBBject)
assert len(result.results) > 0


@pytest.mark.skip(reason="Not providers implement this yet.")
@pytest.mark.parametrize("params", [])
@pytest.mark.integration
def test_news_sector(params, obb):
params = {p: v for p, v in params.items() if v}

result = obb.news.sector(**params)
assert result
assert isinstance(result, OBBject)
assert len(result.results) > 0
11 changes: 11 additions & 0 deletions openbb_platform/extensions/news/openbb_news/news_router.py
Original file line number Diff line number Diff line change
Expand Up @@ -35,3 +35,14 @@ async def company(
) -> OBBject[BaseModel]:
"""Company News. Get news for one or more companies."""
return await OBBject.from_query(Query(**locals()))


@router.command(model="SectorNews")
async def sector(
cc: CommandContext,
provider_choices: ProviderChoices,
standard_params: StandardParams,
extra_params: ExtraParams,
) -> OBBject[BaseModel]:
"""Sector News. Get news for one or more sectors."""
return await OBBject.from_query(Query(**locals()))
Loading

0 comments on commit c852b02

Please sign in to comment.