使用 Python 创建股票分析仪表板

2022-05-23 01:50:00 首页 > 股票 庄志炎

  使用 Python 构建股票分析仪表板的综合指南。

使用 Python 创建股票分析仪表板

  在过去的几周里,我使用 Python 的 Dash 库设计了一个股票价格分析面板。 我的主要布局灵感来自 Trading View 的网站。 面板需要显示一个烛台图表,其中包含一组要使用的指标以及用户选择的股票的一些其他额外细节。 所有这些信息都将由众所周知的 pandas.data_reader.DataReader 对象检索。

  我们即将构建的视觉展示了一些公司在 2015 年 1 月 1 日至 2021 年 12 月 31 日期间的表现。

使用 Python 创建股票分析仪表板

  该项目的代码可以分为四个主要部分,按顺序排列:

  1. 数据收集与清理

  2.数据导入和默认图表

  3. 应用布局

  4. 交互性

加载所需的数据

  首先,需要获取股票名称,以便 DataReader 可以在 Internet 上收集它们的数据。 为了完成这项工作,我发现了一个有趣的网页,其中显示了一个表格,其中包含公司的 BOVESPA 标识符以及它们所属的经济部门。

  此阶段的代码包含项目“数据收集和清理”部分的一部分。

  # These are the libaries to be used.nimport dashnfrom dash import html, dcc, dash_table, callback_contextnimport plotly.graph_objects as gonimport dash_trich_components as dtcnfrom dash.dependencies import Input, Outputnimport dash_bootstrap_components as dbcnimport plotly.express as pxnimport jsonnimport pandas as pdnfrom pandas_ta import bbandsnimport pandas_datareader as webnimport numpy as npnimport datetimenfrom scipy.stats import pearsonrnn# 1. Data Collection & Cleaning nstocks = pd.read_html(n 'https://blog.toroinvestimentos.com.br/empresas-listadas-b3-bovespa', decimal=',')nstocks_sectores = stocks[1]nstocks_sectores.columns = stocks_sectores.iloc[0]nstocks_sectores.drop(index=0, inplace=True)nstocks_sectores_dict = stocks_sectores[[n 'Ticker', 'Setor']].to_dict(orient='list')nn# Implementing the economic sector names as the dictionay key and their stocks as values.nd = {}nfor stock, sector in zip(stocks_sectores_dict['Ticker'], stocks_sectores_dict['Setor']):n if sector not in d.keys():n d[sector] = [stock]n else:n d[sector].append(stock)nn# Correcting a tiny issue with the resulting dictionary: sometimes, two of its keys n# were concerning the very same economic sector! Let's merge them into a single one.nd['Bens Industriais'].extend(d['Bens industriais'])nd.pop('Bens industriais')nd['Bens Industriais']nd['Energia Elétrica'].extend(d['Energia elétrica'])nd.pop('Energia elétrica')nd['Energia Elétrica']nd['Aluguel de Veículos'].extend(d['Locação de veículos'])nd.pop('Locação de veículos')nd['Construção civil'].extend(d['Construção'])nd.pop('Construção')nd['Shopping Centers'].extend(d['Exploração de imóveis'])nd.pop('Exploração de imóveis')nn# Now, we'll translate the economic sectors names to English for better understanding.ntranslate = {'Alimentos': 'Food & Beverages', 'Varejo': 'Retail', n 'Companhia aérea': 'Aerospace', 'Seguros': 'Insurace', n 'Shopping Centers': 'Shopping Malls', 'Financeiro': 'Finance',n 'Mineração': 'Mining', 'Químicos': 'Chemical', 'Educação': 'Education',n 'Energia Elétrica': 'Electrical Energy', 'Viagens e lazer': 'Traveling',n 'Construção civil': 'Real Estate', 'Saúde': 'Health', n 'Siderurgia e Metalurgia': 'Steel & Metallurgy',n 'Madeira e papel': 'Wood & Paper', 'Aluguel de Veículos': 'Vehicle Rental',n 'Petróleo e Gás': 'Oil & Gas', 'Saneamento': 'Sanitation', n 'Telecomunicações': 'Telecommunication', 'Tecnologia': 'Technology', n 'Comércio': 'Commerce', 'Bens Industriais': 'Industrial Goods'}nfor key, value in translate.items():n d[value] = d.pop(key)nnn# Unfortunately, some of the stocks listed in the dictionary cannot be accessed with yahoo's API. n# Thus, we'll need to exclude them.nfor sector in list(d.keys()):n for stock in d[sector]:n # Trying to read the stock's data and removing it if it's not possible.n try:n web.DataReader(f'{stock}.SA', 'yahoo', '01-01-2015', '31-12-2021')n except:n d[sector].remove(stock)n # After the removing process is completed, some economic sectors may not have n # any stocks at all, so they won't be of use for the project.n if d[sector] == []:n d.pop(sector)nn# Converting it into a json filenwith open("sector_stocks.json", "w") as outfile:n json.dump(d, outfile)

  此操作的最终输出是一个名为“sector_stocks.json”的 JSON 文件,其键和值是经济部门名称及其各自的股票。

