Skip to content

Commit

Permalink
Add dividend history from yfinance (OpenBB-finance#1021)
Browse files Browse the repository at this point in the history
  • Loading branch information
jmaslek authored Dec 6, 2021
1 parent c800c16 commit cdd04cf
Show file tree
Hide file tree
Showing 6 changed files with 130 additions and 2 deletions.
29 changes: 28 additions & 1 deletion gamestonk_terminal/stocks/fundamental_analysis/fa_controller.py
Original file line number Diff line number Diff line change
Expand Up @@ -64,6 +64,7 @@ class FundamentalAnalysisController:
"cash",
"earnings",
"warnings",
"divs",
]

CHOICES_MENUS = [
Expand Down Expand Up @@ -122,7 +123,8 @@ def print_help(self):
sust sustainability values of the company
cal calendar earnings and estimates of the company
web open web browser of the company
hq open HQ location of the company {Style.DIM if self.suffix else ""}
hq open HQ location of the company
divs show historical dividends for company {Style.DIM if self.suffix else ""}
Alpha Vantage:
overview overview of the company
key company key metrics
Expand Down Expand Up @@ -399,6 +401,31 @@ def call_hq(self, other_args: List[str]):
return
yahoo_finance_view.open_headquarters_map(self.ticker)

@try_except
def call_divs(self, other_args: List[str]):
"""Process divs command"""
parser = argparse.ArgumentParser(
add_help=False,
formatter_class=argparse.ArgumentDefaultsHelpFormatter,
prog="divs",
description="Get historical dividends for company",
)
parser.add_argument(
"-n",
"--num",
dest="num",
default=12,
help="Number of previous dividends to show",
)
ns_parser = parse_known_args_and_warn(
parser, other_args, export_allowed=EXPORT_ONLY_RAW_DATA_ALLOWED
)
if not ns_parser:
return
yahoo_finance_view.display_dividends(
ticker=self.ticker, num=ns_parser.num, export=ns_parser.export
)

@try_except
def call_overview(self, other_args: List[str]):
"""Process overview command"""
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -203,3 +203,19 @@ def get_hq(ticker: str) -> str:
+ ","
)
return maps[:-1]


def get_dividends(ticker: str) -> pd.DataFrame:
"""Get historical dividend for ticker
Parameters
----------
ticker: str
Ticker to get dividend for
Returns
-------
pd.DataFrame:
Dataframe of dividends and dates
"""
return pd.DataFrame(yf.Ticker(ticker).dividends)
Original file line number Diff line number Diff line change
@@ -1,11 +1,14 @@
""" Yahoo Finance View """
__docformat__ = "numpy"

import os
import webbrowser
import pandas as pd
from tabulate import tabulate

from gamestonk_terminal.stocks.fundamental_analysis import yahoo_finance_model
from gamestonk_terminal import feature_flags as gtff
from gamestonk_terminal.helper_funcs import export_data


def open_headquarters_map(ticker: str):
Expand Down Expand Up @@ -142,3 +145,39 @@ def display_calendar_earnings(ticker: str):
else:
print(df_calendar.to_string(index=False))
print("")


def display_dividends(ticker: str, num: int = 12, export: str = ""):
"""Display historical dividends
Parameters
----------
ticker: str
Stock ticker
num: int
Number to show
export: str
Format to export data
"""
div_history = yahoo_finance_model.get_dividends(ticker)
if div_history.empty:
print("No dividends found.\n")
return
div_history["Dif"] = div_history.diff()
div_history = div_history[::-1]
div_history.index = pd.to_datetime(div_history.index, format="%Y%m%d").strftime(
"%Y-%m-%d"
)
if gtff.USE_TABULATE_DF:
print(
tabulate(
div_history.head(num),
tablefmt="fancy_grid",
headers=["Amount Paid ($)", "Change"],
floatfmt=".2f",
)
)
else:
print(div_history.to_string())
print("")
export_data(export, os.path.dirname(os.path.abspath(__file__)), "divs", div_history)
2 changes: 1 addition & 1 deletion gamestonk_terminal/stocks/stocks_helper.py
Original file line number Diff line number Diff line change
Expand Up @@ -724,7 +724,7 @@ def quote(other_args: List[str], s_ticker: str):

# If price only option, return immediate market price for ticker.
if ns_parser.price_only:
print(f"Price of {ns_parser.s_ticker} {ticker.info['regularMarketPrice']}")
print(f"Price of {ns_parser.s_ticker} {ticker.info['regularMarketPrice']} \n")
return

try:
Expand Down
44 changes: 44 additions & 0 deletions website/content/stocks/fundamental_analysis/divs/_index.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,44 @@
```
usage: divs [-n NUM] [-h] [--export {csv,json,xlsx}]
```

Get historical dividends for company

```
optional arguments:
-n NUM, --num NUM Number of previous dividends to show (default: 12)
-h, --help show this help message (default: False)
--export {csv,json,xlsx}
Export raw data into csv, json, xlsx (default: )
```

Sample output:
```
╒════════════╤═══════════════════╤══════════╕
│ │ Amount Paid ($) │ Change │
╞════════════╪═══════════════════╪══════════╡
│ 2021-11-05 │ 0.22 │ 0.00 │
├────────────┼───────────────────┼──────────┤
│ 2021-08-06 │ 0.22 │ 0.00 │
├────────────┼───────────────────┼──────────┤
│ 2021-05-07 │ 0.22 │ 0.02 │
├────────────┼───────────────────┼──────────┤
│ 2021-02-05 │ 0.20 │ 0.00 │
├────────────┼───────────────────┼──────────┤
│ 2020-11-06 │ 0.20 │ 0.00 │
├────────────┼───────────────────┼──────────┤
│ 2020-08-07 │ 0.20 │ 0.00 │
├────────────┼───────────────────┼──────────┤
│ 2020-05-08 │ 0.20 │ 0.01 │
├────────────┼───────────────────┼──────────┤
│ 2020-02-07 │ 0.19 │ 0.00 │
├────────────┼───────────────────┼──────────┤
│ 2019-11-07 │ 0.19 │ 0.00 │
├────────────┼───────────────────┼──────────┤
│ 2019-08-09 │ 0.19 │ 0.00 │
├────────────┼───────────────────┼──────────┤
│ 2019-05-10 │ 0.19 │ 0.01 │
├────────────┼───────────────────┼──────────┤
│ 2019-02-08 │ 0.18 │ 0.00 │
╘════════════╧═══════════════════╧══════════╛
```
2 changes: 2 additions & 0 deletions website/data/menu/main.yml
Original file line number Diff line number Diff line change
Expand Up @@ -203,6 +203,8 @@ main:
ref: "/stocks/fundamental_analysis/web"
- name: hq
ref: "/stocks/fundamental_analysis/hq"
- name: divs
ref: "/stocks/fundamental_analysis/divs"
- name: overview
ref: "/stocks/fundamental_analysis/overview"
- name: key
Expand Down

0 comments on commit cdd04cf

Please sign in to comment.