dashboard/finance.py
2021-06-22 12:30:42 +02:00

264 lines
14 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
# 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(columns=stock_list, index=["średnia", "cena", "dywidenda", "wolatylność"])
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',
style_header={'backgroundColor': 'rgb(30, 30, 30)'},
style_cell={
'backgroundColor': 'rgb(50, 50, 50)',
'color': 'white'
},
)
]),
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),
]),
]),
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 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')],
[Input('table_selector', 'value')])
def update_table(selected_dropdown_value):
global selected_stock_in_table
global selected_stock_in_table_df
selected_stock_in_table = selected_dropdown_value
selected_stock_in_table_df = fullTableDf.xs(selected_stock_in_table, axis=1, level=1)
data = selected_stock_in_table_df.to_dict('records')
columns = [{"name": i, "id": i} for i in selected_stock_in_table_df.columns]
return data, columns
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
@app.callback([Output('average_gauge', 'figure'),
Output('volatility_gauge', 'figure'),
Output('info_in_time_period', 'data')],
Input('timeseries', 'relayoutData'))
def change_time_period(selectedData):
global from_time
global to_time
global average_gauge
global volatility_gauge
global stock_info_in_time_period_df
if selectedData is not None:
if "xaxis.range[0]" in selectedData and "xaxis.range[1]" in selectedData:
from_time = selectedData["xaxis.range[0]"]
to_time = selectedData["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)
full_table_in_time_period = fullTableDf.loc[from_time:to_time]
mean = full_table_in_time_period.mean(axis=0)
mean = mean.xs('Close', level=0)
std = full_table_in_time_period.std(axis=0)
std = std.xs('Close', level=0)
time_period = selected_stock_in_table_df.loc[from_time:to_time]
mean = time_period.mean(axis=0)
std = time_period.std(axis=0)
# TODO: oblicz stock_info_in_time_period_df tutuaj !!!
average_gauge = make_gauge('średnia', 0, mean['Close'], 400)
volatility_gauge = make_gauge('wolatylność', 0, std['Close'], 400)
return average_gauge, volatility_gauge, stock_info_in_time_period_df.T.to_dict('records')
if __name__ == '__main__':
app.run_server(debug=True)