Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- import pandas as pd
- import plotly.graph_objects as go
- from plotly.subplots import make_subplots
- import dash
- from dash import dcc
- from dash import html
- from dash.dependencies import Input, Output
- import dash_bootstrap_components as dbc
- import math
- def string_to_number(df, column):
- if isinstance(df.iloc[0, df.columns.get_loc(column)], str):
- df[column] = df[column].str.replace(',','')
- df[column] = df[column].astype(float)
- return df
- def read_data(filename, stock_code, usecols):
- df = pd.read_csv(filename, header=None, usecols=usecols,
- names=['time', stock_code, 'price change', 'volume'],
- index_col= 'time', parse_dates=['time'])
- index_with_nan = df.index[df.isnull().any(axis=1)]
- df.drop(index_with_nan, axis=0, inplace=True)
- df = string_to_number(df, stock_code)
- df = string_to_number(df, 'volume')
- latest_info = df.iloc[-1, :]
- latest_price = str(round(latest_info.iloc[0], 2))
- latest_price_change = str(latest_info.iloc[1])
- dfvol = df['volume'].resample('1Min').mean()
- data = df[stock_code].resample('1Min').ohlc()
- data['time'] = data.index
- data['time'] = pd.to_datetime(data['time'], format='%Y-%m-%d %H:%M:%S')
- data['MA5'] = data['close'].rolling(5).mean()
- data['MA10'] = data['close'].rolling(10).mean()
- data['MA20'] = data['close'].rolling(20).mean()
- data['volume_diff'] = dfvol.diff()
- data[data['volume_diff'] < 0] = None
- index_with_nan = data.index[data.isnull().any(axis=1)]
- data.reset_index(drop=True, inplace=True)
- return data, latest_price, latest_price_change, df['volume'][-1]
- app = dash.Dash(__name__, external_stylesheets=[dbc.themes.BOOTSTRAP])
- stock = ['BOIL', 'PYPL', 'INTC', 'AAPL', 'AMZN', 'MSFT', 'TSLA']
- filename = 'stock_data.csv'
- data, latest_price, latest_price_change, volume = read_data('stock_data.csv', stock[0], [1, 2, 3, 4])
- app.layout = html.Div(style={'backgroundColor': 'black'}, children=[
- dbc.Row( style={
- 'textAlign': 'center',
- 'backgroundColor': 'black',
- 'color': 'white',
- }, children=[
- dbc.Col( dcc.Slider(id='candles_slider',min=10,max=len(data),step=1,value=len(data),marks={i: str(i) for i in range(10, len(data) + 1,10)},updatemode='drag',), style={'padding-left': '55px' , 'padding-right': '55px','padding-top': '40px'}, width={'size': 8},md=8,sm=12,xs=12),
- dbc.Col("2023/22/03", style={'content-align': 'center','padding-left': '50px' , 'padding-right': '50px','padding-top': '40px'}, width={'size': 4},md=4,sm=12,xs=12),
- ],),
- dbc.Row(style={
- 'textAlign': 'center',
- 'height': '100vh',
- 'backgroundColor': 'black',
- 'color': 'white'}, children=[
- dbc.Col( style={'content-align': 'center','padding-left': '20px' , 'padding-right': '50px','padding-top': '40px'}, children=[
- dbc.Row([
- dbc.Col(id='stock_name',align='center', width={'size': 1},style={'font-weight': 'bold','fontSize': '16','background-color': '#FFBF00','color': 'black', 'margin-left': '45px'}),
- dbc.Col(id='latest_price',align='center', width={'size': 2}, style={'color': 'white'}),
- dbc.Col(id='latest_price_change',align='center', width={'size': 2})
- ] ),
- dbc.Row([dbc.Col(
- dcc.Graph(id="candles"), align='center',
- ),],),
- dbc.Row([
- dbc.Col('Volume',align='center', width={'size': 1},style={'font-weight': 'bold','fontSize': '16','width': '15%','background-color': '#FFBF00','color': 'black', 'margin-left': '45px', 'margin-right': '10px'}),
- dbc.Col(id='volume',align='center', width={'size': 1},style={'color': 'white'}),
- ] ),
- dbc.Row([dbc.Col(
- dcc.Graph(id="volume_chart",config={'displayModeBar': False}), align='center',
- ),],),
- dbc.Row([
- dbc.Col("Rsi",align='center', width={'size': 2},style={'font-weight': 'bold','fontSize': '16','width': '10%','background-color': '#FFBF00','color': 'black', 'margin-left': '45px', 'margin-right': '10px'}),
- dbc.Col('um teste',align='center', width={'size': 2},style={'color': 'white'}),
- ] ),
- dbc.Row([dbc.Col(
- dcc.Graph(id="Rsi",config={'displayModeBar': False}), align='center',
- ),],),
- ], width={'size': 8},md=8,sm=12,xs=12),
- dbc.Col(style={'content-align': 'center','padding-left': '50px' , 'padding-right': '50px','padding-top': '40px'}, children=[
- dbc.Row([
- dbc.Col(id='stock_name1',align='center', width={'size': 2},style={'width': '20%','text-align': 'center','font-weight': 'bold','fontSize': '16','background-color': '#FFBF00','color': 'black', 'margin-left': '15px', 'margin-right': '15px'}),
- dbc.Col(id='latest_price1',align='center', width={'size': 2},style={'color': 'white'}),
- dbc.Col(id='latest_price_change1',align='center', width={'size': 2})
- ]),
- dbc.Row([dbc.Col(
- dcc.Graph(id="stocks1",config={'displayModeBar': False}) , align='center',
- ),],),
- dbc.Row([
- dbc.Col(id='stock_name2',align='center', width={'size': 2},style={'width': '20%','text-align': 'center','font-weight': 'bold','fontSize': '16','background-color': '#FFBF00','color': 'black', 'margin-left': '15px', 'margin-right': '15px'}),
- dbc.Col(id='latest_price2',align='center', width={'size': 2},style={'color': 'white'}),
- dbc.Col(id='latest_price_change2',align='center', width={'size': 2})
- ]),
- dbc.Row([dbc.Col(
- dcc.Graph(id="stocks2",config={'displayModeBar': False}) , align='center',
- ),],),
- dbc.Row([
- dbc.Col(id='stock_name3',align='center', width={'size': 2},style={'width': '20%','text-align': 'center','font-weight': 'bold','fontSize': '16','background-color': '#FFBF00','color': 'black', 'margin-left': '15px', 'margin-right': '15px'}),
- dbc.Col(id='latest_price3',align='center', width={'size': 2},style={'color': 'white'}),
- dbc.Col(id='latest_price_change3',align='center', width={'size': 2})
- ]),
- dbc.Row([dbc.Col(
- dcc.Graph(id="stocks3",config={'displayModeBar': False}) , align='center',
- ),],),
- ], width={'size': 4},md=4,sm=12,xs=12),
- ]),
- dcc.Store(id='zoom_store'),
- dcc.Interval(id= "interval", interval = 1000),
- ])
- @app.callback(
- Output("candles_slider", "max"),
- Output("candles_slider", "marks"),
- Input("interval", "n_intervals"),
- )
- def update_slider_max(n_intervals):
- data, latest_price, latest_price_change, volume = read_data(filename, stock[0], [1, 2, 3, 4])
- max_value = len(data)
- marks = {i: str(i) for i in range(10, max_value + 1, 10)}
- return max_value, marks
- @app.callback(
- Output("candles", "figure"),
- Output("stock_name", "children"),
- Output("latest_price", "children"),
- Output("latest_price_change", "children"),
- Output("latest_price_change", "style"),
- Output("volume_chart", "figure"),
- Output("volume", "children"),
- Output("Rsi", "figure"),
- Output("stocks1", "figure"),
- Output("stock_name1", "children"),
- Output("latest_price1", "children"),
- Output("latest_price_change1", "children"),
- Output("latest_price_change1", "style"),
- Output("stocks2", "figure"),
- Output("stock_name2", "children"),
- Output("latest_price2", "children"),
- Output("latest_price_change2", "children"),
- Output("latest_price_change2", "style"),
- #Output("stocks3", "figure"),
- #Output("stock_name3", "children"),
- #Output("latest_price3", "children"),
- #Output("latest_price_change3", "children"),
- #Output("latest_price_change3", "style"),
- Input("interval", "n_intervals"),
- Input('zoom_store', 'data'),
- Input("candles_slider", "value"),
- )
- def update_figure(n_intervals,zoom_data,num_candles):
- #data
- stock = ['BOIL', 'PYPL', 'INTC', 'AAPL', 'AMZN', 'MSFT', 'TSLA']
- filename = 'stock_data.csv'
- data, latest_price, latest_price_change, volume = read_data(filename, stock[0], [1, 2, 3, 4])
- data['x_axis'] = list(range(1, len(data['volume_diff']) +1))
- pos = data['open'] - data['close'] < 0
- neg = data['open'] - data['close'] > 0
- data['x_axis'] = list(range(1, len(data['volume_diff']) +1))
- ymax = data['volume_diff'].max()
- ystd = data['volume_diff'].std()
- # Main candlestick chart
- candles = go.Figure(go.Candlestick(x=data.index,open=data['open'],high=data['high'],low=data['low'],close=data['close'],name=stock[0],showlegend=False))
- with candles.batch_update():
- data = data.tail(num_candles)
- candles.update_layout(
- height=400,
- margin=dict(l=0, r=0, t=10, b=20),
- xaxis_rangeslider_visible=False,
- yaxis_range=[data['low'].min()- data['high'].std()*0.5,data['high'].max()+data['high'].std()*3 if not math.isnan(data['high'].max()) and data['high'].max() !=0 else [] ]
- )
- # Add volume chart to second subplot
- volume_chart = go.Figure(go.Bar(x=[],y=[],name='Volume',showlegend=False,marker={'color': 'Green'}))
- with volume_chart.batch_update():
- volume_chart.add_trace(go.Bar(x=[],y=[],name='Volume',showlegend=False,marker={'color': 'Red'}))
- volume_chart.update_layout(
- height=80,
- yaxis_range=[0, ymax+ystd*3 if not math.isnan(ymax)else []],
- margin=dict(l=0, r=0, t=10, b=20),
- xaxis_rangeslider_visible=False,
- )
- # Add RSI chart to second subplot
- Rsi = go.Figure()
- with Rsi.batch_update():
- Rsi.add_trace(go.Bar(x=[],y=[],name='Volume2',showlegend=False,marker={'color': 'Green'}))
- Rsi.update_layout(
- height=80,
- yaxis_range=[0, ymax+ystd*3 if not math.isnan(ymax)else []],
- margin=dict(l=0, r=0, t=10, b=20),
- xaxis_rangeslider_visible=False,
- )
- # Extra chart 1
- d2, latest_price1, latest_price_change1, volume = read_data('stock_data.csv', stock[1], [1, 5, 6, 7])
- stocks1 = go.Figure(go.Scatter(x=d2.index, y=d2['close'],showlegend=False,marker={'color': 'White'}, name=stock[1]))
- with stocks1.batch_update():
- stocks1.update_layout(
- height=82,
- margin=dict(l=0, r=0, t=10, b=20),
- xaxis_rangeslider_visible=False,
- )
- # Extra chart 2
- d3, latest_price2, latest_price_change2, volume = read_data('stock_data.csv', stock[2], [1, 8, 9, 10])
- stocks2 = go.Figure(go.Scatter(x=d3.index, y=d3['close'],showlegend=False,marker={'color': 'White'}, name=stock[1]))
- with stocks2.batch_update():
- stocks2.update_layout(
- height=82,
- margin=dict(l=0, r=0, t=10, b=20),
- xaxis_rangeslider_visible=False,
- )
- # Extra chart 3
- #d4, latest_price3, latest_price_change3, volume = read_data('stock_data.csv', stock[3], [1, 11, 12, 13])
- #stocks3 = go.Figure(go.Scatter(x=d4.index, y=d4['close'],showlegend=False,marker={'color': 'White'}, name=stock[3]))
- #with stocks3.batch_update():
- #stocks3.update_layout(
- #height=82,
- #margin=dict(l=0, r=0, t=10, b=20),
- #xaxis_rangeslider_visible=False,
- #)
- if zoom_data is not None:
- candles.update_xaxes(range=zoom_data),
- return candles,stock[0], latest_price, latest_price_change,{'color': '#18b800' if latest_price_change[0] == '+' else '#ff3503'}, \
- volume_chart,volume, \
- Rsi, \
- stocks1 ,stock[1], latest_price1, latest_price_change1,{'color': '#18b800' if latest_price_change1[0] == '+' else '#ff3503'},\
- stocks2,stock[2], latest_price2, latest_price_change2,{'color': '#18b800' if latest_price_change2[0] == '+' else '#ff3503'},\
- #stocks3,stock[3], latest_price3, latest_price_change3,{'color': '#18b800' if latest_price_change3[0] == '+' else '#ff3503'},\
- @app.callback(
- Output('zoom_store', 'data'),
- Input('candles', 'relayoutData'),
- )
- def update_zoom(relayout_data):
- if relayout_data is not None and 'xaxis.range[0]' in relayout_data and 'xaxis.range[1]' in relayout_data:
- return [relayout_data['xaxis.range[0]'], relayout_data['xaxis.range[1]']]
- return None
- if __name__== '__main__':
- app.run_server(debug=True)
Add Comment
Please, Sign In to add comment