设置默认图表

  正如您在视觉效果的 GIF 中所看到的,仪表板总共包含三个图表。 主要的是显示 OHLC 价格信息的烛台图。 另外两个显示了对公司过去 52 周业绩的一些见解。 折线图代表股票的每周平均价格,速度计显示当前价格与该期间达到的最小值和最大值之间的差距。

  Dash 要求我们设置这些视觉效果的默认版本。 加载仪表板后,它们将立即显示。 考虑到这一点,我决定这些图表将按标准涵盖饮料行业巨头 AMBEV (ABEV3) 的股票数据。 请注意,以下代码构成了项目的“数据导入和默认图表”部分。

  # 2. Data Importing & Default Chartsnn# The standard stock displayed when the dashboard is initialized will be ABEV3.nambev = web.DataReader('ABEV3.SA', 'yahoo',n start='01-01-2015', end='31-12-2021')nn# 'ambev_variation' is a complementary information stored inside the card that n# shows the stock's current price (to be built futurely). It presents, as its n# variable name already suggests, the stock's price variation when compared to n# its previous value.nambev_variation = 1 - (ambev['Close'].iloc[-1] / ambev['Close'].iloc[-2])nn# 'fig' exposes the candlestick chart with the prices of the stock since 2015.nfig = go.Figure()nn# Observe that we are promtly filling the charts with AMBEV's data.nfig.add_trace(go.Candlestick(x=ambev.index,n open=ambev['Open'],n close=ambev['Close'],n high=ambev['High'],n low=ambev['Low'],n name='Stock Price'))nfig.update_layout(n paper_bgcolor='black',n font_color='grey',n height=500,n width=1000,n margin=dict(l=10, r=10, b=5, t=5),n autosize=False,n showlegend=Falsen)n# Setting the graph to display the 2021 prices in a first moment. n# Nonetheless,the user can also manually ajust the zoom size either by selecting a n# section of the chart or using one of the time span buttons available.nn# These two variables are going to be of use for the time span buttons.nmin_date = '2021-01-01'nmax_date = '2021-12-31'nfig.update_xaxes(range=[min_date, max_date])nfig.update_yaxes(tickprefix='R$')nn# The output from this small resample operation feeds the weekly average price chart.nambev_mean_52 = ambev.resample('W')[n 'Close'].mean().iloc[-52:]nfig2 = go.Figure()nfig2.add_trace(go.Scatter(x=ambev_mean_52.index, y=ambev_mean_52.values))nfig2.update_layout(n title={'text': 'Weekly Average Price', 'y': 0.9},n font={'size': 8},n plot_bgcolor='black',n paper_bgcolor='black',n font_color='grey',n height=220,n width=310,n margin=dict(l=10, r=10, b=5, t=5),n autosize=False,n showlegend=Falsen)nfig2.update_xaxes(showticklabels=False, showgrid=False)nfig2.update_yaxes(range=[ambev_mean_52.min()-1, ambev_mean_52.max()+1.5],n showticklabels=False, gridcolor='darkgrey', showgrid=False)nn# Making a speedometer chart which indicates the stock' minimum and maximum closing pricesn# reached during the last 52 weeks along its current price.ndf_52_weeks_min = ambev.resample('W')['Close'].min()[-52:].min()ndf_52_weeks_max = ambev.resample('W')['Close'].max()[-52:].max()ncurrent_price = ambev.iloc[-1]['Close']nfig3 = go.Figure()nfig3.add_trace(go.Indicator(mode='gauge+number', value=current_price,n domain={'x': [0, 1], 'y': [0, 1]},n gauge={n 'axis': {'range': [df_52_weeks_min, df_52_weeks_max]},n 'bar': {'color': '#606bf3'}}))nfig3.update_layout(n title={'text': 'Min-Max Prices', 'y': 0.9},n font={'size': 8},n paper_bgcolor='black',n font_color='grey',n height=220,n width=280,n margin=dict(l=35, r=0, b=5, t=5),n autosize=False,n showlegend=Falsen)

  完成此任务后,我们终于可以开始创建仪表板了!

