Skip to content

Commit

Permalink
Merge pull request #21 from dpguthrie/yahooquery
Browse files Browse the repository at this point in the history
Add yahooquery streamlit tutorial
  • Loading branch information
MarcSkovMadsen authored Jan 9, 2020
2 parents 442ec88 + 4385ba6 commit 77ed2a3
Show file tree
Hide file tree
Showing 4 changed files with 233 additions and 1 deletion.
222 changes: 222 additions & 0 deletions gallery/yahooquery/yahooquery.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,222 @@
"""
## YahooQuery Demo
This app allows you to demo the yahooquery python package
Author: [Doug Guthrie](https://github/dpguthrie))\n
Source: [Github](https://github.com/dpguthrie/yahooquery)
"""
import streamlit as st

import altair as alt
from yahooquery import Ticker
import datetime


BASE_ENDPOINTS = {
'asset_profile': 'Asset Profile',
'calendar_events': 'Calendar Events',
'esg_scores': 'ESG Scores',
'financial_data': 'Financial Data',
'fund_profile': 'Fund Profile',
'key_stats': 'Key Statistics',
'major_holders': 'Major Holders',
'price': 'Pricing',
'quote_type': 'Quote Type',
'share_purchase_activity': 'Share Purchase Activity',
'summary_detail': 'Summary Detail',
'summary_profile': 'Summary Profile',
'balance_sheet': 'Balance Sheet',
'cash_flow': 'Cash Flow',
'company_officers': 'Company Officers',
'earning_history': 'Earning History',
'fund_ownership': 'Fund Ownership',
'grading_history': 'Grading History',
'income_statement': 'Income Statement',
'insider_holders': 'Insider Holders',
'insider_transactions': 'Insider Transactions',
'institution_ownership': 'Institution Ownership',
'recommendation_trend': 'Recommendation Trends',
'sec_filings': 'SEC Filings',
'fund_bond_holdings': 'Fund Bond Holdings',
'fund_bond_ratings': 'Fund Bond Ratings',
'fund_equity_holdings': 'Fund Equity Holdings',
'fund_holding_info': 'Fund Holding Information',
'fund_performance': 'Fund Performance',
'fund_sector_weightings': 'Fund Sector Weightings',
'fund_top_holdings': 'Fund Top Holdings',
}

def format_func(option):
return BASE_ENDPOINTS[option]


@st.cache
def get_data(ticker, attribute, *args):
try:
data = getattr(ticker, attribute)(*args)
except TypeError:
data = getattr(ticker, attribute)
return data


def main():
symbols = st.sidebar.text_input(
"Enter symbol or list of symbols (comma separated)", value="aapl")
symbols = [x.strip() for x in symbols.split(',')]
tickers = Ticker(symbols)

page = st.sidebar.selectbox("Choose a page", [
"Homepage", "Base", "Base - Multiple", "Options", "Historical Pricing"])

history_args = {
'period': '1y', 'interval': '1d',
'start': datetime.datetime.now() - datetime.timedelta(days=365),
'end': None}

st.markdown("# Welcome to [YahooQuery](https://github.com/dpguthrie/yahooquery)")

if page == "Homepage":
st.markdown(f"""
## Streamlit Instructions
Enter a symbol or list of symbols in the box to the left (**comma
separated**). Then select different pages in the dropdown to view
the data available to you.
## Short README
### Install
```python
pip install yahooquery
```
### Ticker
The `Ticker` class provides the access point to data residing on
Yahoo Finance. It accepts either a symbol or list of symbols.
Additionally, you can supply `formatted` as a keyword argument
to the class to format the data returned from the API (default is
`True`)
```python
from yahooquery import Ticker
tickers = Ticker({symbols})
```
""")
st.help(tickers)
elif page == "Base":
st.header("Base Endpoints")
st.write("""
Select an option below to see the data available through
the base endpoints.""")
endpoint = st.selectbox(
"Select Endpoint", options=sorted(list(BASE_ENDPOINTS.keys())),
format_func=format_func)
st.help(getattr(Ticker, endpoint))
is_property = isinstance(getattr(Ticker, endpoint), property)
if is_property:
st.code(f"Ticker({symbols}).{endpoint}", language="python")
data = get_data(tickers, endpoint)
else:
frequency = st.selectbox(
"Select Frequency", options=["Annual", "Quarterly"])
arg = frequency[:1].lower()
st.code(f"Ticker({symbols}).{endpoint}(frequency='{arg}')")
data = get_data(tickers, endpoint, arg)
st.write(data)
elif page == "Base - Multiple":
st.header("Base Endpoints - Multiple")
st.markdown("""
Two methods to the `Ticker` class allow you to obtain multiple
endpoints with one call. The `get_endpoints` method takes a list
of allowable endpoints, which you can view through `Ticker._ENDPOINTS`,
and the `all_endpoints` property retrieves all Base endpoints""")
method = st.selectbox(
"Select Method", options=['All Endpoints', 'Multiple Endpoints'],
index=1)
if method == "All Endpoints":
st.help(getattr(Ticker, 'all_endpoints'))
st.code(f"Ticker({symbols}).all_endpoints", language="python")
data = get_data(tickers, "all_endpoints")
st.json(data)
else:

