<?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 Gabriel Francisco Reus on Medium]]></title>
        <description><![CDATA[Stories by Gabriel Francisco Reus on Medium]]></description>
        <link>https://medium.com/@gabrielfranciscoreus?source=rss-d5c1b9d8b9b6------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/0*NEuOsNOvQ2--8BVV</url>
            <title>Stories by Gabriel Francisco Reus on Medium</title>
            <link>https://medium.com/@gabrielfranciscoreus?source=rss-d5c1b9d8b9b6------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Mon, 30 Nov 2026 11:38:52 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@gabrielfranciscoreus/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[Bollinger Bands for Commodities Price Analysis — Python Guide and Theory]]></title>
            <link>https://medium.com/@gabrielfranciscoreus/bollinger-bands-for-commodities-price-analysis-python-guide-and-theory-f39fd379cc3f?source=rss-d5c1b9d8b9b6------2</link>
            <guid isPermaLink="false">https://medium.com/p/f39fd379cc3f</guid>
            <category><![CDATA[bollinger]]></category>
            <category><![CDATA[data-science]]></category>
            <category><![CDATA[commodities]]></category>
            <category><![CDATA[trade]]></category>
            <category><![CDATA[data-visualization]]></category>
            <dc:creator><![CDATA[Gabriel Francisco Reus]]></dc:creator>
            <pubDate>Tue, 25 Apr 2023 03:00:52 GMT</pubDate>
            <atom:updated>2023-04-25T03:00:52.743Z</atom:updated>
            <content:encoded><![CDATA[<h3>Bollinger Bands for Commodities Price Analysis — Python Guide and Theory</h3><p><em>Analyzing commodities price using the Bollinger Bands theory. A real case applied at a Brazillian Wholesale company.</em></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*3--HEJ6YMgy4HNjFdy0G4g.png" /><figcaption>Found on <a href="https://br.investing.com/equities/ibm-chart">Investing</a></figcaption></figure><p>Traders who rely on quantitative analysis often seek trading tools capable of detecting trends or reversals. These tools should adjust themselves to market conditions and accurately describe the current situation.</p><p>The funny fact is that these kinds of tools are commonly used for stock analysis and trades, but what if we apply them to help our company purchase team?</p><p>In this article, we will explore Bollinger Bands and provide guidance on working with them in Python from a different perspective.</p><h3><strong>Bollinger Bands: What is it?</strong></h3><p>Bollinger Bands, developed by John Bollinger, a prominent quantitative trader in the 1980s, is a technical analysis tool used to measure market volatility. It comprises two lines, which envelope the price time series in a way that is linked to market volatility. The bands expand as market volatility increases, and contract when volatility is low.</p><p>The construction of Bollinger Bands is relatively simple, typically calculated as:</p><ul><li>Higher band: a 20-period Simple Moving Average plus 2 times the 20-period rolling standard deviation, both computed based on the close price.</li><li>Lower band: a 20-period Simple Moving Average minus 2 times the 20-period rolling standard deviation, both computed based on the close price.</li></ul><p>Here is an example that I have taken out of the Investing.com website for IBM stock prices:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*9StDc9ZVFWCO9G3ZQYS5Yw.png" /></figure><p>As evident, the Bollinger Bands attempt to envelop the price action, but there are instances when the price moves beyond the bands. Such occurrences can be leveraged to devise several trading strategies.</p><p>Bollinger Bands are widely used by traders and investors to analyze price trends, identify potential buy and sell signals, and manage risk. In the following sections, we will explore the significance of Bollinger Bands in trading and how to use them effectively to enhance trading performance.</p><p>You can read more about it <a href="https://www.bollingerbands.com/"><strong>here</strong></a><strong>.</strong></p><h3>Bollinger Bands Strategies</h3><p>There are a few strategies that can be applied when using Bollinger Bands.</p><p>Bollinger Bands are a popular tool used by binary options traders to identify dynamic support and resistance levels. Traders often consider a band break to be a signal that the price will likely return to the SMA. However, it is important to note that Bollinger Bands are best used in conjunction with other indicators such as oscillators. Bollinger himself recommends using multiple indicators for more accurate predictions. While breaking the bands may not always be a reversal signal, traders can use this tool to identify potential entry and exit points.</p><p>When a trend is strong, the price will often stay close to a band for a few candles. This is because strong trends are usually accompanied by high volatility, which causes the bands to expand, and the price to follow. By understanding this trend, traders can make more informed decisions about when to enter or exit a trade.</p><p>Bollinger Bands are also useful for identifying market volatility changes over time. Low volatility periods often precede significant directional bursts in the market. When the bands are flat and their width is constant, this is referred to as a “squeeze.” Traders should look for a breakout from this condition, marked by a large candle, which indicates a directional explosion in the price. By following the direction of the breakout, traders can capitalize on the market movement.</p><p>We will focus on the use of <strong>Break Out and Rejection.</strong></p><p>This technique consists of the analysis of the prices outside or touching the upper or lower bands and drawback into the reverse trend. Here is an example.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*vzkY6s5qLcJoNbvgn4EXvg.png" /><figcaption>Image from the Author</figcaption></figure><p>Here we can see that we had an upper trend, the price hits the upper band and went back to the red center line (the mean). That we call Break Out and Reject.</p><h3>Bands Parameters and Intro of price theory</h3><p>Bollinger Bands consists of a moving average (MA) and two standard deviations (SD) bands plotted above and below it. The distance between the upper and lower bands varies according to the volatility of the market, which is calculated by measuring the standard deviation of the price data over a certain period of time.</p><p>Bollinger Bands’ default settings are a 20-period MA and two SD bands set at 2 standard deviations away from the MA. However, these parameters can be adjusted to fit different market conditions. Traders can experiment with different timeframes and multiplier values to suit their trading strategies. Bollinger himself recommends using the bands in conjunction with other technical indicators to confirm trading signals. Overall, Bollinger Bands are a popular tool among traders to identify potential price breakouts, trend reversals, and market volatility.</p><p>It is important to observe that prices do not follow a normal distribution, we can see it clearly when we draw a price histogram. In counterpoint to Bollinger&#39;s assumption Chebyshev’s inequality states that for any random variable with a finite variance, the probability of a value being more than two standard deviations away from the mean value is far higher than 5%.</p><p>But still, Bollinger&#39;s assumption is a fair price analysis tool and can be a great ally when dealing with pricing data and trends.</p><h3>Let&#39;s get started — Python and example.</h3><p>The full code can be found in the following <a href="https://github.com/reussfg/import_trading_data_br">Github</a> repo.</p><p>We will wrap up the code so it is not so extensive. We are going to use Brazilian national import trade data to gather our entry data.</p><p>We have imported and queried the data from the following <a href="https://www.gov.br/produtividade-e-comercio-exterior/pt-br/assuntos/comercio-exterior/estatisticas/base-de-dados-bruta"><em>link</em></a>.</p><p>The data was imported, pre-analyzed, cleansed, and prepared. To build our Bollinger Bands Chart and manipulate data we will need the following libraries:</p><pre>import pandas as pd<br>import matplotlib.pyplot as plt</pre><p>The raw data comes separated by &#39;;&#39; and to gather data we used the requests library as follows:</p><pre>import requests<br><br># Collecting data<br>URL = &quot;https://balanca.economia.gov.br/balanca/bd/comexstat-bd/ncm/IMP_COMPLETA.zip&quot;<br># 2. download the data behind the URL<br>response = requests.get(URL, verify = False)<br># 3. Open the response into a new file with the same name<br>open(&quot;IMP_COMPLETA_MUN.zip&quot;, &quot;wb&quot;).write(response.content)<br><br>df = pd.read_csv(f&#39;IMP_COMPLETA_MUN.zip&#39;, sep=&#39;;&#39;)<br>df.info()</pre><p>After that, we should get our raw data, and we manipulated it to filter by the product codes we want (it is an international standard). We transformed the date column to DateTime and added the final price (product + freight).</p><p>Our data frame should look like this:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*yV_1fsyZGFF0D_ooNc2GSQ.png" /><figcaption>Image by the author</figcaption></figure><p>Now we can finally plot the bands since we have all data. Important to mention, as price value we used the median value of the column VL_CIF. We decided to use it since the distribution is not normal and the histogram showed a skewed pattern. Another approach could be using the weighted average.</p><p>This can be used because the raw data collected contains import data in low volume (KG_LIQUIDO) and we observe that the lower the volume higher the price.</p><p>Getting started, we created a function to calculate our bands. As follows:</p><pre># Bollinger Price Plot;<br>def bollinger (dataframe, p, m, ncm):<br>    # Set up dataframe<br>    dataframe = dataframe[dataframe[&#39;CO_NCM&#39;] == ncm] # Filter by NCM code<br>    dataframe = dataframe[dataframe[&#39;CO_ANOMES&#39;] &gt; &#39;2010-12&#39;]<br>    dataframe1 = dataframe[[&#39;CO_ANOMES&#39;, &#39;VL_CIF&#39;]]<br>    dataframe1 = dataframe1.groupby(by=[&#39;CO_ANOMES&#39;]).median()<br>    print(dataframe1.head())<br><br>    # Bollinger<br>    dataframe1[&#39;UpperBand&#39;] = dataframe1[&#39;VL_CIF&#39;].rolling(p).mean() + dataframe1[&#39;VL_CIF&#39;].rolling(p).std() * m<br>    dataframe1[&#39;LowerBand&#39;] = dataframe1[&#39;VL_CIF&#39;].rolling(p).mean() - dataframe1[&#39;VL_CIF&#39;].rolling(p).std() * m<br><br>    # Plot<br>    plt.figure(figsize=(12,8))<br>    dataframe1[&#39;VL_CIF&#39;].plot(label = &#39;Price&#39;)<br>    dataframe1[&#39;UpperBand&#39;].plot()<br>    dataframe1[&#39;LowerBand&#39;].plot()<br>    plt.xlabel(&#39;Date&#39;)<br>    plt.ylabel(&#39;Price&#39;)<br>    plt.title(f&#39;Price over time: {str(ncm)} &#39;)<br>    plt.legend()<br>    plt.savefig(f&#39;Bollinger {str(ncm)}.png&#39;)<br>    plt.show()</pre><p>Using the parameters we mention before we get the following graph:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*gnAmEkjKgpzHhAq_iFufUg.png" /><figcaption>Image by the author</figcaption></figure><p>And Ta-Dah! The price is wrapped by the bands as anticipated.</p><p>We can see that prices tend to go out or touch the bands and go back into the middle just as the theory says, now imagine how happy the purchasing team will be when they have this to guide and base them.</p><h3><strong>Conclusion</strong></h3><p>We can conclude that Bollinger Bands are an indispensable tool for any price analysis due to their simplicity and effectiveness. They can be easily calculated and applied in a variety of trading strategies. However, it is important to note that different approaches to using this dynamic tool may yield varying outcomes.</p><p>Therefore, a thorough backtesting of a trading strategy is recommended to fine-tune the parameters of the indicators for optimal performance.</p><p>Another important conclusion is that we can think out of the box and use regular trading strategies inside companies to base and guide purchase workers through data driven solutions. I hope you have enjoyed it and it can be useful to you.</p><p>Cheers.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=f39fd379cc3f" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Going through a beginner Data Analysis example.]]></title>
            <link>https://medium.com/@gabrielfranciscoreus/going-through-a-beginner-data-analysis-example-3758d95af9a9?source=rss-d5c1b9d8b9b6------2</link>
            <guid isPermaLink="false">https://medium.com/p/3758d95af9a9</guid>
            <category><![CDATA[music]]></category>
            <category><![CDATA[data-science]]></category>
            <category><![CDATA[data-analytics-tools]]></category>
            <category><![CDATA[data-analysis]]></category>
            <dc:creator><![CDATA[Gabriel Francisco Reus]]></dc:creator>
            <pubDate>Thu, 02 Mar 2023 02:17:23 GMT</pubDate>
            <atom:updated>2023-03-02T02:17:23.736Z</atom:updated>
            <content:encoded><![CDATA[<p><em>A case using Yandex Music CSV Database with Pandas for hypothesis checking.</em></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*VWYHHSyQyYjDC8Gi7hGncA.jpeg" /><figcaption>Photo found in <a href="https://pixabay.com/photos/lemur-ring-tailed-wildlife-zoo-1602313/">Pixabay</a></figcaption></figure><p>Today we will use Pandas and Python to test some real-case hypotheses of music listeners in two USA cities, Springfield and Shelbyville.</p><p>We will pass through several steps from data cleansing to data analysis. The steps presented here are very useful for beginners since it is basic analysis steps.</p><p>Hope you enjoy it.</p><p><em>The code presented here can be found on </em><a href="https://github.com/reussfg/springfield_shelbyville_music_project"><em>GitHub</em></a></p><h3><strong>Intro</strong></h3><p>So what is better to give some taste to life than music? We all know that music is all, but do we have all the same taste? Are we living a hype? In this project, we will analyze what Springfield and Shelbyville listen to and trends to behave regarding their music taste.</p><p>To begin with, we need to talk about Data Analysis, why is it good and what is it.<br>Data analysis is the process of collecting, processing, and interpreting data to identify patterns, trends, and insights that can inform strategic decision-making. This process is applicable in various fields, including healthcare, education, and social sciences, and has become a valuable tool for businesses seeking to stay competitive. Analysts use various techniques such as statistical analysis, data visualization, and machine learning to effectively analyze data and identify trends and patterns, which can be used to optimize operations, reduce costs, increase revenue, and inform decision-making. As the importance of data analysis continues to grow, businesses and organizations must ensure they have the right skills and tools to effectively leverage data for strategic decision-making.</p><p>Ok, that seems good but how the heck I am going to use it? Good question, here we will present you a good example of how it helps.</p><h3>Our premises</h3><p>Here is what we want to understand from the people of Springfield and Shelbyville:</p><ol><li>The user&#39;s activity varies depending on the day of the week and the city.</li><li>On Monday mornings, residents of Springfield and Shelbyville listen to different genres. This is also true for Friday nights.</li><li>The listeners in Springfield and Shelbyville have different preferences. In Springfield, people prefer pop, while Shelbyville has more rap fans.</li></ol><p>Why this premise? Idk someone wanted to know about it, so we analyzed it (:</p><h3>Steps to analyze</h3><p>Before we start coding and making our code, we need first to analyze our Database and see if it is already ready to go. Some basic steps to work and analyze any data:</p><ol><li>Data overview.</li><li>Data pre-processing.</li><li>Hypothesis testing.</li></ol><p>Now we know what we want and how we gonna do it, let&#39;s get it on.</p><h3>1. Data overview</h3><p>First of all, we need to import the library that we will work with, in this case, we will use pandas.</p><p>We need to use pandas to read our CSV archive and analyze our DB for any missing data, out-of-good coding practice patterns, etc.</p><pre>import pandas as pd<br><br># reading our DB<br>df = pd.read_csv(&#39;/datasets/music_project_en.csv&#39;)<br><br># get the first 10 lines<br>df.head(10)<br><br># summary of DB info<br>df.info()</pre><p>By that we get the following outputs:</p><p>a. The data seems to be organized in the right columns</p><p>b. By the info() function, we can observe that the header is not in the right pattern having spaces.</p><p>c. Also by info() function we receive that there are some rows without data and we need to deal with it.</p><h3>2. Pre-processing data</h3><p>When we talk about pre-processing data we refer to the set of operations performed on raw data before it can be used for analysis or modeling. This typically involves several steps such as data cleaning, data transformation, and data normalization, aimed at improving data quality, reducing noise, and making it more suitable for specific analytical tasks. Pre-processing data is a critical step in data analysis, as it directly affects the accuracy and effectiveness of any subsequent data analysis or machine learning algorithms applied to the data.</p><p>In this case, by the last step, we need to do these several things:</p><p>a. Remove spaces from the headers;</p><p>b. Pattern the header to snake_case.</p><p>c. Remove or add a string to empty (NaN) row values.</p><p>To do that we will execute the following code lines:</p><pre># rename columns to snake_case and remove spaces<br>df.columns = df.columns.str.replace(&#39; &#39;, &#39;&#39;)<br>df.columns= df.columns.str.strip().str.lower()<br>df.columns = df.columns.str.replace(&quot;userid&quot;, &quot;user_id&quot;)<br><br># Setting the columns with NaN values<br>columns_to_replace = [&#39;track&#39;, &#39;artist&#39;, &#39;genre&#39;]<br><br># Filling &quot;unknown&quot; string in empty values<br>df[columns_to_replace] = df[columns_to_replace].fillna(&#39;unknown&#39;)</pre><p>The second thing it is important to check is if the DB has any duplicated values.</p><pre># count clear duplicates<br>df.duplicated().sum()</pre><p>By running the code we receive 3826 duplicates, so we need to clear it.</p><pre># removing clear duplicates<br>df.drop_duplicates(inplace = True)</pre><p>Right now we already cleared our obvious data and patterned it, but we still need to be careful with some hidden duplicated data. For instance, in this specific case, we will work with the &#39;genre&#39; column, so it is important to verify the data in this column before working with it.</p><pre># listing unique values in column genre<br>column_genre = df[&#39;genre&#39;].drop_duplicates()<br><br># listing it in alphabetic order<br>list_genre = list(column_genre.sort_values())<br>print(list_genre)</pre><p>The output:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*BpT4BaHCJErn6SE6ZwDcbw.png" /></figure><p>By reading it manually it is possible to check that the music genre hiphop is repeated several times in different ways such hip-hop, hip, hip-hop, hop.</p><p>This kind of error is very common when data is parsed/added manually. It can occur and it is always important to check data before working with it.</p><p>To solve it we need to replace the duplicated data.</p><pre># Using a function to replace duplicated data<br>def replace_wrong_genres(df, wrong_genres, correct_genre):<br>    <br>    bool_mask = df[&#39;genre&#39;].str.contains(&#39;|&#39;.join(wrong_genres), case=False)<br><br>    df.loc[bool_mask, &#39;genre&#39;] = correct_genre<br><br>    return df<br><br># Applying the funcion<br>wrong_list = [&#39;hip&#39;,&#39;hop&#39;,&#39;hip-hop&#39;]<br>replace_wrong_genres(df,wrong_list,&#39;hiphop&#39;)</pre><p>So at this point, we already loaded, cleaned, and analyzed our database, now it is time, to begin with, the real data analysis.</p><h3>3. Data Analysis</h3><p>The last and final point right now, we will start analyzing our data and testing our premises.</p><p>Premise 1: The user’s activity varies depending on the day of the week and the city.</p><p>The first thing to is separate the cities into two different DataFrames. Then we use groupby() function to cluster data by day of the week and number of users.</p><pre># Split DF for cities<br>df_shelby = df[df[&#39;city&#39;] == &#39;Shelbyville&#39;]<br>df_spring = df[df[&#39;city&#39;] == &#39;Springfield&#39;]<br><br># Counting the activity between cities<br>print(f&#39;Musicas em Shelby \n {df_shelby.count()}&#39;)<br>print(f&#39;Musicas em Spring \n {df_spring.count()}&#39;)</pre><p>Springfield has more songs played than Shelbyville. But that doesn’t mean that the citizens of Springfield listen to music more often. This city is just bigger and has more users.</p><p>We can affirm that Springfield is more &quot;active&quot; than Shelbyville, but a deeper analysis taking a number of citizens should be done.</p><p>Right now we can create different day clusters using the pandas groupby() function.</p><pre># Separating between data we need for the analysis<br>df_shelby = df_shelby[[&#39;day&#39;,&#39;user_id&#39;]]<br>df_spring = df_spring[[&#39;day&#39;,&#39;user_id&#39;]]<br>df_general = df[[&#39;day&#39;,&#39;user_id&#39;]]<br><br># Music in Shelbyville<br>df_shelby = df_shelby.groupby(by=[&#39;day&#39;])<br>print(f&#39;Music in Shelbyville \n {df_shelby.describe()}&#39;)<br>      <br># Music in Springfield<br>df_spring = df_spring.groupby(by=[&#39;day&#39;])<br>print(f&#39;Music in Springfield \n {df_spring.describe()}&#39;)<br><br># Music in general<br>df_general = df_general.groupby(by=[&#39;day&#39;])<br>print(f&#39;Music in General \n {df_general.describe()}&#39;)</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/642/1*NQolFYmLudYZ283srUzM_Q.png" /></figure><p><strong>Conclusions</strong></p><p>The data reveal differences in user behavior:</p><ul><li>In Springfield, the peak of music played occurs on Mondays and Fridays, while there is a decrease in activity on Wednesdays.</li><li>In Shelbyville, on the other hand, users listen to more music on Wednesdays. Activity on Mondays and Fridays is low.</li><li>So the first hypothesis appears to be correct.</li></ul><p>Premise 2: On Monday mornings, residents of Springfield and Shelbyville listen to different genres. This is also true for Friday nights.</p><p>To do so, we need again to cluster city data and then analyzed genre data by clustering it by day and filtering by the hour of the day. We will consider as:</p><ul><li>Morning: 07 am to 11 am</li><li>Night: 5 pm to 11 pm</li></ul><pre># Clustering for Springfield<br>spr_general = df[df[&#39;city&#39;] == &#39;Springfield&#39;]<br><br># Clustering for Shelbyville<br>shel_general = df[df[&#39;city&#39;] == &#39;Shelbyville&#39;]<br><br># Creating a function for filtering day, db and genre<br>def genre_weekday(df, day, time1, time2):<br>    genre_df = df[df[&#39;day&#39;] == day]<br>    genre_df = genre_df[genre_df[&#39;time&#39;] &lt; time2]<br>    genre_df = genre_df[genre_df[&#39;time&#39;] &gt; time1]<br>    genre_df_grouped = genre_df.groupby(&#39;genre&#39;)[&#39;genre&#39;].count()<br>    genre_df_sorted = genre_df_grouped.sort_values(ascending=False)<br>    return genre_df_sorted[:15]</pre><p>Now we can call the function of the day, the beginning hour we want to analyze, and the final hour. For example for our premise:</p><pre>genre_weekday(spr_general, &#39;Monday&#39;, &#39;07:00&#39;, &#39;11:00&#39;)<br>genre_weekday(shel_general, &#39;Monday&#39;, &#39;07:00&#39;, &#39;11:00&#39;)<br>genre_weekday(spr_general, &#39;Friday&#39;, &#39;17:00&#39;, &#39;23:00&#39;)<br>genre_weekday(shel_general, &#39;Friday&#39;, &#39;17:00&#39;, &#39;23:00&#39;)</pre><p>From the data, we can conclude:</p><ul><li>In Springfield, the number of missing values turned out to be so high that the value ‘unknown’ came in 10th. This means that missing values had a considerable portion of the data, which may be the basis for questioning the reliability of the conclusions.</li><li>Users in Springfield and Shelbyville listen to similar music. The top five most listened-to genres are the same, only rock and electronic music switched places.</li><li>For Friday afternoon, the situation is similar. Individual genres vary a bit, but overall, the 15 most listened to genres are similar for the two cities.</li></ul><p>Thus, the second hypothesis was partially proven:</p><p>Users listen to similar genres of music at the beginning and end of the week. There is no significant difference between Springfield and Shelbyville. In both cities, pop is the most popular genre. However, the number of missing values makes this result questionable. In Springfield, there are so many that they affected the top 15. If we didn’t miss these values, things could be different.</p><p>Premise 3: The listeners in Springfield and Shelbyville have different preferences. In Springfield, people prefer pop, while Shelbyville has more rap fans.</p><p>For this one it is very simple, we use again groupby() for our last city clusters:</p><pre>spr_genres = spr_general.groupby(&#39;genre&#39;)[&#39;genre&#39;].count().sort_values(ascending=False)<br>shel_genres = shel_general.groupby(&#39;genre&#39;)[&#39;genre&#39;].count().sort_values(ascending=False)</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/418/1*esvugmzH4Y1-qGE8QQNp_g.png" /><figcaption>Shelbyville Genre Data</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/414/1*6vg7aoAjlz1FPtt_CTPiAw.png" /><figcaption>Springfield Genre Data</figcaption></figure><p>In conclusion:</p><p>The hypothesis was partially proven:</p><ul><li>Pop music is the most popular genre in Springfield, as expected.</li><li>However, pop music turned out to be equally popular in Springfield and Shelbyville, and rap was not in the top 5 in either city.</li></ul><h3>4. Final conclusion</h3><p>The first conclusion is that we always need to conduct a pre-analysis with the DB we have to check the potential errors, missing values, or duplicates.</p><p>Through our analysis we have that:</p><p>After conducting an analysis of user behavior in two different cities, Springfield and Shelbyville, we have come to some interesting conclusions about their musical preferences. We tested three hypotheses and found that the activity of users in both cities does vary depending on the day of the week, although the cities differ in certain ways. In addition, we found that users in both cities have similar preferences when it comes to music genres, with pop being the most popular.</p><p>Our analysis revealed that the first hypothesis is fully accepted. The second hypothesis is partially proven, as we found that the musical preferences of users in both cities do differ slightly on Monday mornings and Friday nights. However, the difference is not significant enough to reject the hypothesis that users have similar musical preferences throughout the week.</p><p>We also found that the third hypothesis, which stated that the musical preferences of users in Springfield and Shelbyville differ significantly, was rejected. Our analysis revealed that if there is any difference in preferences, it cannot be seen in the data we analyzed. Overall, our findings suggest that users in both cities have similar musical tastes and that their activity varies depending on the day of the week.</p><p>However, we should note that the analysis is based on limited data and may not represent the entire population of these cities. Further research is necessary to confirm these findings and to gain a better understanding of user behavior and preferences in these cities.</p><p><em>I hope it gave you a direction about Data Analysis projects and how to conduct one.</em></p><p>To effectively analyze data, analysts use various techniques, including statistical analysis, data visualization, and machine learning. These techniques help to identify trends and patterns in data, make predictions, and discover insights that can be used to inform decision-making. As the importance of data analysis continues to grow, businesses and organizations must ensure they have the right skills and tools to effectively leverage data for strategic decision-making.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=3758d95af9a9" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Real DataScraper code example to collect business data]]></title>
            <link>https://medium.com/@gabrielfranciscoreus/real-datascraper-code-example-to-collect-business-data-a1df2b541bd5?source=rss-d5c1b9d8b9b6------2</link>
            <guid isPermaLink="false">https://medium.com/p/a1df2b541bd5</guid>
            <category><![CDATA[data-science]]></category>
            <category><![CDATA[data]]></category>
            <category><![CDATA[data-analysis]]></category>
            <category><![CDATA[big-data]]></category>
            <category><![CDATA[data-scraping]]></category>
            <dc:creator><![CDATA[Gabriel Francisco Reus]]></dc:creator>
            <pubDate>Thu, 16 Feb 2023 20:31:41 GMT</pubDate>
            <atom:updated>2023-02-28T22:17:09.924Z</atom:updated>
            <content:encoded><![CDATA[<p><em>A real case guide on how to scrape data from a hotel website.</em></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*87X-RrVfkZd8ww_01_WuRg.jpeg" /><figcaption>Image by fatmawatilauda on <a href="https://www.freepik.com/free-vector/mining-industry-cryptocurrency_15620871.htm#query=mining%20data&amp;position=9&amp;from_view=search&amp;track=ais">Freepik</a></figcaption></figure><p>Have you ever heard that data is the new gold? I&#39;ve never believed that to be so true before I needed to use and collect a bunch of data during my startup&#39;s MVP. Nowadays with easy access, fast connections, and online coding servers, it gets easier every day to dig some gold (ops, Data) and enhance business knowledge.</p><p><em>The codes presented can be found in this </em><a href="https://github.com/reussfg/hotel_scraping"><em>GitHub</em></a><em> repo.</em></p><h3><strong>What is Data Scraping?</strong></h3><p>In summary, data scraping is the process of extracting data from websites and other digital sources using automated tools and algorithms. It is a valuable tool for gathering insights and information for a variety of purposes, such as market research, competitive analysis, and content aggregation.</p><p>However, it is important to approach data scraping with caution, as it can raise ethical and legal concerns. Some websites prohibit data scraping in their terms of service, and scraping data from public sources for commercial purposes may violate certain privacy laws. It is important to ensure that data scraping is being done in a legal and ethical manner to avoid any potential legal repercussions.</p><p>In the new data trend, this method can give Data Scientists, ML Scientists, and Data Analysts valuable inputs to work on. In this specific case, we used it for the purpose of gathering market research and lead generation.</p><h3>What do we need for it?</h3><ol><li>Python IDE;</li><li>BeautifulSoup;</li><li>Selenium;</li><li>Google Chrome;</li><li>A bit of HTML knowledge;</li><li>A little bit of creativity;</li></ol><h3>Let&#39;s get started</h3><p>For this specific case, I used a website called Hoteis.com as said before many websites do not allow bulk data extraction due to (obviously) data leaks and an easy way for getting their business info. So before you start read carefully the website policies.</p><p>Hands-on then.</p><p><strong>a. Importing our libraries.</strong></p><pre>import requests<br>from bs4 import BeautifulSoup<br>from selenium import webdriver<br>import html5lib<br>from selenium import webdriver<br>from selenium.webdriver.chrome.options import Options<br>from time import sleep<br>from selenium.webdriver.common.keys import Keys</pre><p>So we are using:</p><ol><li>Requests &gt; It can be used to retrieve data from websites</li><li>BeautifulSoup &gt; It is often used in web scraping to extract data from web pages.</li><li>Selenium &gt; It can be used to simulate user interactions with a website, such as filling out forms, clicking buttons, and scrolling.</li><li>html5lib &gt; It can be used to parse web data.</li><li>web driver&gt; It provides a high-level API for automating web browser interactions.</li><li>Options &gt; Allows us to set various options and preferences for the Google Chrome browser.</li><li>Sleep &gt; Module that pauses the execution of a Python script for a specified number of seconds.</li><li>Keys &gt; Provides a way to simulate keyboard keys, such as pressing the Enter key or the arrow keys.</li></ol><p><strong>b. Find the specific website link you want to dig data from</strong></p><p>In this case, what I have done is:</p><p>Opened Hoteis.com (our website) &gt; Searched for a location &gt; Used the website breakfast and pool filter &gt; get the final URL</p><p>Our final URL is:</p><p><a href="https://www.hoteis.com/Hotel-Search?adults=2&amp;amenities=POOL&amp;d1=2023-03-01&amp;d2=2023-03-02&amp;destination=Bali%2C%20Indon%C3%A9sia&amp;endDate=2023-03-02&amp;latLong=-8.340539%2C115.09195&amp;mealPlan=FREE_BREAKFAST&amp;regionId=602651&amp;selected=&amp;semdtl=&amp;sort=RECOMMENDED&amp;startDate=2023-03-01&amp;theme=&amp;useRewards=false&amp;userIntent=">Properties in Bali, Indonesia. March 1, 2023 through March 2, 2023</a></p><p><strong>c. Start the coding process</strong></p><pre># Input of the city I want do dig in<br>url = input(&#39;Insert the URL of what you want to dig in: &#39;)<br><br># Setting Chrome Window Sizes<br>options = Options()<br>options.add_argument(&#39;window-size= 400,800&#39;)<br><br># Opening Chrome<br>browser = webdriver.Chrome()<br>url_open = browser.get(url)  # Website I want to open with its search<br><br># Waiting for response time<br>sleep(5)</pre><p>The first line prompts the user to enter the URL of the website they want to extract data.</p><p>The next few lines set the size of the Chrome browser window using the Options() method. The add_argument() method is used to specify the window size.</p><p>Then, a Chrome browser instance is opened using the webdriver.Chrome() method. The get() method is used to open the URL entered by the user in the previous step.</p><p>After that, the sleep() function is used to pause the script for 5 seconds to wait for the website to load completely before proceeding with further actions.</p><pre># Get the Loop to Start Dig in<br>a = 1<br>while a &lt; 30:<br>    # Start the Soup Process<br>    link = requests.get(&#39;https://bit.ly/3hSIkW9&#39;)<br>    resultado = link.content<br>    soup = BeautifulSoup(resultado, &#39;html.parser&#39;)<br>    urls = []</pre><p>The while loop runs as long as the value a is less than 30. This means that the loop will iterate 29 times. I used it because, at the end of the code, we will iterate on the webpage to scroll down several times to collect more data, and it will scroll down 29 times to collect all the hotel&#39;s data.</p><p>Inside the while loop, the script sends a request to the URL specified in the requests.get() method, which in this case is &#39;https://bit.ly/3hSIkW9&#39;. This request is used to retrieve the HTML content of the webpage.</p><p>The content of the webpage is then passed as an argument to the BeautifulSoup() method, which is used to parse the HTML content and create a BeautifulSoup object.</p><p>Finally, an empty list called urls is created to store the URLs that will be extracted from the web page.</p><p><strong>d. Find the exact HTLM root that we want to collect data</strong></p><p>To do that we need to use Google Chrome help. We need to find the HTLM root of the data. Normally HTLM is divided as (div, h2, body, etc).</p><p>What we need to do is:</p><p>Open the URL page &gt; Right Click on the mouse &gt; Click on &quot;Inspect&quot; &gt; Find the unique <strong>class name</strong>.</p><p>In my case it is posible to see that:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/912/1*wSDxUgHJp9OUmwNeJUSYaw.png" /></figure><ol><li>It is separated by &quot;<strong>div</strong>&quot; columns where the main class for any hotel ad is <strong>class</strong> = &quot;uitk-spacing uitk-spacing-margin-blockstart-three&quot;.</li><li>All the ads link stay on a <strong>&lt;a</strong> class right after the <strong>href.</strong></li><li>Analysing all links with Google Chrome Inspector we can see that it is a pattern.</li></ol><p>So my code follows as:</p><pre>  # Start Looping for All Links<br>    for div in soup.find_all(&#39;div&#39;, attrs={&#39;class&#39;, &#39;-uitk-spacing uitk-spacing-margin-blockstart-three&#39;}):<br>        a_tag = div.find(&#39;a&#39;)<br>        urls.append(a_tag.attrs[&#39;href&#39;])</pre><p>With it we loop to collect all the <strong>href</strong> links for future analysis.</p><p><strong>e. Cleaning data and adding to a list</strong></p><p>So by now we already have collected all the data and attached to the list of the URL, next thing we need to do is add a prefix thus our data comes as:</p><p><a href="https://www.hoteis.com/ho230403/the-vira-bali-boutique-hotel-suite-kuta-indonesia/?chkin=2023-03-01&amp;chkout=2023-03-02&amp;x_pwa=1&amp;rfrr=HSR&amp;pwa_ts=1676575600799&amp;referrerUrl=aHR0cHM6Ly93d3cuaG90ZWlzLmNvbS9Ib3RlbC1TZWFyY2g%3D&amp;useRewards=false&amp;rm1=a2&amp;regionId=602651&amp;destination=Bali%2C+Indon%C3%A9sia&amp;destType=MARKET&amp;neighborhoodId=553248633981737329&amp;amenities=POOL&amp;mealPlan=FREE_BREAKFAST&amp;sort=RECOMMENDED&amp;top_dp=296&amp;top_cur=BRL&amp;userIntent=&amp;selectedRoomType=59031&amp;selectedRatePlan=136061&amp;expediaPropertyId=1224948">ho230403/the-vira-bali-boutique-hotel-suite-kuta-indonesia/?chkin=2023-03-01&amp;chkout=2023-03-02&amp;x_pwa=1&amp;rfrr=HSR&amp;pwa_ts=1676575600799&amp;referrerUrl=aHR0cHM6Ly93d3cuaG90ZWlzLmNvbS9Ib3RlbC1TZWFyY2g%3D&amp;useRewards=false&amp;rm1=a2&amp;regionId=602651&amp;destination=Bali%2C+Indon%C3%A9sia&amp;destType=MARKET&amp;neighborhoodId=553248633981737329&amp;amenities=POOL&amp;mealPlan=FREE_BREAKFAST&amp;sort=RECOMMENDED&amp;top_dp=296&amp;top_cur=BRL&amp;userIntent=&amp;selectedRoomType=59031&amp;selectedRatePlan=136061&amp;expediaPropertyId=1224948</a></p><p>We can see that the href returns the reference for the main domain. So:</p><pre>    # Adding the prefix to the link<br>    for i in range(len(urls)):<br>        urls[i] = str(urls[i])<br>        urls[i] = &#39;hoteis.com&#39; + urls[i]<br>        print(urls[i])</pre><p>The for loop iterates through each URL in the list “urls” using the range() function to generate an index for each element.</p><p>In each iteration, the current URL is converted to a string using the str() function. Then, the string “hoteis.com” is concatenated with the URL using the + operator.</p><p>The modified URL is then assigned back to the original index position in the “urls” list. Finally, the code prints each modified URL to the console using the print() function.</p><p>Overall, this code is useful when working with a list of URLs that need to be modified to include a specific domain or prefix.</p><p><strong>f. Continuing the loop</strong></p><p>Using the website and analyzing the UX it is possible to observe that loading more data is needed to scroll down. To do that we use Selenium as follows:</p><pre>    # Scroll down on the page<br>    down = browser.find_element_by_class_name(&#39;_12VuEX&#39;)<br>    down.send_keys(Keys.END)<br>    sleep(7)<br>    browser.execute_script(&quot;window.scrollTo(document.body.scrollHeight, 700);&quot;)<br>    a += 1<br>    sleep(10)</pre><p>The find_element_by_class_name() method finds the first element with the specified class name, which in this case is &quot;_12VuEX&quot;.</p><p>The send_keys() method simulates pressing the &quot;END&quot; key on the keyboard, which scrolls the page down to the bottom.</p><p>The sleep() function causes the program to pause for 7 seconds after the page is scrolled to the bottom, allowing time for the page to load new content.</p><p>The execute_script() method executes a JavaScript code that scrolls down the page to a specified height of 700 pixels from the top of the page.</p><p>The a += 1 increments a counter variable &quot;a&quot; by 1, which keeps track of how many times the code has scrolled down the page.</p><p>Finally, the program pauses for 10 seconds before continuing with the next iteration of scrolling.</p><p>Overall, this code is useful when working with web pages that load new content dynamically as the user scrolls down, allowing the program to automate the process of scrolling and scraping content.</p><p><strong>g. Conclusion</strong></p><ol><li>Data scraping is a powerful technique used to extract data from websites and other online sources, which can be used for various purposes such as market research, competitor analysis, and lead generation.</li><li>Data scraping can be performed manually or through automated scripts, using tools like Python’s Beautiful Soup or the Selenium WebDriver, and can be tailored to specific requirements such as filtering out irrelevant data or handling large volumes of data.</li><li>Data scraping raises concerns over privacy, copyright infringement, and legality, and should be performed responsibly, with respect to the website owner’s terms of service and applicable laws and regulations.</li><li>As technology continues to evolve, and data becomes more critical to businesses and organizations, data scraping will likely become an increasingly essential tool for obtaining valuable insights and gaining a competitive edge in various industries.</li></ol><p><em>However, it is vital to use data scraping ethically and legally, respecting the boundaries set by the source websites and applicable laws and regulations.</em></p><p>Thanks for reading until the end! I hope you have learned something and it helped you somehow.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=a1df2b541bd5" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>