配置布局

  仪表板的大部分组件都包含在两个 Bootstrap 列中。左侧部分占可用宽度的 75%,而右侧部分占据剩余空间。

  然而,有一个元素不会放在这些分段中,即页面顶部的轮播。它显示了一些 BOVESPA 最相关股票的价格变化。

库存变化轮播

  制作这个组件给我们带来了项目的技术限制之一。由于轮播需要显示一组股票的价格变化,它必须向 Yahoo Finance 的 API 发出多个请求。这会损害系统快速显示仪表板的速度。

  考虑到这一点,我计划了一种方法,可以在不影响应用程序效率的情况下为我们提供我们想要的东西。

  在创建“sector_stocks.json”文档时,还会生成第二个 JSON 文件。它将包含股票名称作为键,它们的价格变化作为值。由于仪表板的时间范围固定到 2021 年 12 月 1 日,因此不会给项目带来任何问题。

  # 1. Data Collection & Cleaning (Continuance)nn# A function that is going to measure the stocks' price variation.ndef variation(name):n df = web.DataReader(f'{name}.SA', 'yahoo',n start='29-12-2021', end='30-12-2021')n return 1-(df['Close'].iloc[-1] / df['Close'].iloc[-2])nnn# Listing the companies to be shown in the Carousel.ncarousel_stocks = ['ITUB4', 'BBDC4', 'VALE3', 'PETR4', 'PETR3',n 'ABEV3', 'BBAS3', 'B3SA3', 'ITSA4', 'CRFB3', 'CIEL3',n 'EMBR3', 'JBSS3', 'MGLU3', 'PCAR3', 'SANB11', 'SULA11']nn# This dictionary will later be converted into a json file.ncarousel_prices = {}nfor stock in carousel_stocks:n # Applying the 'variation' function for each of the list elements.n carousel_prices[stock] = variation(stock)nn# Turning 'carousel_prices' into a json file.nwith open('carousel_prices.json', 'w') as outfile:n json.dump(carousel_prices, outfile)

  完成最后一个操作后,我们完成了脚本的第一部分。 是时候最终构建应用程序的布局了。

  # 2. Data Importing & Default Charts (Ending)nn# Loading the dashboard's 'sector_stock' and 'carousel_prices' json files.nsector_stocks = json.load(open('sector_stocks.json', 'r'))ncarousel_prices = json.load(open('carousel_prices.json', 'r'))nn# 3. Application's Layoutnapp = dash.Dash(external_stylesheets=[dbc.themes.CYBORG])nn# Beginning the layout. The whole dashboard is contained inside a Div and a Bootstrapn# Row.napp.layout = html.Div([n dbc.Row([n dtc.Carousel([nn html.Div([n # This span shows the name of the stock.n html.Span(stock, style={n 'margin-right': '10px'}),nn # This other one shows its variation.n html.Span('{}{:.2%}'.format('+' if carousel_prices[stock] > 0 else '', n carousel_prices[stock]), n style={'color': 'green' if carousel_prices[stock] > 0 else 'red'})n ]) for stock in sorted(carousel_prices.keys())n ], id='main-carousel', autoplay=True, slides_to_show=4),n n n ])n])

  HTML Spans 显示股票名称及其价格变化。

仪表板的左侧部分

  如前所述,应用程序的大部分内容都放在两个 Bootstrap 列中。 左边一个占可用宽度的 75%,另一个占据其余空间。 查看本文的 GIF 时,我们看到仪表板左侧的第一个功能是两个下拉菜单。

