From ebf96273aa8ad92e1e7211f4b931a977f792a48e Mon Sep 17 00:00:00 2001 From: minhhoang1023 <40023817+minhhoang1023@users.noreply.github.com> Date: Sun, 9 Oct 2022 14:46:24 +0200 Subject: [PATCH] New OpenBB SDK documentation (#2696) * First draft for SDK documentation * add in styles and documentation screenshots * add more screenshots * more screenshots * Polish texts * Update portfolio screenshots * Make changes from feedback * Update API_README.md * Create API_README.md * Update README * Create API_README.md * Update API_README.md * Update API_README.md * Update API_README.md * Update API_README.md * fix linting * fix lintings * Update API_README.md Co-authored-by: montezdesousa <79287829+montezdesousa@users.noreply.github.com> --- openbb_terminal/API_README.md | 372 +++++++++++++++++++++++++++------- 1 file changed, 298 insertions(+), 74 deletions(-) diff --git a/openbb_terminal/API_README.md b/openbb_terminal/API_README.md index 0ee4298a6aa..59a9a5e5aca 100644 --- a/openbb_terminal/API_README.md +++ b/openbb_terminal/API_README.md @@ -1,37 +1,312 @@ -# OpenBB API +# OpenBB SDK -## Usage +OpenBB SDK gives you direct and programmatic access to all capabilities from OpenBB Terminal. +You will have the necessary building blocks to create your own financial tools and applications, +whether that be a visualization dashboard or a custom report on Jupyter Notebook. -The OpenBB API can simply be imported with: +With OpenBB SDK, you can access to normalized financial data from dozens of data providers, +without having to develop your own integrations from scratch. +On top of financial data feeds, OpenBB SDK also provides you with a toolbox to perform financial analysis +on a variety of asset classes, including stocks, crypto, ETFs, funds; the economy as well as your portfolios. + +OpenBB SDK is created and maintained by OpenBB team together with the contributions from hundreds of community members. +This gives us an unrivaled speed of development and the ability to maintain stable integrations with numerous third-party data providers. +Developing and maintaining an full-blown investment research infrastructure from the ground up takes a lot of time and effort. +However, it does not have to be. Take advantage of OpenBB SDK with its out-of-the-box data connectors and financial analysis toolkit. +So that you can focus on designing and building your financial reports and applications. + +## Setup + +### 1. Import OpenBB SDK + +First off, import OpenBB SDK into your python script or Jupyter Notebook with: ```python from openbb_terminal.api import openbb ``` -This imports all the commands at once. Now you can directly begin to use it. The api function is structured -in the way that it always retrieves the underlying data. For charts add the `chart=True` parameter. +This imports all Terminal commands at once. To see all the available commands, you can press `tab` in jupyter notebook. +Another approach is to check out [OpenBB SDK Documentation](https://openbb-finance.github.io/OpenBBTerminal/api/), where you can explore its capabilities -For example see: +### 2. Customize chart style + +With OpenBB SDK, you can customize your chart style. You can switch between `dark` and `light` easily using this block of code: ```python -# Returns data: -openbb.stocks.ba.snews("aapl") -# Returns charts: -openbb.stocks.ba.snews("aapl", chart=True) +from openbb_terminal.api import TerminalStyle +theme = TerminalStyle("light", "light", "light") ``` -This allows easy integration to the jupyter notebook and allows you to build new applications on top of the terminal. -The api also has new functionalities that are used in the backend of the Terminal (CLI). With these backend functions -you can develop new functionalities and avoid copy-pasting the code from the repository. +Screenshot 2022-10-03 at 23 56 52 -**Note:**\ -API keys for data fetching still have to be entered +OR -### Jupyter Notebook Tricks +```python +from openbb_terminal.api import TerminalStyle +theme = TerminalStyle("dark", "dark", "dark") +``` -**Get matplotlib charts in the output cells**\ -If you copy-paste the code below and use it as your initialization then you're matplotlib graphs will be inside -the result cell. +Screenshot 2022-10-03 at 23 46 33 + +### 3. Access Documentation + +Each and every command of OpenBB SDK has detailed documentation about input parameters and returned outputs. You can access them in multiple ways: + +**Approach 1: Press `shift + tab`** +This will work out of the box if you're using Jupyter Notebook. In case your IDE is VSCode, you will need to install the [Jupyter PowerToys +extension](https://marketplace.visualstudio.com/items?itemName=ms-toolsai.vscode-jupyter-powertoys). + +Screenshot 2022-10-03 at 23 31 55 + +**Approach 2: Type `help(command)`** + +You can also type `help(command)`, see example below, to see the command' docstring. + +Screenshot 2022-10-03 at 23 33 05 + +**Approach 3: Use OpenBB SDK Documentation page** + +Finally, if you prefer to check documentation on a web browser, [OpenBB SDK Documentation](https://openbb-finance.github.io/OpenBBTerminal/api/) will be your best friend. You can browse available commands and search for any specific one that you need. + +Screenshot 2022-10-03 at 18 41 48 + +### 4. Set API Keys + +You can set your external API keys through OpenBB SDK. + +* Single API setup + +```python +openbb.keys.fmp(key="example") + +openbb.keys.reddit( + client_id="example", + client_secret="example", + password="example", + username="example", + useragent="example") +``` + +![image](https://user-images.githubusercontent.com/79287829/194706829-dd720d06-9027-4da6-87f1-f39c7d2d725a.png) + +* API key setup with persistence: `persist=True` means that your key will be saved and can be reused after, otherwise it will be lost when you restart the kernel. + +```python +openbb.keys.fmp(key="example", persist=True) +``` + +![image](https://user-images.githubusercontent.com/79287829/194706848-80302ffa-6e75-4f7a-b8ce-788e083977d4.png) + +* Set multiple keys from dictionary + +```python +d = { + "fed": { + "key":"XXXXX" + }, + "binance": { + "key":"YYYYY", + "secret":"ZZZZZ" + }, +} + +openbb.keys.set_keys(d) +``` + +![image](https://user-images.githubusercontent.com/79287829/194706945-f1e6937f-74e2-4702-9e5e-c463287d61bd.png) + +* Get info about API setup arguments + +```python +openbb.keys.get_keys_info() +``` + +![image](https://user-images.githubusercontent.com/79287829/194706740-54bcc166-460a-410d-b34d-23e8b6c7aaf2.png) + +* Get your defined keys + +```python +openbb.keys.mykeys() +openbb.keys.mykeys(show=True) +``` + +![image](https://user-images.githubusercontent.com/79287829/194706907-239fe861-31c3-47c0-9051-7717cd026b76.png) + +## Usage + +Now, let's explore what OpenBB SDK can do. At a high level, you can break down OpenBB SDK's functionalities into two main buckets: (1) Data layer and (2) Toolbox layer. + +### 1. Data Layer + +### **Getting financial data from multiple data sources using one single API** + +OpenBB SDK provides you access to normalized financial data from dozens of data sources, without having to built your own integration or relying on multiple third-party packages. Let's explore how we can do that. + +First, you will need to load in the desired ticker. If it's not on the top of your mind, make use of our search functionality. + +```python +openbb.stocks.search("apple") +``` + +Screenshot 2022-10-04 at 00 00 14 + +We want to load `Apple Inc.` listed on US exchange, so our ticker should be `AAPL`. If you want to load `Apple Inc.` from Brazilian exchange, you should load in `AAPL34.SA`. + +```python +df = openbb.stocks.load("AAPL") +``` + +What's extremely powerful about OpenBB SDK is that you can specify the data source. Depending on the asset class, we have a list of available data sources and it's only getting bigger with contributions from our open-source community. + +```python +## From YahooFinance +df_yf = openbb.stocks.load("AAPL", source='YahooFinance') + +## From AlphaVantage +df_av = openbb.stocks.load("AAPL", source='AlphaVantage') + +## From IEXCloud +df_iex = openbb.stocks.load("AAPL", source='IEXCloud') + +## From Polygon +df_pol = openbb.stocks.load("AAPL", source='Polygon') +``` + +### **Easy option to switch between obtaining underlying data and charts** + +Depending on your needs, you can get the outputs in form of data (e.g. `pandas dataframe`) or charts. If the latter is what you want, simple add `chart=True` as the last parameter. + +### 1. Getting underlying data + +```python +openbb.economy.index(indices = ['sp500', 'nyse_ny', 'russell1000'], start_date = '2010-01-01') +``` + +Screenshot 2022-10-04 at 00 02 23 + +You might be wondering how to find all the available indices. This type of information should be available in the docstring. Let's give it a try. + +Screenshot 2022-10-04 at 13 20 58 + +As mentioned in the docstring, you can access it with the following helper function. + +```python +openbb.economy.available_indices() +``` + +Screenshot 2022-10-04 at 00 16 36 + +### 2. Getting charts + +```python +openbb.economy.index(indices = ['sp500', 'nyse_ny', 'russell1000'], start_date = '2010-01-01', chart=True) +``` + +Screenshot 2022-10-04 at 00 03 57 + +## 2. Toolbox Layer + +In addition to financial data, you can also get access to a robust and powerful toolbox to perform analysis on different asset classes and on your portfolio. + +Imagine that you would like to leverage existing financial calculations from OpenBB and apply them on your own data. This can be done easily - OpenBB SDK's commands usually accept a `dataframe` as an input. Here you can load it your data, either via a `csv`, `excel` file, or connecting directly with an `API` or a `database`. The possibilities are endless. + +Let's go through an example to see how we can do it in a few simple steps. Here we shall see how to use `portfolio optimization` functionalities from OpenBB SDK. + +### Step 1. Loading order book + +Here we will use an example orderbook for illustration purposes. You can choose to upload your own orderbook instead. + +```python +order_book_path = "portfolio/allocation/60_40_Portfolio.xlsx" +tickers, categories = openbb.portfolio.po.load(excel_file = order_book_path) +``` + +### Step 2. Optimizing portfolio + +We provide multiple portfolio optimization techniques. You can utilize basic mean-variance techniques, such as optimizing for the maximum Sharpe ratio, or minimum variance, as well as advanced optimization techniques including Hierarchical Risk Parity and Nested Clustered Optimization. + +```python +## Max Sharpe optimization +weights_max_sharpe, data_returns_max_sharpe = openbb.portfolio.po.maxsharpe(tickers) + +print("Max Sharpe") +weights_max_sharpe +``` + +Screenshot 2022-10-04 at 13 23 45 + +```python +## Minimum risk optimization +weights_min_risk, data_returns_min_risk = openbb.portfolio.po.minrisk(tickers) + +print("Min Risk") +weights_min_risk +``` + +Screenshot 2022-10-04 at 13 24 45 + +```python +## Hierarchical Risk Parity optimization + +weights_hrp, data_returns_hrp = openbb.portfolio.po.hrp(tickers) + +print("Hierarchical Risk Parity") +weights_hrp +``` + +Screenshot 2022-10-04 at 13 34 39 + +After having obtained the asset allocation outcomes, you can plot a correlation heatmap across tickers, as well as their individual risk contributition. + +```python +openbb.portfolio.po.plot(data=data_returns_hrp,weights=weights_hrp,heat=True) +``` + +Screenshot 2022-10-04 at 13 35 14 + +```python +openbb.portfolio.po.plot(data=data_returns_hrp,weights=weights_hrp,rc_chart=True) +``` + +Screenshot 2022-10-04 at 13 36 10 + +These techniques have an extensive list of parameters and thus the optimization outcome is highly dependent on the chosen parameters. For instance, you can refer to the documentation below. +Screenshot 2022-10-04 at 00 35 00 + +This allows us to alter certain assumption which also modify the asset allocation. + +```python +weights_hrp_2, data_returns_hrp_2 = openbb.portfolio.po.hrp( + tickers, + interval="5y", + risk_measure="cVaR", + risk_aversion=0.8 +) + +pd.DataFrame([weights_hrp, weights_hrp_2], index=["Basic", "Extended"]).T +``` + +Screenshot 2022-10-04 at 00 37 18 + +The basic method was optimized for *variance*. The extended method increases the period of historical data, optimizes for conditional Value at Risk and has a lower risk aversion. + +```python +openbb.portfolio.po.plot(data=data_returns_hrp,weights=weights_hrp,pie=True) +``` + +Screenshot 2022-10-04 at 13 38 12 + +```python +openbb.portfolio.po.plot(data=data_returns_hrp_2,weights=weights_hrp_2,pie=True) +``` + +Screenshot 2022-10-04 at 13 38 30 + +## Useful tips + +### 1. Display matplotlib charts in Jupyter Notebook + +To display matplotlib charts inside the Jupyter notebook output cells, you can use the block of code below, and initialize it at the top of the Notebook. ```python import matplotlib.pyplot as plt @@ -41,44 +316,9 @@ from openbb_terminal.api import openbb matplotlib_inline.backend_inline.set_matplotlib_formats("svg") ``` -**Get function signature and docstring**\ -When you press `shift + tab` in jupyter notebook while having the mouse parser in an API function, you get the -signature and docstring of the function. +### 2. Take advantage of `external_axes` -### Visual Studio Code Tricks - -**Get function docstring and signature**\ -In order to get the docstrings and function signatures for the API when opening a Jupyter Notebook in VSCode, -you have to install the [Jupyter PowerToys -extension](https://marketplace.visualstudio.com/items?itemName=ms-toolsai.vscode-jupyter-powertoys). - -## Code Examples - -Just copy-paste the code examples below into a python script or jupyter notebook, and you're ready to go. - -**Basic Stock Information**\ -Prints general information about the selected stock (in this case Gamsetop) - -```python -from openbb_terminal.api import openbb -gme_info = openbb.stocks.fa.info("gme").transpose() -print("-- Gamstop Stock --\n\n- Basic Info -") -print(f"Sector: {gme_info['Sector'].iloc[0]}") -print(f"Country: {gme_info['Country'].iloc[0]}") -print(f"Description: {gme_info['Long business summary'].iloc[0]}") -print("\n- Financial Info -") -print(f"Ebitda Margins: {gme_info['Ebitda margins'].iloc[0]}") -print(f"Profit Margins: {gme_info['Profit margins'].iloc[0]}") -print(f"Revenue growth: {gme_info['Revenue growth'].iloc[0]}") -print("\n- Target Price -") -print(f"Current price: {gme_info['Current price'].iloc[0]}") -print(f"Target mean price: {gme_info['Target mean price'].iloc[0]}") -print(f"Target high price: {gme_info['Target high price'].iloc[0]}") -print(f"Target low price: {gme_info['Target low price'].iloc[0]}") -``` - -**Use external axis**\ -The code below utilises the `external_axes` parameter to get two axis in one chart +The code below utilizes the `external_axes` parameter to get two axis in one chart. ```python import matplotlib.pyplot as plt @@ -92,22 +332,6 @@ openbb.stocks.dps.dpotc( fig.tight_layout() ``` -**Stocks Return Distribution** \ -Fetches data from the OpenBB API and then plots the return distribution. This is a good example, where the data from -the API is leveraged to build a new feature on top of the API. +You can also do this to save output charts in a variable for later uses. -```python -import numpy as np -import matplotlib.pyplot as plt -from openbb_terminal.api import openbb -# Fetches data from the api -gme = openbb.stocks.load("gme") -# Calculates logarithmic returns -gme["Log Returns"] = np.log(gme["Adj Close"]/gme["Adjusted Close"].shift(1)) -# Plots the return distributions -gme["Log Returns"].hist(bins=1000) -plt.thight_layout() -plt.show() -``` - -For more examples see the OpenBB jupyter notebook reports. They all use the API to its fullest extent! +### For more examples, we'd recommend checking out our [curated Jupyter Notebook reports](https://github.com/OpenBB-finance/OpenBBTerminal/tree/main/openbb_terminal/reports). They are excellent demonstration on how to use the SDK to its fullest extent