Files
OpenBB/openbb_terminal/common/technical_analysis/custom_indicators_view.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

145 lines
3.7 KiB
Python

"""Custom TA indicators"""
__docformat__ = "numpy"
import logging
import os
from typing import List, Optional, Union
import matplotlib.pyplot as plt
import pandas as pd
from openbb_terminal.common.technical_analysis import (
custom_indicators_model,
ta_helpers,
)
from openbb_terminal.config_plot import PLOT_DPI
from openbb_terminal.config_terminal import theme
from openbb_terminal.decorators import log_start_end
from openbb_terminal.helper_funcs import (
export_data,
is_intraday,
is_valid_axes_count,
plot_autoscale,
print_rich_table,
reindex_dates,
)
logger = logging.getLogger(__name__)
@log_start_end(log=logger)
def fibonacci_retracement(
data: pd.DataFrame,
limit: int = 120,
start_date: Optional[Union[str, None]] = None,
end_date: Optional[Union[str, None]] = None,
symbol: str = "",
export: str = "",
sheet_name: Optional[str] = None,
external_axes: Optional[List[plt.Axes]] = None,
):
"""Plots Calculated fibonacci retracement levels
Parameters
----------
data: pd.DataFrame
OHLC data
limit: int
Days to lookback
start_date: Optional[str, None]
User picked date for starting retracement
end_date: Optional[str, None]
User picked date for ending retracement
symbol: str
Ticker symbol
sheet_name: str
Optionally specify the name of the sheet the data is exported to.
export: str
Format to export data
external_axes : Optional[List[plt.Axes]], optional
External axes (2 axes are expected in the list), by default None
Examples
--------
>>> from openbb_terminal.sdk import openbb
>>> df = openbb.stocks.load(symbol="aapl")
>>> openbb.ta.fib_chart(data=df)
"""
(
df_fib,
min_date,
max_date,
min_pr,
max_pr,
) = custom_indicators_model.calculate_fib_levels(data, limit, start_date, end_date)
levels = df_fib.Price
plot_data = reindex_dates(data)
# This plot has 2 axes
if external_axes is None:
_, ax1 = plt.subplots(
figsize=plot_autoscale(),
dpi=PLOT_DPI,
)
ax2 = ax1.twinx()
elif is_valid_axes_count(external_axes, 2):
(ax1, ax2) = external_axes
else:
return
close_col = ta_helpers.check_columns(data)
if close_col is None:
return
ax1.plot(plot_data[close_col])
date_format = "%b %d %H:%M" if is_intraday(data) else "%Y-%m-%d"
min_date_index = plot_data[
plot_data["date"] == min_date.strftime(date_format)
].index
max_date_index = plot_data[
plot_data["date"] == max_date.strftime(date_format)
].index
ax1.plot(
[min_date_index, max_date_index],
[min_pr, max_pr],
)
for i in levels:
ax1.axhline(y=i, alpha=0.5)
for i in range(6):
ax1.fill_between(plot_data.index, levels[i], levels[i + 1], alpha=0.15)
ax1.set_xlim(plot_data.index[0], plot_data.index[-1])
ax1.set_title(f"Fibonacci Support for {symbol.upper()}")
ax1.set_yticks(levels)
ax1.set_yticklabels([0, 0.235, 0.382, 0.5, 0.618, 0.65, 1])
theme.style_primary_axis(
ax1,
data_index=plot_data.index.to_list(),
tick_labels=plot_data["date"].to_list(),
)
ax2.set_ylim(ax1.get_ylim())
ax2.set_ylabel("Price")
theme.style_primary_axis(ax2)
if external_axes is None:
theme.visualize_output()
print_rich_table(
df_fib,
headers=["Fib Level", "Price"],
show_index=False,
title="Fibonacci retracement levels",
)
export_data(
export,
os.path.dirname(os.path.abspath(__file__)).replace("common", "stocks"),
"fib",
df_fib,
sheet_name,
)