dashboard/finance.py
2021-06-22 16:48:30 +02:00

312 lines
17 KiB
Python
Executable File

import dash
import dash_html_components as html
import dash_core_components as dcc
import dash_table
import plotly.express as px
import yfinance as yf
from dash.dependencies import Input, Output, State
import plotly.graph_objects as go
import numpy as np
import pandas as pd
import datetime
import time
from pandas_datareader import data
import requests
from bs4 import BeautifulSoup
# Load data
stock_list = ['MMM', 'ABT', 'ABBV', 'ABMD', 'ACN', 'ATVI', 'ADBE', 'AMD', 'AAP', 'AES', 'AFL', 'A', 'APD', 'AKAM',
'ALK', 'ALB', 'ARE', 'ALXN', 'ALGN', 'ALLE', 'LNT', 'ALL', 'GOOGL', 'GOOG', 'MO', 'AMZN', 'AMCR', 'AEE',
'AAL', 'AEP', 'AXP', 'AIG', 'AMT', 'AWK', 'AMP', 'ABC', 'AME', 'AMGN', 'APH', 'ADI', 'ANSS', 'ANTM',
'AON', 'AOS', 'APA', 'AAPL', 'AMAT', 'APTV', 'ADM', 'ANET', 'AJG', 'AIZ', 'T', 'ATO', 'ADSK', 'ADP',
'AZO', 'AVB', 'AVY', 'BKR', 'BLL', 'BAC', 'BK', 'BAX', 'BDX', 'BRK.B', 'BBY', 'BIO', 'BIIB', 'BLK', 'BA',
'BKNG', 'BWA', 'BXP', 'BSX', 'BMY', 'AVGO', 'BR', 'BF.B', 'CHRW', 'COG', 'CDNS', 'CZR', 'CPB', 'COF',
'CAH', 'KMX', 'CCL', 'CARR', 'CTLT', 'CAT', 'CBOE', 'CBRE', 'CDW', 'CE', 'CNC', 'CNP', 'CERN', 'CF',
'CRL', 'SCHW', 'CHTR', 'CVX', 'CMG', 'CB', 'CHD', 'CI', 'CINF', 'CTAS', 'CSCO', 'C', 'CFG', 'CTXS', 'CLX',
'CME', 'CMS', 'KO', 'CTSH', 'CL', 'CMCSA', 'CMA', 'CAG', 'COP', 'ED', 'STZ', 'COO', 'CPRT', 'GLW', 'CTVA',
'COST', 'CCI', 'CSX', 'CMI', 'CVS', 'DHI', 'DHR', 'DRI', 'DVA', 'DE', 'DAL', 'XRAY', 'DVN', 'DXCM',
'FANG', 'DLR', 'DFS', 'DISCA', 'DISCK', 'DISH', 'DG', 'DLTR', 'D', 'DPZ', 'DOV', 'DOW', 'DTE', 'DUK',
'DRE', 'DD', 'DXC', 'EMN', 'ETN', 'EBAY', 'ECL', 'EIX', 'EW', 'EA', 'EMR', 'ENPH', 'ETR', 'EOG', 'EFX',
'EQIX', 'EQR', 'ESS', 'EL', 'ETSY', 'EVRG', 'ES', 'RE', 'EXC', 'EXPE', 'EXPD', 'EXR', 'XOM', 'FFIV', 'FB',
'FAST', 'FRT', 'FDX', 'FIS', 'FITB', 'FE', 'FRC', 'FISV', 'FLT', 'FMC', 'F', 'FTNT', 'FTV', 'FBHS',
'FOXA', 'FOX', 'BEN', 'FCX', 'GPS', 'GRMN', 'IT', 'GNRC', 'GD', 'GE', 'GIS', 'GM', 'GPC', 'GILD', 'GL',
'GPN', 'GS', 'GWW', 'HAL', 'HBI', 'HIG', 'HAS', 'HCA', 'PEAK', 'HSIC', 'HSY', 'HES', 'HPE', 'HLT', 'HOLX',
'HD', 'HON', 'HRL', 'HST', 'HWM', 'HPQ', 'HUM', 'HBAN', 'HII', 'IEX', 'IDXX', 'INFO', 'ITW', 'ILMN',
'INCY', 'IR', 'INTC', 'ICE', 'IBM', 'IP', 'IPG', 'IFF', 'INTU', 'ISRG', 'IVZ', 'IPGP', 'IQV', 'IRM',
'JKHY', 'J', 'JBHT', 'SJM', 'JNJ', 'JCI', 'JPM', 'JNPR', 'KSU', 'K', 'KEY', 'KEYS', 'KMB', 'KIM', 'KMI',
'KLAC', 'KHC', 'KR', 'LB', 'LHX', 'LH', 'LRCX', 'LW', 'LVS', 'LEG', 'LDOS', 'LEN', 'LLY', 'LNC', 'LIN',
'LYV', 'LKQ', 'LMT', 'L', 'LOW', 'LUMN', 'LYB', 'MTB', 'MRO', 'MPC', 'MKTX', 'MAR', 'MMC', 'MLM', 'MAS',
'MA', 'MKC', 'MXIM', 'MCD', 'MCK', 'MDT', 'MRK', 'MET', 'MTD', 'MGM', 'MCHP', 'MU', 'MSFT', 'MAA', 'MHK',
'TAP', 'MDLZ', 'MPWR', 'MNST', 'MCO', 'MS', 'MOS', 'MSI', 'MSCI', 'NDAQ', 'NTAP', 'NFLX', 'NWL', 'NEM',
'NWSA', 'NWS', 'NEE', 'NLSN', 'NKE', 'NI', 'NSC', 'NTRS', 'NOC', 'NLOK', 'NCLH', 'NOV', 'NRG', 'NUE',
'NVDA', 'NVR', 'NXPI', 'ORLY', 'OXY', 'ODFL', 'OMC', 'OKE', 'ORCL', 'OGN', 'OTIS', 'PCAR', 'PKG', 'PH',
'PAYX', 'PAYC', 'PYPL', 'PENN', 'PNR', 'PBCT', 'PEP', 'PKI', 'PRGO', 'PFE', 'PM', 'PSX', 'PNW', 'PXD',
'PNC', 'POOL', 'PPG', 'PPL', 'PFG', 'PG', 'PGR', 'PLD', 'PRU', 'PTC', 'PEG', 'PSA', 'PHM', 'PVH', 'QRVO',
'PWR', 'QCOM', 'DGX', 'RL', 'RJF', 'RTX', 'O', 'REG', 'REGN', 'RF', 'RSG', 'RMD', 'RHI', 'ROK', 'ROL',
'ROP', 'ROST', 'RCL', 'SPGI', 'CRM', 'SBAC', 'SLB', 'STX', 'SEE', 'SRE', 'NOW', 'SHW', 'SPG', 'SWKS',
'SNA', 'SO', 'LUV', 'SWK', 'SBUX', 'STT', 'STE', 'SYK', 'SIVB', 'SYF', 'SNPS', 'SYY', 'TMUS', 'TROW',
'TTWO', 'TPR', 'TGT', 'TEL', 'TDY', 'TFX', 'TER', 'TSLA', 'TXN', 'TXT', 'TMO', 'TJX', 'TSCO', 'TT', 'TDG',
'TRV', 'TRMB', 'TFC', 'TWTR', 'TYL', 'TSN', 'UDR', 'ULTA', 'USB', 'UAA', 'UA', 'UNP', 'UAL', 'UNH', 'UPS',
'URI', 'UHS', 'UNM', 'VLO', 'VTR', 'VRSN', 'VRSK', 'VZ', 'VRTX', 'VFC', 'VIAC', 'VTRS', 'V', 'VNO', 'VMC',
'WRB', 'WAB', 'WMT', 'WBA', 'DIS', 'WM', 'WAT', 'WEC', 'WFC', 'WELL', 'WST', 'WDC', 'WU', 'WRK', 'WY',
'WHR', 'WMB', 'WLTW', 'WYNN', 'XEL', 'XLNX', 'XYL', 'YUM', 'ZBRA', 'ZBH', 'ZION', 'ZTS']
stock_list = ['WHR', 'WMB', 'WLTW', 'WYNN', 'XEL', 'XLNX', 'XYL', 'YUM', 'ZBRA', 'ZBH', 'ZION', 'ZTS']
tickerData = yf.Tickers(stock_list)
market_cap = data.get_quote_yahoo(stock_list)['marketCap']
fullTableDf = tickerData.history(period='1d', start='2019-1-1', end='2020-1-25')
closePrices = fullTableDf['Close']
selected_stocks_in_graph = [stock_list[0]]
selected_stocks_in_graph_df = closePrices[selected_stocks_in_graph]
selected_stock_in_table = stock_list[0]
selected_stock_in_table_df = fullTableDf.xs(selected_stock_in_table, axis=1, level=1)
from_time = None
to_time = None
# Initialize the app
app = dash.Dash(__name__)
app.config.suppress_callback_exceptions = True
stock_info_in_time_period_df = pd.DataFrame(index=stock_list, columns=["tracker", "średnia", "cena"])
stock_info_in_time_period_df['tracker'] = stock_info_in_time_period_df.index
mean_prices_and_dividends = fullTableDf[['Close', 'Dividends']].mean(axis=0).unstack(level=0)
mean_prices_and_dividends_and_market_cap = pd.concat([mean_prices_and_dividends, market_cap], axis=1)
mean_prices_and_dividends_figure = px.scatter(mean_prices_and_dividends_and_market_cap.reset_index(), size="marketCap",
x='Dividends', y='Close', text="index", template='plotly_dark')
def make_gauge(title, min_v, value, max_v):
gauge_size = 180
fig = go.Figure(go.Indicator(
mode="gauge+number",
value=value,
domain={'x': [0, 1], 'y': [0, 1]},
title={'text': title}))
fig.layout.height = gauge_size
fig.layout.width = gauge_size
fig.layout.margin = dict(l=2, r=2, t=10, b=2)
fig.layout.paper_bgcolor = "#1E1E1E"
fig.layout.font.color = "white"
fig.layout.font.family = "Arial"
return fig
def get_options(list_stocks):
dict_list = []
for i in list_stocks:
dict_list.append({'label': i, 'value': i})
return dict_list
app.layout = html.Div(
children=[
html.Div(className='row',
children=[
html.Div(className='four columns div-user-controls',
children=[
html.P('Wybierz akcje (jedną lub więcej) do porównania na wykresie'),
html.Div(
className='div-for-dropdown',
children=[
dcc.Dropdown(id='stockselector',
options=get_options(stock_list),
multi=True,
value=selected_stocks_in_graph,
style={'backgroundColor': '#1E1E1E'},
className='stockselector'
)
],
style={'color': '#1E1E1E'}),
html.P('Wybierz jedną akcję aby zobaczyć szczegóły w tabeli'),
html.Div(
className='div-for-dropdown',
children=[
dcc.Dropdown(id='table_selector',
options=get_options(stock_list),
multi=False, value=selected_stock_in_table,
style={'backgroundColor': '#1E1E1E'},
className='stockselector'
),
html.Button("Pobierz dane", id="btn_data", style={'margin-top': '3rem'}),
dcc.Download(id="download-data")
],
style={'color': '#1E1E1E'}),
html.P('Wybierz przedział czasu by policzyć średnie i wachania'),
html.Div(
className='gauges',
children=[
dcc.Graph(id='average_gauge'),
dcc.Graph(id='volatility_gauge')
]),
dash_table.DataTable(
id='info_in_time_period',
columns=[{"name": i, "id": i} for i in stock_info_in_time_period_df.columns],
style_header={'backgroundColor': 'rgb(30, 30, 30)'},
style_cell={
'backgroundColor': 'rgb(50, 50, 50)',
'color': 'white'
},
style_data_conditional=[
{
'if': {
'filter_query': '{cena} > {średnia}',
'column_id': 'tracker'
},
'backgroundColor': 'green',
'color': 'black'
},
{
'if': {
'filter_query': '{cena} <= {średnia}',
'column_id': 'tracker'
},
'backgroundColor': 'red',
'color': 'black'
},
]
)
]),
html.Div(className='eight columns div-for-charts bg-grey',
children=[
dcc.Tabs(id='tabs', value='tab-1', children=[
dcc.Tab(id='tab-1', label='Chart 1', value='tab-1', children=[
dcc.Graph(id='timeseries', config={'displayModeBar': False}, animate=True),
]),
dcc.Tab(id='tab-2', label='Chart 2', value='tab-2', children=[
dcc.Graph(id='price-dividends', figure=mean_prices_and_dividends_figure,
config={'displayModeBar': False}, animate=True),
]),
dcc.Tab(id='tab-3', label='Copmany description', value='tab-3', children=[
html.Div(id="company-desritpion"),
]),
]),
dash_table.DataTable(
id='stock_price_table',
style_header={'backgroundColor': 'rgb(30, 30, 30)'},
style_cell={
'backgroundColor': 'rgb(50, 50, 50)',
'color': 'white'
},
)
])
])
]
)
# Callback for scraping company description
@app.callback(Output('company-desritpion', 'children'), [Input('table_selector', 'value')])
def update_graph(selected_dropdown_value):
url = 'https://finance.yahoo.com/quote/{company}/profile?p={company}'.format(company=selected_dropdown_value)
page = requests.get(url)
soup = BeautifulSoup(page.content, 'html.parser')
comp_name = soup.find(id="Main").h3.text
description = soup.find_all('section', class_='quote-sub-section')[0].p.text
return dcc.Markdown('''
# [{comp_name}]({url})
{description}
'''.format(comp_name=comp_name, description=description, url=url))
# Callback for downloading file
@app.callback(
Output("download-data", "data"),
Input("btn_data", "n_clicks"),
State('table_selector', 'value'),
prevent_initial_call=True,
)
def create_download_file(n_clicks, selected_table):
global selected_stock_in_table_df
return dcc.send_data_frame(selected_stock_in_table_df.to_csv, "data-{table}.csv".format(table=selected_table))
# Callback for timeseries price
@app.callback(Output('timeseries', 'figure'), [Input('stockselector', 'value')])
def update_graph(selected_dropdown_value):
global selected_stocks_in_graph
global selected_stocks_in_graph_df
selected_stocks_in_graph = selected_dropdown_value
selected_stocks_in_graph_df = closePrices[selected_stocks_in_graph]
figure = px.line(selected_stocks_in_graph_df, template='plotly_dark', title='Stock Prices')
# figure.update_layout(clickmode='event+select')
return figure
@app.callback([Output("stock_price_table", "data"),
Output('stock_price_table', 'columns'),
Output('average_gauge', 'figure'),
Output('volatility_gauge', 'figure'),
Output('info_in_time_period', 'data')],
[Input('timeseries', 'relayoutData'),
Input('table_selector', 'value')])
def common_table_callback(callback_data_time_period, callback_data_table_selector):
global selected_stock_in_table
global selected_stock_in_table_df
global from_time
global to_time
global average_gauge
global volatility_gauge
global stock_info_in_time_period_df
selected_stock_in_table_changed = False
change_time_period = False
for trigger in dash.callback_context.triggered:
if trigger['prop_id'] == 'table_selector.value':
selected_stock_in_table_changed = True
if trigger['prop_id'] == 'timeseries.relayoutData':
change_time_period = True
if selected_stock_in_table_changed:
selected_stock_in_table = callback_data_table_selector
selected_stock_in_table_df = fullTableDf.xs(selected_stock_in_table, axis=1, level=1)
if change_time_period:
if "xaxis.range[0]" in callback_data_time_period and "xaxis.range[1]" in callback_data_time_period:
from_time = callback_data_time_period["xaxis.range[0]"]
to_time = callback_data_time_period["xaxis.range[1]"]
else:
from_time = selected_stock_in_table_df.index.min()
to_time = selected_stock_in_table_df.index.max()
from_time = round_to_nearest_weekday(from_time)
to_time = round_to_nearest_weekday(to_time)
if change_time_period or selected_stock_in_table_changed:
stock_info_in_time_period_df['średnia'] = fullTableDf['Close'].loc[from_time:to_time].mean(axis=0)
stock_info_in_time_period_df['cena'] = fullTableDf['Close'].loc[fullTableDf.index.max()]
time_period = selected_stock_in_table_df['Close'].loc[from_time:to_time]
mean = time_period.mean(axis=0)
std = time_period.std(axis=0)
average_gauge = make_gauge('średnia', 0, mean, 400)
volatility_gauge = make_gauge('wolatylność', 0, std, 400)
stock_price_table_data = selected_stock_in_table_df.to_dict('records')
stock_price_table_columns = [{"name": i, "id": i} for i in selected_stock_in_table_df.columns]
stock_info_in_time_period_data = stock_info_in_time_period_df.to_dict('records')
return stock_price_table_data, stock_price_table_columns, average_gauge, volatility_gauge, stock_info_in_time_period_data
average_gauge = make_gauge('średnia', 0, 0, 400)
volatility_gauge = make_gauge('wolatylność', 0, 0, 400)
def round_to_nearest_weekday(date):
if isinstance(date, pd.Timestamp):
if date.dayofweek > 5:
date += datetime.timedelta(days=8 - date.dayofweek)
assert date.dayofweek <= 5
return date
elif isinstance(date, str):
if '.' in date:
date = datetime.datetime.strptime(date, "%Y-%m-%d %H:%M:%S.%f")
elif ':' in date:
date = datetime.datetime.strptime(date, "%Y-%m-%d %H:%M:%S")
else:
date = datetime.datetime.strptime(date, "%Y-%m-%d")
if date.isoweekday() > 5:
date += datetime.timedelta(days=8 - date.isoweekday())
assert date.isoweekday() <= 5
return date
if __name__ == '__main__':
app.run_server(debug=True)