srcveiga

Untitled

Mar 24th, 2023
43
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 14.02 KB | None | 0 0
  1. import pandas as pd
  2. import plotly.graph_objects as go
  3. from plotly.subplots import make_subplots
  4. import dash
  5. from dash import dcc
  6. from dash import html
  7. from dash.dependencies import Input, Output
  8. import dash_bootstrap_components as dbc
  9. import math
  10.  
  11. def string_to_number(df, column):
  12. if isinstance(df.iloc[0, df.columns.get_loc(column)], str):
  13. df[column] = df[column].str.replace(',','')
  14. df[column] = df[column].astype(float)
  15. return df
  16.  
  17. def read_data(filename, stock_code, usecols):
  18. df = pd.read_csv(filename, header=None, usecols=usecols,
  19. names=['time', stock_code, 'price change', 'volume'],
  20. index_col= 'time', parse_dates=['time'])
  21. index_with_nan = df.index[df.isnull().any(axis=1)]
  22. df.drop(index_with_nan, axis=0, inplace=True)
  23. df = string_to_number(df, stock_code)
  24. df = string_to_number(df, 'volume')
  25. latest_info = df.iloc[-1, :]
  26. latest_price = str(round(latest_info.iloc[0], 2))
  27. latest_price_change = str(latest_info.iloc[1])
  28. dfvol = df['volume'].resample('1Min').mean()
  29. data = df[stock_code].resample('1Min').ohlc()
  30. data['time'] = data.index
  31. data['time'] = pd.to_datetime(data['time'], format='%Y-%m-%d %H:%M:%S')
  32. data['MA5'] = data['close'].rolling(5).mean()
  33. data['MA10'] = data['close'].rolling(10).mean()
  34. data['MA20'] = data['close'].rolling(20).mean()
  35. data['volume_diff'] = dfvol.diff()
  36. data[data['volume_diff'] < 0] = None
  37. index_with_nan = data.index[data.isnull().any(axis=1)]
  38. data.reset_index(drop=True, inplace=True)
  39.  
  40. return data, latest_price, latest_price_change, df['volume'][-1]
  41.  
  42.  
  43. app = dash.Dash(__name__, external_stylesheets=[dbc.themes.BOOTSTRAP])
  44. stock = ['BOIL', 'PYPL', 'INTC', 'AAPL', 'AMZN', 'MSFT', 'TSLA']
  45. filename = 'stock_data.csv'
  46. data, latest_price, latest_price_change, volume = read_data('stock_data.csv', stock[0], [1, 2, 3, 4])
  47.  
  48. app.layout = html.Div(style={'backgroundColor': 'black'}, children=[
  49.  
  50. dbc.Row( style={
  51. 'textAlign': 'center',
  52. 'backgroundColor': 'black',
  53. 'color': 'white',
  54. }, children=[
  55.  
  56. 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),
  57.  
  58. 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),
  59.  
  60. ],),
  61.  
  62. dbc.Row(style={
  63. 'textAlign': 'center',
  64. 'height': '100vh',
  65. 'backgroundColor': 'black',
  66. 'color': 'white'}, children=[
  67.  
  68. dbc.Col( style={'content-align': 'center','padding-left': '20px' , 'padding-right': '50px','padding-top': '40px'}, children=[
  69.  
  70. dbc.Row([
  71. dbc.Col(id='stock_name',align='center', width={'size': 1},style={'font-weight': 'bold','fontSize': '16','background-color': '#FFBF00','color': 'black', 'margin-left': '45px'}),
  72. dbc.Col(id='latest_price',align='center', width={'size': 2}, style={'color': 'white'}),
  73. dbc.Col(id='latest_price_change',align='center', width={'size': 2})
  74.  
  75. ] ),
  76.  
  77. dbc.Row([dbc.Col(
  78. dcc.Graph(id="candles"), align='center',
  79. ),],),
  80.  
  81. dbc.Row([
  82. 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'}),
  83. dbc.Col(id='volume',align='center', width={'size': 1},style={'color': 'white'}),
  84. ] ),
  85.  
  86. dbc.Row([dbc.Col(
  87. dcc.Graph(id="volume_chart",config={'displayModeBar': False}), align='center',
  88. ),],),
  89.  
  90. dbc.Row([
  91. 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'}),
  92. dbc.Col('um teste',align='center', width={'size': 2},style={'color': 'white'}),
  93. ] ),
  94.  
  95. dbc.Row([dbc.Col(
  96. dcc.Graph(id="Rsi",config={'displayModeBar': False}), align='center',
  97. ),],),
  98.  
  99. ], width={'size': 8},md=8,sm=12,xs=12),
  100.  
  101. dbc.Col(style={'content-align': 'center','padding-left': '50px' , 'padding-right': '50px','padding-top': '40px'}, children=[
  102.  
  103. dbc.Row([
  104. 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'}),
  105. dbc.Col(id='latest_price1',align='center', width={'size': 2},style={'color': 'white'}),
  106. dbc.Col(id='latest_price_change1',align='center', width={'size': 2})
  107.  
  108. ]),
  109. dbc.Row([dbc.Col(
  110. dcc.Graph(id="stocks1",config={'displayModeBar': False}) , align='center',
  111. ),],),
  112.  
  113. dbc.Row([
  114. 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'}),
  115. dbc.Col(id='latest_price2',align='center', width={'size': 2},style={'color': 'white'}),
  116. dbc.Col(id='latest_price_change2',align='center', width={'size': 2})
  117.  
  118. ]),
  119. dbc.Row([dbc.Col(
  120. dcc.Graph(id="stocks2",config={'displayModeBar': False}) , align='center',
  121. ),],),
  122.  
  123. dbc.Row([
  124. 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'}),
  125. dbc.Col(id='latest_price3',align='center', width={'size': 2},style={'color': 'white'}),
  126. dbc.Col(id='latest_price_change3',align='center', width={'size': 2})
  127.  
  128. ]),
  129. dbc.Row([dbc.Col(
  130. dcc.Graph(id="stocks3",config={'displayModeBar': False}) , align='center',
  131. ),],),
  132.  
  133. ], width={'size': 4},md=4,sm=12,xs=12),
  134. ]),
  135.  
  136. dcc.Store(id='zoom_store'),
  137. dcc.Interval(id= "interval", interval = 1000),
  138. ])
  139.  
  140. @app.callback(
  141. Output("candles_slider", "max"),
  142. Output("candles_slider", "marks"),
  143. Input("interval", "n_intervals"),
  144.  
  145. )
  146. def update_slider_max(n_intervals):
  147. data, latest_price, latest_price_change, volume = read_data(filename, stock[0], [1, 2, 3, 4])
  148.  
  149. max_value = len(data)
  150. marks = {i: str(i) for i in range(10, max_value + 1, 10)}
  151.  
  152. return max_value, marks
  153.  
  154. @app.callback(
  155. Output("candles", "figure"),
  156. Output("stock_name", "children"),
  157. Output("latest_price", "children"),
  158. Output("latest_price_change", "children"),
  159. Output("latest_price_change", "style"),
  160.  
  161. Output("volume_chart", "figure"),
  162. Output("volume", "children"),
  163.  
  164. Output("Rsi", "figure"),
  165.  
  166. Output("stocks1", "figure"),
  167. Output("stock_name1", "children"),
  168. Output("latest_price1", "children"),
  169. Output("latest_price_change1", "children"),
  170. Output("latest_price_change1", "style"),
  171.  
  172. Output("stocks2", "figure"),
  173. Output("stock_name2", "children"),
  174. Output("latest_price2", "children"),
  175. Output("latest_price_change2", "children"),
  176. Output("latest_price_change2", "style"),
  177.  
  178. #Output("stocks3", "figure"),
  179. #Output("stock_name3", "children"),
  180. #Output("latest_price3", "children"),
  181. #Output("latest_price_change3", "children"),
  182. #Output("latest_price_change3", "style"),
  183.  
  184. Input("interval", "n_intervals"),
  185. Input('zoom_store', 'data'),
  186. Input("candles_slider", "value"),
  187.  
  188. )
  189. def update_figure(n_intervals,zoom_data,num_candles):
  190.  
  191. #data
  192. stock = ['BOIL', 'PYPL', 'INTC', 'AAPL', 'AMZN', 'MSFT', 'TSLA']
  193. filename = 'stock_data.csv'
  194. data, latest_price, latest_price_change, volume = read_data(filename, stock[0], [1, 2, 3, 4])
  195. data['x_axis'] = list(range(1, len(data['volume_diff']) +1))
  196. pos = data['open'] - data['close'] < 0
  197. neg = data['open'] - data['close'] > 0
  198. data['x_axis'] = list(range(1, len(data['volume_diff']) +1))
  199. ymax = data['volume_diff'].max()
  200. ystd = data['volume_diff'].std()
  201.  
  202. # Main candlestick chart
  203. 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))
  204. with candles.batch_update():
  205. data = data.tail(num_candles)
  206. candles.update_layout(
  207. height=400,
  208. margin=dict(l=0, r=0, t=10, b=20),
  209. xaxis_rangeslider_visible=False,
  210. 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 [] ]
  211. )
  212.  
  213. # Add volume chart to second subplot
  214. volume_chart = go.Figure(go.Bar(x=[],y=[],name='Volume',showlegend=False,marker={'color': 'Green'}))
  215. with volume_chart.batch_update():
  216. volume_chart.add_trace(go.Bar(x=[],y=[],name='Volume',showlegend=False,marker={'color': 'Red'}))
  217. volume_chart.update_layout(
  218. height=80,
  219. yaxis_range=[0, ymax+ystd*3 if not math.isnan(ymax)else []],
  220. margin=dict(l=0, r=0, t=10, b=20),
  221. xaxis_rangeslider_visible=False,
  222. )
  223.  
  224. # Add RSI chart to second subplot
  225. Rsi = go.Figure()
  226. with Rsi.batch_update():
  227. Rsi.add_trace(go.Bar(x=[],y=[],name='Volume2',showlegend=False,marker={'color': 'Green'}))
  228. Rsi.update_layout(
  229. height=80,
  230. yaxis_range=[0, ymax+ystd*3 if not math.isnan(ymax)else []],
  231. margin=dict(l=0, r=0, t=10, b=20),
  232. xaxis_rangeslider_visible=False,
  233. )
  234.  
  235. # Extra chart 1
  236. d2, latest_price1, latest_price_change1, volume = read_data('stock_data.csv', stock[1], [1, 5, 6, 7])
  237. stocks1 = go.Figure(go.Scatter(x=d2.index, y=d2['close'],showlegend=False,marker={'color': 'White'}, name=stock[1]))
  238. with stocks1.batch_update():
  239. stocks1.update_layout(
  240. height=82,
  241. margin=dict(l=0, r=0, t=10, b=20),
  242. xaxis_rangeslider_visible=False,
  243. )
  244.  
  245. # Extra chart 2
  246. d3, latest_price2, latest_price_change2, volume = read_data('stock_data.csv', stock[2], [1, 8, 9, 10])
  247. stocks2 = go.Figure(go.Scatter(x=d3.index, y=d3['close'],showlegend=False,marker={'color': 'White'}, name=stock[1]))
  248. with stocks2.batch_update():
  249. stocks2.update_layout(
  250. height=82,
  251. margin=dict(l=0, r=0, t=10, b=20),
  252. xaxis_rangeslider_visible=False,
  253. )
  254.  
  255. # Extra chart 3
  256. #d4, latest_price3, latest_price_change3, volume = read_data('stock_data.csv', stock[3], [1, 11, 12, 13])
  257. #stocks3 = go.Figure(go.Scatter(x=d4.index, y=d4['close'],showlegend=False,marker={'color': 'White'}, name=stock[3]))
  258. #with stocks3.batch_update():
  259. #stocks3.update_layout(
  260. #height=82,
  261. #margin=dict(l=0, r=0, t=10, b=20),
  262. #xaxis_rangeslider_visible=False,
  263. #)
  264.  
  265. if zoom_data is not None:
  266. candles.update_xaxes(range=zoom_data),
  267.  
  268. return candles,stock[0], latest_price, latest_price_change,{'color': '#18b800' if latest_price_change[0] == '+' else '#ff3503'}, \
  269. volume_chart,volume, \
  270. Rsi, \
  271. stocks1 ,stock[1], latest_price1, latest_price_change1,{'color': '#18b800' if latest_price_change1[0] == '+' else '#ff3503'},\
  272. stocks2,stock[2], latest_price2, latest_price_change2,{'color': '#18b800' if latest_price_change2[0] == '+' else '#ff3503'},\
  273. #stocks3,stock[3], latest_price3, latest_price_change3,{'color': '#18b800' if latest_price_change3[0] == '+' else '#ff3503'},\
  274.  
  275. @app.callback(
  276. Output('zoom_store', 'data'),
  277. Input('candles', 'relayoutData'),
  278. )
  279. def update_zoom(relayout_data):
  280. if relayout_data is not None and 'xaxis.range[0]' in relayout_data and 'xaxis.range[1]' in relayout_data:
  281. return [relayout_data['xaxis.range[0]'], relayout_data['xaxis.range[1]']]
  282. return None
  283.  
  284. if __name__== '__main__':
  285. app.run_server(debug=True)
Add Comment
Please, Sign In to add comment