下拉菜单

  这两个组件的目的是使用户能够选择将向其公开数据的公司。

  首先,需要告知所需企业经营所在的经济部门(第一个下拉菜单)。 选择此选项后,第二个下拉列表会列出属于该行业的公司。 所需要做的就是单击想要的股票名称,仪表板将显示其数据。

  但是由于我们没有设置所有的可视化组件,所以现在我们只处理两个下拉菜单之间的内部交互。

  # 3. Application's Layout (Continuance)nn# Place the following code under the top carousel structure. n# The column below will occupy 75% of the width available in the dashboard.n dbc.Col([nn # This row holds the dropdowns responsible for the selection of the stockn # which informations are going to be displayed.n dbc.Row([n n # Both dropdowns are placed inside two Bootstrap columns with equal length.n dbc.Col([n # A small title guiding the user on how to use the component.n html.Label('Select the desired sector',n style={'margin-left': '40px'}),n n # The economic sectors dropdown. It mentions all the ones that are n # available in the 'sector_stocks' dictionary.n dcc.Dropdown(options=[{'label': sector, 'value': sector}n for sector in sorted(list(sector_stocks.keys()))],n n # The dashboard's default stock is ABEV3, which pertains n # to the 'Food & Beverages' sector. So make sure n # these informations are automatically displayed n # when the dashboard is loaded. n value='Food & Beverages',n n # It is essential to create an identification for the n # components which will be used in interactivity operations.n id='sectors-dropdown', n style={'margin-left': '20px', 'width': '400px'}, n searchable=False)n ], width=6),n n # The column holding the stock names dropdown.n dbc.Col([n n # Nothing new here. Just using the same commands as above.n html.Label('Select the stock to be displayed'),n dcc.Dropdown(n id='stocks-dropdown',n value='ABEV3',n style={'margin-right': '20px'},n searchable=Falsen )n ], width=6)n ]),n n # The left major column closing bracketn ], width=9),n n # These are the dashboard's major dbc.Row and html.Div closing brackets.n ])n ])n n# 4. Interactivitynn# Allowing the stock dropdown to display the companies that are pertained to the n# economic sector chosen.n@ app.callback(n n # Observe how important the components id are to reference from where the function'sn # input comes from and in which element its output is used.n@ app.callback(n Output('stocks-dropdown', 'options'),n Input('sectors-dropdown', 'value')n)ndef modify_stocks_dropdown(sector):n n # The 'stocks-dropdown' dropdown values are the stocks that are part of then # selected economic domain.n stocks = sector_stocks[sector]n return stocks

  上面的代码足以生成两个元素并激活它们的内部关系。

烛台图、时间跨度按钮和指标

  本节将处理三个组件,因为将有一个方法来管理它们之间的关系。

  烛台图是最相关的特征。 它显示了 pandas_datareader 的 DataReader 对象检索到的 OHLC 价格。 与交易视图一样,它的 x 轴长度可以使用时间跨度按钮进行编辑。 技术分析指标被列为清单元素; 当有人选择他们喜欢的那个时,必须在视觉上绘制其各自的线条

