Hrispens

Untitled

Nov 16th, 2023
91
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 16.39 KB | None | 0 0
  1. import numpy
  2. from click import style
  3. from dash import Dash, html, dcc, callback, Output, Input, State
  4. import pandas as pd
  5. import dash_mantine_components as dmc
  6. import plotly.graph_objects as go
  7. from dash import dash_table
  8. import dash_bootstrap_components as dbc
  9. import plotly.express as px
  10. import base64
  11. import datetime
  12. import io
  13. import numpy as np
  14.  
  15. local_data_frame = pd.read_excel("data2.xlsx")
  16.  
  17.  
  18.  
  19. app = Dash(__name__, external_stylesheets=[dbc.themes.BOOTSTRAP])
  20.  
  21.  
  22. def generate_capital():
  23.     labels = ['Уставный капитал', 'Добавочный капитал', 'Резервный капитал', 'Нераспределенная прибыль']
  24.     f1310 = local_data_frame.loc[local_data_frame['Код'] == "Ф1.1310"].iloc[:, 3:].to_numpy()[0][0]
  25.     f1340 = local_data_frame.loc[local_data_frame['Код'] == "Ф1.1340"].iloc[:, 3:].to_numpy()[0][0]
  26.     f1350 = local_data_frame.loc[local_data_frame['Код'] == "Ф1.1350"].iloc[:, 3:].to_numpy()[0][0]
  27.     f1370 = local_data_frame.loc[local_data_frame['Код'] == "Ф1.1370"].iloc[:, 3:].to_numpy()[0][0]
  28.     f1360 = local_data_frame.loc[local_data_frame['Код'] == "Ф1.1360"].iloc[:, 3:].to_numpy()[0][0]
  29.     dk = f1340+f1350
  30.     values = list(map(lambda x: 0if x<0 else x,[f1310, dk, f1360, f1370]))
  31.     # print(values)
  32.     fig = go.Figure(data=[go.Pie(labels=labels, values=values, textinfo='label+percent',
  33.                                  insidetextorientation='radial',
  34.                                  hole=.7
  35.                                  )])
  36.     fig.update_layout(plot_bgcolor='white', )
  37.     return fig
  38.  
  39.  
  40. def parse_contents(contents, filename, date):
  41.     content_type, content_string = contents.split(',')
  42.     decoded = base64.b64decode(content_string)
  43.     try:
  44.         if 'csv' in filename:
  45.  
  46.             data_frame = pd.read_csv(
  47.                 io.StringIO(decoded.decode('utf-8')))
  48.         elif 'xlsx' in filename:
  49.  
  50.             data_frame = pd.read_excel(io.BytesIO(decoded))
  51.             # local_data_frame = data_frame
  52.     except Exception as e:
  53.  
  54.         return html.Div([
  55.             'There was an error processing this file.'
  56.         ])
  57.  
  58.     return [data_frame]
  59.  
  60.  
  61. @callback(Output('output-data-upload', 'data'),
  62.           Input('upload-data', 'contents'),
  63.           State('upload-data', 'filename'),
  64.           State('upload-data', 'last_modified'))
  65. def update_output(list_of_contents, list_of_names, list_of_dates):
  66.  
  67.     if list_of_contents is not None:
  68.         children = [
  69.             parse_contents(c, n, d) for c, n, d in
  70.             zip(list_of_contents, list_of_names, list_of_dates)]
  71.         return children[0]
  72.  
  73.  
  74. def generate_obligations():
  75.     # print(f"VREDSV {outputDataUpload}")
  76.  
  77.     years = years = list(local_data_frame.iloc[:, 3:].columns.values)
  78.     f1400 = local_data_frame.loc[local_data_frame['Код'] == "Ф1.1400"].iloc[:, 3:].to_numpy()[0]
  79.     fig = go.Figure(data=[go.Scatter(x=years, y=f1400)])
  80.     fig.update_layout(plot_bgcolor='white', )
  81.     return fig
  82. def generate_actives():
  83.     f1240 = local_data_frame.loc[local_data_frame['Код'] == "Ф1.1240"].iloc[:, 3:]
  84.     f1250 = local_data_frame.loc[local_data_frame['Код'] == "Ф1.1250"].iloc[:, 3:]
  85.     f1230 = local_data_frame.loc[local_data_frame['Код'] == "Ф1.1230"].iloc[:, 3:]
  86.     f1210 = local_data_frame.loc[local_data_frame['Код'] == "Ф1.1210"].iloc[:, 3:]
  87.     f1220 = local_data_frame.loc[local_data_frame['Код'] == "Ф1.1220"].iloc[:, 3:]
  88.     f1260 = local_data_frame.loc[local_data_frame['Код'] == "Ф1.1260"].iloc[:, 3:]
  89.     f1100 = local_data_frame.loc[local_data_frame['Код'] == "Ф1.1100"].iloc[:, 3:]
  90.     years = list(local_data_frame.iloc[:, 3:].columns.values)
  91.     years = list(map(lambda year: str(year)+"<br>",years))[:4]
  92.     a1 = f1240.to_numpy() + f1250.to_numpy()
  93.     a2 = f1230.to_numpy()
  94.     a3 = f1210.to_numpy() + f1220.to_numpy() + f1260.to_numpy()
  95.     a4 = f1100.to_numpy()
  96.     print(a1)
  97.     x_data = np.array([a1[0][:4],a2[0][:4],a3[0][:4],a4[0][:4]]).T
  98.     a1 = x_data[:, 0]
  99.     a1 = a1 / sum(a1)
  100.     a1 = numpy.rint((a1 * 100))
  101.     a2 = x_data[:, 1]
  102.     a2 = a2 / sum(a2)
  103.     a2 = numpy.rint((a2 * 100))
  104.     a3 = x_data[:, 2]
  105.     a3 = a3 / sum(a3)
  106.     a3 = numpy.rint((a3 * 100))
  107.     a4 = x_data[:, 3]
  108.     a4 = a4 / sum(a4)
  109.     a4 = numpy.rint((a4 * 100))
  110.     x_data = np.array([a1,a2,a3,a4]).T
  111.  
  112.  
  113.     return  generate_smart_grid(    top_labels=['A1', 'A2', 'A3', 'A4' ],
  114.                                                                 x_data=x_data,
  115.                                                                 y_data=years,
  116.                                                                 colors=['rgba(38, 24, 74, 0.8)',
  117.                                                                         'rgba(71, 58, 131, 0.8)',
  118.                                                                         'rgba(122, 120, 168, 0.8)',
  119.                                                                         'rgba(164, 163, 204, 0.85)',
  120.                                                                         'rgba(190, 192, 213, 1)'],)
  121. def generate_passivities():
  122.     f1520 = local_data_frame.loc[local_data_frame['Код'] == "Ф1.1520"].iloc[:, 3:]
  123.     f1510 = local_data_frame.loc[local_data_frame['Код'] == "Ф1.1510"].iloc[:, 3:]
  124.     f1540 = local_data_frame.loc[local_data_frame['Код'] == "Ф1.1540"].iloc[:, 3:]
  125.     f1550 = local_data_frame.loc[local_data_frame['Код'] == "Ф1.1550"].iloc[:, 3:]
  126.     f1400 = local_data_frame.loc[local_data_frame['Код'] == "Ф1.1400"].iloc[:, 3:]
  127.     f1300 = local_data_frame.loc[local_data_frame['Код'] == "Ф1.1300"].iloc[:, 3:]
  128.     years = list(local_data_frame.iloc[:, 3:].columns.values)
  129.     years = list(map(lambda year: str(year) + "<br>", years))[:4]
  130.     p1 = f1520.to_numpy()
  131.     p2 = f1510.to_numpy()+f1540.to_numpy()+f1550.to_numpy()
  132.     p3 = f1400.to_numpy()
  133.     p4 = f1300.to_numpy()
  134.  
  135.  
  136.     x_data = np.array([p1[0][:4], p2[0][:4], p3[0][:4], p4[0][:4]]).T
  137.     p1 = x_data[:, 0]
  138.     p1 = p1 / sum(p1)
  139.     p1 = numpy.rint((p1 * 100))
  140.     p2 = x_data[:, 1]
  141.     p2 = p2 / sum(p2)
  142.     p2 = numpy.rint((p2 * 100))
  143.     p3 = x_data[:, 2]
  144.     p3 = p3 / sum(p3)
  145.     p3 = numpy.rint((p3 * 100))
  146.     p4 = x_data[:, 3]
  147.     p4 = p4 / sum(p4)
  148.     p4 = numpy.rint((p4 * 100))
  149.     x_data = np.array([p1, p2, p3, p4]).T
  150.  
  151.     return  generate_smart_grid(     top_labels=['П1', 'П2', 'П3', 'П4', ],
  152.                                                                           x_data=x_data,
  153.                                                                           y_data=years,
  154.                                                                           colors=['rgba(169, 29, 17, 0.5)',
  155.                                                                                   'rgba(239, 48, 56, 0.6)',
  156.                                                                                   'rgba(255, 64, 64, 0.7)',
  157.                                                                                   'rgba(246, 74, 70, 0.8)',
  158.                                                                                   'rgba(246, 74, 70, 1)'],)
  159. def generate_smart_grid(top_labels, colors, x_data, y_data):
  160.  
  161.     fig = go.Figure()
  162.     for i in range(0, len(x_data[0])):
  163.         for xd, yd in zip(x_data, y_data):
  164.             fig.add_trace(go.Bar(
  165.                 x=[xd[i]], y=[yd],
  166.                 orientation='h',
  167.                 marker=dict(
  168.                     color=colors[i],
  169.                     line=dict(color='rgb(248, 248, 249)', width=1)
  170.                 )
  171.             ))
  172.     fig.update_layout(
  173.         xaxis=dict(
  174.             showgrid=False,
  175.             showline=False,
  176.             showticklabels=False,
  177.             zeroline=False,
  178.             domain=[0.15, 1]
  179.         ),
  180.         yaxis=dict(
  181.             showgrid=False,
  182.             showline=False,
  183.             showticklabels=False,
  184.             zeroline=False,
  185.         ),
  186.         barmode='stack',
  187.         # paper_bgcolor='rgb(248, 248, 255)',
  188.         plot_bgcolor='white',
  189.         margin=dict(l=0, r=10, t=140, b=80),
  190.         showlegend=False,
  191.     )
  192.     annotations = []
  193.  
  194.     for yd, xd in zip(y_data, x_data):
  195.         # labeling the y-axis
  196.         annotations.append(dict(xref='paper', yref='y',
  197.                                 x=0.14, y=yd,
  198.                                 xanchor='right',
  199.                                 text=str(yd),
  200.                                 font=dict(family='Arial', size=14,
  201.                                           color='rgb(67, 67, 67)'),
  202.                                 showarrow=False, align='right'))
  203.         # labeling the first percentage of each bar (x_axis)
  204.         annotations.append(dict(xref='x', yref='y',
  205.                                 x=xd[0] / 2, y=yd,
  206.                                 text=str(xd[0]) + '%',
  207.                                 font=dict(family='Arial', size=14,
  208.                                           color='rgb(248, 248, 255)'),
  209.                                 showarrow=False))
  210.         # labeling the first Likert scale (on the top)
  211.         if yd == y_data[-1]:
  212.             annotations.append(dict(xref='x', yref='paper',
  213.                                     x=xd[0] / 2, y=1.1,
  214.                                     text=top_labels[0],
  215.                                     font=dict(family='Arial', size=14,
  216.                                               color='rgb(67, 67, 67)'),
  217.                                     showarrow=False))
  218.         space = xd[0]
  219.         for i in range(1, len(xd)):
  220.             # labeling the rest of percentages for each bar (x_axis)
  221.             annotations.append(dict(xref='x', yref='y',
  222.                                     x=space + (xd[i] / 2), y=yd,
  223.                                     text=str(xd[i]) + '%',
  224.                                     font=dict(family='Arial', size=14,
  225.                                               color='rgb(248, 248, 255)'),
  226.                                     showarrow=False))
  227.             # labeling the Likert scale
  228.             if yd == y_data[-1]:
  229.                 annotations.append(dict(xref='x', yref='paper',
  230.                                         x=space + (xd[i] / 2), y=1.1,
  231.                                         text=top_labels[i],
  232.                                         font=dict(family='Arial', size=14,
  233.                                                   color='rgb(67, 67, 67)'),
  234.                                         showarrow=False))
  235.             space += xd[i]
  236.  
  237.     fig.update_layout(annotations=annotations)
  238.     return fig
  239.  
  240.  
  241.  
  242.  
  243.  
  244. def generate_net_profit():
  245.  
  246.     f1370 = list(local_data_frame.loc[local_data_frame['Код'] == "Ф1.1370"].iloc[:, 3:].to_numpy()[0])
  247.     cp = []
  248.     l = len(f1370)
  249.     for i in range(len(f1370)):
  250.         if(i+1<l):
  251.             cp.append(f1370[i]-f1370[i+1])
  252.  
  253.     years = list(local_data_frame.iloc[:, 3:].columns.values)
  254.     y = len(cp)
  255.  
  256.     years = years[:y]
  257.     colors = ['lightslategray', ] * len(years)
  258.     for i in range(len(cp)):
  259.         if cp[i] < 0:
  260.             colors[i] = 'crimson'
  261.     fig = go.Figure(data=[go.Bar(
  262.         x=years,
  263.         y=cp,
  264.  
  265.         marker_color=colors  # marker color can be a single color value or an iterable
  266.     )])
  267.     fig.update_layout(plot_bgcolor='white', )
  268.     # df = px.data.iris()
  269.     # fig = px.scatter_3d(df, x='sepal_length', y='sepal_width', z='petal_width',
  270.     #                     color='petal_length', symbol='species')
  271.     return fig
  272.  
  273.  
  274. app.layout = html.Div(children=[
  275. html.Div([
  276.     dcc.Upload(
  277.         id='upload-data',
  278.         children=html.Div([
  279.             'Перетащите файл или',
  280.             html.A(' Выберите файл')
  281.         ]),
  282.         style={
  283.             'width': '100%',
  284.             'height': '60px',
  285.             'lineHeight': '60px',
  286.             'borderWidth': '1px',
  287.             'borderStyle': 'dashed',
  288.             'borderRadius': '5px',
  289.             'textAlign': 'center',
  290.             'margin': '10px'
  291.         },
  292.  
  293.         multiple=True
  294.     ),
  295.  
  296. ]),
  297. dcc.Store(id="output-data-upload",),
  298. html.Div(id="main_container",)
  299.  
  300. ])
  301.  
  302.  
  303. @callback(Output('main_container', 'children'),
  304.           Input('output-data-upload','data',),)
  305. def build_main_container(data):
  306.  
  307.  
  308.     return  html.Div(children=[
  309.     dbc.Container([
  310.  
  311.         html.Br(),
  312.         html.H1(children='Бизнес-аналитика', style={'textAlign': 'center'}),
  313.         html.Br(),
  314.         dbc.Row(style={"paddingBottom": 18}, children=[
  315.             # dbc.Col(dbc.Card(children=[dbc.Row(), ]), md=2),
  316.             dbc.Col(dbc.Card(style={"border": 0}, children=[html.Br(), dbc.Row(dmc.Text(
  317.                 "Капитал",
  318.                 size="lg",
  319.                 color="dimmed",
  320.                 align="center"
  321.             )),
  322.                                                             dcc.Graph(id="capital_graph", figure=generate_capital())
  323.                                                             ]), md=6),
  324.             dbc.Col(dbc.Card(style={"border": 0}, children=[html.Br(), dbc.Row(dmc.Text(
  325.                 "Чистая прибыль",
  326.                 size="lg",
  327.                 color="dimmed",
  328.                 align="center"
  329.             )),
  330.                                                             dcc.Graph(id="generate_net_profit",
  331.                                                                       figure=generate_net_profit())
  332.                                                             ]), md=6)
  333.         ], ),
  334.         dbc.Row(children=[   dbc.Col(dbc.Card(style={"border": 0}, children=[html.Br(), dbc.Row(dmc.Text(
  335.                 "Активы",
  336.                 size="lg",
  337.                 color="dimmed",
  338.                 align="center"
  339.             )),
  340.                                                             dcc.Graph(id="generate_actives", figure=generate_actives())
  341.                                                             ]), md=12)],style={"paddingBottom": 18}, ),
  342.         dbc.Row(children=[dbc.Col(dbc.Card(style={"border": 0}, children=[html.Br(), dbc.Row(dmc.Text(
  343.             "Пассивы",
  344.             size="lg",
  345.             color="dimmed",
  346.             align="center"
  347.         )),
  348.                                                                           dcc.Graph(id="generate_passivities",
  349.                                                                                     figure=generate_passivities())
  350.                                                                           ]), md=12)],style={"paddingBottom": 18}, ),
  351.         dbc.Row(children=[
  352.             dbc.Col(dbc.Card(style={"border": 0}, children=[html.Br(), dbc.Row(dmc.Text(
  353.                 "Долгосрочные обязательства",
  354.                 size="lg",
  355.                 color="dimmed",
  356.                 align="center"
  357.             ))
  358.                 , dcc.Graph(id="generate_obligations",figure=generate_obligations())
  359.                                                             ]), md=12),
  360.  
  361.  
  362.         ], ),
  363.         # dcc.Store(id='output-data-upload', ),
  364.     ], style={"background": "#F7F7F8", "margin": 0}, fluid=True),
  365.     html.Div(children=[dash_table.DataTable(
  366.             local_data_frame.to_dict('records'),
  367.             [{'name': str(i), 'id': str(i)} for i in local_data_frame.columns]
  368.         )]),
  369. ])
  370.  
  371.  
  372.  
  373. if __name__ == '__main__':
  374.     app.run_server(debug=True,threaded=True,)
  375.  
  376. # print(  df.to_markdown())
  377. f1240 = local_data_frame.loc[local_data_frame['Код'] == "Ф1.1240"].iloc[:, 3:]
  378. f1250 = local_data_frame.loc[local_data_frame['Код'] == "Ф1.1250"].iloc[:, 3:]
  379. f1230 = local_data_frame.loc[local_data_frame['Код'] == "Ф1.1230"].iloc[:, 3:]
  380. f1210 = local_data_frame.loc[local_data_frame['Код'] == "Ф1.1210"].iloc[:, 3:]
  381. f1220 = local_data_frame.loc[local_data_frame['Код'] == "Ф1.1220"].iloc[:, 3:]
  382. f1260 = local_data_frame.loc[local_data_frame['Код'] == "Ф1.1260"].iloc[:, 3:]
  383. f1100 = local_data_frame.loc[local_data_frame['Код'] == "Ф1.1100"].iloc[:, 3:]
  384. f1370= local_data_frame.loc[local_data_frame['Код'] == "Ф1.1370"].iloc[:, 3:]
  385. # years = list(df.iloc[:, 3:].columns.values)
  386. # years = list(map(lambda year: str(year) + "<br>", years))
  387. # a1 = f1240.to_numpy() + f1250.to_numpy()
  388. # a2 = f1230.to_numpy()
  389. # a3 = f1210.to_numpy() + f1220.to_numpy() + f1260.to_numpy()
  390. # a4 = f1100.to_numpy()
  391. # x_data = np.array([a1[0][:4], a2[0][:4], a3[0][:4], a4[0][:4]]).T
  392. # print(x_data)
  393. # a1 = x_data[:,0]
  394. # a1 = a1/sum(a1)
  395. # a1 = numpy.rint((a1*100))
  396. # print(x_data[:,0])
  397. # print(numpy.rint((a1*100)))
Add Comment
Please, Sign In to add comment