swing-trading-dashboard/dashboard.py

92 lines
3.0 KiB
Python

import dash_bootstrap_components as dbc
from dash import Dash, dcc, html
from dash_ag_grid import AgGrid
from dash_bootstrap_templates import load_figure_template
from datetime import datetime, timedelta
from pandas import DataFrame, Series
from typing import Callable, List, Dict
from ohlc import ohlc
from plotting import CandlestickChart, figure_with_subplots
from strategies import internal_bar_strength
from strategies import end_of_month
from stylesheets import grid_stylesheet, theme_stylesheet
app = Dash(__name__, external_stylesheets = [theme_stylesheet, grid_stylesheet])
app.title = 'Swing Trading Dashboard'
load_figure_template('lux_dark')
SignalFunction = Callable[[DataFrame], Series]
signal_functions: List[Dict[str, SignalFunction]] = [
{'strategy': 'End of Month', 'function': end_of_month.signals},
{'strategy': 'Internal Bar Strength', 'function': internal_bar_strength.signals}
]
symbol = 'SPY'
def calculate_signals(data: DataFrame, days: int = 12) -> DataFrame:
end_date = datetime.today()
start_date = end_date - timedelta(days = days + 10)
data = ohlc(symbol = symbol, start_date = start_date, end_date = end_date)
recent_signals = data.tail(days)
signal_data = []
for signal_info in signal_functions:
signals = signal_info['function'](recent_signals)
signal_dict = {'Strategy': signal_info['strategy']}
dates = [datetime.strptime(str(date), '%Y-%m-%d').strftime('%m/%d') for date in recent_signals['Date']]
for date, signal in zip(dates, signals):
signal_dict[date] = signal
signal_data.append(signal_dict)
return DataFrame(signal_data)
def load_chart() -> dict:
today = datetime.today()
data = ohlc(symbol = symbol, start_date = today - timedelta(days = 180), end_date = today)
candlestick_chart = CandlestickChart(
x = data['Date'],
opens = data['Open'],
highs = data['High'],
lows = data['Low'],
closes = data['Close']
)
return figure_with_subplots([[candlestick_chart]])
signal_data = calculate_signals(DataFrame(), days = 12)
app.layout = dbc.Container(
[
dcc.Graph(
id = 'candlestick-chart',
config = {'displayModeBar': False},
figure = load_chart(),
),
html.Div(
AgGrid(
columnDefs = [
{'field': col, 'flex': 3} if col == 'Strategy' else {'field': col, 'flex': 1, 'cellRenderer': 'SignalRenderer'}
for col in signal_data.columns
],
rowData = signal_data.to_dict(orient = 'records'),
defaultColDef = {'flex': 1, 'sortable': False, 'resizable': False},
dashGridOptions = {'domLayout': 'autoHeight'},
style = {'height': None}
),
className = 'dbc dbc-ag-grid'
)
],
style = {'maxWidth': '1200px', 'margin': '0 auto'},
fluid = True
)
if __name__ == '__main__':
app.run_server(debug = False)