使用 Python 创建股票分析仪表板

  在这部分脚本中产生了多种交互。 我们必须耐心地创造它们。

  # 3. Application's Layout (Continuance)nn# Insert the following portion of the code under the Dropdowns' dbc.Row.nn# All the three components are placed inside this dbc.Row.n dbc.Row([n n # Firstly, the candlestick chart is invoked. It is contained in a dcc.Loadingn # object, which presents a loading animation while the data is retrieved.n dcc.Loading(n [dcc.Graph(id='price-chart', figure=fig)], n id='loading-price-chart', type='dot', color='#1F51FF'),n n # Next, this row will store the time span buttons as well n # as the indicators checklistn dbc.Row([n n # The buttons occupy 1/3 of the available width.n dbc.Col([nn # This Div contains the time span buttons for adjustingn # of the x-axis' length.n html.Div([n html.Button('1W', id='1W-button',n n_clicks=0, className='btn-secondary'),n html.Button('1M', id='1M-button',n n_clicks=0, className='btn-secondary'),n html.Button('3M', id='3M-button',n n_clicks=0, className='btn-secondary'),n html.Button('6M', id='6M-button',n n_clicks=0, className='btn-secondary'),n html.Button('1Y', id='1Y-button',n n_clicks=0, className='btn-secondary'),n html.Button('3Y', id='3Y-button',n n_clicks=0, className='btn-secondary'),nn ], style={'padding': '15px', 'margin-left': '35px'})n ], width=4),nn # The indicators have the remaining two thirds of the space.n dbc.Col([n dcc.Checklist(n ['Rolling Mean',n 'Exponential Rolling Mean',n 'Bollinger Bands'],n inputStyle={'margin-left': '15px',n 'margin-right': '5px'},n id='complements-checklist',n style={'margin-top': '20px'})n ], width=8)n ]),n ]),n # The left major column's closing bracket.n ], width=9),n n # The dashboard's major dbc.Row and html.Div closing brackets.n ])n ])n n# 4. Interactivity (Continuance)n# Place this function below the dropdowns' interactivity method. It manages the n# relationship among the three elements just created.n@ app.callback(n Output('price-chart', 'figure'),n Input('stocks-dropdown', 'value'),n Input('complements-checklist', 'value'),n Input('1W-button', 'n_clicks'),n Input('1M-button', 'n_clicks'),n Input('3M-button', 'n_clicks'),n Input('6M-button', 'n_clicks'),n Input('1Y-button', 'n_clicks'),n Input('3Y-button', 'n_clicks'),n)ndef change_price_chart(stock, checklist_values, button_1w, button_1m, button_3m, n button_6m, button_1y, button_3y):n # Retrieving the stock's data.n df = web.DataReader(f'{stock}.SA', 'yahoo',n start='01-01-2015', end='31-12-2021')nn # Applying some indicators to its closing prices. Below we are measuring n # Bollinger Bands.n df_bbands = bbands(df['Close'], length=20, std=2)nn # Measuring the Rolling Mean and Exponential Rolling meansn df['Rolling Mean'] = df['Close'].rolling(window=9).mean()n df['Exponential Rolling Mean'] = df['Close'].ewm(n span=9, adjust=False).mean()nn # Each metric will have its own color in the chart.n colors = {'Rolling Mean': '#6fa8dc',n 'Exponential Rolling Mean': '#03396c', 'Bollinger Bands Low': 'darkorange',n 'Bollinger Bands AVG': 'brown',n 'Bollinger Bands High': 'darkorange'}nn fig = go.Figure()n fig.add_trace(go.Candlestick(x=df.index, open=df['Open'], close=df['Close'],n high=df['High'], low=df['Low'], name='Stock Price'))nn # If the user has selected any of the indicators in the checklist, we'll represent it in the chart.n if checklist_values != None:n for metric in checklist_values:nn # Adding the Bollinger Bands' typical three lines.n if metric == 'Bollinger Bands':n fig.add_trace(go.Scatter(n x=df.index, y=df_bbands.iloc[:, 0],n mode='lines', name=metric, n line={'color': colors['Bollinger Bands Low'], 'width': 1}))nn fig.add_trace(go.Scatter(n x=df.index, y=df_bbands.iloc[:, 1],n mode='lines', name=metric, n line={'color': colors['Bollinger Bands AVG'], 'width': 1}))nn fig.add_trace(go.Scatter(n x=df.index, y=df_bbands.iloc[:, 2],n mode='lines', name=metric, n line={'color': colors['Bollinger Bands High'], 'width': 1}))nn # Plotting any of the other metrics remained, if they are chosen.n else:n fig.add_trace(go.Scatter(n x=df.index, y=df[metric], mode='lines', name=metric, n line={'color': colors[metric], 'width': 1}))n n fig.update_layout(n paper_bgcolor='black',n font_color='grey',n height=500,n width=1000,n margin=dict(l=10, r=10, b=5, t=5),n autosize=False,n showlegend=Falsen )n # Defining the chart's x-axis length according to the button clicked.n # To do this, we'll alter the 'min_date' and 'max_date' global variables that were n # defined in the beginning of the script.n global min_date, max_daten changed_id = [p['prop_id'] for p in callback_context.triggered][0]n if '1W-button' in changed_id:n min_date = df.iloc[-1].name - datetime.timedelta(7)n max_date = df.iloc[-1].namen elif '1M-button' in changed_id:n min_date = df.iloc[-1].name - datetime.timedelta(30)n max_date = df.iloc[-1].namen elif '3M-button' in changed_id:n min_date = df.iloc[-1].name - datetime.timedelta(90)n max_date = df.iloc[-1].namen elif '6M-button' in changed_id:n min_date = df.iloc[-1].name - datetime.timedelta(180)n max_date = df.iloc[-1].namen elif '1Y-button' in changed_id:n min_date = df.iloc[-1].name - datetime.timedelta(365)n max_date = df.iloc[-1].namen elif '3Y-button' in changed_id:n min_date = df.iloc[-1].name - datetime.timedelta(1095)n max_date = df.iloc[-1].namen else:n min_date = min_daten max_date = max_daten fig.update_xaxes(range=[min_date, max_date])n fig.update_yaxes(tickprefix='R$')n return fign n # Updating the x-axis range.n fig.update_xaxes(range=[min_date, max_date])n fig.update_yaxes(tickprefix='R$')n return fig

  完成这部分代码后,我们已经结束了面板的左侧。

仪表板的右侧部分

  这整个区域暴露了一些关于股票及其各自经济部门的补充信息。 我们将要编写的代码比我们刚刚编写的代码要简单得多。

