update core README

This commit is contained in:
Diogo Sousa
2023-07-24 11:27:19 +01:00
parent 7b76ab4839
commit 98b50c3149

View File

@@ -4,22 +4,15 @@
- [THIS README IS A WORK IN PROGRESS AND CAN BE VERY MUCH OUT OF DATE. REFRESH THE PAGE UNTIL THIS BANNER IS GONE](#this-readme-is-a-work-in-progress-and-can-be-very-much-out-of-date-refresh-the-page-until-this-banner-is-gone)
- [1. Introduction](#1-introduction)
- [2. How to install?](#2-how-to-install)
- [3. How to add a plugin?](#3-how-to-add-a-plugin)
- [3. How to add an extension?](#3-how-to-add-an-extension)
- [4. Usage](#4-usage)
- [4.1. Update the settings](#41-update-the-settings)
- [4.2. Define the CommandRunnerSession](#42-define-the-commandrunnersession)
- [4.2.1. Use your OpenBB Hub account](#421-use-your-openbb-hub-account)
- [4.3. Define the Command parameters](#43-define-the-command-parameters)
- [4.4. Run the command](#44-run-the-command)
- [4.5 Run the static version (LEAST STABLE ON DEVELOP)](#45-run-the-static-version-least-stable-on-develop)
- [4.5.1. App settings and system](#451-app-settings-and-system)
- [4.5.2. Use your OpenBB Hub account](#452-use-your-openbb-hub-account)
- [5. See routes](#5-see-routes)
- [6. Using the REST API](#6-using-the-rest-api)
- [7. Static version (BEING REFACTORED)](#7-static-version-being-refactored)
- [8. Front-end typing](#8-front-end-typing)
- [9. Default User](#9-default-user)
- [4.1. Static version](#41-static-version)
- [4.1.1. Command output](#411-command-output)
- [4.1.2. Utilities](#412-utilities)
- [4.1.3. OpenBB Hub account](#413-openbb-hub-account)
- [5. REST API](#5-rest-api)
- [5.1. Test users](#51-test-users)
- [6. Front-end typing](#6-front-end-typing)
## 1. Introduction
@@ -39,26 +32,27 @@ These functions are special:
Git clone the repository:
```bash
git clone git@github.com:OpenBB-finance/openbb-sdk-core.git
git clone git@github.com:OpenBB-finance/OpenBBTerminal.git
```
**INSTALL**
Install the package.
Go to `openbb_sdk` folder and install the package.
```bash
cd openbb_sdk
poetry install
```
## 3. How to add a plugin?
## 3. How to add an extension?
**PROJECT**
Build a Python package:
```bash
poetry new openbb-sdk-my_plugin
poetry new openbb-sdk-my_extension
```
**COMMAND**
@@ -66,44 +60,56 @@ poetry new openbb-sdk-my_plugin
Add a router and a command.
```python
# File my_plugin/plugin_router.py
# File my_extension/extension_router.py
from openbb_core.app.router import Router
router = Router(prefix="/my_name")
router = Router(prefix="/router_name")
@router.command
def some_command(
cc: CommandContext,
query: StockQueryParams,
provider: ProviderName,
some_param: some_param_type,
) -> CommandOutput[Item]:
pass
```
If your command only makes use of a `openbb-provider` model, there is no need to repeat its structure in the parameters. Just pass the model name as an argument. This is an example how we do it for `stocks.load` which only depends on `StockEOD` model defined in `openbb-provider`.
```python
@router.command(model="StockEOD")
def load(
cc: CommandContext, # user settings inside
provider_choices: ProviderChoices, # available providers
standard_params: StandardParams, # symbol, start_date, etc.
extra_params: ExtraParams, # provider specific parameters
) -> CommandOutput[BaseModel]:
"""Load stock data for a specific ticker."""
return CommandOutput(results=Query(**locals()).execute())
```
**ENTRYPOINT**
Add an entrypoint for the plugin inside your `pyproject.toml` file.
Add an entrypoint for the extension inside your `pyproject.toml` file.
```toml
# File pyproject.toml
packages = [{include = "openbb_sdk_my_plugin"}]
packages = [{include = "openbb_sdk_my_extension"}]
...
[tool.poetry.plugins."openbb_plugins"]
plugin_name_space = "my_plugin.plugin_router:router"
[tool.poetry.extensions."openbb_extensions"]
extension_name_space = "my_extension.extension_router:router"
```
**INSTALL**
Install your plugin.
Install your extension.
```bash
cd openbb_sdk_my_extension
poetry install
```
## 4. Usage
# 4. Usage
### 4.1. Update the settings
Update the settings
```
# FILE <your_home_directory>/.openbb_sdk/user_settings.json
@@ -137,146 +143,163 @@ poetry install
}
```
### 4.2. Define the CommandRunnerSession
## 4.1 Static version
Run your command:
```python
from datetime import datetime
from openbb_core.app.command_runner import CommandRunner, CommandRunnerSession
from openbb import sdk
app = CommandRunnerSession()
```
#### 4.2.1. Use your OpenBB Hub account
```python
# Create Hub manager
hs = HubService()
# Connect with email, password or SDK token
hs.connect(email="your_email", password="your_password") # pragma: allowlist secret
# Pull your settings
user_settings = hs.pull()
# Make the app aware
app = CommandRunnerSession(user_settings=user_settings)
# Change a credential
user_settings.credentials.polygon_api_key = "new_key" # pragma: allowlist secret
# Send change back to Hub
hs.push(user_settings)
# Disconnect
hs.disconnect()
```
### 4.3. Define the Command parameters
```python
from datetime import datetime
from openbb_provider.models.stock_eod import StockEODQueryParams
from openbb_provider.registry import ProviderName
stock_query = StockEODQueryParams(
output = sdk.stocks.load(
symbol="TSLA",
start_date=datetime.fromisoformat("2023-05-01"),
end_date=datetime.fromisoformat("2023-05-04"),
)
provider = ProviderName.fmp
start_date="2023-01-01",
provider="fmp",
chart=True
)
```
### 4.1.1. Command output
### 4.4. Run the command
**ATTRIBUTES**
Each command will always return a `CommandOutput`. There you will find:
- `results`: the data returned by the command, if any
- `provider`: the external data source used to get the data, if any
- `warnings`: a list of warnings caught during the command execution
- `error`: any error that occurred during the command execution
- `chart`: the formatted data used to display the results in a chart
**HELPERS**
To help you manipulate or visualize the data we make some helpers available.
- `to_dataframe`: transforms `results` into a pandas DataFrame
```python
command_output = app.run(
"/openbb/stocks/fetch",
query=stock_query,
provider=provider,
).output
# Access the StockData
command_output.results
>>> output.to_dataframe()
open high low close adj_close ...
date
2023-07-21 268.00 268.00 255.8000 260.02 260.019989 ...
2023-07-20 279.56 280.93 261.2000 262.90 262.899994 ...
2023-07-19 296.04 299.29 289.5201 291.26 291.260010 ...
```
### 4.5 Run the static version (LEAST STABLE ON DEVELOP)
You also have the static version.
First update the cache:
- `to_dict`: transforms `results` into a dict of lists
```python
from openbb_core.app.static.cache_builder import CacheBuilder
CacheBuilder.build()
```
Then run your command:
```python
from openbb_core import openbb
stock_data = openbb.stocks.load(symbol="TSLA", start_date="2023-01-01", provider="fmp")
stock_data.dataframe()
```
#### 4.5.1. App settings and system
```python
from openbb_core.app.static import app
app.settings
app.settings.profile
app.settings.credentials
app.settings.preferences
app.system
```
#### 4.5.2. Use your OpenBB Hub account
```python
from openbb_core.app.static import app
# Login with email, password or SDK token
app.account.login(email="your_email", password="your_password", remember_me=True) # pragma: allowlist secret
# Change a credential
app.account.settings.credentials.polygon_api_key = "new_key" # pragma: allowlist secret
# Save account changes
app.account.save()
# Refresh account with latest changes
app.account.refresh()
# Logout
app.account.logout()
```
## 5. See routes
```python
from openbb_core.app.router import CommandMap
command_map = CommandMap()
command_map.map
```
```
"{
'/ff/qa/load_random': <function ff_plugin.router.qa.qa_router.load_random(name: str) -> ff_plugin.router.qa.qa_router.CommandOutput[RandData]>,
'/ff/qa/calc_ret': <function ff_plugin.router.qa.qa_router.calc_ret(column: str, rand_data: ff_plugin.router.qa.qa_router.RandData) -> ff_plugin.router.qa.qa_router.CommandOutput[ReturnSeries]>,
'/ff/qa/garch': <function ff_plugin.router.qa.qa_router.garch(return_series: ff_plugin.router.qa.qa_router.ReturnSeries, p: int = 1, o: int = 0, q: int = 1, mean: str = 'constant', horizon: int = 100) -> ff_plugin.router.qa.qa_router.CommandOutput[GARCH]>,
'/ff/qa/summary': <function ff_plugin.router.qa.qa_router.summary(rand_data: ff_plugin.router.qa.qa_router.RandData) -> ff_plugin.router.qa.qa_router.CommandOutput[Dataset]>,
...
>>> output.to_dict()
{
'open': [268.0, 279.56, 296.04],
'high': [268.0, 280.93, 299.29],
'low': [255.8, 261.2, 289.5201],
'close': [260.02, 262.9, 291.26],
'adj_close': [260.019989, 262.899994, 291.26001],
...
}
```
## 6. Using the REST API
- `show`: displays `chart.content` to a chart
```python
>>> output.show()
# Jupyter Notebook: inline chart
# Python Interpreter: opens a PyWry window with the chart
```
Setup `<your_home_directory>/.openbb_sdk/user_settings.json`:
- `to_plotly_json()`: proxy to `chart.content`
```python
>>> output.to_plotly_json()
{'data':
[
{
'close': [260.02, 262.9, 291.26],
'decreasing': {'line': {'width': 1.1}},
'high': [268.0, 280.93, 299.29],
'increasing': {'line': {'width': 1.1}},
...
}
...
]
}
```
### 4.1.2. Utilities
**SETTINGS**
These are your user settings, you can change them at anytime and they will be applied. Don't forget to `sdk.account.save()` if you want these changes to persist.
```python
from openbb import sdk
sdk.settings.profile
sdk.settings.credentials
sdk.settings.preferences
sdk.settings.defaults
```
**SYSTEM**
Check your system settings. Most of the properties are read-only during runtime, so any changes there will be void.
- `debug_mode`: here if you set `debug_mode = True` any exception that occurs during execution will be raised immediatly.
```python
from openbb import sdk
sdk.system
```
**COVERAGE**
```python
from openbb import sdk
# Commands
>>> sdk.coverage.commands
{
'/crypto/load': ['fmp', 'polygon'],
'/economy/const': ['fmp'],
'/economy/cpi': ['fred'],
...
}
# Providers
sdk.coverage.providers
{
'fmp':
[
'/crypto/load',
'/economy/const',
'/economy/index',
...
],
'fred': ['/economy/cpi'],
...
}
```
### 4.1.3. OpenBB Hub account
```python
from openbb import sdk
# Login with email, password or SDK token
sdk.account.login(email="your_email", password="your_password", remember_me=True) # pragma: allowlist secret
# Change a credential
sdk.account.settings.credentials.polygon_api_key = "new_key" # pragma: allowlist secret
# Save account changes
sdk.account.save()
# Refresh account with latest changes
sdk.account.refresh()
# Logout
sdk.account.logout()
```
## 5. REST API
OpenBB SDK comes with a ready to use Rest API built with FastAPI.
```
# FILE <your_home_directory>/.openbb_sdk/user_settings.json
@@ -316,38 +339,7 @@ Start the application:
uvicorn openbb_core.api.rest_api:app --reload
```
## 7. Static version (BEING REFACTORED)
Usage
```python
from openbb_core.app.static.cache_builder import CacheBuilder
CacheBuilder.build()
from openbb_core import openbb
openbb.stocks.load(...)
```
## 8. Front-end typing
Here are libraries to get frontend typing.
openapi-typescript + openapi-fetch
- https://github.com/drwpow/openapi-typescript
openapi-generator
- https://fastapi.tiangolo.com/advanced/generate-clients/
## 9. Default User
## 5.1 Test users
There are 2 default users for testing purpose:
@@ -359,3 +351,14 @@ User "openbb"
User "finance"
- username : finance
- password : finance
## 6. Front-end typing
Here are libraries to get frontend typing.
openapi-typescript + openapi-fetch
- https://github.com/drwpow/openapi-typescript
openapi-generator
- https://fastapi.tiangolo.com/advanced/generate-clients/