default_endpoints = ['assetProfile']
endpoints = st.multiselect(
"Select endpoints", options=sorted(Ticker._ENDPOINTS),
default=default_endpoints)
st.help(getattr(Ticker, "get_endpoints"))
st.code(f"Ticker({symbols}).get_endpoints({endpoints})", language="python")
if not endpoints:
st.warning("You must select at least one endpoint")
else:
data = get_data(tickers, "get_endpoints")(endpoints)
st.json(data)
elif page == "Options":
st.header("Option Chain")
st.write("""
Yahooquery also gives you the ability to view option chain data
for all expiration dates for a given symbol(s)
""")
st.help(getattr(Ticker, 'option_chain'))
st.code(f"Ticker({symbols}).option_chain", language="python")
data = get_data(tickers, 'option_chain')
st.dataframe(data)
else:
st.header("Historical Pricing")
st.write("""
Retrieve historical pricing data for a given symbol(s)
""")
st.help(getattr(Ticker, 'history'))
st.markdown("""
1. Select a period **or** enter start and end dates.
2. Select interval (**note: some intervals are not available for
certain lengths of time**)
""")
option_1 = st.selectbox(
"Select Period or Start / End Dates", ["Period", "Dates"], 0)
if option_1 == "Period":
history_args['period'] = st.selectbox(
"Select Period", options=Ticker._PERIODS, index=5)
history_args['start'] = None
history_args['end'] = None
else:
history_args['start'] = st.date_input(
"Select Start Date", value=history_args['start'])
history_args['end'] = st.date_input("Select End Date")
history_args['period'] = None

st.markdown("**THEN**")
history_args['interval'] = st.selectbox(
"Select Interval", options=Ticker._INTERVALS, index=8)
args_string = [
str(k) + "='" + str(v) + "'" for k, v in history_args.items()
if v is not None]
st.code(f"Ticker({symbols}).history({', '.join(args_string)})",
language="python")
df = tickers.history(**history_args)

if isinstance(df, dict):
st.write(df)
else:
if len(symbols) > 1:
chart = (
alt.Chart(df.reset_index()).mark_line().encode(
alt.Y('close:Q', scale=alt.Scale(zero=False)),
x='dates',
color='symbol'
)
)
else:
chart = (
alt.Chart(df.reset_index()).mark_line().encode(
alt.Y('close:Q', scale=alt.Scale(zero=False)),
x='dates:T',
)
)
st.write("", "", chart)
st.dataframe(df)


if __name__ == "__main__":
main()
7 changes: 7 additions & 0 deletions package/awesome_streamlit/database/apps_in_gallery.py
Original file line number Diff line number Diff line change
Expand Up @@ -196,5 +196,12 @@
is_awesome=True,
author=authors.JCHARIS,
),
Resource(
name="YahooQuery",
url=GITHUB_RAW_GALLERY_URL + "yahooquery/yahooquery.py",
tags=[tags.CODE, tags.APP_IN_GALLERY, tags.FINANCE, tags.TUTORIAL],
is_awesome=True,
author=authors.DOUG_GUTHRIE,
),
DEFAULT_APP_IN_GALLERY,
]
2 changes: 2 additions & 0 deletions package/awesome_streamlit/database/authors.py
Original file line number Diff line number Diff line change
Expand Up @@ -22,6 +22,7 @@
NOAH_SAUNDERS = Author(name="Noah Saunders", url="https://morioh.com/p/7066169a0314")
NAVEEN_KUMAR = Author(name="Naveen Kumar", url="https://github.com/QAInsights")
MAARTEN_GROOTENDORST = Author(name="Maarten Grootendorst", url="https://github.com/MaartenGr")
DOUG_GUTHRIE = Author(name="Doug Guthrie", url="https://github.com/dpguthrie")
PETER_BAUMGARTNER = Author(
name="Peter Baumgartner",
url="https://pmbaumgartner.github.io/",
Expand Down Expand Up @@ -51,4 +52,5 @@
PETER_BAUMGARTNER,
POSEY,
STREAMLIT_AUTHOR,
DOUG_GUTHRIE,
]
3 changes: 2 additions & 1 deletion requirements_base.txt
Original file line number Diff line number Diff line change
Expand Up @@ -65,4 +65,5 @@ lxml==4.4.1
vaderSentiment==3.2.1 # A lexicon and rule-based sentiment analysis tool that is specifically attuned to sentiments expressed in social media. See https://github.com/cjhutto/vaderSentiment
hvplot==0.5.2
panel==0.7.0
keras==2.3.1
keras==2.3.1
yahooquery==1.0.11

0 comments on commit 77ed2a3

Please sign in to comment.