经济部门价格表

  右上角的表格显示了在下拉列表中选择的属于经济领域的企业的当前价格。 这样一来,个人就能够想象公司在与竞争对手的竞争中表现如何。

  # 3. Application's Layout (Continuance)nn# Beginning the Dashboard's right section. It should be under the panel's left-side code.n# This other column occupies 25% of the dashboard's width.n dbc.Col([nn dbc.Row([nn # The DataTable stores the prices from the companies that pertain n # to the same economic sector as the one chosen in the dropdowns.n dcc.Loading([nn dash_table.DataTable(n id='stocks-table', style_cell={'font_size': '12px', n 'textAlign': 'center'},n style_header={'backgroundColor': 'black',n 'padding-right': '62px', 'border': 'none'},n style_data={'height': '12px', 'backgroundColor': 'black', n 'border': 'none'}, style_table={n 'height': '90px', 'overflowY': 'auto'})n ], id='loading-table', type='circle', color='#1F51FF')nn ], style={'margin-top': '28px'}),n n # The right major column closing bracket.n ], width=3)n n # The dashboard's major dbc.Row and html.Div closing brackets.n ])n])nn# 4. Interactivity (Continuance)nn# The following function goes after the candlestick interactivity method.n@ app.callback(n Output('stocks-table', 'data'),n Output('stocks-table', 'columns'),n Input('sectors-dropdown', 'value')n)n# Updating the panel's DataTablendef update_stocks_table(sector):n global sector_stocksn # This DataFrame will be the base for the table.n df = pd.DataFrame({'Stock': [stock for stock in sector_stocks[sector]], n 'Close': [np.nan for i in range(len(sector_stocks[sector]))]},n index=[stock for stock in sector_stocks[sector]])n # Each one of the stock names and their respective prices are going to be stored n # in the 'df' DataFrame.n for stock in sector_stocks[sector]:n stock_value = web.DataReader(n f'{stock}.SA', 'yahoo', start='30-12-2021', end='31-12-2021')['Close'].iloc[-1]n df.loc[stock, 'Close'] = f'R$ {stock_value :.2f}'n n # Finally, the DataFrame cell values are stored in a dictionary and its columnn # names in a list of dictionaries.n return df.to_dict('records'), [{'name': i, 'id': i} for i in df.columns]

  update_stocks_table 可能看起来令人困惑,但它基本上需要返回两件事:填充字典中表格单元格的信息和字典列表中其列的名称。 有关 Dash 的 DataTable 工作原理的更多见解,请查看该库的文档。

当前价格卡

  毫无疑问,这是最重要的家庭经纪人功能之一,此卡旨在显示所选公司的名称、当前价值以及与前一天相比的价格变化。

  # 3. Application's Layout (Continuance)nn# Place this section beneath the DataTable coden# This Div will hold a card displaying the selected stock's current price.n html.Div([nn dbc.Card([nn # The card below presents the selected stock's current price.n dbc.CardBody([n # Recall that the name shown as default needs to be 'ABEV3', n # since it is the panel's standard stock.n html.H1('ABEV3', id='stock-name',n style={'font-size': '13px', 'text-align': 'center'}),n dbc.Row([n dbc.Col([n # Placing the current price.n html.P('R$ {:.2f}'.format(ambev['Close'].iloc[-1]), n id='stock-price', style={n 'font-size': '40px', 'margin-left': '5px'})n ], width=8),n dbc.Col([nn # This another paragraph shows the price variation.n html.P(n '{}{:.2%}'.format(n '+' if ambev_variation > 0 else '-', ambev_variation),n id='stock-variation', n style={'font-size': '14px', n 'margin-top': '25px', n 'color': 'green' if ambev_variation > 0 else 'red'})n ], width=4)nn ])nn ])n ], id='stock-data', style={'height': '105px'}, color='black'),n ])n # The right major column closing bracket.n ], width=3)n n # The dashboard's major dbc.Row and html.Div closing brackets.n ])n ])n n# 4. Interactivity (Continuance)n# The following function will edit the values being displayed in the price cardn# and it should follow the method that handles the DataTable.n@app.callback(n Output('stock-name', 'children'),n Output('stock-price', 'children'),n Output('stock-variation', 'children'),n Output('stock-variation', 'style'),n Input('stocks-dropdown', 'value')n)ndef update_stock_data_card(stock):nn # Retrieving data from the Yahoo Finance API.n df = web.DataReader(f'{stock}.SA', 'yahoo',n start='2021-12-29', end='2021-12-31')['Close']n # Getting the chosen stock's current price and variation in comparison to n # its previous value.n stock_current_price = df.iloc[-1]n stock_variation = 1 - (df.iloc[-1] / df.iloc[-2])nn # Note that as in the Carousel, the varitation value will be painted in red or n # green depending if it is a negative or positive number.n return stock, 'R$ {:.2f}'.format(stock_current_price), n '{}{:.2%}'.format('+' if stock_variation > 0 else'-', stock_variation), n {'font-size': '14px', 'margin-top': '25px',n 'color': 'green' if stock_variation > 0 else 'red'}

