<?xml version="1.0" encoding="UTF-8"?><rss xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:content="http://purl.org/rss/1.0/modules/content/" xmlns:atom="http://www.w3.org/2005/Atom" version="2.0" xmlns:cc="http://cyber.law.harvard.edu/rss/creativeCommonsRssModule.html">
    <channel>
        <title><![CDATA[Stories by Everton Almeida on Medium]]></title>
        <description><![CDATA[Stories by Everton Almeida on Medium]]></description>
        <link>https://medium.com/@almeida.eas?source=rss-7060488ff9e------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*FWqN6NqBhE0u9EY71rfoOw.jpeg</url>
            <title>Stories by Everton Almeida on Medium</title>
            <link>https://medium.com/@almeida.eas?source=rss-7060488ff9e------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Sat, 05 Dec 2026 02:05:24 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@almeida.eas/feed" rel="self" type="application/rss+xml"/>
        <webMaster><![CDATA[yourfriends@medium.com]]></webMaster>
        <atom:link href="http://medium.superfeedr.com/" rel="hub"/>
        <item>
            <title><![CDATA[Discrete Choice Models: An Introduction to Demand Estimation and Product and Price Differentiation]]></title>
            <link>https://medium.com/data-science-collective/discrete-choice-models-an-introduction-to-demand-estimation-and-product-and-price-differentiation-099028c91410?source=rss-7060488ff9e------2</link>
            <guid isPermaLink="false">https://medium.com/p/099028c91410</guid>
            <dc:creator><![CDATA[Everton Almeida]]></dc:creator>
            <pubDate>Thu, 11 Sep 2025 23:29:33 GMT</pubDate>
            <atom:updated>2025-09-22T11:28:43.420Z</atom:updated>
            <content:encoded><![CDATA[<h4>Understanding Consumer Preferences and Competitive Positioning Through Econometrics</h4><p>Every day, companies of all sizes face decisions regarding the launch of a new product, the introduction of a variation of an existing product, or the creation of a promotional price for a product with unsatisfactory sales performance. Invariably, the central question is: <em>“How much is the consumer willing to pay for this?”</em></p><p>In all three cases, the issue boils down to consumer preferences. Consumer Theory posits that a rational utility-maximizing agent will determine their optimal consumption based on: i) the utility derived from a given good, and ii) the “disutility,” which is the monetary cost of acquiring that good.</p><p>Although it is currently impossible to determine the “optimal basket of goods” and how much of it is dedicated to our product, a class of econometric models can help us understand how preferable one good is over another; how much more a consumer is willing to pay for a specific product attribute; and how sensitive a consumer is to price increases.</p><p>These questions are crucial from both a marketing perspective — <em>“Is the new feature of my product truly desired by consumers?”</em> — and from a pricing and revenue optimization standpoint — <em>“What is the impact of a price adjustment on demand and revenue?”</em></p><p>Many microeconomic problems are related to consumer decisions among a set of alternative goods — Which handbag to buy? Where to travel for vacation? Should one commute by train or car? These are all examples of choices consumers face, weighing perceived costs and benefits. Measuring these preferences provides us with knowledge that can help us make better decisions regarding the positioning of a product in the market.</p><p><strong>The objective of this text is to serve as a practical and introductory guide to discrete choice models using R</strong>. I plan to publish other texts about other models and details regarding the use of each one of them. The R code I used can be accessed on my GitHub: <a href="https://github.com/almeidaeas/demand_modelling/">almeidaeas/demand_modelling</a></p><h3>Model Specification and Estimation</h3><p>A discrete choice model involves three steps: i) defining the choice set,<br>ii) designing an experiment that replicates the agents’ decision-making process, and iii) estimating the unknown parameters of a model to obtain the perceived utility of individuals. The perceived utility can be defined as:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/236/1*fx9g37TCGPluS56tJr11mA.png" /></figure><p>The utility <em>(Unj)</em>​ of an individual <em>n</em> for alternative <em>j</em>, given a vector of attributes, is composed of a representative (observable) component and an unobservable error term. The latter reflects the fact that, when analyzing individual choices, we only have access to a subset of the attributes considered and a limited view of personal preferences. For example, we may observe choices between brand X and Y, but not latent preferences such as the impact of packaging color — would a blue or red label influence the decision? How many consumers could assert that confidently?</p><p>Since utility is not directly observable, we estimate <em>Unj</em>​, typically modeled as a linear function of product and/or consumer characteristics:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/281/1*pj0LfYX8Bu-I13yRuS2WEw.png" /></figure><p>Where <em>Xnj</em>​ is the vector of attributes and <em>β</em> are the structural parameters to be estimated. The consumer chooses alternative <em>j</em> if and only if</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/310/1*T3-yXs8cwDARmZ3Az_OtPQ.png" /></figure><p>Assuming the error terms are independently and identically distributed (i.i.d.) with a Type I Extreme Value distribution, we can estimate choice probabilities using a multinomial logit model. This model, a type of Random Utility Model, yields probabilities between 0 and 1 for each alternative, summing up to 1. Marginal effects vary depending on the attributes and predicted probabilities.</p><p>However, a known limitation of the logit model is the Independence of Irrelevant Alternatives (IIA) property, which may be problematic in contexts with similar options — e.g., choosing between bus line 001 and 002.</p><h3>A First Model: Price Sensitivity</h3><p>Among the various datasets available for discrete choice modeling, I choose the “Consumer WTP for Sustainability Attributes in Beer” dataset, which aims to estimate how much consumers are willing to pay for sustainability-related attributes in beer products. Although the dataset contains numerous attributes for both products and individuals, we begin with the simplest: Price.</p><pre>library(mlogit)<br>library(haven)<br>library(dplyr)<br>library(ggplot2)<br>library(ggthemes)<br><br>#Load Data Set<br>Beer_Data &lt;- read_dta(&quot;/DCM - Beer/Code/Model 1 - MNL with Full Dataset/Beer Data Full Dataset.dta&quot;)<br><br>#Alternative 3 is an Opt-Out<br>Beer_Data &lt;- Beer_Data %&gt;%<br>  mutate(Dummy_Alt_3 = ifelse(Alternative == 3, 1, 0))<br><br>#Convert data set to mlogit.data format<br>mlogit_data &lt;- mlogit.data(Beer_Data,<br>                           choice = &quot;Choice&quot;,<br>                           shape = &quot;long&quot;,<br>                           alt.var = &quot;Alternative&quot;,<br>                           id.var = &quot;RespondentID&quot;)<br><br>#Model 1: Choice given the price<br>model_1 &lt;- mlogit(Choice ~ Price + Dummy_Alt_3  | 0 | 0 , data = mlogit_data)<br>summary(model_1)</pre><p>Using the mlogit package in R, we specified a model where the probability of choosing an alternative depends on its price and whether it represents an opt-out option. The results are consistent with microeconomic theory: as the price of an alternative increases, its perceived utility and probability of being chosen decrease. Additionally, the dummy variable for the opt-out option indicates that “choosing not to choose” also yields lower utility. Although consumers do not pay for this option (price is zero), they also do not enjoy the benefits of the product.</p><pre>Frequencies of alternatives:choice<br>      1       2       3 <br>0.32223 0.35515 0.32262 <br><br><br>Coefficients :<br>              Estimate Std. Error z-value  Pr(&gt;|z|)    <br>Price       -0.2271945  0.0089048 -25.514 &lt; 2.2e-16 ***<br>Dummy_Alt_3 -2.1297399  0.0836278 -25.467 &lt; 2.2e-16 ***<br>---<br>Signif. codes:  0 ‘***’ 0.001 ‘**’ 0.01 ‘*’ 0.05 ‘.’ 0.1 ‘ ’ 1<br><br>Log-Likelihood: -11017</pre><p>Two relevant <em>insights</em> regarding our first model can be confirmed from the graphs below. First, let us analyze the relationship between our linear function <em>(Unj)</em> and the choice probability <em>(Pnj)</em>: although the choice probability is dispersed along the estimated utility fractions, the expected positive relationship is maintained. Consequently, in the second graph, we have a negative relationship between price and choice probability — which is consistent with our <strong>coefficient of -0.227</strong>, and with economic theory (the higher the price, the lower the quantity demanded). After estimating the marginal effects of the price coefficient, we concluded that, on average, <strong>an increase in price by one monetary unit reduces the probability of an alternative being chosen by approximately 5 percentage points</strong>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/791/1*rm_r442Mu6260FeQrf2MHQ.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/791/1*Q1ztaVLkke16APOdNVd5tQ.png" /></figure><h3>Product Attributes and Willingness to Pay (WTP)</h3><p>Having confirmed that consumers are sensitive to price, we now ask: what if the price increases due to a unique product feature? What if it reflects the location of production or values shared by the consumer? To explore this, we developed a second model that incorporates product attributes to assess how much consumers value them and are willing to pay for them.</p><pre>#Model 2: Choice given price and products attributes<br>model_2 &lt;- mlogit(Choice ~ Price + Dummy_Alt_3  + Package + Water + Carbon <br>+ Landfill + Localness | 0, data = mlogit_data)</pre><p>In addition to price and the opt-out dummy variable, this model includes attributes such as sustainable packaging, reduced water usage, carbon emissions, landfill diversion, and local production. With a more comprehensive specification, the model’s log-likelihood improves (−10,504 vs. −11,017 in the first model), indicating better fit. Except for the Water variable, all coefficients are statistically significant (p-value &lt; 0.05).</p><pre>Coefficients :<br>             Estimate Std. Error  z-value  Pr(&gt;|z|)    <br>Price       -0.240672   0.011467 -20.9884 &lt; 2.2e-16 ***<br>Dummy_Alt_3 -1.580772   0.098034 -16.1247 &lt; 2.2e-16 ***<br>Package      0.716364   0.026340  27.1972 &lt; 2.2e-16 ***<br>Water        0.047383   0.033803   1.4017  0.160997    <br>Carbon       0.220917   0.026883   8.2176  2.22e-16 ***<br>Landfill     0.296540   0.025903  11.4480 &lt; 2.2e-16 ***<br>Localness   -0.070657   0.026916  -2.6252  0.008661 ** <br>---<br>Signif. codes:  0 ‘***’ 0.001 ‘**’ 0.01 ‘*’ 0.05 ‘.’ 0.1 ‘ ’ 1<br><br>Log-Likelihood: -10504</pre><p>The results suggest that consumers tend to prefer products with sustainable packaging, lower carbon emissions, and reduced landfill impact, although they show a negative preference for locally produced items. <strong>But how much are they willing to pay for these characteristics?</strong> The willingness to pay (WTP) for an attribute is measured based on the coefficients that the model provided us in the following way:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/481/1*iKidjq7hf5O5L9Ykn_xDxw.png" /></figure><p>Below, we can see consumers’ willingness to pay for each of the attributes included in the model. Consumers are willing to pay approximately $2.98 more for sustainable packaging (up to $3.33), $1.23 for landfill diversion, and $0.98 for reduced carbon emissions. The Localness attribute has a negative WTP of −$0.29, suggesting that a price reduction could increase demand for local products. The Water attribute has a confidence interval that crosses zero, consistent with its lack of statistical significance.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/791/1*4fGE-DFcyY2x_K933_omug.png" /></figure><h3>Third Model: Consumer Characteristics and… Price</h3><p>Having estimated the willingness to pay for product attributes, we now turn to consumer-specific characteristics. This class of model is capable of estimating these coefficients, and that is the goal of our third model.<br>Here, in addition to the variables already used, we want to understand how the perceived utility — and consequently the probability of choosing an alternative — varies according to gender (Gender), whether the customer buys beer weekly (BuyBeer_Weekly), and whether they have the habit of recycling (Recycle_Yes).</p><p>All variables are binary, and our model is specified as follows:</p><pre>#Model 3: Choice given Price, products attributes and consumer characteristics<br>model_3 &lt;- mlogit( Choice ~ Price + Package + Water + Carbon + Landfill + Localness | Gender + BuyBeer_Weekly + Recycle_Yes, <br>                    data = mlogit_data)</pre><p>Once again, our <em>log-likelihood</em> improved — since we have more variables and the model was able to capture nuances previously ignored. It is important to note that we have intercepts for alternatives 2 and 3 (the <em>opt-out</em>), given that alternative 1 would be our reference. Similarly, we have coefficients for each alternative of the individual variables. The intercepts show that alternative 2 is slightly preferred over alternative 1, while alternative 3 is the least preferred. Regarding gender, being male (Gender = 1) is not statistically significant in relation to choosing alternative 2, but it has a negative effect on the probability of choosing none. The same conclusion applies to the other two variables:</p><pre>Coefficients :<br>                  Estimate Std. Error  z-value  Pr(&gt;|z|)    <br>(Intercept):2     0.173794   0.068237   2.5469   0.01087 *  <br>(Intercept):3    -0.731248   0.114534  -6.3846 1.719e-10 ***<br>Price            -0.245443   0.011718 -20.9459 &lt; 2.2e-16 ***<br>Package           0.715102   0.026393  27.0944 &lt; 2.2e-16 ***<br>Water             0.056772   0.034292   1.6555   0.09782 .  <br>Carbon            0.220342   0.026988   8.1645 2.220e-16 ***<br>Landfill          0.299420   0.025985  11.5227 &lt; 2.2e-16 ***<br>Localness        -0.067995   0.027022  -2.5163   0.01186 *  <br>Gender:2         -0.068723   0.052371  -1.3122   0.18944    <br>Gender:3         -0.522898   0.051902 -10.0747 &lt; 2.2e-16 ***<br>BuyBeer_Weekly:2  0.045721   0.073379   0.6231   0.53323    <br>BuyBeer_Weekly:3 -1.016146   0.093465 -10.8719 &lt; 2.2e-16 ***<br>Recycle_Yes:2    -0.087309   0.068997  -1.2654   0.20573    <br>Recycle_Yes:3    -0.649459   0.063613 -10.2095 &lt; 2.2e-16 ***<br>---<br>Signif. codes:  0 ‘***’ 0.001 ‘**’ 0.01 ‘*’ 0.05 ‘.’ 0.1 ‘ ’ 1<br><br>Log-Likelihood: -10248</pre><p>The choice probability naturally varies according to the consumer’s profile. In the plot below, we can see that, generally, Alternative 2 is the most chosen regardless of any characteristics. In turn, Alternative 1 is marginally more frequently chosen by those who buy beer weekly and recycle:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*-H3BUeqZk2dhopX32d-8PA.png" /></figure><p>Although Alternative 1 tends to be less frequently chosen, we have already seen that consumers are price-sensitive (negative coefficient). Thus, what would happen if we granted a 1% discount to Alternative 1? And if the discount were a 50% promotion? We can simulate those scenarios with our model. The graph below gives us an idea of the demand curve for Alternative 1. Although the probability increases, this increase is quite marginal relative to the simulated discount rates. Note that for a 50% discount, the choice probability of Alternative 1 increases by only ~2.6 p.p:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/791/1*wjYWorWnTKOvvl_gKUyC1A.png" /></figure><p>These results imply a relatively inelastic demand and we can calculate the elasticity in the following manner:</p><pre>prices &lt;- seq(0.00, 0.5, by = 0.01)<br>probabilities &lt;- sapply(prices, calc_prob_alt1) #Where calc_prob_alt1 is a function that adjusts probability given the discount<br><br>#Numerical derivative:<br>dP_dPrice &lt;- diff(probabilities) / diff(prices)<br><br>#Adjust length to match prices<br>dP_dPrice &lt;- c(dP_dPrice[1], dP_dPrice)<br><br>#Elasticity = (dP / dPrice) * (Price / P)<br>elasticity &lt;- dP_dPrice * (prices / probabilities)<br><br>df_elasticities &lt;- data.frame(Discount_Rate = prices, <br>                              Probability = probabilities, <br>                              Elasticity = elasticity)<br>df_elasticities[c(1, 11, 26, 36, 46, 51), ]</pre><p>We can see that at the maximum point of our curve, the elasticity, despite being positive, is very close to zero, indicating a product with relatively inelastic demand or that the consumer would not react significantly to the range of discounts tested:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/321/1*JDCyJ5s6cNJlwYn7Ow4AKw.png" /></figure><p>Throughout the text, we have seen how discrete choice models help answer questions that all of us somehow ask ourselves: <em>“What really matters to the consumer when making a decision?”</em> The model we applied showed us how important price is — consumers are sensitive to it — but that is only part of the story. Characteristics such as sustainable packaging, lower environmental impact, and even whether the product is local (or not) also significantly influence the choice of a product.</p><p>Furthermore, we saw that not every discount guarantees a significant increase in demand. The estimated elasticity showed that, even with aggressive price cuts, consumer response can be modest. <strong>This reinforces the idea that understanding perceived value is as important as, or more important than, adjusting prices.</strong></p><p>Finally, by including consumer profile variables, we were able to see interesting nuances: those who recycle or frequently buy beer tend to make different choices. <strong>In other words, knowing the audience is essential for making more intelligent and targeted decisions</strong>. These models not only help understand consumer behavior, but also open space for more precise simulations and strategies. <strong>And the best part: all of this based on data and applied econometrics.</strong></p><h3>References</h3><p>Hortaçsu, A., Joo, J. (2023). <strong><em>Structural Econometrics Modeling in Industrial Organisation and Quantitative Marketing.</em></strong> Princeton University Press.</p><p>Train, Kenneth. (2009). <strong><em>Dicrete Choice Methods with Simulations </em></strong>(2º Edição). Cambridge University Press. <a href="https://eml.berkeley.edu/books/choice2.html">https://eml.berkeley.edu/books/choice2.html</a></p><p>Staples, A., Reeling, C., Widmar, N., &amp; Lusk, J. (2020). <strong><em>Consumer WTP for Sustainability Attributes in Beer</em> </strong>(Version 2) [Data set]. Mendeley Data. <a href="https://doi.org/10.17632/4z748jnnjs.2">https://doi.org/10.17632/4z748jnnjs.2</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=099028c91410" width="1" height="1" alt=""><hr><p><a href="https://medium.com/data-science-collective/discrete-choice-models-an-introduction-to-demand-estimation-and-product-and-price-differentiation-099028c91410">Discrete Choice Models: An Introduction to Demand Estimation and Product and Price Differentiation</a> was originally published in <a href="https://medium.com/data-science-collective">Data Science Collective</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Modelos de Escolha Discreta: Uma Introdução a Estimativa de Demanda e Diferenciação de Produtos e…]]></title>
            <link>https://medium.com/@almeida.eas/modelos-de-escolha-discreta-uma-introdu%C3%A7%C3%A3o-a-estimativa-de-demanda-e-diferencia%C3%A7%C3%A3o-de-produtos-e-febb57517f89?source=rss-7060488ff9e------2</link>
            <guid isPermaLink="false">https://medium.com/p/febb57517f89</guid>
            <dc:creator><![CDATA[Everton Almeida]]></dc:creator>
            <pubDate>Thu, 28 Aug 2025 20:19:16 GMT</pubDate>
            <atom:updated>2025-09-14T14:08:49.033Z</atom:updated>
            <content:encoded><![CDATA[<h3>Modelos de Escolha Discreta: Uma Introdução à Estimativa de Demanda e Diferenciação de Produtos e Preços</h3><h4>Entendendo Preferências do Consumidor e Posicionamento Competitivo por Meio da Econometria</h4><p>Diariamente inúmeras empresas de todos os tamanhos tomam decisões em relação ao lançamento de um novo produto, à introdução de uma variação de um produto já existente, ou, por fim, a criação de um preço promocional para um produto cujo resultado em vendas é insatisfatório. Invariavelmente, a questão que se coloca é: <em>“Quanto o consumidor está disposto à pagar por isso?”</em> Em todos os três casos o problema se resume às preferências dos consumidores. A Teoria do Consumidor determina que um agente racional maximizador de utilidade determinará seu consumo ótimo levando em consideração i) a utilidade que ele absorve de um determinado bem e ii) a “desutilidade”, que é o custo monetário para adquirir aquele bem.</p><p>Embora seja impossível — pelo menos por enquanto — determinar essa “cesta ótima de bens” e o quanto dela é dedicada ao nosso produto, uma classe de modelos econométricos pode nos ajudar a entender o quão determinado bem é preferível à outro; quanto a mais um consumidor está disposto a pagar por determinada característica de um produto; quão sensível um consumidor é à um aumento de preços. Essas questões são cruciais tanto do ponto de vista de marketing — <em>“A nova característica do meu produto realmente é desejada pelos consumidores?”</em> — quanto do ponto de vista de <em>pricing </em>e <em>revenue optimization</em> — <em>“Qual o impacto de um reajuste de preço na demanda e na receita?”</em></p><p>Muitos problemas na microeconomia estão relacionados à decisão dos consumidores entre um conjunto de bens alternativos — Que bolsa comprar? Para onde viajar nas férias? Usar o trem ou o carro para ir trabalhar? são todos exemplos de escolhas que o consumidor enfrenta e precisa decidir face os custos e benefícios percebidos. Um modelo de escolha discreta envolve 3 passos, quais sejam: i) determinar o conjunto de escolhas, ii) formular um <em>design</em> de experimento que replique o processo de escolha dos agentes e iii) estimar os parâmetros desconhecidos de um modelo para obter a utilidade percebida dos indivíduos. Essa utilidade pode ser definida como:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/237/1*EgNhy4sJ5Z1LuBTAhOufQg.png" /></figure><p>Temos que a utilidade (<em>U</em>) de um indivíduo, observada um vetor de atributos das alternativas e de cada indivíduo (<em>nj</em>), é igual a utilidade representativa (ou observada) mais um termo de erro (utilidade não observada) dado o mesmo conjunto de vetores para cada alternativa j. A utilidade não observada reflete o fato de que ao analisar a escolha de um indivíduo, teremos acesso à apenas algumas das características avaliadas do conjunto de escolhas, bem como à apenas algumas das preferências ou características pessoais dos invidíduos. Para cada produto, obervamos as opções da marca X ou Y, mas não características intrinsecas que apenas determinados consumidores latentemente valorizariam: o fato de a embalagem ser azul ou vermelha teria impacto na escolha? Quantos consumidores podem afirmar isso de forma assertiva?</p><p>O problema dessa formulação é que não observamos a utilidade de um individuo, mas sim suas escolhas e preferencias. Precisamos, então, estimar Unj, que geralmente é modelado como uma função linear das características do produto e/ou consumidor:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/283/1*lzKf4zWVGWjZao9dtL8R7A.png" /></figure><p>O vetor contendo os atributos de cada alternativa é denotado por <em>X</em>, enquanto <em>β </em>são os parâmetros estruturais — precisamos encontrar esses parâmetros que fazem com que a utilidade inferida pelo modelo seja consistente com a escolha do indivíduo.</p><p>Naturalmente, isso implica que o consumidor escolhe a alternativa <em>j</em> se, e somente se:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/289/1*aYvhVtv0iq5roSet04T_Bw.png" /></figure><p>O termo de erro possui papel importante na modelagem desse tipo de problema. Se assumirmos que os erros são independentes e identicamente distribuídos (i.i.d.) com distribuição extremo do tipo I, podemos estimar a probabilidade de escolha por meio de um modelo logit multinomial, cuja probabilidade de escolha da alternativa <em>j </em>é:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/296/1*gFpOL5LH2FzvxSr61u3xig.png" /></figure><p>Como um modelo de utilidade aleatória (<em>Random Utility Model), </em>o modelo <strong>logit<em> </em></strong>atende a todas essas especificações. Nosso resultado será uma probabilidade de 0 a 1 para cada alternativa que somam 1. Os efeitos marginais variam conforme os atributos e probabilidades previstas. Uma limitação, contudo, é que esse modelo tem como uma de suas propriedades a independencia de alternativas irrelevantes (IIA) — o que implicaria dizer que em contextos de alternativas similares (<em>“Ir trabalhar de ônibus, pegando a linha 001 ou a 002”</em>) teremos uma limitação.</p><h3>Um Primeiro Modelo</h3><p>Dentre as inúmeras possibilidades de base de dados disponíveis para aplicação em modelos de escolha discreta, selecione a <em>“Consumer WTP for Sustainability Attributes in Beer”</em>, que tenta estimar o quanto os consumidores entrevistados estão dispostos a pagar por atributos relacionados à sustentabilidade das cervejas. Embora a base tenha inúmeros atributos tanto dos produtos quanto dos indivíduos, comecemos pelo mais simples: o preço!</p><pre>library(mlogit)<br>library(haven)<br>library(dplyr)<br>library(ggplot2)<br>library(ggthemes)<br><br>#Carregar o arquivo .dta<br>Beer_Data &lt;- read_dta(&quot;/DCM - Beer/Code/Model 1 - MNL with Full Dataset/Beer Data Full Dataset.dta&quot;)<br><br>#A alternativa 3 é um Opt-Out do design do experimento (isto é, entre a alternativa 1 e 2, o consumidor escolheria nenhuma delas), então crio uma dummy para ela<br>Beer_Data &lt;- Beer_Data %&gt;%<br>  mutate(Dummy_Alt_3 = ifelse(Alternative == 3, 1, 0))<br><br>#Converter para formato mlogit<br>mlogit_data &lt;- mlogit.data(Beer_Data,<br>                           choice = &quot;Choice&quot;,<br>                           shape = &quot;long&quot;,<br>                           alt.var = &quot;Alternative&quot;,<br>                           id.var = &quot;RespondentID&quot;)<br><br>#Modelo 1: Escolha dado o preço<br>modelo_1 &lt;- mlogit(Choice ~ Price + Dummy_Alt_3  | 0 | 0 , data = mlogit_data)<br>summary(modelo_1)</pre><p>O resultado do modelo é consistente com a teoria microeconomica: Conforme o preço da alternativa aumenta, observa-se uma redução na utilidade percebida e na probabilidade de escolha desta alternativa. Outro dado importante é que nossa dummy nos diz que “escolher não escolher” também possui menor utilidade, visto que embora não paguem (o preço é zero), eles também não desfrutam do beneficio do produto.</p><pre>Frequencies of alternatives:choice<br>      1       2       3 <br>0.32223 0.35515 0.32262 <br><br><br>Coefficients :<br>              Estimate Std. Error z-value  Pr(&gt;|z|)    <br>Price       -0.2271945  0.0089048 -25.514 &lt; 2.2e-16 ***<br>Dummy_Alt_3 -2.1297399  0.0836278 -25.467 &lt; 2.2e-16 ***<br>---<br>Signif. codes:  0 ‘***’ 0.001 ‘**’ 0.01 ‘*’ 0.05 ‘.’ 0.1 ‘ ’ 1<br><br>Log-Likelihood: -11017</pre><p>Dois <em>insights </em>relevantes à respeito de nosso primeiro modelo podem ser confirmados a partir dos gráficos abaixo. Em primeiro lugar, analisemos a relação existente entre nossa função linear (Unj) e a probabilidade de escolha (Pnj): embora a probabilidade de escolha se disperse ao longo das frações de utilidades estimadas, a relação positiva esperada se mantém. Por conseguinte, no segundo gráfico, temos uma relação negativa entre preço e probabilidade de escolha — o que está condizente com o nosso <strong>coeficente de -0.227</strong>, e com a teoria economica (quanto maior o preço, menor a quantidade demandada). Após estimar os efeitos marginais do coeficiente preço, chegamos à conclusão de que, em média, <strong>o aumento do preço em uma unidade monetária reduz cerca de 5 p.p. a probabilidade de uma alternativa ser escolhida</strong>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/780/1*ihmYAJSVv-gpOdAPGkvxpQ.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/780/1*fMgE2QOdTTOLJQp8FHZ7cg.png" /></figure><h3>A Diposição à Pagar (WTP — Willingness to Pay)</h3><p>Nosso estimador respondeu à uma pergunta importante: os clientes são sensíveis à preço. Mas e se o preço aumentar em função de uma característica única de um determinado produto? E se esse preço for maior em função do local onde ele é produzido? E se o preço tiver relação com valores compartilhados pelo consumidor? Vamos considerar um modelo que leve em consideração algumas características dos produtos para entender <strong>o quanto o consumidor as valoriza e está disposto a pagar por elas</strong>.</p><pre>#Modelo 2: Escolha dado o Preço + Variáveis do Produto<br>modelo_2 &lt;- mlogit(Choice ~ Price + Dummy_Alt_3  + Package + Water + Carbon <br>+ Landfill + Localness | 0, data = mlogit_data)</pre><p>Nosso segundo modelo, possui, além das primeiras variáveis, caracterísitcas relativas à embalagens sustentáveis (<em>Package</em>), uso reduzido de água (<em>Water</em>), emissão de carbono (<em>Carbon</em>), desvio de resíduos de aterros sanitários (<em>Landfill</em>) e localização (<em>Localness</em>). Em primeiro lugar, vale destacar que por termos um modelo mais completo, nosso <em>log-likelihood</em> é menor (-10.504 contra -11.017 do primeiro modelo). Com exceção da variável <em>Water</em> todos os coeficientes possuem significancia estatística (p-valor &lt;=0.05).</p><pre>Coefficients :<br>             Estimate Std. Error  z-value  Pr(&gt;|z|)    <br>Price       -0.240672   0.011467 -20.9884 &lt; 2.2e-16 ***<br>Dummy_Alt_3 -1.580772   0.098034 -16.1247 &lt; 2.2e-16 ***<br>Package      0.716364   0.026340  27.1972 &lt; 2.2e-16 ***<br>Water        0.047383   0.033803   1.4017  0.160997    <br>Carbon       0.220917   0.026883   8.2176  2.22e-16 ***<br>Landfill     0.296540   0.025903  11.4480 &lt; 2.2e-16 ***<br>Localness   -0.070657   0.026916  -2.6252  0.008661 ** <br>---<br>Signif. codes:  0 ‘***’ 0.001 ‘**’ 0.01 ‘*’ 0.05 ‘.’ 0.1 ‘ ’ 1<br><br>Log-Likelihood: -10504</pre><p>No geral os consumidores estão inclinados à escolher produtos pelas característica da embalagem, pela emissão reduzida de carbono e impacto em aterros sanitários, embora prefiram produtos não locais. <strong>Mas o quanto eles estão dispostos a pagar por essas características? </strong>A disposição a pagar (ou Willingness to Pay) de um atributo é mensurada com base nos coeficientes que o modelo nos deu da seguinte maneira:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/442/1*S8-f-tbVkxUVioe0dlfV1A.png" /></figure><p>Abaixo podemos ver à diposição dos consumidores à pagar por cada um dos atributos que incluímos no modelo. O atributo de maior valor é embalagem sustentável, pela qual os consumidores pagam cerca de $2,98 a mais (podendo chegar a $3,33). Por conseguinte temos a utilização de aterros sanitários, com um WTP de $1,23, seguido por emissão de carbono ($0,98). O WTP do atributo de localidade nos mostra que os consumidores não valorizam esse atributo e um reajuste de -$0,29 nos preços poderia aumentar a demanda de produtos locais. Por fim, o atributo que mensura a utilização da água: não supreende que o intervalo de confiança do WTP desse atributo cruze o zero (entre -$0,01 e $0,47), visto que seu coeficiente não tem signifancia estatística.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/870/1*777_92M3wui065aow2RdoQ.png" /></figure><h3>Ahhhh… O Preço</h3><p>Assim, sabemos o quanto um consumidor está disposto a pagar por cada uma características que controlamos em nosso modelo. Mas e em relação às caracterísitcas de cada consumidor ou grupo de consumidores? Essa classe de modelo é capaz de estimar esses coeficientes e esse e o objetivo do nosso terceiro modelo. Aqui além das variáveis já utilizadas, queremos saber o quanto a utilidade percebida e por conseguinte a probabilidade de escolha de uma alternativa varia conforme o gênero <em>(Gender)</em>, o fato de o cliente comprar cerveja semanalmente <em>(BuyBeer_Weekly)</em> e se ele tem o hábito de reciclar <em>(Recycle_Yes)</em>. Todas as variáveis são binárias e o nosso modelo é especificado da seguinte maneira:</p><pre>#Modelo 3: Escolha dado o Preço + Variáveis do Produto + Características dos Consumidores<br>modelo_3 &lt;- mlogit( Choice ~ Price + Package + Water + Carbon + Landfill + Localness | Gender + BuyBeer_Weekly + Recycle_Yes, <br>                    data = mlogit_data)</pre><p>Novamente, nosso <em>log-likelihood</em> melhorou — pois temos mais variáveis e o modelo foi capaz de capturar nuances antes ignoradas. É importante notar que temos interceptos para as alternativas 2 e 3 (o <em>opt-out</em>), visto que a a alternativa 1 seria a nossa referência. Da mesma forma temos coeficientes para cada alternativa das variáveis dos indivíduos. Os interceptos nos mostram que a alternativa 2 teriam leve preferencia em relação à alternativa 1, enquanto a 3 seria a menos preferida. Considerando o gênero, ser homem <em>(Gender = 1)</em> não tem significancia estatística em relação à escolher a alternativa 2, mas tem um peso negativo em relação a não escolher nenhum. A mesma conclusão de se aplica às duas outras variáveis:</p><pre>Coefficients :<br>                  Estimate Std. Error  z-value  Pr(&gt;|z|)    <br>(Intercept):2     0.173794   0.068237   2.5469   0.01087 *  <br>(Intercept):3    -0.731248   0.114534  -6.3846 1.719e-10 ***<br>Price            -0.245443   0.011718 -20.9459 &lt; 2.2e-16 ***<br>Package           0.715102   0.026393  27.0944 &lt; 2.2e-16 ***<br>Water             0.056772   0.034292   1.6555   0.09782 .  <br>Carbon            0.220342   0.026988   8.1645 2.220e-16 ***<br>Landfill          0.299420   0.025985  11.5227 &lt; 2.2e-16 ***<br>Localness        -0.067995   0.027022  -2.5163   0.01186 *  <br>Gender:2         -0.068723   0.052371  -1.3122   0.18944    <br>Gender:3         -0.522898   0.051902 -10.0747 &lt; 2.2e-16 ***<br>BuyBeer_Weekly:2  0.045721   0.073379   0.6231   0.53323    <br>BuyBeer_Weekly:3 -1.016146   0.093465 -10.8719 &lt; 2.2e-16 ***<br>Recycle_Yes:2    -0.087309   0.068997  -1.2654   0.20573    <br>Recycle_Yes:3    -0.649459   0.063613 -10.2095 &lt; 2.2e-16 ***<br>---<br>Signif. codes:  0 ‘***’ 0.001 ‘**’ 0.01 ‘*’ 0.05 ‘.’ 0.1 ‘ ’ 1<br><br>Log-Likelihood: -10248</pre><p>A probabilidade de escolha, naturalmente, varia conforme o perfil em questão. No gráfico abaixo, podemos ver que, geralmente, a Alternativa 2 é a mais escolhida independente do perfil. Por seu turno, a Alternativa 1 é marginalmente mais frequentemente escolhida por quem compra cerveja semanalmente e recicla.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/910/1*EEwUYG-OqYGgZMdwHC-P0A.png" /></figure><p>Embora a Alternativa 1 tenda a ser menos escolhida, já vimos que os consumidores são sensíveis ao preço (coeficiente negativo). Dessa forma, o que aconteceria se concedêssemos um desconto de 1% à Alternativa 1? E se o desconto fosse uma promoção de 50%? Podemos simular esses cenáriso com nosso modelo. O gráfico abaixo nos dá uma ideia da curva de demanda da Alternativa 1. Embora a probabilidade aumente, esse aumento é bem marginal em relação às taxas de descontos simuladas. Note que para 50% de desconto, a probabilidade de escolha da Alternativa 1 aumenta apenas ~2,6p.p.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/805/1*7sioRCMbGY2aCam8XskmKw.png" /></figure><p>Esses resultados implicam uma demanda relativamente ineslática e podemos calcular a elasticidade da seguinte maneira:</p><pre>precos &lt;- seq(0.00, 0.5, by = 0.01)<br>probabilidades &lt;- sapply(precos, calc_prob_alt1) #Onde calc_prob_alt1 é uma função que ajusta a probabilidade dado o desconto<br><br><br>#Derivada numérica<br>dP_dPreco &lt;- diff(probabilidades) / diff(precos)<br><br>#Ajustar comprimento para combinar com precos<br>dP_dPreco &lt;- c(dP_dPreco[1], dP_dPreco)<br><br>#Elasticidade: E = (dP/dPreco) * (Preco / P)<br>elasticidade &lt;- dP_dPreco * (precos / probabilidades)<br><br>df_elasticidades &lt;- data.frame(Taxa_Desconto = precos, Probabilidade = probabilidades, Elasticidade = elasticidade)<br>df_elasticidades[c(1, 11, 26, 36, 46, 51), ]</pre><p>Podemos ver que no ponto máximo da nossa curva, a elasticidade, apesar de ser positiva, é bem próxima a zero, indicando um produto com demanda relativamente inelástica ou que o consumidor não reagiria significativamente ao intervalo de descontos testado.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/356/1*CQFCyPfJfLLLzyKhmKTDgg.png" /></figure><p>Ao longo do texto, vimos como os modelos de escolha discreta ajudam a responder perguntas que todos nós de algum modo nos indagamos: <em>“O que realmente importa para o consumidor na hora de decidir?”</em> O modelo que aplicamos nos mostrou o quão importante é o preço — os consumidores são sensíveis a ele — mas isso é só parte da história. Características como embalagem sustentável, menor impacto ambiental e até o fato de o produto ser local (ou não) também influenciam bastante a escolha por um produto.</p><p>Além disso, vimos que nem todo desconto é garantia de aumento significativo na demanda. A elasticidade estimada mostrou que, mesmo com cortes agressivos de preço, a resposta do consumidor pode ser tímida.<strong> Isso reforça a ideia de que entender o valor percebido é tão ou mais importante que mexer no preço.</strong></p><p>Por fim, ao incluir variáveis do perfil dos consumidores, conseguimos enxergar nuances interessantes: quem recicla ou compra cerveja com frequência tende a fazer escolhas diferentes. <strong>Ou seja, conhecer o público é essencial para tomar decisões mais inteligentes e direcionadas</strong>. Esses modelos não só ajudam a entender o comportamento do consumidor, como também abrem espaço para simulações e estratégias mais precisas.<strong> E o melhor: tudo isso com base em dados e econometria aplicada.</strong></p><h3><strong>Referências</strong></h3><p>Hortaçsu, A., Joo, J. (2023). <strong><em>Structural Econometrics Modeling in Industrial Organisation and Quantitative Marketing.</em></strong> Princeton University Press.</p><p>Train, Kenneth. (2009). <strong><em>Dicrete Choice Methods with Simulations </em></strong>(2º Edição). Cambridge University Press. <a href="https://eml.berkeley.edu/books/choice2.html">https://eml.berkeley.edu/books/choice2.html</a></p><p>Staples, A., Reeling, C., Widmar, N., &amp; Lusk, J. (2020). <strong><em>Consumer WTP for Sustainability Attributes in Beer</em> </strong>(Version 2) [Data set]. Mendeley Data. <a href="https://doi.org/10.17632/4z748jnnjs.2">https://doi.org/10.17632/4z748jnnjs.2</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=febb57517f89" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Change Point Detection — A Bayesian Approach]]></title>
            <description><![CDATA[<div class="medium-feed-item"><p class="medium-feed-image"><a href="https://medium.com/data-science/change-point-detection-a-bayesian-approach-8eb3cfca4a6e?source=rss-7060488ff9e------2"><img src="https://cdn-images-1.medium.com/max/2600/1*RFWEPSHAfj2AWwcn4hUTfQ.jpeg" width="4000"></a></p><p class="medium-feed-snippet">Identifying a change point in time series analysis could provide you much more information about the series than you previously thought</p><p class="medium-feed-link"><a href="https://medium.com/data-science/change-point-detection-a-bayesian-approach-8eb3cfca4a6e?source=rss-7060488ff9e------2">Continue reading on TDS Archive »</a></p></div>]]></description>
            <link>https://medium.com/data-science/change-point-detection-a-bayesian-approach-8eb3cfca4a6e?source=rss-7060488ff9e------2</link>
            <guid isPermaLink="false">https://medium.com/p/8eb3cfca4a6e</guid>
            <category><![CDATA[kohonen]]></category>
            <category><![CDATA[bayesian-statistics]]></category>
            <category><![CDATA[time-series-analysis]]></category>
            <category><![CDATA[change-point-detection]]></category>
            <category><![CDATA[data-science]]></category>
            <dc:creator><![CDATA[Everton Almeida]]></dc:creator>
            <pubDate>Thu, 04 May 2023 18:15:30 GMT</pubDate>
            <atom:updated>2023-12-01T16:43:52.240Z</atom:updated>
        </item>
        <item>
            <title><![CDATA[Sentiment analysis and the stock market: A Brazilian tale?]]></title>
            <link>https://medium.com/data-science/sentiment-analysis-and-the-stock-market-a-brazilian-tale-be128098787e?source=rss-7060488ff9e------2</link>
            <guid isPermaLink="false">https://medium.com/p/be128098787e</guid>
            <dc:creator><![CDATA[Everton Almeida]]></dc:creator>
            <pubDate>Thu, 03 Sep 2020 17:33:52 GMT</pubDate>
            <atom:updated>2020-09-04T13:14:15.729Z</atom:updated>
            <content:encoded><![CDATA[<h3>Sentiment analysis and the stock market: A new Brazilian tale?</h3><h4>Despite its tiny size, the brazilian Fintwit grows, raising fears of a bubble in the Brazilian stock market.</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*pyIC6KJBvIeoNwmvnf-3aA.jpeg" /><figcaption>Photo by <a href="https://unsplash.com/@freestocks?utm_source=unsplash&amp;utm_medium=referral&amp;utm_content=creditCopyText">freestocks</a> on <a href="https://unsplash.com/photos/Lh_sFxD8AkI?utm_source=unsplash&amp;utm_medium=referral&amp;utm_content=creditCopyText">Unsplash</a></figcaption></figure><p><strong><em>Note from Towards Data Science’s editors:</em></strong><em> While we allow independent authors to publish articles in accordance with our </em><a href="https://towardsdatascience.com/questions-96667b06af5"><em>rules and guidelines</em></a><em>, we do not endorse each author’s contribution. You should not rely on an author’s works without seeking professional advice. See our </em><a href="https://towardsdatascience.com/readers-terms-b5d780a700a4"><em>Reader Terms</em></a><em> for details.</em></p><p>The recent cyclical changes in the Brazilian economy caused a massive entry of individuals into the stock market. Due to the country’s historical high interest rates, these investors used to invest their money in government bonds or in savings accounts, but, once the inflation seems to be under control since 2016, the returns of lower risk investments began to be compromised as the central bank lowered the basic interest rate (known as SELIC).</p><p>As we can see in the graph below, the return on an LTN bond, which used to have a return above 10% per year, currently yields no more than 6% in nominal terms.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*g6mCxyNaa-V7iTxC3yvIcA.png" /><figcaption>LTN yield bid since 2002</figcaption></figure><p>As Brazilian investors started looking for new alternatives to invest their money, the Ibovespa (the main index in the Brazilian market) started to rise inexorably, until the recent outbreak of Coronavirus. As we can see in the chart below, the Brazilian stock market recovered significantly fast, following the trend in other world markets, after the coronavirus outbreak.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*1yao3tQQ7DfX3GlmMlrWoA.png" /><figcaption>Ibovespa Index (2016–2020)</figcaption></figure><p>Although it is not yet clear whether prices will return to the level of December 2019, many fund managers have already raised the possibility that the assets may be already overpriced, because of the movement that involves the reallocation of resources of the Brazilian investors. Anyway, one of these managers recently <a href="https://valor.globo.com/financas/noticia/2020/08/06/squadra-ve-possivel-bolha-em-acoes-inflada-por-redes-sociais.ghtml">raised the possibility that the fintwit community in Brazil could potentially trigger what Charles Kindleberger called “euphoria”</a>¹ — paving the way for a stock market bubble. Could that really happen?</p><p>The goal of this text is to assess this possibility, firstly providing an overview of the size of that community. Finally, applying a sentiment analysis algorithm, to understand whether opinions in those tweets tend to maintain a balanced trend in general. <strong>IMPORTANT</strong>: We do not intend to analyze whether these opinions eventually drive the markets, or are influenced by them. But merely to understand whether these opinions are overly positive, in this way, creating an atmosphere of euphoria. In this way, I will use not only tweets but also the retweets, since this gives us a clearer sense of how many people may view that information.</p><p>Our first step is, of course, to collect tweets. I’m not going to go into that too much, since there are countless texts here talking about the different procedures and techniques. For this analysis, I will use R, and the twitteR package. The package has a limitation: we cannot collect tweets older than seven days. Despite this limitation, let’s see what this short time horizon can tell us. The terms I searched for was:</p><ul><li><em>IBOVESPA</em></li><li><em>Investimentos</em></li><li><em>Ibov</em></li><li><em>All the assets in the Ibovespa Index (76 assets)</em></li></ul><p>Thus, our time horizon and the searched terms can be seen below:</p><pre>setup_twitter_oauth(consumerKey, consumerSecret, <br>                    access_token = accessToken, <br>                    access_secret = accessTokenSecret)</pre><pre>#Collect the tweets into lists<br>list1 &lt;- searchTwitter(&#39;Ibovespa&#39;,n=10000, lang=&quot;pt&quot;, <br>                       since=&#39;2020-08-26&#39;, until =&#39;2020-09-03&#39;)<br>list2 &lt;- searchTwitter(&#39;Investimento&#39;, n=10000,  lang=&quot;pt&quot;, <br>                       since=&#39;2020-08-26&#39;, until =&#39;2020-09-03&#39;)<br>list3 &lt;- searchTwitter(&#39;Ibov&#39;, n=10000, lang=&quot;pt&quot;, <br>                       since=&#39;2020-08-26&#39;, until =&#39;2020-09-03&#39;)<br>list4 &lt;- searchTwitter(list_of_assets, n=10000, lang=&quot;pt&quot;,<br>                       since=&#39;2020-08-26&#39;, until =&#39;2020-09-03&#39;)</pre><pre>#Concatenate them<br>list_ &lt;- c(list1, list2, list3, list4)</pre><pre>#Create a df from the list_assets<br>df_assets &lt;- twListToDF(list_assets)<br>df_assets &lt;- df_ativos[, order(names(df_assets))]<br>df_assets$created &lt;- strftime(df_assets$created, &#39;%Y-%m-%d&#39;)</pre><p>With our df in hand, we can see how many tweets are generated daily with the search terms. First, I will not consider RTs, and as we can see bellow, the chart shows us that each day one can find at least ~1,400 tweets about those terms on Twitter, which I would say is significant, because, despite its recent expansion, the Brazilian stock market is highly concentrated. Thus, the number of users capable of generating content or solely issuing an opinion on Twitter is quite small.</p><pre>#Df with number of tweets each day<br>df_q &lt;- data.frame(df_assets %&gt;% count(created))<br>ggplot(df_q, aes(created, n)) + <br>  geom_bar(stat = &quot;identity&quot;, color=&quot;black&quot;, fill=rgb(0.1,0.4,0.5,0.7)) +<br>  labs(y=&quot;# of Tweets&quot;, x = &quot;Date of the Tweets&quot;)</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*KPA1XYrUJ-7uMRMPzlHLLQ.png" /><figcaption>Tweets per day</figcaption></figure><p>All of those 22,000 tweets were created by around 5,000 users, which means that during that period each user tweeted about those subjects 4 times. But we’re missing something: how many users actually take part of that community. While it’s impossible to say how many others users saw those tweets, we can assess the engagement with them. We can easily see that bellow. The average for the ‘favoriteCount’ variable is 14,547 and for the retweetCount is 1,437. That’s why we could argue that engagement is not really significant: each one of the 1,400 daily tweets, gets, in average, no more than 10 Favs and 1 Rt.</p><pre>#Df with sum of favs and rts for each tweet per day<br>df_favs &lt;- aggregate(favoriteCount ~ created, df_assets, sum)<br>df_rts &lt;- aggregate(retweetCount ~ created, df_assets, sum)<br>df_interac &lt;- merge(df_favs, df_rts)</pre><pre>df_interac2 &lt;- melt(df_interac)</pre><pre>ggplot(df_interac2, aes(x=created, y=value, fill=variable)) +<br>  geom_bar(stat=&#39;identity&#39;, position=&#39;dodge&#39;) +<br>  labs(y=&quot;#&quot;, x = &quot;Date of the Tweets&quot;)</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*KZP0YhdTfmuXoRXTsPm3rw.png" /><figcaption>Interactions (Favs and Rts) per day</figcaption></figure><p>In our sample, this engagement was generated by 11,700 unique users, which represent only 0,44% of the current total number of investors. That’s not really representative, but could we at least argue that there really is a feeling of euphoria in this social network that could eventually affect the stock market? In order to analyze that, we need a function capable of determining a score for each text, based on positive and negative words, which were previously chosen.</p><pre>#Positive and Negative Word<br>pos &lt;- scan(&#39;positive_words.txt&#39;, what=&#39;character&#39;, comment.char=&#39;;&#39;) <br>neg &lt;- scan(&#39;negative_words.txt&#39;, what=&#39;character&#39;, comment.char=&#39;;&#39;)</pre><pre>#Sentiment score model<br>score.sentiment &lt;- function(sentences, pos.words, neg.words){<br>  scores &lt;- laply(sentences, function(sentence, pos, neg){<br>    sentence &lt;- gsub(&#39;[[:punct:]]&#39;, &quot;&quot;, sentence)<br>    sentence &lt;- gsub(&#39;[[:cntrl:]]&#39;, &quot;&quot;, sentence)<br>    sentence &lt;- gsub(&#39;\\d+&#39;, &quot;&quot;, sentence)<br>    sentence &lt;- str_replace_all(sentence, &quot;[^[:alnum:]]&quot;, &quot; &quot;)<br>    sentence &lt;- tolower(sentence)<br>    word.list &lt;- str_split(sentence, &#39;\\s+&#39;)<br>    words &lt;- unlist(word.list)<br>    pos.matches &lt;- match(words, pos.words)<br>    neg.matches &lt;- match(words, neg.words)<br>    pos.matches &lt;- !is.na(pos.matches)<br>    neg.matches &lt;- !is.na(neg.matches)<br>    score &lt;- sum(pos.matches) - sum(neg.matches)<br>    return(score)<br>  }, pos.words, neg.words)<br>  scores.df &lt;- data.frame(score=scores, text=sentences)<br>  return(scores.df)<br>}</pre><pre>#Applying the model to the dataset<br>Dataset &lt;- df_assets<br>Dataset$text &lt;- as.factor(Dataset$stripped_text)<br>scores &lt;- score.sentiment(Dataset$stripped_text, pos.words, neg.words)</pre><pre>stat &lt;- scores<br>stat$created &lt;- stripped_text$created<br>stat$created &lt;- as.Date(stat$created)<br>stat &lt;- mutate(stat, tweet=ifelse(stat$score &gt; 0, &#39;positive&#39;, <br>                                  ifelse(stat$score &lt; 0, &#39;negative&#39;, &#39;neutral&#39;)))<br>by.tweet &lt;- group_by(stat, tweet, created)<br>by.tweet &lt;- summarise(by.tweet, number=n())</pre><pre>ggplot(by.tweet, aes(created, number)) + geom_line(aes(group=tweet, color=tweet), size=1) +<br>  geom_point(aes(group=tweet, color=tweet), size=4) +<br>  labs(y=&quot;# of Tweets&quot;, x = &quot;Date of the Tweets&quot;)<br>theme(text = element_text(size=10), axis.text.x = element_text(angle=90, vjust=1)) +<br>  ggtitle(&#39;cted tweets: FintwitBr&#39;)</pre><p>The graph shows us 3 types of categories, which are positive (score&gt; 1), negative (score &lt;1) and neutral. At least in our sample, there is clear evidence that tweets are likely to be more positive than negative. And the proportion changed significantly on August 28th and September 1st. But, since the community is not representative in relation to the market as a whole, it would be an exaggeration to claim that the euphoria on Twitter is impacting the market.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*e40wQ8hYaUfHpBCLLGPACw.png" /><figcaption>Sentiment Analysis</figcaption></figure><p>That doesn’t mean that there isn’t something happening in the Brazilian stock market; I really think it is. It just means that, for the moment, there is a little bit of alarmism — and with some reason. Especially because, when Robert Shiller warned the market about the irrational exuberance that could bring the financial market to a breakdown in his 2005 book, nobody took him seriously. I mean, nowadays you can find several profiles, either on Twitter, YouTube or Instagram talking about investments, for an audience that until the last few years used to see this as something no more than obscurantism.</p><p>¹ You can find Charles Kindleberger’s book in Portuguese (<a href="https://amzn.to/3jDl5NP">Manias, pânicos e crises: Uma história das catástrofes econômicas mundiais</a>) or english (<a href="https://amzn.to/2EVixfc">Manias, Panics, and Crashes: A History of Financial Crises</a>).</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=be128098787e" width="1" height="1" alt=""><hr><p><a href="https://medium.com/data-science/sentiment-analysis-and-the-stock-market-a-brazilian-tale-be128098787e">Sentiment analysis and the stock market: A Brazilian tale?</a> was originally published in <a href="https://medium.com/data-science">TDS Archive</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Economia Política Internacional e os Negócios Internacionais — Leituras Obrigatórias]]></title>
            <link>https://medium.com/@almeida.eas/economia-pol%C3%ADtica-internacional-e-os-neg%C3%B3cios-internacionais-leituras-obrigat%C3%B3rias-d2934085fbf2?source=rss-7060488ff9e------2</link>
            <guid isPermaLink="false">https://medium.com/p/d2934085fbf2</guid>
            <category><![CDATA[risco-político]]></category>
            <category><![CDATA[economia-internacional]]></category>
            <category><![CDATA[economia-política]]></category>
            <category><![CDATA[comercio-internacional]]></category>
            <category><![CDATA[relacoes-internacionais]]></category>
            <dc:creator><![CDATA[Everton Almeida]]></dc:creator>
            <pubDate>Mon, 13 Jul 2020 22:54:21 GMT</pubDate>
            <atom:updated>2020-07-14T22:20:38.767Z</atom:updated>
            <content:encoded><![CDATA[<h3>Economia Política Internacional e os Negócios Internacionais — Leituras Fundamentais</h3><h4>Porque entender EPI se tornou mandatório e por onde iniciar ou aprofundar seus estudos na área</h4><p>A Economia Política Internacional (EPI) é um campo de estudos relativamente novo, quando comparamos com outras áreas das Ciências Sociais Aplicadas. Como área de estudo, a EPI se encontra em área intersecção entre as disciplinas de Economia, Ciências Políticas e Relações Internacionais e passou a ser melhor elaborada e trabalhada a partir da década de 1970, quando assuntos de ordem econômica, passaram a determinar a agenda das relações internacionais, até então fundamentalmente pautadas em assuntos de segurança nacional.</p><p>Ainda que seja uma cinquentona, no mundo dos negócios a EPI é ainda muito pouco explorada. Seja por desconhecimento de suas atribuições para análise de realidade, seja por descuido ou falta de esmero no trato dos negócios internacionais, compreender a realidade política e econômica contemporânea e suas manifestações sobre os negócios privados e dos governos se tornou fundamental em uma época na qual o conjunto de instituições criado ao fim da Segunda Guerra Mundial, vem sendo questionado. Some a isso, a crescente incerteza que dominou o ambiente político, com a emersão do radicalismo e o populismo e a forma como esses fatores vem impactando a agenda econômica.</p><h3><strong>“Mas por qual motivo entender EPI é importante?”</strong></h3><p>A matéria em vídeo abaixo foi elaborada por <a href="https://www.nytimes.com/by/erica-berenstein"><strong>Erica Berenstein<em> do New York Times</em> </strong></a>e é um exemplo de como as relações entre Estados e Mercados é determinante nos negócios internacionais:</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fwww.youtube.com%2Fembed%2FPCZnYnssyDE%3Ffeature%3Doembed&amp;display_name=YouTube&amp;url=https%3A%2F%2Fwww.youtube.com%2Fwatch%3Fv%3DPCZnYnssyDE&amp;image=https%3A%2F%2Fi.ytimg.com%2Fvi%2FPCZnYnssyDE%2Fhqdefault.jpg&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=youtube" width="854" height="480" frameborder="0" scrolling="no"><a href="https://medium.com/media/801d41149e6b410c283e89b157bedd5c/href">https://medium.com/media/801d41149e6b410c283e89b157bedd5c/href</a></iframe><p>Como visto, o Peugeot 405 era um sucesso no Irã e parte importante da estratégia da companhia francesa, até as relações entre os Estados envolvidos se complicarem, devido às sanções que visavam coagir o país a restringir seu programa nuclear.</p><p>A EPI tem como objeto de estudos as relações entre Estados e Mercados e a dinâmica do sistema econômico internacional. Como visto no caso da Peugeot, as decisões de um ator em uma esfera (as sanções propostas pelos governos), tem o potencial de impactar terceiros (a companhia que operava no mercado estrangeiro).</p><p>De fato, quando realizou o investimento no exterior, a companhia não tinha como prever que tais medidas seriam tomadas contra o país, embora já houvesse indícios de que o Irã não submeteria seu programa nuclear às restrições da Agência Internacional de Energia Atômica. Mas esse é justamente o foco da EPI: servir como instrumento de análise das relações entre os Estados para compreendermos como tais relações potencialmente impactam os mercados.</p><p>Um caso não menos importante é mais recente, foi a crise entre os países da Opep e a Rússia, que culminou em queda vertiginosa do preço do petróleo e trouxe pânico aos mercados. Por que a Rússia, simplesmente não concordava em reduzir sua produção, visto que isso aumentaria os preços no mercado internacional e, consequentemente, seus lucros? Do ponto de vista meramente econômico, o problema era bem prático. Contudo, as medidas do país tinham outro alvo: os EUA. <a href="https://edition.cnn.com/2020/03/10/business/russia-us-shale-oil-putin-opec/index.html">O país pretendia trazer o preço do petróleo à um nível que tornasse a produção de petróleo de xisto americana economicamente inviável</a>.</p><figure><img alt="As peças estão no tabuleiro" src="https://cdn-images-1.medium.com/max/640/1*v0kos39r0qpc4K55NJjbeg.jpeg" /><figcaption>Um jogo de soma-zero</figcaption></figure><p>O mercado simplesmente perdeu esse ponto de seu campo de visão, e quando se tornou claro que as reuniões da Opep+ seriam infrutíferas, o preço do óleo derreteu.</p><h3><strong>“O início de um sonho / Deu tudo errado”</strong></h3><p>A pandemia provocada pelo vírus Sars-Cov-2 já é um dos maiores acontecimentos do jovem século XXI que, com apenas 20 anos, já conta a guerra no oriente médio e uma crise migratória na Europa, uma crise financeira global e naturalmente a recente insurreição populista nas democracias ocidentais. Mas em 1990, os prospectos para nossa era eram bem diferentes. Há trinta anos havia um consenso sobre os desenvolvimentos subsequentes que a queda do regime soviético traria: um mundo sem regimes dicotômicos, operacionalizado pelo capitalismo global e regido pela democracia liberal.</p><p>Longe disso, hoje, manter a globalização e suas instituições se tornou o principal esforço de líderes globais. Esses fatos recentes, podem encerrar (?) a liderança mundial dos EUA que já dura há 70 anos e, como proposto recentemente, já estão sendo usados como meios de manobra em uma nova <a href="https://www.bloomberg.com/opinion/articles/2020-07-05/is-the-u-s-in-a-new-cold-war-china-has-already-declared-it">Guerra Fria</a> — iniciada, pasmem(!), pelos mercados. Não que a retórica trumpista não tenha ajudado, mas foi a guerra comercial iniciada pelos dois países e a disputa pelas redes de telecomunicações 5G o que, de fato, nos trouxe ao “sopé de uma Guerra Fria”, como diria conhecido teórico americano.</p><h3>“Então, por onde começar a entender essas águas turbulentas?”</h3><p>Um livro básico, que julgo ser de leitura obrigatória, é o livro de Reinaldo Gonçalves, <a href="https://www.amazon.com.br/gp/product/8535215115/ref=as_li_tl?ie=UTF8&amp;camp=1789&amp;creative=9325&amp;creativeASIN=8535215115&amp;linkCode=as2&amp;tag=almeidaeas-20&amp;linkId=874cc8babd309b77c620ceda0d630840"><strong>Economia Política Internacional: Fundamentos Teóricos e as Relações Internacionais do Brasil</strong></a> (Editora Campus Elsevier):</p><p><a href="https://www.amazon.com.br/gp/product/8535215115/ref=as_li_tl?ie=UTF8&amp;camp=1789&amp;creative=9325&amp;creativeASIN=8535215115&amp;linkCode=as2&amp;tag=almeidaeas-20&amp;linkId=874cc8babd309b77c620ceda0d630840">Economia Política Internacional. Fundamentos Teóricos Eas Relações Internacionais do Brasil</a></p><p>Eu, particularmente, gosto bastante do livro, por ser uma boa introdução à estrutura de estudo de EPI, além de abordar questões relacionadas à posição do Brasil frente ao mundo.</p><p>Como abordagem sistematizada, meu preferido ainda é <a href="https://www.amazon.com.br/gp/product/B088CW1SD6/ref=as_li_tl?ie=UTF8&amp;camp=1789&amp;creative=9325&amp;creativeASIN=B088CW1SD6&amp;linkCode=as2&amp;tag=almeidaeas-20&amp;linkId=c5bf230dce1ae11057c81f78c4eb3c96"><strong>A Economia Política das Relações Internacionais</strong></a><strong> </strong>de Robert Gilpin (Editora UNB). O objetivo de Gilpin é sistematizar o estudo da EPI como disciplina, partir das três linhas ideológicas, quais sejam o Nacionalismo, o Liberalismo e o Marxismo. Para tanto, o autor toma uma posição Estado-Centrica e, partir dessas linhas ideológicas, estuda as relações entre Estados e Mercado. Infelizmente, o texto em português está esgotado, e a única opção aos sebos seria a edição em inglês:</p><p><a href="https://www.amazon.com.br/gp/product/B088CW1SD6/ref=as_li_tl?ie=UTF8&amp;camp=1789&amp;creative=9325&amp;creativeASIN=B088CW1SD6&amp;linkCode=as2&amp;tag=almeidaeas-20&amp;linkId=c5bf230dce1ae11057c81f78c4eb3c96">The Political Economy of International Relations (English Edition)</a></p><p>O texto de Gilpin é importante, por que como visto, as relações entre Estados e Mercados é nosso ponto focal, e isso passou a chamar a atenção quando os EUA começaram a criar um estrutura internacional de comércio que garantisse sua hegemonia (para os realistas) ou um ambiente cooperativo e pacífico (para os idealistas). Um livro que descobri recentemente em português e que serve tanto para se iniciar nesse tipo de discussão, quanto para aprofundar os estudos nesse tipo de relação a partir do sistema multilateral de comércio, é o livro de Sebastião Velasco e Cruz, chamado <a href="https://www.amazon.com.br/gp/product/B07BFFHRYX/ref=as_li_tl?ie=UTF8&amp;camp=1789&amp;creative=9325&amp;creativeASIN=B07BFFHRYX&amp;linkCode=as2&amp;tag=almeidaeas-20&amp;linkId=260c5e7c2c01ebc69a2925bdd7b0adc6"><strong>Estados e Mercados: Os Estados Unidos e o Sistema Multilateral de Comércio</strong></a><strong> </strong>(Editora UNESP):</p><p><a href="https://www.amazon.com.br/gp/product/B07BFFHRYX/ref=as_li_tl?ie=UTF8&amp;camp=1789&amp;creative=9325&amp;creativeASIN=B07BFFHRYX&amp;linkCode=as2&amp;tag=almeidaeas-20&amp;linkId=260c5e7c2c01ebc69a2925bdd7b0adc6">Estados e mercados: Os Estados Unidos e o sistema multilateral de comércio</a></p><p>Como sabemos, o sistema multilateral de comércio é sustentado por uma série de organizações, como a Organização Mundial do Comercio (OMC). O papel das organizações internacionais, é fundamental nesse sentido. Por isso, em português, sempre recorra à referência elaborada por Mônica Hertz e Andreas Hoffman, <a href="https://www.amazon.com.br/gp/product/8535279865/ref=as_li_tl?ie=UTF8&amp;camp=1789&amp;creative=9325&amp;creativeASIN=8535279865&amp;linkCode=as2&amp;tag=almeidaeas-20&amp;linkId=d62f9d758a73d685319efd1601728d88"><strong>Organizações Internacionais: História e Prática </strong></a>(Editora Campus Elsevier):</p><p><a href="https://www.amazon.com.br/gp/product/8535279865/ref=as_li_tl?ie=UTF8&amp;camp=1789&amp;creative=9325&amp;creativeASIN=8535279865&amp;linkCode=as2&amp;tag=almeidaeas-20&amp;linkId=d62f9d758a73d685319efd1601728d88">Organizações internacionais: História e Práticas</a></p><p>Embora o texto seja fantástico, caso você deseje entender o porquê dessas organizações surgirem e qual é o papel da cooperação internacional na EPI, o título indicado é <a href="https://www.amazon.com.br/gp/product/B00CXLKFKE/ref=as_li_tl?ie=UTF8&amp;camp=1789&amp;creative=9325&amp;creativeASIN=B00CXLKFKE&amp;linkCode=as2&amp;tag=almeidaeas-20&amp;linkId=8b9afa1b6fb9db333a6159ae41de092a"><strong>After Hegemony: Cooperation and Discord in the World Political Economy </strong></a>de Robert O. Keohane (Princeton University Press):</p><p><a href="https://www.amazon.com.br/gp/product/B00CXLKFKE/ref=as_li_tl?ie=UTF8&amp;camp=1789&amp;creative=9325&amp;creativeASIN=B00CXLKFKE&amp;linkCode=as2&amp;tag=almeidaeas-20&amp;linkId=8b9afa1b6fb9db333a6159ae41de092a">After Hegemony: Cooperation and Discord in the World Political Economy (Princeton Classic Editions) (English Edition)</a></p><p>Keohane é a referência no assunto e esse livro é super indicado para quem quer começar a entender o papel do poder nas relações internacionais. O autor parte do princípio de que uma hegemonia é sempre necessária como meio de sustentar um regime internacional. Mas então, por que um Estado cooperaria com o outro se, via de regra, ele estará submetido ao poder projetado por esse Estado hegemônico? Essa pergunta está nas fundações da teoria que sustenta a cooperação como forma de alcançar objetivos em comum. Quem te responde ela é outro “Robert”: Robert Axelrod em <a href="https://www.amazon.com.br/gp/product/B06XCGTJQX/ref=as_li_tl?ie=UTF8&amp;camp=1789&amp;creative=9325&amp;creativeASIN=B06XCGTJQX&amp;linkCode=as2&amp;tag=almeidaeas-20&amp;linkId=6359651db8acb2e50c3025536c86dea3"><strong>The Evolution of Cooperation</strong></a> (Basic Books AZ) — e se você gosta de Teoria dos Jogos, definitivamente deveria ler esse texto:</p><p><a href="https://www.amazon.com.br/gp/product/B06XCGTJQX/ref=as_li_tl?ie=UTF8&amp;camp=1789&amp;creative=9325&amp;creativeASIN=B06XCGTJQX&amp;linkCode=as2&amp;tag=almeidaeas-20&amp;linkId=6359651db8acb2e50c3025536c86dea3">The Evolution of Cooperation: Revised Edition (English Edition)</a></p><p>O poder nas relações internacionais te chamou a atenção? Procure mais sobre <a href="https://www.amazon.com.br/gp/product/0205082912/ref=as_li_tl?ie=UTF8&amp;camp=1789&amp;creative=9325&amp;creativeASIN=0205082912&amp;linkCode=as2&amp;tag=almeidaeas-20&amp;linkId=e8ed37e9c413793e74a6e40fdbcd28a7"><strong>Power &amp; Interdependence</strong></a><strong> </strong>de Robert O. Keohane e Joseph Nye (Pearson). A ausência de uma edição para o Kindle, torna o preço bem proibitivo, mas teria como não citar esse livro:</p><p>Geralmente, o poder de uma nação sobre outra não é exercido diretamente por meios militares (em nosso exemplo, foram sanções econômicas). Afora o poder comercial, um Estado pode fazer valer sua força por meios financeiros. Entender a evolução do sistema monetário internacional é obrigatório, e ele tem seu histórico abordado por Barry Eichengreen, em <a href="https://www.amazon.com.br/gp/product/8573261749/ref=as_li_tl?ie=UTF8&amp;camp=1789&amp;creative=9325&amp;creativeASIN=8573261749&amp;linkCode=as2&amp;tag=almeidaeas-20&amp;linkId=888aeef9178b5245dd8a0adb412e4c15"><strong>A Globalização do Capital: Uma História do Sistema Monetário Internacional</strong></a><strong> </strong>(Editora 34):</p><p><a href="https://www.amazon.com.br/gp/product/8573261749/ref=as_li_tl?ie=UTF8&amp;camp=1789&amp;creative=9325&amp;creativeASIN=8573261749&amp;linkCode=as2&amp;tag=almeidaeas-20&amp;linkId=888aeef9178b5245dd8a0adb412e4c15">A globalização do capital: uma História do Sistema Monetário Internacional</a></p><p>Como elemento que azeita as relações políticas, econômicas e internacionais, o papel da moeda é discutido pelo brilhante livro de Benjamin Cohen, <a href="https://www.amazon.com.br/gp/product/8539305437/ref=as_li_tl?ie=UTF8&amp;camp=1789&amp;creative=9325&amp;creativeASIN=8539305437&amp;linkCode=as2&amp;tag=almeidaeas-20&amp;linkId=7046db1254ac4d877cb6639d79006a07"><strong>A Geografia do Dinheiro</strong></a> (Editora UNESP):</p><p><a href="https://www.amazon.com.br/gp/product/8539305437/ref=as_li_tl?ie=UTF8&amp;camp=1789&amp;creative=9325&amp;creativeASIN=8539305437&amp;linkCode=as2&amp;tag=almeidaeas-20&amp;linkId=7046db1254ac4d877cb6639d79006a07">Geografia do Dinheiro, a</a></p><p>O livro faz parte da Coleção Estudo Internacionais (assim como o anteriormente citado <strong>Estados e Mercados</strong>) e traça um breve histórico das relações monetárias internacionais, além de destacar a <em>hierarquia monetária</em> existente entre o papel moeda das nações. Se o tema parece um pouco “esotérico” para você, entender o privilégio usufruído pelo dólar pode ser uma boa ideia. Então, vá de <a href="https://www.amazon.com.br/gp/product/8535247157/ref=as_li_tl?ie=UTF8&amp;camp=1789&amp;creative=9325&amp;creativeASIN=8535247157&amp;linkCode=as2&amp;tag=almeidaeas-20&amp;linkId=91a976d5f0582a202a963a61fac2ef2a"><strong>Privilégio Exorbitante: A Ascensão e Queda do Dólar e o Futuro do Sistema Monetário Internacional</strong></a> de John Kenneth Galbraith (Editora Campus Elsevier).</p><p>Apesar de o texto estar localizado no campo de economia internacional (assim como o livro de Eichengreen), é fundamental para entender a estrutura de poder criado pelo chamado <em>padrão dólar.</em></p><p>Mas se um Estado não usufrui de condições hegemônicas, nem possui Mercado ou Moeda com os quais possa valer sua vontade, qual outro meio de projetar poder, sem recorrer ao uso da força? Esse é um tema já antigo, mas ainda pouco evoluído ao meu ver. <a href="https://www.amazon.com.br/gp/product/B06XCG4J18/ref=as_li_tl?ie=UTF8&amp;camp=1789&amp;creative=9325&amp;creativeASIN=B06XCG4J18&amp;linkCode=as2&amp;tag=almeidaeas-20&amp;linkId=644867ca1f7ba4d2e0b88f97e39c4934"><strong>Soft Power: The Means to Success in World Politics</strong></a> de Joseph Nye (Public Affairs) vai te ajudar a entender isso:</p><h3><strong>“Tá! E como aplicar tudo isso aos negócios?”</strong></h3><p>Todo esse referencial é de fundamental importância para podermos entender como a incerteza gerada por essas relações em distintas esferas, pode impactar seus negócios. Mas se você quiser leituras mais prática sobre como as relações entre Estados e Mercados impactam os negócios, tenho duas leituras sugeridas.</p><p>A primeira, <a href="https://www.amazon.com.br/gp/product/8522104433/ref=as_li_tl?ie=UTF8&amp;camp=1789&amp;creative=9325&amp;creativeASIN=8522104433&amp;linkCode=as2&amp;tag=almeidaeas-20&amp;linkId=93c128ea898518c9d76bf6d14646b80f"><strong>Introdução à Gestão de Negócios Internacionais</strong></a><strong> </strong>de Joaquim Carlos Racy (Pioneira Thomson Learning), conta com a contribuição de vários autores, que tratam de forma introdutória desde questões basilares, como as relações internacionais, até questões mais específicas que envolvem os negócios internacionais, como comunicação, cultura e marketing.</p><p>O livro acima seria a porta de entrada no assunto e é especialmente utilizado em cursos de pós-graduação em negócios internacionais em algumas universidades do Brasil. Posteriores desenvolvimentos podem ser encontrados em <a href="https://www.amazon.com.br/gp/product/8576053799/ref=as_li_tl?ie=UTF8&amp;camp=1789&amp;creative=9325&amp;creativeASIN=8576053799&amp;linkCode=as2&amp;tag=almeidaeas-20&amp;linkId=97c393975f8ae4d79a468b8651c9b0fb"><strong>Negócios Internacionais: Estratégia, Gestão e Novas Realidades</strong></a><strong> </strong>de S. Tamer Cavusgil, Gary Knight e John R. Resenberger:</p><p>O texto é enciclopédico (no bom sentido) e muito conhecido por quem trabalha com internacionalização de mercados. Foco na parte em que trata sobre sistemas políticos e legais e tendências globais para o comércio e sistema financeiro.</p><p>Por fim, uma última leitura que, frente ao que foi discutido aqui, pode ser importante, embora não esteja relacionado à EPI, é <a href="https://www.amazon.com.br/gp/product/8535273255/ref=as_li_tl?ie=UTF8&amp;camp=1789&amp;creative=9325&amp;creativeASIN=8535273255&amp;linkCode=as2&amp;tag=almeidaeas-20&amp;linkId=bd91cadde469cdf0d284f15c6b09d23f"><strong>Introdução ao Risco Político: Conceitos, Análises e Problemas </strong></a>(Editora Campus Elsevier)organizado por Flávio Marques e Moisés Rocha:</p><p><a href="https://www.amazon.com.br/gp/product/8535273255/ref=as_li_tl?ie=UTF8&amp;camp=1789&amp;creative=9325&amp;creativeASIN=8535273255&amp;linkCode=as2&amp;tag=almeidaeas-20&amp;linkId=bd91cadde469cdf0d284f15c6b09d23f">Introdução ao risco político: Conceitos, Análises e Problemas</a></p><p>Além de contextualizar o risco político nas organizações, o livro traz uma série de metodologias para a análise do risco político, além exemplos de suas aplicações.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=d2934085fbf2" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Why was Pippen such a bargain to the Chicago Bulls?]]></title>
            <link>https://medium.com/data-science/why-was-pippen-such-a-bargain-to-the-chicago-bulls-8436f273beca?source=rss-7060488ff9e------2</link>
            <guid isPermaLink="false">https://medium.com/p/8436f273beca</guid>
            <category><![CDATA[chicago-bulls]]></category>
            <category><![CDATA[sport-economics]]></category>
            <category><![CDATA[data-science]]></category>
            <category><![CDATA[last-dance-documentary]]></category>
            <category><![CDATA[scottie-pippen]]></category>
            <dc:creator><![CDATA[Everton Almeida]]></dc:creator>
            <pubDate>Fri, 29 May 2020 15:54:29 GMT</pubDate>
            <atom:updated>2020-11-19T17:36:21.884Z</atom:updated>
            <content:encoded><![CDATA[<h4>Despite his invaluable contribution to the team, Scottie Pippen’s contract was not just circumstantial.</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/800/1*6E6g26bToaTWb2JsnRH8Cg.jpeg" /><figcaption>Source: <a href="https://pt-br.facebook.com/chicagobulls/photos/happy-birthday-scottie-pippen/10155930727761614/">Chicago Bulls’ Facebook Page</a></figcaption></figure><p>For those who watched Netflix’s <a href="https://www.youtube.com/watch?v=cBGZPXEdrlM">“The Last Dance”</a>, one of the most curious points brought up by the documentary, was the relatively low salary of Chicago Bulls’ Small Forward, Scottie Pippen. Drafted by the Bulls in 1987, the player became the All-Star Michael Jordan’s main partner during the dynasty that ruled NBA during the 1990s. Still, during the last championship won by that team, the Bulls star had only the league’s 112th highest salary and only Bull’s 6th. In comparison, while Jordan made $ 33 mm during the 1997–98 season, Pippen made no more than $ 2.7 mm.</p><p>What would have brought Pippen to this outcome? During the second episode of the documentary, which focused on the SF’s history, Pippen explains that he accepted the Bulls’ initial proposal for security. The player feared an early career end, while none of the cap rules that currently protect both team and players existed in 1991.<a href="https://www.cbssports.com/nba/news/scottie-pippen-contract-explained-how-chicago-bulls-managed-to-sign-hall-of-famer-for-pennies-on-the-dollar/"> Sam Quin of CBS Sports </a>offers a detailed look at the conditions of Pippen’s contract.</p><p>While it is widely acknowledged that Pippen accepted a bad contract, how much should Pippen make in the 1997–98 season, according to his potential if the Bulls was able to renegotiate his contract or waive him? Initially, let’s take a step back: In view of Pippen’s performance in the 1996–97 season, how much would be Pippen value to the Bulls for next season? According to the data collected, during the 1996–97 season, Pippen had a VORP of 6.1 and an adjusted use of 15.7% (behind Michael Jordan with 8.6 and 15.8%, respectively). But, as we know, this performance was not reflected in Pippen’s wages during that season. Pippen was left with only the 6th highest salary, receiving the equivalent of 80% of Center Luc Longley’s salary, who had an adjusted use of 7.5% and a poor VORP of 0.1. In other words: Pippen was the second most valuable player for the Bulls, but his earnings were far from that.</p><p>According to data collected from hoopshype.com (<a href="https://github.com/almeidaeas">see my Github to access my web-scraping scripts</a>), during the 1996–97 a Small Forward received an average salary of $1.5 mm. Pippen’s contract guaranteed him a salary of $2.25 mm. Although his salary was 55% higher than the average salary for a Small Forward, he wasn’t able to get one of the twenty-four largest salaries for a SF. But according to reports, Pippen could get much more than that. As a matter of fact, he really did, when he signed a sign-and-trade deal with the Bulls and the Rockets, almost tripling his annual salary.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/567/1*WzxkoXoC205-VT7NSCZQpA.png" /><figcaption>Fig 1: Salary Distribution for Small Forward (1996–97)</figcaption></figure><p>But what affects the salary of a player in the 1990s NBA? How do GM decide how much a player value? Maybe they rely on players’ stats, previous results, the impact a player could cause to a team (good and bad), the team’s need for a player with certain characteristics and finally how much could they pay the player. The first and obvious attempt of anyone interested in that subject would be to design a regression and adjust it, according to the stats available. Unfortunately, we may recognize that a linear model using players stats would be highly complex to build and might produce poor results. That’s why I tried to use the as few players’ stats as possible to answer that question, and got Value Over Replacement Player (VORP), the Player Efficiency Rating (PER) and the age as proxies to explain the salary earned for each season. I also used the games and minutes played to estimate a kind of “adjusted usage rate”, given by the expression below:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/589/1*uiQLWv091mVK30vQqb3LOA.png" /></figure><p>So, it’s easy to understand that the adjusted usage rate will never be higher than 0.20 because one player can’t be at the court more than 20% of all minutes a team have played.</p><p>But instead of building a regression, I divided the stats into the 5 percentiles below:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/373/1*flcJDBuI0xl9zpMlGiHysA.png" /><figcaption>Fig 2: Stats Percentiles</figcaption></figure><p>That could be a good measure to predict the Pippen’s deserved salary, according to his contribution, since a club GM is not able to maximize the VORP or PER received for each monetary unity paid for each player, for three reason: (i) NBA is not a competitive labor market (a limited number of clubs are trying to get a limited number of valuable players); (ii) the negotiation between clubs and players more closely resembles an auction (if a player doesn’t agree with the terms given him by a club, he could expect for another team’s propose); and (iii) the negotiation takes the form of a long-term contract (that means that a club and a player don’t negotiate the salary in terms of productivity, year-by-year).</p><p>Could the salary earned by a player be determined by those percentiles? Once I loaded the percentile as characters, we may run a one-way analysis of variance (ANOVA), to answer this question. As we see in the p-value bellow, we should deny our null hypothesis (H0) that the populational mean is equal, according to the percentiles of the variables.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/493/1*0GMZ3kUJqud6oSPNDnP4gg.png" /><figcaption>Fig 3: ANOVA — Percentiles</figcaption></figure><p>As we may see in the interaction plot bellow, both VORP and PER seem to be good explanatory variables, since the lower the performance the lower the salary. During the 1996–97 season the NBA clubs’ executives managed well to determine a player’s salary according to the expected performance. What seem not to be the case only when we focus on the players of age at the 5th percentile and the most reasonable explanation for that may be longer deals signed with a player when he is about to complete 30 years: as a player ages, he cannot deliver as he used to.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/605/1*MXn413eia1Rkhpc0sLDiaw.png" /><figcaption>Fig 4: Interaction Plot (Performance x Salary x Age)</figcaption></figure><p>So, my next step was to clustering my base using those stats. As a usual step, I ran an Elbow Method to help me to discover the optimal number of cluster and posteriorly I ran the Kmeans algorithm, with the optimal number of 4 cluster. Note that I didn’t scale the data because all of my variables were already at the same scale. Then I merged to the cluster number of each player to my primary data frame to discover that Pippen was ranked at the first cluster alongside Michael Jordan, Dennis Rodman, Chris Mullin, Hakeem Olajuwon, Reggie Miller and so on.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/570/1*ne42nO9jEVjCYuWHaPSSIw.png" /><figcaption>Fig 5: Kmeans analysis</figcaption></figure><p>With the knowledge of those clusters we may now analyze the expected salary for a player according to his performance and importance to the team, as well as his position:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/481/1*TM6Vpw23rUtdMLWukE1ZGA.png" /><figcaption>Fig 6: Creating my boxplot</figcaption></figure><p>And that’s what we got. It’s no surprise that players with better performance and higher importance to a team used to earn more and that tends to be true until our days. According to this plot, the mean salary for a player at cluster 1 used to be at least 1.8 higher than the mean salary paid for a player at the others. But what caught my attention was value of the minimum salary and the standard deviation. The relative lower salary to a player that delivered more could be explained by the rookie contracts signed by Kevin Garnett ($1.6 m), Ray Allen ($1.8 m), Allen Iverson ($2.2 m) and etc. But Pippen received even less than the mean salary ($2.25 m).</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/620/1*fjm_wan2Ofh9YARLCank2w.png" /><figcaption>Fig 7: Bloxplot and means salaries by cluster</figcaption></figure><p>Until now, we’ve got good clues, but not determined a value yet. I tried to adapt a Chi-Square Test of Independence, using the mean salary as my reference value, to discover whether the salary of a player is associated with his cluster and position, since we are interested in the salary for a Small Forward at Cluster 1. The p-value is an indication that the that both Cluster and Position are statistically associated with each other. Following this analysis and checked the observed and the expected values. As I demonstrated previously, the salary for a Small Forward at the first with has a mean of $ 2 mm, but the expected mean should be around $ 2.7 mm — not really higher, but about $ 500 k more than Pippen got that season.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/397/1*MVWV9iXUldntDqee8lyzqQ.png" /><figcaption>Fig 8: Chi-Squared Test</figcaption></figure><p>So, what about the salary for a Small Forward? Used they to earn more than the players in other positions? Less? The boxplot above shows us that the mean salary for a SF at first cluster was $ 2 mm with a standard deviation of $ 700 k. Once Rodman made almost the triple Pippen made and, considering that Latrell Sprewell was the highest paid Small Forward ($ 7 mm) during the season 1996–97, it’s not inadequate to think that a Small Forward used to earn less — especially if we ponder that during the 90s, bigs (Power Forward or Center) used to have more influence in the game — and if you doubt about that, I strongly recommend you Kirk Goldsberry’s book, “<a href="https://www.amazon.com/SprawlBall-Visual-Tour-New-Era-ebook/dp/B07M7S6JLK">Sprawlball</a>”!</p><p>To eliminate that doubt, I also ran an ANOVA in addition to a Tukey Test to assess this possibility using the average salary per position and (guess what…) the answer is that the position could determine the salary of a player</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/417/1*HXkoBgm3GY5L_6AEXrgU8g.png" /><figcaption>Fig 9: ANOVA — Position</figcaption></figure><p>According to this, we could suggest that one of the greatest Small Forward of the game was a bargain not just because of his bad contract, but also because the NBA executives was not paying the deserved salary for a major part of the Small Forwards as a whole. Power Forwards and Centers were the most targeted players, perhaps due to the characteristics of the sport at that time, in which fighting for space was a determining factor and they got better deals for that — it’s not coincidence that Hakeem was drafted above Jordan, or that the Bulls’ third man was a rebounder or even that Charles Barkley was elected MVP in 1993. They were all players who, in addition to the absurd talent, had the physicality, strength and willingness to fight for space.</p><p>Pippen best shot would be trying to get a better contract, as he did during the 1997–98 season. But taking into account that bigs were the most targeted kind of players, there was no incentive for Bulls’ executives to grant him a better deal, if they ponder that they could get another good player for that position. Even the 33-years-old Warriors’ legend, Chris Mullin, made just $2.8 mm that season (~ one standard deviation more).</p><p>Finally, one may argue that Pippen should make at least $7 mm like Sprewell, but why grant Pippen $ 7 mm and get over the cap, if a sign-and-trade deal could bring two exceptional players to the team? We could analyze the choices of Bulls executives faced at the end of the 1996–97 season, towards giving a new contract to Pippen. But that would require a bunch of game theory and it’s a matter for another post.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=8436f273beca" width="1" height="1" alt=""><hr><p><a href="https://medium.com/data-science/why-was-pippen-such-a-bargain-to-the-chicago-bulls-8436f273beca">Why was Pippen such a bargain to the Chicago Bulls?</a> was originally published in <a href="https://medium.com/data-science">TDS Archive</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
    </channel>
</rss>