mirror of
https://github.com/OpenBB-finance/OpenBB.git
synced 2026-10-28 21:12:16 +00:00
* Fixes * Update stocks_helper.py * update git-actions set-output to new format * Update stocks_helper.py * Update terminal_helper.py * removed LineAnnotateDrawer from qa_view * lint * few changes * updates * sdk auto gen modules done * Update stocks_helper.py * updates to changed imports, and remove first sdk_modules * Update generate_sdk.py * Update generate_sdk.py * pylint * revert stocks_helper * Update generate_sdk.py * Update sdk.py * Update generate_sdk.py * full auto generation, added sdk.py/controllers creation * missed enable forecasting * added running black in subprocess after sdk files generation completes * removed deleted sdk_arg_logger * comment out tests * property doc fix * clean up * Update generate_sdk.py * make trailmap classes useable for doc generation * Update generate_sdk.py * added lineon to trailmap class for linking to func in markdown * changed lineon to dict * added full_path to trailmap for linking in docs * updated portfolio * feat: initial files * feat: added meta head * feat: added funcdef * added func_def to trailmap attributes for markdown in docs, added missing type hints to covid functions * feat: added view and merged with jaun * Update generate_sdk.py * Update generate_sdk.py * Update generate_sdk.py * Update generate_sdk.py * init * fix returns * fix: random stuff * fix: random * fixed encoding issue on windows * fix: generate tabs * update * Update generate_sdk_markdown.py * Create .pydocstyle.ini * added type hint classes for views * fixes * alt, ba * alt-economy * Update finviz_compare_model.py * fixs * Update substack_model.py * Update generate_sdk.py * last of my section * porfolio * po * Update optimizer_model.py * fixing more things * few more * keys done * update * fixes * Update generate_sdk_markdown.py * Update generate_sdk_markdown.py * mypy forecast fix * Update generate_sdk_markdown.py * Update generate_sdk_markdown.py * Update generate_sdk_markdown.py * fixes * forecast fixes * one more fix * Update coinbase_model.py * Update generate_sdk_markdown.py Co-authored-by: Colin Delahunty <72827203+colin99d@users.noreply.github.com> Co-authored-by: James Maslek <jmaslek11@gmail.com> Co-authored-by: jose-donato <zmcdonato@gmail.com> Co-authored-by: andrewkenreich <andrew.kenreich@gmail.com>
160 lines
4.0 KiB
Python
160 lines
4.0 KiB
Python
"""Yahoo Finance model"""
|
|
__docformat__ = "numpy"
|
|
|
|
import os
|
|
import sys
|
|
import logging
|
|
from typing import List
|
|
from datetime import datetime
|
|
|
|
import yfinance as yf
|
|
import pandas as pd
|
|
from dateutil.relativedelta import relativedelta
|
|
|
|
from openbb_terminal.decorators import log_start_end
|
|
from openbb_terminal.core.config.paths import MISCELLANEOUS_DIRECTORY
|
|
|
|
# pylint: disable=attribute-defined-outside-init
|
|
|
|
logger = logging.getLogger(__name__)
|
|
|
|
FUTURES_DATA = pd.read_csv(MISCELLANEOUS_DIRECTORY / "futures" / "futures.csv")
|
|
|
|
MONTHS = {
|
|
1: "F",
|
|
2: "G",
|
|
3: "H",
|
|
4: "J",
|
|
5: "K",
|
|
6: "M",
|
|
7: "N",
|
|
8: "Q",
|
|
9: "U",
|
|
10: "V",
|
|
11: "X",
|
|
12: "Z",
|
|
}
|
|
|
|
|
|
class HiddenPrints:
|
|
def __enter__(self):
|
|
self._original_stdout = sys.stdout
|
|
sys.stdout = open(os.devnull, "w")
|
|
|
|
def __exit__(self, exc_type, exc_val, exc_tb):
|
|
sys.stdout.close()
|
|
sys.stdout = self._original_stdout
|
|
|
|
|
|
@log_start_end(log=logger)
|
|
def get_search_futures(
|
|
category: str = "",
|
|
exchange: str = "",
|
|
description: str = "",
|
|
):
|
|
"""Get search futures [Source: Yahoo Finance]
|
|
|
|
Parameters
|
|
----------
|
|
category: str
|
|
Select the category where the future exists
|
|
exchange: str
|
|
Select the exchange where the future exists
|
|
description: str
|
|
Select the description where the future exists
|
|
"""
|
|
df = FUTURES_DATA
|
|
if category:
|
|
df = df[df["Category"] == category]
|
|
if exchange:
|
|
df = df[df["Exchange"] == exchange]
|
|
if description:
|
|
df = df[
|
|
[description.lower() in desc.lower() for desc in df["Description"].values]
|
|
]
|
|
return df
|
|
|
|
|
|
@log_start_end(log=logger)
|
|
def get_historical_futures(symbols: List[str], expiry: str = "") -> pd.DataFrame:
|
|
"""Get historical futures [Source: Yahoo Finance]
|
|
|
|
Parameters
|
|
----------
|
|
symbols: List[str]
|
|
List of future timeseries symbols to display
|
|
expiry: str
|
|
Future expiry date with format YYYY-MM
|
|
|
|
Returns
|
|
-------
|
|
pd.DataFrame
|
|
Dictionary with sector weightings allocation
|
|
"""
|
|
if expiry:
|
|
symbols_with_expiry = list()
|
|
|
|
for symbol in symbols:
|
|
expiry_date = datetime.strptime(expiry, "%Y-%m")
|
|
exchange = FUTURES_DATA[FUTURES_DATA["Ticker"] == symbol][
|
|
"Exchange"
|
|
].values[0]
|
|
|
|
symbols_with_expiry.append(
|
|
f"{symbol}{MONTHS[expiry_date.month]}{str(expiry_date.year)[-2:]}.{exchange}"
|
|
)
|
|
|
|
return yf.download(symbols_with_expiry, progress=False, period="max")
|
|
|
|
df = yf.download([t + "=F" for t in symbols], progress=False, period="max")
|
|
if len(symbols) > 1:
|
|
df.columns = pd.MultiIndex.from_tuples(
|
|
[(tup[0], tup[1].replace("=F", "")) for tup in df.columns]
|
|
)
|
|
return df
|
|
|
|
|
|
@log_start_end(log=logger)
|
|
def get_curve_futures(
|
|
symbol: str = "",
|
|
) -> pd.DataFrame:
|
|
"""Get curve futures [Source: Yahoo Finance]
|
|
|
|
Parameters
|
|
----------
|
|
symbol: str
|
|
symbol to get forward curve
|
|
|
|
Returns
|
|
-------
|
|
pd.DataFrame
|
|
Dictionary with sector weightings allocation
|
|
"""
|
|
if symbol not in FUTURES_DATA["Ticker"].unique().tolist():
|
|
return pd.DataFrame()
|
|
|
|
exchange = FUTURES_DATA[FUTURES_DATA["Ticker"] == symbol]["Exchange"].values[0]
|
|
today = datetime.today()
|
|
|
|
futures_index = list()
|
|
futures_curve = list()
|
|
for i in range(36):
|
|
future = today + relativedelta(months=i)
|
|
future_symbol = (
|
|
f"{symbol}{MONTHS[future.month]}{str(future.year)[-2:]}.{exchange}"
|
|
)
|
|
|
|
with HiddenPrints():
|
|
data = yf.download(future_symbol, progress=False)
|
|
|
|
if not data.empty:
|
|
futures_index.append(future.strftime("%Y-%b"))
|
|
futures_curve.append(data["Adj Close"].values[-1])
|
|
|
|
if not futures_index:
|
|
return pd.DataFrame()
|
|
|
|
futures_index = pd.to_datetime(futures_index)
|
|
|
|
return pd.DataFrame(index=futures_index, data=futures_curve, columns=["Futures"])
|