52 周数据轮播

  这个轮播在面板右侧启动了 52 周信息区域。 该组件将包含一个显示公司每周平均价格的折线图和一个速度计,它基本上显示了当前值与该期间达到的最低和最高水平之间的距离。

使用 Python 创建股票分析仪表板

  与创建的任何其他事物一样,此结构需要与股票下拉列表中选择的值进行通信,以显示正确的信息。 但与这个项目中构建的其他不同,这个有两种交互方法,一种用于每个图表。

  # 3. Application's Layout (Continuance)nn# This part of the script goes right under the price card construct.n# In the section below, some informations about the stock's performance in the last n# 52 weeks are going to be exposed.n html.Hr(),n html.H1(n '52-Week Data', style={'font-size': '25px', 'text-align': 'center', n 'color': 'grey', 'margin-top': '5px',n 'margin-bottom': '0px'}),n # Creating a Carousel showing the stock's weekly average price and a n # Speedoemeter displaying how far its current price is from n # the minimum and maximum values achieved.n dtc.Carousel([n n # By standard, the charts 'fig2' and 'fig3' made in the beginningn # of the script are displayed.n dcc.Graph(id='52-avg-week-price', figure=fig2),n dcc.Graph(id='52-week-min-max', figure=fig3)n ], slides_to_show=1, autoplay=True, speed=2000, n style={'height': '220px', 'width': '310px', 'margin-bottom': '0px'}),n n # The right major column closing bracket.n ], width=3)n n # The dashboard's major dbc.Row and html.Div closing brackets.n ])nn])nn# 4. Interactivity (Continuance)n# The function here is placed under the one dealing with the price card andn# is responsible for updating the weekly average price chart.nn@app.callback(n Output('52-avg-week-price', 'figure'),n Input('stocks-dropdown', 'value')n)ndef update_average_weekly_price(stock):n # Receiving the stock's prices and measuring its average weekly price n # in the last 52 weeks.n df = web.DataReader(f'{stock}.SA', 'yahoo',n start='2021-01-01', end='2021-12-31')['Close']n df_avg_52 = df.resample('W').mean().iloc[-52:]nn # Plotting the data in a line chart.n fig2 = go.Figure()n fig2.add_trace(go.Scatter(x=df_avg_52.index, y=df_avg_52.values))n fig2.update_layout(n title={'text': 'Weekly Average Price', 'y': 0.9},n font={'size': 8},n plot_bgcolor='black',n paper_bgcolor='black',n font_color='grey',n height=220,n width=310,n margin=dict(l=10, r=10, b=5, t=5),n autosize=False,n showlegend=Falsen )n fig2.update_xaxes(tickformat='%m-%y', showticklabels=False,n gridcolor='darkgrey', showgrid=False)n fig2.update_yaxes(range=[df_avg_52.min()-1, df_avg_52.max()+1.5],n showticklabels=False, gridcolor='darkgrey', showgrid=False)nn return fig2nn# This function will update the speedometer chart.n@app.callback(n Output('52-week-min-max', 'figure'),n Input('stocks-dropdown', 'value')n)ndef update_min_max(stock):n # The same logic as 'update_average_weekly_price', but instead we are gettingn # the minimum and maximum prices reached in the last 52 weeks and comparing n # them with the stock's current price.n df = web.DataReader(f'{stock}.SA', 'yahoo',n start='2021-01-01', end='2021-12-31')['Close']n df_avg_52 = df.resample('W').mean().iloc[-52:]n df_52_weeks_min = df_avg_52.resample('W').min()[-52:].min()n df_52_weeks_max = df_avg_52.resample('W').max()[-52:].max()n current_price = df.iloc[-1]n fig3 = go.Figure()n fig3.add_trace(go.Indicator(mode='gauge+number', value=current_price,n domain={'x': [0, 1], 'y': [0, 1]},n gauge={n 'axis': {'range': [df_52_weeks_min, df_52_weeks_max]},n 'bar': {'color': '#606bf3'}}))n fig3.update_layout(n title={'text': 'Min-Max Prices', 'y': 0.9},n font={'size': 8},n paper_bgcolor='black',n font_color='grey',n height=220,n width=280,n margin=dict(l=35, r=0, b=5, t=5),n autosize=False,n showlegend=Falsen )nn return fig3

  我们即将结束仪表板的结构。 我们需要插入的只是股票与 BOVESPA 指数 (IBOVESPA) 及其经济领域平均价格的相关性。

股票的相关性

  如前所述,这些最后的数字旨在提供与 IBOVESPA 及其经济部门同行相比企业绩效的一些观点。 要使用的统计量是 Pearson 的 r。

  # 3. Application's Layout (Ending!)nn# This row is beneath the carousel just made and places the stock's correlations with n# the BOVESPA index (IBOVESPA) and its sector's daily average price.n dbc.Row([n # A small title for the section.n html.H2('Correlations', style={n 'font-size': '12px', 'color': 'grey', 'text-align': 'center'}),n dbc.Col([nn # IBOVESPA correlation.n html.Div([n html.H1('IBOVESPA',n style={'font-size': '10px'}),n html.P(id='ibovespa-correlation',n style={'font-size': '20px', 'margin-top': '5px'})n ], style={'text-align': 'center'})nnn ], width=6),nn dbc.Col([nn # Sector correlation.n html.Div([n html.H1('Sector',n style={'font-size': '10px'}),n html.P(id='sector-correlation',n style={'font-size': '20px', 'margin-top': '5px'})n ], style={'text-align': 'center'})nn ], width=6)n ], style={'margin-top': '2px'})n ], style={'backgroundColor': 'black', 'margin-top': '20px', 'padding': '5px'})nn # The right major column closing bracket.n ], width=3)n n # The dashboard's major dbc.Row and html.Div closing brackets.n ])nn])nn# 4. Interactivity (Ending!)n# This function will measure the correlation coefficient between the stock's closing n# values and the BOVESPA index.n@ app.callback(n Output('ibovespa-correlation', 'children'),n Input('stocks-dropdown', 'value')n)ndef ibovespa_correlation(stock):n start = datetime.datetime(2021, 12, 31).date() - n datetime.timedelta(days=7 * 52)n end = datetime.datetime(2021, 12, 31).date()nn # Retrieving the IBOVESPA values in the last 52 weeks.n ibovespa = web.DataReader('^BVSP', 'yahoo', start=start, end=end)['Close']nn # Now, doing the same with the chosen stock's prices.n stock_close = web.DataReader(n f'{stock}.SA', 'yahoo', start=start, end=end)['Close']nn # Returning the correlation coefficient.n return f'{pearsonr(ibovespa, stock_close)[0] :.2%}'nn# Now, this other function will measure the same stat, but now between the stock's valuen# and the daily average closing price from its respective sector in the last 52 weeks.n@ app.callback(n Output('sector-correlation', 'children'),n Input('sectors-dropdown', 'value'),n Input('stocks-dropdown', 'value')n)ndef sector_correlation(sector, stock):n start = datetime.datetime(2021, 12, 31).date() - n datetime.timedelta(days=7 * 52)n end = datetime.datetime(2021, 12, 31).date()nn # Retrieving the daily closing prices from the selected stocks in the prior 52 weeks.n stock_close = web.DataReader(n f'{stock}.SA', 'yahoo', start=start, end=end)['Close']nn # Creating a DataFrame that will store the prices in the past 52 weeks n # from all the stocks that pertain to the economic domain selected.n sector_df = pd.DataFrame()nn # Retrieving the price for each of the stocks included in 'sector_stocks'n global sector_stocksn stocks_from_sector = [stock_ for stock_ in sector_stocks[sector]]n for stock_ in stocks_from_sector:n sector_df[stock_] = web.DataReader(n f'{stock_}.SA', 'yahoo', start=start, end=end)['Close']nn # With all the prices obtained, let's measure the sector's daily average value.n sector_daily_average = sector_df.mean(axis=1)nn # Now, returning the correlation coefficient.n return f'{pearsonr(sector_daily_average, stock_close)[0] :.2%}'nnn# Finally, running the Dash app.nif __name__ == '__main__':n app.run_server(debug=True)

  就是这样! 编写最后一段脚本将确保您拥有完整的股票数据分析仪表板!

结论

  我真诚地希望您喜欢和我一起构建这个面板!

股票

MORE>
最近发表
标签列表
最新留言