<?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 IvetaKuncova on Medium]]></title>
        <description><![CDATA[Stories by IvetaKuncova on Medium]]></description>
        <link>https://medium.com/@vtkncv?source=rss-029ab3d9933f------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*kL_frKbrDB-aRzwJ2GFjWQ.png</url>
            <title>Stories by IvetaKuncova on Medium</title>
            <link>https://medium.com/@vtkncv?source=rss-029ab3d9933f------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Tue, 01 Dec 2026 12:13:08 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@vtkncv/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[E-sport data analysis project: Summary]]></title>
            <link>https://medium.com/@vtkncv/e-sport-data-analysis-project-summary-e7b64cd37c84?source=rss-029ab3d9933f------2</link>
            <guid isPermaLink="false">https://medium.com/p/e7b64cd37c84</guid>
            <category><![CDATA[keboola]]></category>
            <category><![CDATA[tableau]]></category>
            <category><![CDATA[python]]></category>
            <category><![CDATA[data-analysis]]></category>
            <category><![CDATA[sql]]></category>
            <dc:creator><![CDATA[IvetaKuncova]]></dc:creator>
            <pubDate>Thu, 15 Feb 2024 12:21:58 GMT</pubDate>
            <atom:updated>2024-02-20T11:08:51.301Z</atom:updated>
            <content:encoded><![CDATA[<p>#datamodel #python #sql #tableau</p><p>My <a href="https://github.com/IvetaKuncova/ESPORT">GitHub</a><br>My <a href="https://public.tableau.com/app/profile/iveta.kuncova/vizzes">Tableau Public</a><br>My <a href="https://www.linkedin.com/in/ivetakuncova/">LinkedIn</a></p><p><strong>More detailed information about this project in blog articles :</strong><br>Article 1: <a href="https://medium.com/@vtkncv/e-sport-part-1-project-plan-and-preparation-98b5178845b5">Project Plan and Preparation</a><br>Article 2: <a href="https://medium.com/@vtkncv/e-sport-part-2-python-acb60fb6d58b">Python</a><br>Article 3: <a href="https://medium.com/@vtkncv/e-sport-part-3-sql-and-data-model-e0de520948ce">Keboola, SQL and data model</a><br>Article 4: <a href="https://medium.com/@vtkncv/e-sport-part-4-analyzing-the-number-of-players-b066904ef750">Analyzing the number of players in countries</a><br>Article 5: <a href="https://medium.com/@vtkncv/e-sport-part-5-analysing-playerss-active-years-in-relation-to-prize-money-8117bd6a6112">Analysing players’s active years in relation to prize money</a></p><h4>SUMMARY:</h4><h3>Part 1: Project Plan and Preparation</h3><p>Go to the <a href="https://medium.com/@vtkncv/e-sport-part-1-project-plan-and-preparation-98b5178845b5">Detailed blog article about Project plan and preparation</a></p><p><strong>Project goal: </strong>Apply SQL, Python, Visualisations etc. in practice. Start a portfolio for my resume.</p><p><strong>Data source: </strong><a href="https://www.esportsearnings.com/">https://www.esportsearnings.com/</a><br>Secondary source: <a href="https://ourworldindata.org/">https://ourworldindata.org/</a></p><p><strong>Time plan:</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*sY_RCyzT-lQsaJadau4pEQ.png" /></figure><h3>Part 2: Python</h3><p>Go to the <a href="https://medium.com/@vtkncv/e-sport-part-2-python-acb60fb6d58b">Detailed blog article about Python</a> (with SCRIPTS) or my <a href="https://github.com/IvetaKuncova/ESPORT/tree/master/01%20python">GitHub</a>.</p><p>I <strong><em>downloaded data from APIs</em></strong> (<strong> </strong><a href="https://www.esportsearnings.com/">https://www.esportsearnings.com/</a>) with my Python scripts and <strong><em>I scraped dates of birth with</em> P</strong>ython script from an AI language model, which I adjusted. I also used Python to <strong><em>calculate correlation statistics</em></strong> in Jupyter notebook.</p><p><strong>The API scripts consist of several parts:</strong><br>- Loading modules<br>- Setting global variables<br>- Script execution time<br>- Creating a session to handle HTTP exceptions<br>- Functions to retrieve data from the API<br>- Functions to save data in JSONL format<br>- Functions to convert JSONL to CSV format<br>- Output time and file data<br>- ANSI colors for terminal outputs</p><p>Go to the <a href="https://medium.com/@vtkncv/e-sport-part-2-python-acb60fb6d58b">Detailed blog article about Python</a> (with SCRIPTS) or my <a href="https://github.com/IvetaKuncova/ESPORT/tree/master/01%20python">GitHub</a>.</p><pre># THIS IS JUST A PART OF ONE SCRIPT<br># Go to my blog article Part 2: Python to see whole script.<br><br># API data retrieval function<br>def get_LookupPlayerTournaments(playerid, offset):<br>    numOfTournament = 1<br>    tournaments = []<br>    for i in range(0, stopoffset):<br>        # API requires min 1 second between queries, min 1 second between requests<br>        time.sleep(1.0)<br>        url = f&#39;https://api.esportsearnings.com/v0/LookupPlayerTournaments?apikey={apikey}&amp;playerid={playerid}&amp;offset={offset}&#39;<br>        # without Verify=False the request will not be executed due to an invalid SSL certificate<br>        response = session.get(url, verify=False)<br>        # on the terminal You can see which address You are currently at. For quick orientation, how far You are in the request, in pink color<br>        print(f&quot;\u001b[35m{url}\u001b[0m&quot;)<br>        <br>        # handling of Errors returned by the API (200 = success)<br>        if response.status_code != 200: <br>            # If the API reports an Error, we display it and also save it to the list, in red color<br>            print(f&quot;\u001b[31;1mError: HTTP {response.status_code}\u001b[0m&quot;) <br>            errorCodes.append(f&quot;PlayerId:{playerid}-error:{response.status_code}&quot;)  <br>            data = [{&quot;Error&quot;: f&quot;HTTP {response.status_code}&quot;}]<br>        # if the API returns &quot;NULL&quot;/none:<br>        elif not response.text:<br>            print(f&quot;\u001b[31;1mError: Empty response\u001b[0m&quot;) <br>            errorCodes.append(f&quot;PlayerId:{playerid}-Error:Empty response&quot;)<br>            data = [{&quot;Error&quot;: &quot;Empty response&quot;}]            <br>            break             <br>        else:<br>            try:<br>                data = response.json()<br>                # Add a new keys and ID values<br>                for dictionary in data:<br>                    dictionary[&quot;PlayerId&quot;] = playerid<br>                    dictionary[&quot;NumOfTournament&quot;] = numOfTournament<br>                    numOfTournament += 1<br>            except:<br>                print(f&quot;\u001b[31;1mError: Invalid response: {url}\u001b[0m&quot;)<br>                print(response.status_code)<br>                print(response.text)<br>                data = [{&quot;Error&quot;: &quot;Invalid response&quot;}]                <br>            <br>        tournaments.append(data)<br>        offset += 100<br>    return tournaments</pre><h3>Part 3: SQL and data model</h3><p>Go to the <a href="https://medium.com/@vtkncv/e-sport-part-3-sql-and-data-model-e0de520948ce">Detailed blog article about Keboola, SQL and data model</a></p><p><strong>Keboola with Snowflake SQL environment:<br></strong>Keboola is self-service cloud data operations platform.<br>I uploaded all CSV files to “Storage” and changed the properties of input columns (integer, float, varchar, char, date …). Then I created “Workspace”, i.e. safe sandbox for testing, with Snowflake SQL sheets and tested my SQL statements first. If they were complete, I could create “Transformation”, i.e. Production environment, and use these statements for creating new tables. When all tables were prepared, I made a live “Connection” from Snowflake to Tableau, where I visualized results.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/990/1*bn7Bj4iHNg_rxyWRBmpHXw.png" /></figure><p>SQL:<br><strong>Used functions:<br>- </strong>CTE, SUBSELECTS, CREATE (TEMPORARY) TABLE<br>- ALTER TABLE, UPDATE, ADD COLUMN, DROP COLUMN, INSERT VALUES<br>- (LEFT) JOIN, UNION (ALL)<br>- WINDOW FUNCTIONS (RANK), CASE WHEN, DISTINCT<br>- Aggregations: SUM, COUNT, MEDIAN, AVG, MIN, MAX, PERCENTILE_CONT<br>- Text functions: TRIM, REPLACE, TRANSLATE, LISTAGG, REGEXP_SUBSTR, CONCAT, LOWER, (I)LIKE (ANY), IFFNULL, TRANSLATE, CONCAT<br>- Date functions: TO_DATE, DATE, YEAR.</p><p>As a step 1 I used SQL to <strong>merge (UNION) all CSV files</strong> from the downloading phase to one table per API.</p><p>Step 2: I prepared URL addresses for web scraping date of births. I had to <strong>transform players’s names </strong>using UTF-8, to get rid of non-ASCII characters not supported by web links (e.g. êøД神ßλ) with RTRIM, REPLACE, TRANSLATE. Then I could <strong>CONCATENATE the parts of the URL link </strong>with CASE WHEN for combinations of missing first name, last name or nickname.</p><p>The next step was to create a <strong>normalized data model:</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*KQem8b520cOQKM0p5P8rHQ.png" /><figcaption>Data model via Lucidcharts.com</figcaption></figure><p>I <strong>created normalized tables </strong>according to the data model. I <strong>updated some values</strong> (e.g. Country names) to match them by joining tables and <strong>cleansed all mistakes or inconsistencies </strong>in the data.</p><p><strong>I checked if the data are consistent </strong>between tables. E.g. if all players in tables 08 a 10 (Tournament results) are also in the 01 Player table. I selected the missing data and inserted them into 01 Player.<br>I <strong>dealt with placeholder player IDs</strong> in one table, which were not unique and had the same value as real player IDs. I added 900 000 to them (max plays ID is about 135 000) to distinguish them from the original IDs. But in a database with more than two users would be more appropriate to treat them more fool-proof.</p><p>As a last SQL step, I prepared <strong>aggregated tables </strong>for Vissualisations for my two hypotheses.</p><p>Through Kebolla Connection I sent all the tables to Tableau, where I made the visualizations.</p><p>Go to the <a href="https://medium.com/@vtkncv/e-sport-part-3-sql-and-data-model-e0de520948ce">Detailed blog article about Keboola, SQL and data model</a></p><pre>-- THIS IS JUST AN EXAMPLE. For more go to my blog article Part 3.<br>-- It is aggregation of tables for the Hypotesis if &quot;players with the highest<br>-- prize money stay playing more years or months than the others. (Part 5)<br><br>/* ===== table 1 ===== */<br><br>CREATE OR REPLACE TABLE WHOSEARLYERRETIRED_KVA AS<br>WITH CTE_WHOSEARLYERRETIRED_QUA AS (<br>SELECT <br>    T4_GAME_ID::int AS GAME_ID,<br>    T4_GAME_NAME AS GAME_NAME,  <br>    T4_RANK_PRIZE_USD::int AS RANK_PRIZE_USD,<br>    T4_RANK_CNT_TOURNAMENTS::int AS RANK_CNT_TOURNAMENTS,<br>    T4_RANK_CNT_PLAYERS::int AS RANK_CNT_PLAYERS,<br>    T4_ISMORETHAN_QUA::int AS ISMORETHAN_QUA, -- an indicator if player is TOP or Casual player according to quantil 0,9<br>    COUNT(DISTINCT T4_PLAYER_ID::int) AS CNT_PLAYER,<br>    SUM(T4_SUM2_PRIZE_USD)::float AS SUM_PRIZE_USD,<br>    AVG(T4_CNT_YEAR_OF_TOURNAMENT)::float AS AVG_YEARS<br>FROM <br>------------------------------------------------------------------  b<br>    (<br>    SELECT<br>        T3_GAME_ID AS T4_GAME_ID,<br>        T3_GAME_NAME AS T4_GAME_NAME,<br>        T3_RANK_PRIZE_USD AS T4_RANK_PRIZE_USD,<br>        T3_RANK_CNT_TOURNAMENTS AS T4_RANK_CNT_TOURNAMENTS,<br>        T3_RANK_CNT_PLAYERS AS T4_RANK_CNT_PLAYERS,<br>        COUNT(DISTINCT T3_TOURNAMENT_ID) AS T4_CNT_TOURNAMENTS, -- how many tournaments has played each player<br>        COUNT(DISTINCT T3_YEAR_OF_TOURNAMENT) AS T4_CNT_YEAR_OF_TOURNAMENT, -- how many years the player played<br>        -- here is not correct to COUNT PLAYERS. I needed to know, how many years !every! player played tournaments<br>        T3_PLAYER_ID AS T4_PLAYER_ID,<br>        SUM(T3_SUM_PRIZE_USD) AS T4_SUM2_PRIZE_USD,<br>        ISMORETHAN_QUA AS T4_ISMORETHAN_QUA<br>    FROM<br>------------------------------------------------------------------  a<br>        (<br>        SELECT <br>            t1.TOURNAMENT_ID AS T3_TOURNAMENT_ID,<br>            t1.YEAR_OF_TOURNAMENT AS T3_YEAR_OF_TOURNAMENT,<br>            t1.PLAYER_ID AS T3_PLAYER_ID,<br>            SUM(t1.SUM_PRIZE) AS T3_SUM_PRIZE_USD,<br>            t1.GAME_ID AS T3_GAME_ID,<br>            t2.G_GAME_NAME AS T3_GAME_NAME,<br>            t2.G_RANK_PRIZE_USD AS T3_RANK_PRIZE_USD,<br>            t2.G_RANK_CNT_TOURNAMENTS AS T3_RANK_CNT_TOURNAMENTS,<br>            t2.G_RANK_CNT_PLAYERS AS T3_RANK_CNT_PLAYERS<br>        FROM TEMP01_PLA_GAME_YEAR t1 <br>        JOIN GAME t2 ON t2.G_GAME_ID=T3_GAME_ID<br>        GROUP BY     <br>            T3_GAME_ID,<br>            T3_GAME_NAME,<br>            T3_RANK_PRIZE_USD,<br>            T3_RANK_CNT_TOURNAMENTS,<br>            T3_RANK_CNT_PLAYERS,<br>            T3_TOURNAMENT_ID,<br>            T3_YEAR_OF_TOURNAMENT,<br>            T3_PLAYER_ID<br>        ) t3 -- 306 541 roes<br>------------------------------------------------------------------  a<br>    JOIN TEMP03_PLAYER_GAME_AVG_MED_QUA t5 ON t5.GAME_ID=T4_GAME_ID AND t5.PLAYER_ID=T4_PLAYER_ID    <br>    GROUP BY<br>        T4_GAME_ID,<br>        T4_GAME_NAME,<br>        T4_RANK_PRIZE_USD,<br>        T4_RANK_CNT_TOURNAMENTS,<br>        T4_RANK_CNT_PLAYERS,<br>        T4_PLAYER_ID,<br>        T4_ISMORETHAN_QUA -- an indicator if player is TOP or Casual player according to quantil 0,9<br>    ) t4 -- 79 504 rows<br>------------------------------------------------------------------  b<br>GROUP BY <br>    GAME_ID,<br>    GAME_NAME,<br>    RANK_PRIZE_USD,<br>    RANK_CNT_TOURNAMENTS,<br>    RANK_CNT_PLAYERS,<br>    ISMORETHAN_QUA<br>) -- 1031 rows<br><br>SELECT <br>    GAME_ID AS W_GAME_ID, <br>    GAME_NAME AS W_GAME_NAME, <br>    RANK_PRIZE_USD AS W_RANK_PRIZE_USD,<br>    RANK_CNT_TOURNAMENTS AS W_RANK_CNT_TOURNAMENTS,<br>    RANK_CNT_PLAYERS AS W_RANK_CNT_PLAYERS,<br>    ISMORETHAN_QUA AS W_ISMORETHAN_QUA,  <br>    CNT_PLAYER AS W_CNT_PLAYERS, <br>    AVG_YEARS AS W_AVG_CNT_YEARS, <br>    SUM_PRIZE_USD AS W_SUM_PRIZE_USD<br>FROM CTE_WHOSEARLYERRETIRED_QUA<br>/* creating final table, where sample of players for a game <br>is more than 100 players (Because a smaller sample is not<br>statistically representative) */<br>WHERE W_GAME_ID IN <br>        (SELECT DISTINCT GAME_ID FROM<br>            (<br>            SELECT GAME_ID, SUM(CNT_PLAYER) AS SUM_PLAYERS<br>            FROM CTE_WHOSEARLYERRETIRED_QUA<br>            GROUP BY GAME_ID<br>            HAVING SUM_PLAYERS &gt;=100<br>            )<br>        );<br><br>-- 252 rows</pre><h3><strong>Part 4: Analyzing the number of players in countries</strong></h3><p>Go to the Detailed blog article about <a href="https://medium.com/@vtkncv/e-sport-part-4-analyzing-the-number-of-players-b066904ef750">Analyzing the number of players in countries</a></p><p>I determined the questions to test:<br><strong>a) Are there more players in richer countries?</strong><br>Indicators: <a href="https://ourworldindata.org/grapher/gdp-per-capita-worldbank">GDP per capita</a>, number of players per 1 million inhabitants.<br><strong>b) Are there more players in countries where the Internet is more widespread?</strong><br>Indicators: <a href="https://ourworldindata.org/grapher/share-of-individuals-using-the-internet">percentage of individuals using the Internet in the total population</a>, number of players per 1 million inhabitants.<br><strong>c) Are there more players in countries with more inhabitants?</strong><br>Indicators: <a href="https://ourworldindata.org/population-growth">population</a>, number of players.<br>Because e-sports players are most often between the ages of 15–24, we included this sub-category in our comparisons. (Available data ranged from 15 to 29).</p><p><strong>Statistics:</strong><br>Widespread data (<a href="https://www.wallstreetmojo.com/heteroskedasticity/">heteroscedasticity</a>), distant observations and many values right on the axes didn’t give an obvious and simple answer to my questions. For that reason, I decided to let the python calculate it more statistically.</p><ol><li>I set a Null hypothesis H0: Correlations exist, and the alternative hypothesis H1, correlations don’t exist.</li><li>I checked the linearity of the data (not all data are linear).</li><li>I checked the normality of data distribution (data are not normally distributed).</li><li>I chose a method (coefficient) for correlation comparison = Kendall Tau</li><li>I evaluated the results (all p-values are significantly less than 0.05 and therefore <strong>correlations exist).</strong></li></ol><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ZHAOpT0cvjLLxVp2JAD_Ew.png" /></figure><p><strong>Visualisations<br></strong>I made dashboards and charts in Tableau. Here is just a sample, for all of them with a description go to my <a href="https://medium.com/@vtkncv/e-sport-part-4-analyzing-the-number-of-players-b066904ef750">blog article</a> or <a href="https://public.tableau.com/app/profile/iveta.kuncova/vizzes">Tableau Public</a> (interactive).</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*P_oQBcVmq7mJyu6YbxlMzA.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*4ojaYjQbEfHc9ODF3bwHXA.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1007/1*rb58K6HS8i_pB_e_X4OdjA.png" /></figure><p>Go to the Detailed blog article about <a href="https://medium.com/@vtkncv/e-sport-part-4-analyzing-the-number-of-players-b066904ef750">Analyzing the number of players in countries</a></p><h3>Part 5: Analysing players’s active years in relation to prize money</h3><p>Go to the <a href="https://medium.com/@vtkncv/e-sport-part-5-analysing-playerss-active-years-in-relation-to-prize-money-8117bd6a6112">detailed blog article about Analysing players’s active years in relation to prize money</a></p><p>It is known, that e-sport players are very young. The average age they are retiring is 24 years. Why? <em>Slower reflexes, injuries like carpal tunnels, stress, financial reasons for non-tier-one players, change of games, </em><strong><em>and absolute lack of personal life. </em>Players are training <em>12 or more</em> hours every day.</strong></p><p><strong><em>I assumed that players with the highest prize money stay playing more years or months than the others.</em></strong></p><p>I divided the players into two groups. The 10 % of the best players with the highest prize money as <strong>“TOP” </strong>and the rest of the casual players as <strong>“Casual”</strong>. This grouping was made for each game separately because every game is different and has different needs of player’s skillset like quick reactions or logic and has different amount of prize money.</p><p><strong>Results</strong></p><p><strong>Most earning players are on average staying more years in gaming.</strong> This hypothesis was confirmed for 92 % of game titles. The average difference between TOP players and Casual players is 18,3 months of playing. With the rising Prize money in games, the difference grows to 24,5 months.<br>TOP players are on average about 7,56 months younger but with the rising Prize money in games, the average age difference declines to 2,64 months (21,16 years Cassual, 20,94 years TOP — for TOP 10 games). It means the TOP players on the top 10 games are 2,64 months younger than Casual players on average.</p><p>Even if the best of the best are naturally equipped with the skills needed to stay,<strong> money is also a significant motivating factor and my hypothesis was confirmed.</strong></p><p><strong>Visualisations</strong><br>I made dashboards and charts in Tableau. Here are just dashboards, for separate charts go to my <a href="https://medium.com/@vtkncv/e-sport-part-5-analysing-playerss-active-years-in-relation-to-prize-money-8117bd6a6112">blog article</a> or <a href="https://public.tableau.com/app/profile/iveta.kuncova/vizzes">Tableau Public.</a></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*cDWByw2qCvbJ8-E-IdhJpA.png" /><figcaption>Do you see the big peak at Starcraft II or an exception at PUBG? I am explaining it in <a href="https://medium.com/@vtkncv/e-sport-part-5-analysing-playerss-active-years-in-relation-to-prize-money-8117bd6a6112">my blog article Part 5.</a></figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*5UPYCZK-KPwARILzWdz_lA.png" /></figure><p>Go to the <a href="https://medium.com/@vtkncv/e-sport-part-5-analysing-playerss-active-years-in-relation-to-prize-money-8117bd6a6112">detailed blog article about Analysing players’s active years in relation to prize money</a></p><p>My <a href="https://github.com/IvetaKuncova/ESPORT"><strong>GitHub</strong></a>, my <a href="https://public.tableau.com/app/profile/iveta.kuncova/vizzes"><strong>Tableau Public</strong></a><strong><br>Next Part:</strong> <a href="https://medium.com/@vtkncv/e-sport-part-1-project-plan-and-preparation-98b5178845b5">E-sport/part 1: Project Plan and Preparation</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=e7b64cd37c84" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[E-sport/part 5: Analysing players’s active years in relation to prize money]]></title>
            <link>https://medium.com/@vtkncv/e-sport-part-5-analysing-playerss-active-years-in-relation-to-prize-money-8117bd6a6112?source=rss-029ab3d9933f------2</link>
            <guid isPermaLink="false">https://medium.com/p/8117bd6a6112</guid>
            <dc:creator><![CDATA[IvetaKuncova]]></dc:creator>
            <pubDate>Wed, 14 Feb 2024 10:06:49 GMT</pubDate>
            <atom:updated>2024-02-16T09:44:14.812Z</atom:updated>
            <content:encoded><![CDATA[<p>#tableau #dataanalysis #visualisations</p><p><strong>Previous part:</strong> <a href="https://medium.com/@vtkncv/e-sport-part-4-analyzing-the-number-of-players-b066904ef750">E-sport/part 4: Analyzing the number of players in countries</a><br><strong>Summary: </strong><a href="https://medium.com/@vtkncv/e-sport-data-analysis-project-summary-e7b64cd37c84">E-sport data analysis project: Summary</a><br>My <a href="https://github.com/IvetaKuncova/ESPORT"><strong>GitHub</strong></a>, my <a href="https://public.tableau.com/app/profile/iveta.kuncova/vizzes"><strong>Tableau Public</strong></a></p><p><strong>Table of contents:</strong><br>- <a href="#c8a3">Hypothesis</a><br>- <a href="#1bb2">Python web scrape</a><br>- <a href="#61f4">Aggregated tables in SQL</a><br>- <a href="#3557">Visualisations</a><br>- <a href="#528d">Statistics again</a></p><h3>Hypothesis</h3><p>It is known, that e-sport players are very young. The average age they are retiring is 24 years.</p><p>Why? <em>Slower reflexes, injuries like carpal tunnels, stress, financial reasons for non-tier-one players, change of games, </em><strong><em>and absolute lack of personal life.<br></em>Players are training <em>12 or more</em> hours every day.</strong></p><p><strong><em>I assumed that players with the highest prize money stay playing more years or months than the others.</em></strong></p><h3>Aggregated tables in SQL</h3><p>I divided the players into two groups. The 10 % of the best players with the highest prize money as <strong>“TOP” </strong>and the rest of the casual players as <strong>“Casual”</strong>. It’s called quantile 0.9. This grouping was made for each game separately because every game is different and has different needs of player’s skillset like quick reactions or logic and has different amount of prize money.</p><p>The sample on which was this statistic performed contained data for 70 521 players and 126 games. I excluded from the data games that had fewer than 100 active players.</p><p>I showed example of <a href="https://medium.com/@vtkncv/e-sport-part-3-sql-and-data-model-e0de520948ce#79d9">SQL script in my blog article Part 3.</a> unshortened scripts are on<em> my </em><a href="https://github.com/IvetaKuncova/ESPORT/blob/master/02%20SQL/04_SQL_AGG_RETIREMENT.sql">GitHub</a>.</p><h3>Visualisations</h3><p>I found out, that on average<strong> the TOP players, who earn more money from e-sports, are retiring later. </strong>In the line chart below you can see, that games with the highest Prize money have the biggest difference between TOP and Casual players. Also, the TOP players stay playing longer in games with the highest Prize money.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ubgHfdhSBSHQt7ANPYQMNw.png" /><figcaption>Games are ranked by Prize money in USD.</figcaption></figure><p>This hypothesis was confirmed for 92 % of game titles.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*tE8cZxooaG8k1_e-zx2qRw.png" /><figcaption>Donut charts in Tableau are not included in the default menu, you<a href="https://www.youtube.com/watch?v=ZfpUzp8mBSw"> have to b</a>uild them by calculations and dual axes.</figcaption></figure><p>It was also interesting to look at the average number of active playing years within the 10 games with the highest win totals. The only <strong>exception here is</strong> <strong>PUBG </strong>where the Top players retire 7 months earlier, although<strong> PUBG mobile</strong> is not the exception and TOP players are retiring 12 months later than Casual. But PUBG players are a little bit older than PUBG mobile (about 2 years on average) and that is probably the reason.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*3vqbUe8yt3HTIEX6PnxDAQ.png" /><figcaption>You can notice the “bar in a bar chart”, which also need a little bit of<a href="https://www.youtube.com/watch?v=bjy2tZhZQWk"> extra work</a>.</figcaption></figure><p>Interesting is also the high peak of TOP players of <strong>Starcraft II</strong> game, which are playing 7,7 years on average (the highest difference (of 5,7 years) at all games).<br> Starcraft II is a Real-time strategy game, released in 2010. The high number of years is probably caused by its <strong>popularity, especially in South Korea</strong> and by the fact <strong>it has the maximum number of Tournaments held: 7 235 (rank 1) from all games,</strong> but “only” 2 209 players (rank 14) — so there is no such pressure as in games with more competitors and players can play longer calmly. It’s played in tournaments until now (14 years), which is also one factor for a high number of active playing years. <br>In the table below, you can see the TOP 18 games according to the number of active years with tournaments (24–14 years). The high difference between TOP and Casual in these ‘old’ games is standard.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*L6TMY0NOFT9ueTDs6kQYRg.png" /></figure><h3>Python web scrape</h3><p><strong>The age of the players:</strong></p><p>To monitor the age of the players, I used a sample of almost 13 000 players. For the rest of the players, the data with the date of birth was not filled in on the EsportsEarnings website, which I scraped via Python.</p><p><a href="https://medium.com/@vtkncv/e-sport-part-2-python-acb60fb6d58b#328d">Blog with information about script</a> or <a href="https://github.com/IvetaKuncova/ESPORT/tree/master/01%20python/SCRAPE">Github with script</a></p><p>The TOP players do beat Casual players in terms of the number of years played, but at the same time, they are slightly younger on average and also on the maximum age. It’s nicely to see it on the chart below:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/660/1*qnP9b-5z2v4X0_5kUX4QYg.png" /><figcaption>Rounded bar chart, dual axis for the lines and change of pane coloring.</figcaption></figure><p>For the top 10 games with the highest prize money, I used a heatmap on the dashboard below.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/783/1*Zc3x6M4x9XXsMxJqarDGHg.png" /></figure><p>On the chart below, you can see, that most of the players have been playing in tournaments for just one year.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*_y0P6QvMpD9kYVSW40oRyA.png" /></figure><p><strong>Results</strong></p><p>Most earning players are on average staying more years in gaming. The question is if they are naturally more adapted to stress and lack of life or other disadvantages of e-sport or if the money is just motivating them to stay in play.</p><p>The average difference between TOP players and Casual players is 18,3 months of playing. With the rising Prize money in games, the difference grows to 24,5 months.<br>TOP players are on average about 7,56 months younger but with the rising Prize money in games, the average age difference declines to 2,64 months (21,16 years Cassual, 20,94 years TOP — for TOP 10 games). It means the TOP players on the top 10 games are 2,64 months younger than Casual players on average.</p><p>Even if the best of the best are naturally equipped with the skills needed to stay,<strong> money is also a significant motivating factor and my hypothesis was confirmed.</strong></p><h3>Statistic again</h3><p>Did you notice a flaw in the analysis?<br><strong>The samples</strong> of TOP and Casual players <strong>are not the same size</strong> (in total TOP players: 7 367, Casual players: 7 367. This big difference can cause inaccuracy or bias in the result because the bigger number has a bigger chance of having a bigger variance in observations. It is reduced by using Average values (SUM of the sample values/ number of observations)</p><p>I used <strong>Welch’s T-test </strong>(for data samples with different variances which I found out from Brown-Forsythe test for non-normally distributed data) t<strong>o test the null hypothesis that two differently sized populations (TOP and Casual) have equal MEANS (</strong>for value<strong> years of active playing).</strong> I tested all games in total.<br>The T-value 72,6 is bigger than the Critical value 6,869 (degrees of freedom 5,25, one-tailed) with the P-value 0,0005 (the chance the result is just a coincidence is really small). The null hypothesis is rejected.<br>These numbers are saying <strong>that the means for value years of active playing are not equal.</strong></p><p>I also checked <strong>Kruskal-Wallis test to test the null hypothesis that two differently sized populations </strong>(TOP and Casual)<strong> have equal MEAN of RANKS (</strong>for value<strong> years of active playing). </strong>The mean of ranks for the TOP group of players is 37 223,9 and for the Casual group is 61 056,8.</p><p>H value 8 130,69 &gt; critical value 3,84, which means I rejected the null hypothesis that MEAN of RANKS are the same. In other words, <strong>TOP and Casual players don’t have the same means of ranks.</strong></p><p><strong><em>Fun fact:</em></strong><em> The eldest players are up to 71 years of age and their game of choice is any variant of e-chess (Playchess.com, Chess.com, Lichess).</em></p><p>My <a href="https://github.com/IvetaKuncova/ESPORT"><strong>GitHub</strong></a>, my <a href="https://public.tableau.com/app/profile/iveta.kuncova/vizzes"><strong>Tableau Public</strong></a><br><strong>Previous part:</strong> <a href="https://medium.com/@vtkncv/e-sport-part-4-analyzing-the-number-of-players-b066904ef750">E-sport/part 4: Analyzing the number of players in countries</a><br><strong>Summary: </strong><a href="https://medium.com/@vtkncv/e-sport-data-analysis-project-summary-e7b64cd37c84">E-sport data analysis project: Summary</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=8117bd6a6112" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[E-sport/part 4: Analyzing the number of players in countries]]></title>
            <link>https://medium.com/@vtkncv/e-sport-part-4-analyzing-the-number-of-players-b066904ef750?source=rss-029ab3d9933f------2</link>
            <guid isPermaLink="false">https://medium.com/p/b066904ef750</guid>
            <dc:creator><![CDATA[IvetaKuncova]]></dc:creator>
            <pubDate>Wed, 14 Feb 2024 10:01:45 GMT</pubDate>
            <atom:updated>2024-02-16T19:29:33.169Z</atom:updated>
            <content:encoded><![CDATA[<p>#dataanalysis #tableau #python #statistic #SQL</p><p><strong>Previous part: </strong><a href="https://medium.com/@vtkncv/e-sport-part-3-sql-and-data-model-e0de520948ce">E-sport/part 3: Keboola, SQL and data model</a><br><strong>Next part:</strong><a href="https://medium.com/@vtkncv/8117bd6a6112"> E-sport/part 5: Analysing players’s active years in relation to prize money</a><br><strong>Summary:</strong><a href="https://medium.com/@vtkncv/e-sport-data-analysis-project-summary-e7b64cd37c84"><strong> </strong>E-sport data analysis project: Summary</a><br>My <a href="https://github.com/IvetaKuncova/ESPORT"><strong>GitHub</strong></a>, my <a href="https://public.tableau.com/app/profile/iveta.kuncova/vizzes"><strong>Tableau Public</strong></a></p><p><strong>Table of contents:</strong><br>- <a href="#c285">Hypotheses</a><br>- <a href="#1519">Aggregating tables via SQL</a><br>- <a href="#705f">Statistics in Python</a><br>- <a href="#5016">Visualisation in Tableau</a></p><h3>Hypotheses:</h3><p>I wanted to find out <strong>which countries have the most players, </strong>or what such countries have in common. I expected it would be a country economically and technically developed and with many residents.</p><p>I determined questions to test:</p><p><strong>a) Are there more players in richer countries?</strong><br>Indicators: <a href="https://ourworldindata.org/grapher/gdp-per-capita-worldbank">GDP per capita</a>, number of players per 1 million inhabitants.</p><p><strong>b) Are there more players in countries where the Internet is more widespread?</strong><br>Indicators: <a href="https://ourworldindata.org/grapher/share-of-individuals-using-the-internet">percentage of individuals using the Internet in the total population</a>, number of players per 1 million inhabitants.</p><p><strong>c) Are there more players in countries with more inhabitants? </strong><br>Indicators: <a href="https://ourworldindata.org/population-growth">population</a>, number of players.<br>Because e-sports players are most often between the ages of 15–24, we included this sub-category in our comparisons. (Available data ranged from 15 to 29).</p><h3>Aggregating tables via SQL</h3><p>For visualization in Tableau and statistics in Python I needed one aggregated denormalized table with prepared data.</p><p>I showed this script in an <a href="https://medium.com/@vtkncv/e-sport-part-3-sql-and-data-model-e0de520948ce">blog article about SQL.</a><br>Or You can see the script on <a href="https://github.com/IvetaKuncova/ESPORT/blob/master/02%20SQL/04_SQL_AGG_PLAYER_CORRELATIONS.sql">GitHub</a></p><h3>Statistic in Python</h3><p>Whole script on <a href="https://github.com/IvetaKuncova/ESPORT/tree/master/03%20correlation%20statistics%20-%20esport%20players">GitHub</a>.</p><p>Before this project, I had no experience with statistical science.</p><p>As I said, I expected strong correlations and linearity something like in the picture below:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*dvHkRod5snbyNng4wJk1IQ.png" /><figcaption>Expectations: linear data, strong correlation.</figcaption></figure><p>But this was what I got:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*-2_ulUOWkuwxj5_naEVpGg.png" /><figcaption>Reality</figcaption></figure><p>Widespread data (<a href="https://www.wallstreetmojo.com/heteroskedasticity/">heteroscedasticity</a>), distant observations and many values right on the axes didn’t give an obvious and simple result. For that reason, I decided to let the python calculate it more statistically.</p><ol><li>I set a Null hypothesis H0: Correelations exist, and the alternative hypotesis H1, correlations don’t exist.</li><li>I checked the linearity of the data.</li><li>I checked the normality of data distribution.</li><li>I chose a method (coefficient) for correlation comparison.</li><li>I evaluated results.</li></ol><p>For selecting proper correlation coefficient is necessary to check linearity and data distribution, otherwise, you will have biased results.</p><h4>add 2. Linearity check</h4><p>Data linearity is a concept used to describe the relationship between two variables. If the relationship between two variables is linear, then the relationship can be expressed as a straight line as in the picture above (Expectations pic.).</p><p><strong>Python: seaborn.scatterplot()</strong><br>This method plots a scatterplot for two variables. If the data is linear, the points on the scatterplot will follow a decreasing or increasing line, see the figure to the right:</p><pre># from The jupyter notebook:<br>import seaborn as sns<br><br>sns.scatterplot(data=data, x=&quot;Avg. GDP per capita&quot;, y=&quot;No. of players/mil. inhabitants&quot;, color=&quot;blue&quot;)<br><br>sns.scatterplot(data=data, x=&quot;Avg. perc. of inhabitants using the Internet&quot;, y=&quot;No. of players/mil. inhabitants&quot;, color=&quot;blue&quot;)<br><br>sns.scatterplot(data=data, x=&quot;Avg. population&quot;, y=&quot;No. of players&quot;, color=&quot;blue&quot;)<br><br>sns.scatterplot(data=data, x=&quot;Avg. population aged 15-19 years&quot;, y=&quot;No. of players&quot;, color=&quot;blue&quot;)</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/668/1*jLSZMT5Ow5mD44HNVigAvQ.png" /></figure><p><strong>Result: Not all data are clearly linear.</strong></p><h4>add. 3. Normal distribution check</h4><p><strong>Python: scipy.normaltest() = D’Agostino and the Pearson test:</strong><br>Based on a combination of skewness and peakedness of the data curve, it tests whether the sample comes from a normal distribution. The normal distribution is always tested for one column of the table.<br><strong>P-value:</strong> expresses the probability that a value of the test statistic that is at least as large as the observed value would occur by chance if the data came from a normal population.<br>If the p-value is less than some predetermined threshold (0.05), then the data do not come from a normal distribution.</p><pre># Normal distribution test:<br># Normal distribution is always tested for one column of the table.<br># If the p-value is less than a certain pre-set threshold (0.05), <br># then the data do not come from a normal distribution.<br><br>print(stats.normaltest(data[&quot;No. of players&quot;]))<br>print(stats.normaltest(data[&quot;No. of players/mil. inhabitants&quot;]))<br>print(stats.normaltest(data[&quot;Avg. GDP per capita&quot;]))<br>print(stats.normaltest(data[&quot;Avg. population&quot;]))<br>print(stats.normaltest(data[&quot;Avg. population aged 15219 years&quot;]))<br>print(stats.normaltest(data[&quot;Avg. perc. of inhabitants using the Internet&quot;]))</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1006/1*sT0WCeuFzTYTxnYC4WP7yw.png" /><figcaption>Scientific notation (E-form) is what I originally got from Python, because the normal notation number is very low and long.</figcaption></figure><p><strong>Results: The P-value is less than 0.05, data are not normally distributed.</strong></p><h4>add 4. Kendall Tau Correlation Coefficient</h4><p>Kendall’s Tau is a non-parametric correlation metric that measures the directional correlation between two sequences. It does not require linear data in a normal distribution.</p><p><strong>Python: scipy.kendalltau()</strong><br>Resulting indicators:<br>“<strong>Statistic</strong>” is the measure of correlation between the two data sets being compared. It is used to test the hypothesis of correlation between H0 and H1. The closer the number is to 1 or -1, the stronger the correlation.</p><p>It can take values from -1 to 1:<br>-1 means a negative correlation<br> 0 means no correlation<br> 1 means a positive correlation</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/834/1*mBi-2N4y-XIZcezyOeMcWA.png" /></figure><p>“<strong>P-value</strong>” is a statistical tool used to test hypotheses. In this case, the null hypothesis is that there is no association between the two sets of data (i.e. tau = 0). If the p-value is less than some predetermined threshold (often 0.05), then we reject the null hypothesis H0 and accept the alternative hypothesis H1 that there is some association between the two sets of data. If the p-value is greater than this threshold, then we cannot reject the null hypothesis.</p><pre># Correlation analysis:<br>print(stats.kendalltau(data[&quot;Avg. population&quot;], data[&quot;No. of players&quot;]))<br>print(stats.kendalltau(data[&quot;Avg. perc. of inhabitants using the Internet&quot;], data[&quot;No. of players/mil. inhabitants&quot;]))<br>print(stats.kendalltau(data[&quot;Avg. GDP per capita&quot;], data[&quot;No. of players/mil. inhabitants&quot;]))<br>print(stats.kendalltau(data[&quot;Avg. population aged 15-29 years&quot;], data[&quot;No. of players&quot;]))</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*qW2mMF8IrHSjdZgqiTTwJA.png" /><figcaption>Results from Python with detailed numbers</figcaption></figure><p><strong>Results:</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ZHAOpT0cvjLLxVp2JAD_Ew.png" /><figcaption>via canva.com</figcaption></figure><p>All p-values are significantly less than 0.05 and therefore <strong>correlations exist</strong>, we reject Hypotheses H0 and confirm Hypotheses H1.</p><h3>Visualisations in Tableau</h3><p>Interactive version of my visualisations on my <a href="https://public.tableau.com/app/profile/iveta.kuncova/viz/E-sport_playercorrelationsDESKTOP/GDP_per_capita">Tableau Public</a>.</p><p>There are two views on “ the Number of players “— absolute numbers and related to population size. I used both as appropriate for the selected indicator.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*P_oQBcVmq7mJyu6YbxlMzA.png" /><figcaption>TOP 11 countries from both columns (some countries are in both, therefore I took one more country to fill 20)</figcaption></figure><p>I distinguished continents by colors in the following visualizations just from curiosity.</p><p><strong>a) Are there more players in richer countries?</strong><br>Yes: moderate correlation, but high heteroscedasticity</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*JhQ7liHzyKsOn-Z5EWJHVg.png" /></figure><p><strong>b) Are there more players in countries where the Internet is more widespread?</strong><br>Yes: strong correlation, but high heteroscedasticity</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*hIrlBAbOCxURwbtWf9ygLA.png" /></figure><p><strong>c) Are there more players in countries with more inhabitants? </strong><br>No: weak correlation and high heteroscedasticity<br>The correlation exists (more inhabitants -&gt; more players), but is weak and not enough to be an exact indicator for more players.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*BvHdkcXhxSKuYu2uzK37YA.png" /></figure><h3>Conclusions</h3><p>For all three hypotheses apply:</p><ul><li>Existing positive correlation / direct and proportional relationship (e.g. more residents -&gt; more players)</li><li>Weak linearity</li><li>Strong heteroscedasticity</li></ul><p>I was not satisfied with these ambiguous results. Correlations exist, but any indicator is not good enough to explain “the recipe for high concentration of players in countries”.</p><p><strong>The best results are with combined indicators.</strong> I took the rank of every indicator and combined them. The lower the rank is, the better the country is. (More players, high GDP per capita, bigger population and bigger share of individuals using the Internet).</p><p>As you can see from the trend line on the graph according to its slope, correlation is very strong and linearity is also clear.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1007/1*rb58K6HS8i_pB_e_X4OdjA.png" /></figure><h3>Bonus vizes:</h3><p>For fun and the joy of learning I made these two visualizations. As it happens with “artsy vizes”, it is not good to understand what it is saying about data. But I just wanted to try something “cool”.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/985/1*QJ1MRofidlWuCmDIPhs4dw.png" /><figcaption>Radial line charts visualization (also known as “starburst”)</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/704/1*emzpyl2eaKxt7TIP7gBmGg.png" /><figcaption>Radial bar chart</figcaption></figure><p>My <a href="https://github.com/IvetaKuncova/ESPORT"><strong>GitHub</strong></a>, my <a href="https://public.tableau.com/app/profile/iveta.kuncova/vizzes"><strong>Tableau Public</strong></a><br><strong>Next part:</strong> <a href="https://medium.com/@vtkncv/8117bd6a6112">E-sport/part 5: Analysing players’s active years in relation to prize money</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=b066904ef750" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[E-sport/part 3: Keboola, SQL and data model]]></title>
            <link>https://medium.com/@vtkncv/e-sport-part-3-sql-and-data-model-e0de520948ce?source=rss-029ab3d9933f------2</link>
            <guid isPermaLink="false">https://medium.com/p/e0de520948ce</guid>
            <dc:creator><![CDATA[IvetaKuncova]]></dc:creator>
            <pubDate>Wed, 14 Feb 2024 09:58:32 GMT</pubDate>
            <atom:updated>2024-02-16T09:43:34.152Z</atom:updated>
            <content:encoded><![CDATA[<p>#sql #snowflake #keboola # datamodel</p><p><strong>Previous part: </strong><a href="https://medium.com/@vtkncv/e-sport-part-2-python-acb60fb6d58b">E-sport/part 2: Python</a><br><strong>Next part:</strong> <a href="https://medium.com/@vtkncv/e-sport-part-a-analyzing-the-number-of-players-b066904ef750">E-sport/part 4: Analyzing the number of players in coutries</a><br><strong>Summary: </strong><a href="https://medium.com/@vtkncv/e-sport-data-analysis-project-summary-e7b64cd37c84">E-sport data analysis project: Summary</a><br>My <a href="https://github.com/IvetaKuncova/ESPORT"><strong>GitHub</strong></a>, my <a href="https://public.tableau.com/app/profile/iveta.kuncova/vizzes"><strong>Tableau Public</strong></a></p><p><strong>Table of content: areas where was SQL used:</strong><br>1) <a href="#1ddd">UNIONing files and cleansing data</a><br>2) <a href="#b326">Preparing URLs for web scraping Date of Birth</a><br>3) <a href="#585e">Creating normalized tables according to the data model</a><br>4)<a href="#ff92"> Aggregating tables for visualizations</a><br> <a href="#f484">4 A) “Correlations of players”</a><br><a href="#79d9"> 4 B) “Retirement of players”</a></p><p><strong>Used functions:<br>- </strong>CTE, SUBSELECTS, CREATE (TEMPORARY) TABLE<br>- ALTER TABLE, UPDATE, ADD COLUMN, DROP COLUMN, INSERT VALUES<br>- (LEFT) JOIN, UNION (ALL)<br>- WINDOW FUNCTIONS (RANK), CASE WHEN, DISTINCT<br>- Aggregations: SUM, COUNT, MEDIAN, AVG, MIN, MAX, PERCENTILE_CONT<br>- Text functions: TRIM, REPLACE, TRANSLATE, LISTAGG, REGEXP_SUBSTR, CONCAT, LOWER, (I)LIKE (ANY), IFFNULL, TRANSLATE, CONCAT<br>- Date functions: TO_DATE, DATE, YEAR.</p><h3>1) UNIONing files and cleansing data</h3><p><em>Unshortened scripts: </em><a href="https://github.com/IvetaKuncova/ESPORT/blob/master/02%20SQL/01_SQL_UNIONS_CLEANSING.sql"><em>GitHub</em></a><br>There was approx. 100 files after the downloading phase. I uploaded all CSV files to the “Storage” in the <strong>Keboola</strong> cloud data operations platform (weirdly Keboola does not accept JSON formats) and I started merging files in Keboola’s “Workspaces” (safe sandbox for testing) with SQL in Snowflake, which is Keboola providing.</p><p>After first unioning files in Keboola’s Workspaces, I filtered error IDs, that were not downloaded, and I downloaded them again. I uploaded these new files to Keboola and added them to unioning SQL statements to retrieve complete datasets. After that, I took the queries from “Workspaces” and copied them to the Keboolas “Transformations” (Production environment) to gain result tables.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*nBqQ8NYQCLCL53IwOoXPxg.png" /><figcaption>Keboola Transformations enviroment</figcaption></figure><p><strong>The goal for this phase was to have 1 complete file per API.<br></strong><em>Unshortened scripts: </em><a href="https://github.com/IvetaKuncova/ESPORT/blob/master/02%20SQL/01_SQL_UNIONS_CLEANSING.sql"><em>GitHub</em></a><em>.</em></p><pre>-- Shortened example of merging files and cleansing<br>/* Rows needed to be unique, UNION is used to get rid of<br>unwanted duplicates created when downloading data.*/<br><br>CREATE OR REPLACE TEMPORARY table TEMP_API01_PLAYER_UNIONED AS<br>/*in the source data were some players with different<br>records which differed only in the WorldRanking or <br>CountryRanking columns. I used MIN() function to remove these<br>duplicates. The duplicity was across more files, <br>therefore it was necessary to union files at first <br>and then filter them.*/<br>SELECT <br>    &quot;PlayerId&quot;<br>    &quot;NameFirst&quot;, <br>    &quot;NameLast&quot;, <br>    &quot;CurrentHandle&quot;,<br>    MIN(&quot;WorldRanking&quot;) as &quot;WorldRanking&quot;, <br>    MIN(&quot;CountryRanking&quot;) as &quot;CountryRanking&quot;, <br>    &quot;TotalUSDPrize&quot;, <br>    &quot;TotalTournaments&quot;,<br>    &quot;CountryCode&quot;<br>FROM ( <br>     SELECT *<br>     FROM &quot;01PlayerById_vystup001000-1999&quot; -- 01<br>  UNION<br>     -- (...) I skipped 16 files, with the same Querry<br>     SELECT *<br>     FROM &quot;01PlayerById_vystup_errorids2&quot; -- 18<br>     )<br>GROUP BY <br>  &quot;PlayerId&quot;, &quot;NameFirst&quot;, &quot;NameLast&quot;, &quot;CurrentHandle&quot;, <br>  &quot;TotalUSDPrize&quot;, &quot;TotalTournaments&quot;, &quot;CountryCode&quot;;<br><br>-- data cleansing (examples)<br>UPDATE TEMP_API01_PLAYER_UNIONED <br>SET &quot;NameFirst&quot; = TRIM(&quot;NameFirst&quot;, &#39;-&#39;);<br>UPDATE TEMP_API01_PLAYER_UNIONED <br>SET &quot;NameFirst&quot; = null<br>WHERE &quot;NameFirst&quot; IN (&#39;-&#39;, &#39;&#39;, &#39;?&#39;, &#39;.&#39;) <br>  OR lower(&quot;NameFirst&quot;) = &#39;null&#39;;<br><br>-- duplicate record, which must be deleted<br>DELETE FROM TEMP_01API_PLAYER_UNIONED<br>WHERE &quot;WorldRanking&quot; = &#39;2443&#39;;<br>/* This one player had two rows with more than WorldRanking <br>difference (TotalUSDPrize and TotalTournaments)<br>WorldRanking    TotalUSDPrize   TotalTournaments    PlayerId<br>2443            117432.53      70                   52762<br>2417            119231.28      71                   52762<br>*/<br><br>DELETE FROM TEMP_01API_PLAYER_UNIONED<br>WHERE &quot;CurrentHandle&quot; ILIKE &#39;%please delete%&#39;;<br>/*<br>NameFirst  NameLast CurrentHandle               PlayerId<br>please     delete   please delete (duplicate)   59935<br>please     delete   please delete                      9195<br>Please     Delete   Please delete                   53229<br>please     delete   duplicate please delete         73341<br>*/<br><br>/*create a final table without null rows (except column<br>&quot;PlayerId&quot;, which is filled even if the player ID does not exists. <br>I was adding IDs automatically in the Python scripts)*/<br>CREATE OR REPLACE table API01_PLAYER AS <br>  SELECT *<br>  FROM TEMP_API01_PLAYER_UNIONED <br>EXCEPT<br>  SELECT *<br>  FROM TEMP_API01_PLAYER_UNIONED <br>  WHERE &quot;NameFirst&quot; is null <br>        AND &quot;NameLast&quot; is null <br>        AND &quot;CurrentHandle&quot; is null <br>        AND &quot;CountryCode&quot; is null <br>        AND &quot;WorldRanking&quot; is null <br>        AND &quot;CountryRanking&quot; is null <br>        AND &quot;TotalUSDPrize&quot; is null <br>        AND &quot;TotalTournaments&quot; is null;</pre><h3>2) Preparing URLs for web scraping Date of Birth</h3><p><em>Unshortened scripts: </em><a href="https://github.com/IvetaKuncova/ESPORT/blob/master/02%20SQL/02_SQL_URLs_for_web_scrape.sql"><em>GitHub</em></a><br>Python script for web scrape:</p><p>Because the API outputs didn’t contain the players’s Date of Birth, but it was on websites, I knew we could web scrape it.<br><strong>I had to prepare a list of web addresses</strong>, from which will be dates scraped.</p><p>The one address looks like this:<br>https://www.esportsearnings.com/players/14671-miracle-amer-al-barkawi<br>It consists of four parts separated by &quot;-&quot;:<br>https://www.esportsearnings.com/players/<br>PlayerID - NickName - FirstName - LastName</p><p>All parts were in the API outputs, hence I had everything needed.<br>I had to edit all three name parts using UTF-8, to get rid of non-ASCII characters not supported by web links (e.g. êøД神ßλ).</p><p>I filtered all unwanted characters for each column as in the example:</p><pre>SELECT <br> LISTAGG(DISTINCT(REGEXP_SUBSTR(&quot;NameLast&quot;, &#39;[^0-9a-zA-Z]&#39;)), &#39;&#39;)<br> WITHIN GROUP(ORDER BY REGEXP_SUBSTR(&quot;NameLast&quot;, &#39;[^0-9a-zA-Z]&#39;)) <br> AS UNWANTED<br>FROM API01_PLAYER;</pre><p><strong>Characters are divided into 3 groups:</strong><br>- Characters to substitute with other ones (ě -&gt; e),<br>- Characters to delete (お)<br>- Special characters to substitute with multiple characters (‘Æ’ -&gt; ‘ae’)</p><pre>-- Shortened example:<br>CREATE OR REPLACE TEMPORARY table TEMP_LINK AS<br>SELECT <br>&quot;PlayerId&quot;, <br>RTRIM(REPLACE(REPLACE(REPLACE(REPLACE(TRANSLATE(&quot;NameFirst&quot;,<br>/* Characters &#39;._ Á&#39; to &#39;ň&#39; were replaced by characters <br>bellow (&#39;---aa ...)*/<br>/* Characters or symbols from Cyrillic, Chinese, Japanesse etc.<br>alphabets were deleted*/<br>&#39;._ ÁÅÇÈÉÍÐÓÖØÞàáâãäåçèéêëìíîïñòóôõöøùúüýþĀāăĄčĐđĒėěğĩīİŁłŅ<br>ŐőřśŞşŠšũūŽžơưȘșţ̦̣̀́̂̌ẠạảấầẩậắếềễệịọốồổộợừửữỳņżặớờứÂÔÜēęĢģļň <br><br>&quot;⁬ΑΚАБЕКОгеёı渡?ιвнос​‎‏’辺﻿μдиртίайλοςΝВГДИМСлмỗụự神кь龙&#39;, <br>/* these are the characters that replaced the ones above:*/<br>&#39;---aaceeidooodaaaaaaceeeeiiiinoooooouuuydaaaacddeeegiiilln<br>oorsssssuuzzousstaaaaaaaaeeeeioooooouuuynzaoouaoueeggln&#39;), <br>/* These special characters were replaced <br>by other groups of characters*/<br>&#39;Æ&#39;, &#39;ae&#39;), <br>&#39;ß&#39;, &#39;sz&#39;), <br>&#39;ð&#39;, &#39;eth&#39; ), <br>&#39;æ&#39;, &#39;ae&#39; ),<br>&#39;-&#39;) AS FIRSTNAME,<br>FROM API01_PLAYER;</pre><p>There were 8 combinations of FIRSTNAME, LASTNAME AND NICKNAME AND its missing variants, and also names of players from Asia had the Last name at the first place, which was taken in account in the case of HTTP addresses (Special Column “ShowLastNameFirst”, which was in data from APIs 08 and 10). It took 10 combinations together.</p><p><em>Unshortened scripts: </em><a href="https://github.com/IvetaKuncova/ESPORT/blob/master/02%20SQL/02_SQL_URLs_for_web_scrape.sql"><em>GitHub</em></a><em>.</em></p><pre>CREATE OR REPLACE table PLAYER_URL AS<br>WITH &quot;LastNameFirst&quot; AS (<br>SELECT DISTINCT &quot;PlayerId&quot; <br>FROM (<br>  SELECT &quot;PlayerId&quot; <br>  FROM API08_TOURNAMENT_INDIVIDUAL_RESULTS<br>  WHERE &quot;ShowLastNameFirst&quot; = 1<br>     UNION<br>  SELECT &quot;PlayerId&quot; <br>  FROM API10_TOURNAMENT_PLAYER_IN_TEAM_RESULTS<br>  WHERE &quot;ShowLastNameFirst&quot; = 1<br>     ))<br><br>SELECT <br>  CASE <br>  WHEN NICKNAME is null <br>       AND FIRSTNAME is null <br>       AND LASTNAME is null <br>  THEN lower(CONCAT(&#39;https://www.esportsearnings.com/players/&#39;, <br>      &quot;PlayerId&quot;, &#39;-&#39;)) <br>  WHEN NICKNAME is null AND FIRSTNAME is null <br>  THEN lower(CONCAT(&#39;https://www.esportsearnings.com/players/&#39;, <br>       &quot;PlayerId&quot;, &#39;-&#39;, LASTNAME))<br>  WHEN FIRSTNAME is null AND LASTNAME is null <br>  THEN lower(CONCAT(&#39;https://www.esportsearnings.com/players/&#39;, <br>       &quot;PlayerId&quot;, &#39;-&#39;, NICKNAME)) <br>  WHEN NICKNAME is null AND LASTNAME is null <br>  THEN lower(CONCAT(&#39;https://www.esportsearnings.com/players/&#39;, <br>       &quot;PlayerId&quot;, &#39;-&#39;, FIRSTNAME)) <br>  WHEN FIRSTNAME is null <br>  THEN lower(CONCAT(&#39;https://www.esportsearnings.com/players/&#39;, <br>       &quot;PlayerId&quot;, &#39;-&#39;, NICKNAME, &#39;-&#39;, LASTNAME))<br>  WHEN LASTNAME is null <br>  THEN lower(CONCAT(&#39;https://www.esportsearnings.com/players/&#39;, <br>       &quot;PlayerId&quot;, &#39;-&#39;, NICKNAME, &#39;-&#39;, FIRSTNAME))<br>  WHEN &quot;PlayerId&quot; IN (SELECT &quot;PlayerId&quot; FROM &quot;LastNameFirst&quot;) <br>       AND NICKNAME is null <br>  THEN lower(CONCAT(&#39;https://www.esportsearnings.com/players/&#39;, <br>       &quot;PlayerId&quot;, &#39;-&#39;, LASTNAME, &#39;-&#39;, FIRSTNAME)) <br>  WHEN &quot;PlayerId&quot; NOT IN (SELECT &quot;PlayerId&quot; FROM &quot;LastNameFirst&quot;) <br>       AND NICKNAME is null <br>  THEN lower(CONCAT(&#39;https://www.esportsearnings.com/players/&#39;, <br>       &quot;PlayerId&quot;, &#39;-&#39;, FIRSTNAME, &#39;-&#39;, LASTNAME)) <br>  WHEN &quot;PlayerId&quot; IN (SELECT &quot;PlayerId&quot; FROM &quot;LastNameFirst&quot;) <br>  /* set of players ids with Last-Name-First is much smaller then <br>  the opposite, therefore managing them first is quicker for <br>  processing */<br>  THEN lower(CONCAT(&#39;https://www.esportsearnings.com/players/&#39;, <br>       &quot;PlayerId&quot;, &#39;-&#39;, NICKNAME, &#39;-&#39;, LASTNAME, &#39;-&#39;, FIRSTNAME))<br>  ELSE lower(CONCAT(&#39;https://www.esportsearnings.com/players/&#39;, <br>       &quot;PlayerId&quot;, &#39;-&#39;, NICKNAME, &#39;-&#39;, FIRSTNAME, &#39;-&#39;, LASTNAME))  <br>  END AS &quot;URL&quot;,<br>  &quot;PlayerId&quot;<br>FROM TEMP_LINK AS TL<br>JOIN &quot;LastNameFirst&quot; AS L ON TL.&quot;PlayerId&quot;=L.&quot;PlayerId&quot; ;</pre><h3>3) Creating normalized tables</h3><p><em>Unshortened scripts: </em><a href="https://github.com/IvetaKuncova/ESPORT/blob/master/02%20SQL/03_SQL_CREATING_NORMALIZED_TABLES.sql"><em>GitHub</em></a><em>.</em><br>I made a data model via Lucidcharts.com:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*KQem8b520cOQKM0p5P8rHQ.png" /><figcaption>Data model</figcaption></figure><p>Then I started creating tables in SQL accordingly.<br>From 12 APIs were used only 6. The other APIs were lists of highest-earning Players, Games or Tournaments, but all information was in the 6 core APIs. This mistake cost me time spent on creating APIs, but I learned to have a data model and hypotheses in the beginning. These unused APIs were also a little bit complicated, so I learned some Python too.</p><p><em>Unshortened scripts: </em><a href="https://github.com/IvetaKuncova/ESPORT/blob/master/02%20SQL/03_SQL_CREATING_NORMALIZED_TABLES.sql"><em>GitHub</em></a><em>.</em></p><pre>-- Example:<br>-- creating a table of results of individual players in teams<br>CREATE OR REPLACE TABLE TOURNAMENT_RESULTS_PLAYER_IN_TEAM AS<br>WITH CTE_CNTPLAYERS AS (<br>SELECT <br>    &quot;TournamentId&quot;::int AS TOURNAMENT_ID,<br>    &quot;TournamentTeamId&quot;::int AS TOURNAMENT_TEAM_ID,<br>    /* Player&#39;s ID here was just placeholder for knowing, <br>    how many players were on the tournament. <br>    Number of players was the information we actually nedded. */<br>    IFNULL(COUNT(DISTINCT &quot;PlayerId&quot;),0)::int AS CNT_PLAYER_ID<br>FROM &quot;API10_TOURNAMENT_PLAYER_IN_TEAM_RESULTS&quot; <br>GROUP BY TOURNAMENT_ID, TOURNAMENT_TEAM_ID<br>ORDER BY TOURNAMENT_ID, TOURNAMENT_TEAM_ID, CNT_PLAYER_ID<br>)<br><br>SELECT <br>    des.&quot;TournamentId&quot;::int AS TRP_TOURNAMENT_ID,<br>    des.&quot;TournamentTeamId&quot;::int AS TRP_TOURNAMENT_TEAM_ID,<br>    des.&quot;PlayerId&quot;::int AS TRP_PLAYER_ID,<br>    /* Calculation of Prize money for one player o Tournament */<br>    (dev.&quot;PrizeUSD&quot;::float / (dev.&quot;UnknownPlayerCount&quot;::int +<br>     c.CNT_PLAYER_ID)) AS TRP_PRIZE_USD_FOR_PLAYER<br>FROM &quot;API10_TOURNAMENT_PLAYER_IN_TEAM_RESULTS&quot; des<br>LEFT JOIN &quot;API09_TOURNAMENT_TEAM_RESULTS&quot; dev ON <br>          dev.&quot;TournamentTeamId&quot;=des.&quot;TournamentTeamId&quot;<br>JOIN CTE_CNTPLAYERS c ON <br>          c.TOURNAMENT_TEAM_ID=des.&quot;TournamentTeamId&quot;<br>ORDER BY <br>   TRP_TOURNAMENT_ID, <br>   TRP_TOURNAMENT_TEAM_ID, <br>   TRP_PLAYER_ID;</pre><p>There also was some work updating Country names or code values to correct joining them between different tables.</p><pre>/* the character &quot;&#39;&quot; in the text &quot;Cote d&#39;Ivoire&quot; was tricky.<br>There can&#39;t be used double quotes: &quot;Cote d&#39;Ivoire&quot; in Snowflake,<br>but it can be handled with $$. */<br>UPDATE TEMP_POPULATION<br>SET POP_COUNTRY = &#39;Cote dIvoire&#39;<br>WHERE POP_COUNTRY = $$Cote d&#39;Ivoire$$;</pre><p>I found out that in database are placeholder IDs (“If a placement is associated with an unknown player, the “CurrentHandle” will be “##UNKNOWN##”. “PlayerId” in this instance is only used to return a unique row for each unknown player and can be discarded.”</p><p>For that reason I added 900 000 to them (max. player ID is about 135 000), and now I can distinguish them from original IDs, and I can easy filter them from real players by filtering &lt; 900000. But i a database with more than two users would be propriate to treat them more fool-proof.</p><pre>UPDATE TEMP_API08_TOURNAMENT_RESULTS_INDIVIDUAL_UNIONED<br>SET &quot;PlayerId&quot; = &quot;PlayerId&quot;::int+900000<br>WHERE &quot;CurrentHandle&quot; = &#39;##UNKNOWN##&#39;;</pre><p>At the and I checked if all players in tables 08 a 10 (Tournament results) are also in 01 Player table. And the same for tournaments in 07 Tournaments table. It turned out, they were not all there. Therefore I selected the missing data and inserted them into 01 Player and 07 Tournament tables. (I filtered out the fake IDs of players.)</p><p><em>Unshortened scripts: </em><a href="https://github.com/IvetaKuncova/ESPORT/blob/master/02%20SQL/03_SQL_CREATING_NORMALIZED_TABLES.sql"><em>GitHub</em></a><em>.</em></p><pre>-- adding records about players who are in API08_TOURNAMENT_INDIVIDUAL_RESULTS and API10_TOURNAMENT_PLAYER_IN_TEAM_RESULTS tables<br>-- but the are not not in PLAYER table<br>INSERT INTO PLAYER        <br>    (P_PLAYER_ID,<br>    P_NAME_FIRST,<br>    P_NAME_LAST,<br>    P_NICK_NAME,<br>    P_COUNTRY2CODE,<br>    P_PRIZE_USD)<br>-- select player detail data from table API08_TOURNAMENT_INDIVIDUAL_RESULTS (detailed data are not in normalized TOURNAMENT_RESULTS_INDIVIDUAL table)<br>SELECT <br>    DISTINCT &quot;PlayerId&quot;::int AS PLAYER_ID,<br>    &quot;NameFirst&quot; AS NAME_FIRST,<br>    &quot;NameLast&quot; AS NAME_LAST,<br>    &quot;CurrentHandle&quot; AS NICK_NAME,<br>    &quot;CountryCode&quot; AS COUNTRY2CODE,<br>    SUM(&quot;PrizeUSD&quot;)::float AS PRIZE_USD<br>    FROM API08_TOURNAMENT_INDIVIDUAL_RESULTS<br>    -- select id of players who are in TOURNAMENT_RESULTS_INDIVIDUAL table but not in PLAYERS table<br>        WHERE PLAYER_ID IN <br>        (SELECT * FROM<br>            (SELECT DISTINCT TRI_PLAYER_ID AS PLAYERID<br>            FROM TOURNAMENT_RESULTS_INDIVIDUAL<br>            EXCEPT<br>            (SELECT DISTINCT P_PLAYER_ID AS PLAYERID<br>            FROM PLAYER)<br>            )<br>        )<br>        -- PLAYER_IDs greater than 900,000 are not real IDs, <br>        -- they only serve as a placeholder to keep track of the number of players and their winnings when the player is unknown.<br>        AND PLAYER_ID &lt; 900000<br>    GROUP BY PLAYER_ID,NAME_FIRST,NAME_LAST,NICK_NAME,COUNTRY2CODE<br>UNION<br>    -- select player detail data from table API10_TOURNAMENT_PLAYER_IN_TEAM_RESULTS (detailed data are not in normalized TOURNAMENT_RESULTS_PLAYER_IN_TEAM table)<br>    SELECT <br>        DISTINCT &quot;PlayerId&quot;::int AS PLAYER_ID,<br>        &quot;NameFirst&quot; AS NAME_FIRST,<br>        &quot;NameLast&quot; AS NAME_LAST,<br>        &quot;CurrentHandle&quot; AS NICK_NAME,<br>        &quot;CountryCode&quot; AS COUNTRY2CODE,<br>        SUM(TRP_PRIZE_USD_FOR_PLAYER)::float AS PRIZE_USD<br>    FROM &quot;API10_TOURNAMENT_PLAYER_IN_TEAM_RESULTS&quot;<br>    LEFT JOIN TOURNAMENT_RESULTS_PLAYER_IN_TEAM ON PLAYER_ID=TRP_PLAYER_ID<br>    -- select id of players who are in  TOURNAMENT_RESULTS_PLAYER_IN_TEAM table but not in PLAYERS table<br>        WHERE PLAYER_ID IN (<br>        SELECT * FROM<br>        (SELECT DISTINCT TRP_PLAYER_ID AS PLAYERID<br>        FROM TOURNAMENT_RESULTS_PLAYER_IN_TEAM)<br>        EXCEPT<br>        (SELECT DISTINCT P_PLAYER_ID AS PLAYERID<br>        FROM PLAYER)<br>        ) <br>    GROUP BY PLAYER_ID, NAME_FIRST, NAME_LAST, NICK_NAME, COUNTRY2CODE<br>ORDER BY PLAYER_ID, NAME_FIRST, NAME_LAST, NICK_NAME, COUNTRY2CODE;</pre><h3>4) Aggregating tables for visualizations</h3><p><em>Unshortened scripts on GitHub: </em><a href="https://github.com/IvetaKuncova/ESPORT/blob/master/02%20SQL/04_SQL_AGG_PLAYER_CORRELATIONS.sql"><em>Player correlations</em></a><em> and </em><a href="https://github.com/IvetaKuncova/ESPORT/blob/master/02%20SQL/04_SQL_AGG_RETIREMENT.sql"><em>Player retirements</em></a><em>.</em></p><h4>A) “Correlations of players”</h4><p>Go to <a href="https://medium.com/@vtkncv/e-sport-part-4-analyzing-the-number-of-players-b066904ef750#5016">Blog article with visualisations.</a></p><p><em>See this code below without width limitation for display</em> <em>on my </em><a href="https://github.com/IvetaKuncova/ESPORT/blob/master/02%20SQL/04_SQL_AGG_PLAYER_CORRELATIONS.sql"><em>GitHub</em></a><em>.</em></p><pre>--  AGGREGATED DENORMALIZED TABLE FOR THE STATISTICS OF PLAYER CORRELATIONS IN PYTHON AND TABLEAU<br>CREATE OR REPLACE TABLE PLAYER_GDP_POP_INT AS<br>SELECT <br>    C_COUNTRY AS GPI_COUNTRY, <br>    C_CONTINENT AS GPI_CONTINENT, <br>    COUNT(DISTINCT P_PLAYER_ID)::int as GPI_CNT_PLAYER_ID, <br>    AVG(GDP_GDP_PER_CAPITA_USD)::float as GPI_AVG_GDP_PER_CAPITA, <br>    AVG(POP_POPULATION)::float as GPI_AVG_POPULATION, <br>    AVG(POP_POPULATION_AGED15_19+POP_POPULATION_AGED20_29)::float as GPI_AVG_POPULATION_AGED_15TO29, <br>    ((COUNT(DISTINCT P_PLAYER_ID)*1000000)/AVG(POP_POPULATION))::float as GPI_CNT_PLAYERS_ON_1MIL_POP,<br>    AVG(I_SHARE_OF_INDIVID_USING_INTERNET)::float as GPI_AVG_SHARE_OF_INDIVIDUALS_USING_INTERNET<br>FROM PLAYER a<br>LEFT JOIN COUNTRY c ON upper(P_COUNTRY2CODE)=C_COUNTRY2CODE<br>LEFT JOIN GDP_PER_CAPITA g ON C_COUNTRY2CODE=GDP_COUNTRY2CODE<br>LEFT JOIN POPULATION p ON POP_COUNTRY2CODE=C_COUNTRY2CODE<br>LEFT JOIN INTERNET s ON I_COUNTRY2CODE=C_COUNTRY2CODE<br>WHERE <br>    GDP_GDP_PER_CAPITA_USD is not null <br>    -- ALL TABLES NEED TO BE UNIFIED FOR THE SAME PERIOD 1997-2021 (TABLES GDP, POP, INT ARE UP TO 2021)<br>    AND GDP_YEAR &gt;= 1997 <br>    AND POP_YEAR &gt;= 1997 <br>    AND I_YEAR &gt;= 1997<br>    AND P_PLAYER_ID IN <br>        -- SELECT A PLAYER_ID OF EACH TOURNAMENT TO BE HELD BETWEEN 1997 and 2021<br>        (SELECT DISTINCT TRI_PLAYER_ID AS PLAYERID<br>        FROM TOURNAMENT_RESULTS_INDIVIDUAL<br>        WHERE TRI_TOURNAMENT_ID IN <br>            (SELECT DISTINCT T_TOURNAMENT_ID FROM TOURNAMENT WHERE YEAR(T_END_DATE) BETWEEN 1997 AND 2021)<br>            AND TRI_PLAYER_ID &lt; 900000<br>        UNION<br>        SELECT DISTINCT TRP_PLAYER_ID AS PLAYERID<br>        FROM TOURNAMENT_RESULTS_PLAYER_IN_TEAM<br>        WHERE TRP_TOURNAMENT_ID IN <br>            (SELECT DISTINCT T_TOURNAMENT_ID FROM TOURNAMENT WHERE YEAR(T_END_DATE) BETWEEN 1997 AND 2021))<br>GROUP BY C_COUNTRY, C_CONTINENT;</pre><h4>B) “Retirement of players”</h4><p><em>Unshortened scripts on </em><a href="https://github.com/IvetaKuncova/ESPORT/blob/master/02%20SQL/04_SQL_AGG_RETIREMENT.sql">GitHub</a>.</p><p>This was a little bit complicated. It took 3 temporary tables and 4 permanent tables. Below is just an example, for all scripts without width limitation for display go to <a href="https://github.com/IvetaKuncova/ESPORT/blob/master/02%20SQL/04_SQL_AGG_RETIREMENT.sql">my Github</a>.</p><pre>/* ===== table 1 ===== */<br><br>CREATE OR REPLACE TABLE WHOSEARLYERRETIRED_KVA AS<br>WITH CTE_WHOSEARLYERRETIRED_QUA AS (<br>SELECT <br>    T4_GAME_ID::int AS GAME_ID,<br>    T4_GAME_NAME AS GAME_NAME,  <br>    T4_RANK_PRIZE_USD::int AS RANK_PRIZE_USD,<br>    T4_RANK_CNT_TOURNAMENTS::int AS RANK_CNT_TOURNAMENTS,<br>    T4_RANK_CNT_PLAYERS::int AS RANK_CNT_PLAYERS,<br>    T4_ISMORETHAN_QUA::int AS ISMORETHAN_QUA, -- an indicator if player is TOP or Casual player according to quantil 0,9<br>    COUNT(DISTINCT T4_PLAYER_ID::int) AS CNT_PLAYER,<br>    SUM(T4_SUM2_PRIZE_USD)::float AS SUM_PRIZE_USD,<br>    AVG(T4_CNT_YEAR_OF_TOURNAMENT)::float AS AVG_YEARS<br>FROM <br>------------------------------------------------------------------  b<br>    (<br>    SELECT<br>        T3_GAME_ID AS T4_GAME_ID,<br>        T3_GAME_NAME AS T4_GAME_NAME,<br>        T3_RANK_PRIZE_USD AS T4_RANK_PRIZE_USD,<br>        T3_RANK_CNT_TOURNAMENTS AS T4_RANK_CNT_TOURNAMENTS,<br>        T3_RANK_CNT_PLAYERS AS T4_RANK_CNT_PLAYERS,<br>        COUNT(DISTINCT T3_TOURNAMENT_ID) AS T4_CNT_TOURNAMENTS, -- how many tournaments has played each player<br>        COUNT(DISTINCT T3_YEAR_OF_TOURNAMENT) AS T4_CNT_YEAR_OF_TOURNAMENT, -- how many years the player played<br>        -- here is not correct to COUNT PLAYERS. I needed to know, how many years !every! player played tournaments<br>        T3_PLAYER_ID AS T4_PLAYER_ID,<br>        SUM(T3_SUM_PRIZE_USD) AS T4_SUM2_PRIZE_USD,<br>        ISMORETHAN_QUA AS T4_ISMORETHAN_QUA<br>    FROM<br>------------------------------------------------------------------  a<br>        (<br>        SELECT <br>            t1.TOURNAMENT_ID AS T3_TOURNAMENT_ID,<br>            t1.YEAR_OF_TOURNAMENT AS T3_YEAR_OF_TOURNAMENT,<br>            t1.PLAYER_ID AS T3_PLAYER_ID,<br>            SUM(t1.SUM_PRIZE) AS T3_SUM_PRIZE_USD,<br>            t1.GAME_ID AS T3_GAME_ID,<br>            t2.G_GAME_NAME AS T3_GAME_NAME,<br>            t2.G_RANK_PRIZE_USD AS T3_RANK_PRIZE_USD,<br>            t2.G_RANK_CNT_TOURNAMENTS AS T3_RANK_CNT_TOURNAMENTS,<br>            t2.G_RANK_CNT_PLAYERS AS T3_RANK_CNT_PLAYERS<br>        FROM TEMP01_PLA_GAME_YEAR t1 <br>        JOIN GAME t2 ON t2.G_GAME_ID=T3_GAME_ID<br>        GROUP BY     <br>            T3_GAME_ID,<br>            T3_GAME_NAME,<br>            T3_RANK_PRIZE_USD,<br>            T3_RANK_CNT_TOURNAMENTS,<br>            T3_RANK_CNT_PLAYERS,<br>            T3_TOURNAMENT_ID,<br>            T3_YEAR_OF_TOURNAMENT,<br>            T3_PLAYER_ID<br>        ) t3 -- 306 541 roes<br>------------------------------------------------------------------  a<br>    JOIN TEMP03_PLAYER_GAME_AVG_MED_QUA t5 ON t5.GAME_ID=T4_GAME_ID AND t5.PLAYER_ID=T4_PLAYER_ID    <br>    GROUP BY<br>        T4_GAME_ID,<br>        T4_GAME_NAME,<br>        T4_RANK_PRIZE_USD,<br>        T4_RANK_CNT_TOURNAMENTS,<br>        T4_RANK_CNT_PLAYERS,<br>        T4_PLAYER_ID,<br>        T4_ISMORETHAN_QUA -- an indicator if player is TOP or Casual player according to quantil 0,9<br>    ) t4 -- 79 504 rows<br>------------------------------------------------------------------  b<br>GROUP BY <br>    GAME_ID,<br>    GAME_NAME,<br>    RANK_PRIZE_USD,<br>    RANK_CNT_TOURNAMENTS,<br>    RANK_CNT_PLAYERS,<br>    ISMORETHAN_QUA<br>) -- 1031 rows<br><br>SELECT <br>    GAME_ID AS W_GAME_ID, <br>    GAME_NAME AS W_GAME_NAME, <br>    RANK_PRIZE_USD AS W_RANK_PRIZE_USD,<br>    RANK_CNT_TOURNAMENTS AS W_RANK_CNT_TOURNAMENTS,<br>    RANK_CNT_PLAYERS AS W_RANK_CNT_PLAYERS,<br>    ISMORETHAN_QUA AS W_ISMORETHAN_QUA,  <br>    CNT_PLAYER AS W_CNT_PLAYERS, <br>    AVG_YEARS AS W_AVG_CNT_YEARS, <br>    SUM_PRIZE_USD AS W_SUM_PRIZE_USD<br>FROM CTE_WHOSEARLYERRETIRED_QUA<br>/* creating final table, where sample of players for a game <br>is more than 100 players (Because a smaller sample is not<br>statistically representative) */<br>WHERE W_GAME_ID IN <br>        (SELECT DISTINCT GAME_ID FROM<br>            (<br>            SELECT GAME_ID, SUM(CNT_PLAYER) AS SUM_PLAYERS<br>            FROM CTE_WHOSEARLYERRETIRED_QUA<br>            GROUP BY GAME_ID<br>            HAVING SUM_PLAYERS &gt;=100<br>            )<br>        );<br><br>-- 252 rows</pre><p>When all tables were created, I made “a live connection” in Keboola. Through this connection I send data directly to Tableau, where I made the visualizations. If I needed some change in data, I didn’t need to recreate charts in Tableau. They just changed according to data with the same graphic setting.</p><p>My <a href="https://github.com/IvetaKuncova/ESPORT"><strong>GitHub</strong></a>, my <a href="https://public.tableau.com/app/profile/iveta.kuncova/vizzes"><strong>Tableau Public</strong></a><br><strong>Next part:</strong> <a href="https://medium.com/@vtkncv/e-sport-part-a-analyzing-the-number-of-players-b066904ef750">E-sport/part 4: Analyzing the number of players in countries</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=e0de520948ce" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[E-sport/part 2: Python]]></title>
            <link>https://medium.com/@vtkncv/e-sport-part-2-python-acb60fb6d58b?source=rss-029ab3d9933f------2</link>
            <guid isPermaLink="false">https://medium.com/p/acb60fb6d58b</guid>
            <category><![CDATA[api]]></category>
            <category><![CDATA[python]]></category>
            <category><![CDATA[web-scrape]]></category>
            <dc:creator><![CDATA[IvetaKuncova]]></dc:creator>
            <pubDate>Wed, 14 Feb 2024 09:52:24 GMT</pubDate>
            <atom:updated>2024-02-17T08:24:15.183Z</atom:updated>
            <content:encoded><![CDATA[<p>#python #api #webscraping</p><p><strong>Previous part:</strong> <a href="https://medium.com/@vtkncv/e-sport-part-1-project-plan-and-preparation-98b5178845b5">E-sport/part 1: Project Plan and Preparation</a><br><strong>Next part: </strong><a href="https://medium.com/@vtkncv/e0de520948ce">E-sport/part 3: Keboola, SQL and data model</a><br><strong>Summary:</strong> <a href="https://medium.com/@vtkncv/e-sport-data-analysis-project-summary-e7b64cd37c84">E-sport data analysis project: Summary</a><br>My <a href="https://github.com/IvetaKuncova/ESPORT"><strong>GitHub</strong></a>, my <a href="https://public.tableau.com/app/profile/iveta.kuncova/vizzes"><strong>Tableau Public</strong></a></p><p><strong>Table of contents: Python was used for:</strong><br>1) <a href="#ea05">Downloading from APIs</a><br>2) <a href="#328d">Web scraping Date of Birth</a><br>3) <a href="#e1a3">Statistics correlation calculations</a></p><h3>1) Downloading data from APIs</h3><p><em>See the code on </em><a href="https://github.com/IvetaKuncova/ESPORT/tree/master/01%20python/API"><em>GitHub</em></a><em>.</em><br>For data downloading from 12 APIs, I created 12 scripts in Python.<br>These 12 scripts are divided into 3 categories according to what you have to enter in a request URL.</p><p><strong>Category:</strong><br>A) ID<br>B) ID and offset<br>C) offset</p><p><strong>The scripts consist of several parts:</strong><br>- Loading modules<br>- Setting global variables<br>- Script execution time<br>- Creating a session to handle HTTP exceptions<br>- Functions to retrieve data from the API<br>- Functions to save data in JSONL format<br>- Functions to convert JSONL to CSV format <br>- Output time and file data</p><p>The one restriction from APIs was one second delay between requests. There were for example about 140 000 players, which means at least 39 hours of continuous downloading for that one part of data. For that reason, <strong>the code had to be written to run for dozens of hours without interruption and store data continuously. </strong><br>If an error occurred, such as “Empty response” or “Bad gateway”, the code needed to either skip the ID or try to download it again and save information about an error for later downloading. <br><strong>Different APIs had different output JSON formats</strong> (e.g. for 1 request: one dictionary { } vs. a list of 100 dictionaries [{ },{ },{ }, …] ),<strong> which I needed to unify </strong>and convert to one output format (JSONL).</p><p><em>See this script below without width limitation</em> <em>on my </em><a href="https://github.com/IvetaKuncova/ESPORT/blob/master/01%20python/API/02-API-LookupPlayerTournaments.py"><em>GitHub</em></a></p><pre>&quot;&quot;&quot;<br>02 LookupPlayerTournaments<br>URL: http://api.esportsearnings.com/v0/LookupPlayerTournaments?apikey=&lt;apikey&gt;&amp;playerid=&lt;playerid&gt;&amp;offset=&lt;offset&gt;<br>Documentation: https://www.esportsearnings.com/apidocs<br>Timeout required: 1 second (BAN)<br>Output format: JSONL+ CSV<br><br>During the execution of the script, the following warnings <br>are generated:<br>&quot;InsecureRequestWarning: Unverified HTTPS request is being <br>made to host &#39;api.esportsearnings.com&#39;. Adding certificate <br>verification is strongly advised.<br>See: https://urllib3.readthedocs.io/en/1.26.x/advanced-usage.html#ssl-warnings<br>warnings.warn(&quot;<br><br>This warning means that the site does not have a valid SSL <br>certificate (i.e., https://). <br>Since we are not sending any personal information to the site, <br>this is not a problem. The code will still execute despite the warning. <br>The warnings are therefore suppressed.<br>&quot;&quot;&quot;<br># load modules<br>import requests<br>import json<br>import csv<br>from datetime import datetime<br>import time<br># for session creation and treatment of HTTP status codes<br>from requests.adapters import HTTPAdapter<br>from requests.packages.urllib3.util.retry import Retry<br># disables the warning of an invalid SSL certificate:<br>from urllib3.exceptions import InsecureRequestWarning<br>from urllib3 import disable_warnings<br>disable_warnings(InsecureRequestWarning)<br><br># setting global variables<br>apikey = &#39;your api key here&#39; # YOU CAN GET AN API KEY BY REGISTERING HERE: https://www.esportsearnings.com/dev<br>playerid = 1000 # !!! ID You want to start on<br>numberofID =  1 # !!! number of IDs You want to process<br>offset = 0 # !!! starting offset (how many tournaments should be skipped)<br>stopoffset = 700 # !!! How many offsets should be processed?<br>file_name = f&quot;02-API-LookupPlayerTournaments_{playerid}-{playerid+numberofID-1}&quot;<br># for overview at the end of the script it saves the error messages that occurred during processing<br>errorCodes = []<br><br># displays the start time and end time of the script execution to estimate the duration of this script<br># to calculate the processing time (the result is the time in seconds):<br>time_start = time.time()<br>time_begin = datetime.fromtimestamp(time_start)<br># display the time on the terminal in blue color (ANSI code)<br>print(f&quot;\u001b[36;1mTime at the beginning of the script: {time_begin}\u001b[0m&quot;)<br><br># to estimate the approximate time you can arrive at a processed script:<br># you can add something extra to the estimated processing time (correct according to real times)<br>estim_time_of_execution = numberofID * 1.6859<br>print(f&quot;\u001b[36;1mEstimated script processing time: {(estim_time_of_execution//60)//60} hours, {(estim_time_of_execution//60)%60} minutes, {((estim_time_of_execution%60)%60):.2f} seconds\u001b[0m&quot;) # in blue color<br><br># creating a session to handle HTTP exceptions<br># If the API returns a code 502 (bad gateway) or 429 (too many requests) instead of the data, <br># the &quot;retry&quot; tries to query the same data again with increasing delay (backoff_factor)<br>session = requests.Session()<br>retry = Retry(<br>    total=5,<br>    backoff_factor=0.5,<br>    status_forcelist=(429, 500, 502, 504))<br>adapter = HTTPAdapter(max_retries=retry)<br>session.mount(&quot;http://&quot;, adapter)<br>session.mount(&quot;https://&quot;, adapter)<br><br># API data retrieval function<br>def get_LookupPlayerTournaments(playerid, offset):<br>    numOfTournament = 1<br>    tournaments = []<br>    for i in range(0, stopoffset):<br>        # API requires min 1 second between queries, min 1 second between requests<br>        time.sleep(1.0)<br>        url = f&#39;https://api.esportsearnings.com/v0/LookupPlayerTournaments?apikey={apikey}&amp;playerid={playerid}&amp;offset={offset}&#39;<br>        # without Verify=False the request will not be executed due to an invalid SSL certificate<br>        response = session.get(url, verify=False)<br>        # on the terminal You can see which address You are currently at. For quick orientation, how far You are in the request, in pink color<br>        print(f&quot;\u001b[35m{url}\u001b[0m&quot;)<br>        <br>        # handling of Errors returned by the API (200 = success)<br>        if response.status_code != 200: <br>            # If the API reports an Error, we display it and also save it to the list, in red color<br>            print(f&quot;\u001b[31;1mError: HTTP {response.status_code}\u001b[0m&quot;) <br>            errorCodes.append(f&quot;PlayerId:{playerid}-error:{response.status_code}&quot;)  <br>            data = [{&quot;Error&quot;: f&quot;HTTP {response.status_code}&quot;}]<br>        # if the API returns &quot;NULL&quot;/none:<br>        elif not response.text:<br>            print(f&quot;\u001b[31;1mError: Empty response\u001b[0m&quot;) <br>            errorCodes.append(f&quot;PlayerId:{playerid}-Error:Empty response&quot;)<br>            data = [{&quot;Error&quot;: &quot;Empty response&quot;}]            <br>            break             <br>        else:<br>            try:<br>                data = response.json()<br>                # Add a new keys and ID values<br>                for dictionary in data:<br>                    dictionary[&quot;PlayerId&quot;] = playerid<br>                    dictionary[&quot;NumOfTournament&quot;] = numOfTournament<br>                    numOfTournament += 1<br>            except:<br>                print(f&quot;\u001b[31;1mError: Invalid response: {url}\u001b[0m&quot;)<br>                print(response.status_code)<br>                print(response.text)<br>                data = [{&quot;Error&quot;: &quot;Invalid response&quot;}]                <br>            <br>        tournaments.append(data)<br>        offset += 100<br>    return tournaments<br><br><br># saving data to a file<br>try:<br>    with open(f&quot;{file_name}.jsonl&quot;, mode=&quot;w&quot;, encoding=&quot;utf-8&quot;) as file: <br>        for i in range(0,numberofID):<br>            # call the function with the parameter corresponding to the first ID where I want to start and offset<br>            dataA = get_LookupPlayerTournaments(playerid + i, offset) <br>            if not dataA:<br>                continue<br>            for listA in dataA:<br>                for dictionary in listA:<br>                    json.dump(dictionary, file, ensure_ascii=False) <br>                    file.write(&quot;\n&quot;) # separate lines<br># the code will be executed even if the user interrupts its execution (which sometimes takes hours):<br>except KeyboardInterrupt:<br>    print(&quot;Interrupted by user&quot;)  <br><br># convert JSONL file to CSV:<br>def jsonl_to_csv():     <br>    with open(f&#39;{file_name}.csv&#39;, &#39;w&#39;, newline=&#39;&#39;, encoding=&quot;utf8&quot;) as fw:<br>        with open(f&#39;{file_name}.jsonl&#39;, &#39;r&#39;, encoding=&quot;utf8&quot;) as fr:<br>            first_row = True<br>            for row in fr:<br>                data = json.loads(row)<br>                if first_row:<br>                    first_row = False<br>                    headers = list(data.keys()) + [&quot;Error&quot;]<br>                    writer = csv.DictWriter(fw, fieldnames=headers)<br>                    writer.writeheader()<br>                writer.writerow(data)<br># call the jsonl_to_csv() function<br>jsonl_to_csv()<br><br><br># Request time summary: (When running longer requests (many IDs) we needed to have some overview, <br># when to go back to the computer to the downloaded file and run the next one)<br># To calculate the processing time (the result is the time in seconds):<br>time_end = time.time()<br>time_over = datetime.fromtimestamp(time_end, tz=None)<br>print(f&quot;\u001b[36;1mTime at the start of the request: {time_begin}\u001b[0m&quot;) # blue<br>print(f&quot;\u001b[36;1mTime at the end   of the request: {time_over}\u001b[0m&quot;) # blue<br>print(f&quot;\u001b[32;1mExpected request duration: {(estim_time_of_execution//60)//60} hours, {(estim_time_of_execution//60)%60} minutes, {((estim_time_of_execution%60)%60):.4f} seconds.\u001b[0m&quot;) # blue<br>print(f&quot;\u001b[32;1mActual   request duration: {(((time_end - time_start)//60)//60)} hours, {(((time_end - time_start)//60)%60)} minutes, {(((time_end - time_start)%60)%60):.4f} seconds.\u001b[0m&quot;) # green<br>print(f&quot;\u001b[31;1mHTTP error codes: {errorCodes}\u001b[0m&quot;) # red<br>print(f&quot;\u001b[33mThe name of the output file is: {file_name}\u001b[0m&quot;) # yellow</pre><p>The scripts have about 150 lines and contain ANSI color formatting for terminal output, e.g., “\u001b[35m”, to be instantly recognizable whether the request is proceeding correctly.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/703/1*qUqXdZuKqQ7bAo50jaBO7w.png" /></figure><p>Data sample in JSONL:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*cA67NxQjJTMkA1tiMocrEg.png" /></figure><p>Data sample in CSV:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/962/1*rGqzMLFhZNiYHk4wkZbdGA.png" /></figure><p>I admit I needed some help with these scripts. I was not familiar with API behavior, possible responses and how to deal with errors when I needed the script to continue through them. Many thanks to awesome coach Martin Stružský, who helped me here.</p><h3>2) Web scrape of Date of Birth</h3><p><em>See the code on my </em><a href="https://github.com/IvetaKuncova/ESPORT/blob/master/01%20python/SCRAPE/Scrape-DateOfBirth.py"><em>GitHub</em></a><em>.</em><br>Because the API outputs didn’t contain the players’s Date of Birth, but it was on websites, I knew we could web scrape it. <br>About the preparation of URL addresses in SQL, you can read here.</p><p>Because we didn’t learn web scraping at the academy at that time, I tried some language models (Bard, Bing, GPT), if they would be able to manage it. It took a few attempts and adjustments to make a simple script, but it worked:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/662/1*V1ErjD1HI8MMqFgyOtw_aA.png" /><figcaption>* after few iterations and little adjustments to make it work</figcaption></figure><h4><strong>I added parts of the code:</strong></h4><ul><li>to open a file with URLs<br>- handling errors<br>- to save dates of births and links or errors to a file<br>- some other details as 1 second pause between requests, printing count of links to process or name of the output file, ANSI color formatting …</li></ul><p><em>See this script without width limitation</em> <em>on my </em><a href="https://github.com/IvetaKuncova/ESPORT/blob/master/01%20python/SCRAPE/Scrape-DateOfBirth.py"><em>GitHub</em></a><em>.</em></p><pre># Resulting script after all adjustments<br><br># load modules<br>import requests<br>import csv<br>import time<br>from bs4 import BeautifulSoup<br># for session creation and treatment of HTTP status codes<br>from requests.adapters import HTTPAdapter<br>from requests.packages.urllib3.util.retry import Retry<br><br>## VARIABLES TO CHANGE:<br>input_file_name_links_todo = &quot;links_todo.csv&quot;<br>output_file_name_DatesOfBirth = &quot;DatesOfBirth.csv&quot;<br><br># creating a session to handle HTTP exceptions<br># If the API returns a code 502 (bad gateway) or 429 (too many requests) instead of the data, <br># the &quot;retry&quot; tries to query the same data again with increasing delay (backoff_factor)<br>session = requests.Session()<br>retry = Retry(<br>    total=5,<br>    backoff_factor=0.5,<br>    status_forcelist=(429, 500, 502, 504))<br>adapter = HTTPAdapter(max_retries=retry)<br>session.mount(&quot;http://&quot;, adapter)<br>session.mount(&quot;https://&quot;, adapter)<br><br>## get links to scrape from file<br>links_todo = []<br>with open(f&quot;{input_file_name_links_todo}&quot;, mode=&quot;r&quot;, encoding=&quot;utf-8&quot;) as fr:<br>    for rows in fr:<br>        rows1 = rows.strip()<br>        rows3 = rows1.split(&#39;,&#39;, 2)<br>        collumn = rows3[0].strip(&#39;&quot;&#39;)<br>        if collumn != &#39;Url&#39;:<br>            links_todo.append(collumn)<br><br>print(f&quot;Number of links to process: {len(links_todo)}&quot;)<br><br>dob_list = []<br>def get_DateOfBirth(url):<br>    time.sleep(1.0)<br><br>    response = session.get(url)<br>    # on the terminal I can see which address I am currently at for quick orientation, how far I am in the request, in pink<br>    print(f&quot;\u001b[35m{url}-{i}\u001b[0m&quot;)<br>    <br>    if response.status_code != 200:<br>        print(f&quot;\u001b[31;1mError: HTTP {response.status_code}\u001b[0m&quot;) <br>        data = [{&quot;Error&quot;: f&quot;HTTP {response.status_code}&quot;, &quot;Url&quot;: url}]<br><br>    elif not response.text:<br>        data = [{&quot;Error&quot;: &quot;Empty response&quot;, &quot;Url&quot;: url}]      <br>          <br>    else:<br>        try:<br>            # Create BeautifulSoup object<br>            soup = BeautifulSoup(response.text, &#39;html.parser&#39;)<br><br>            # Find the element containing the date of birth<br>            dob_element = soup.find(&#39;div&#39;, string=&#39;Date of Birth:&#39;)<br><br>            # Pull the date of birth from the following element<br>            dob = dob_element.find_next_sibling(&#39;div&#39;).text<br>            dictionary = {}<br>            dictionary[&quot;Url&quot;]= url<br>            dictionary[&quot;DateOfBirth&quot;] = dob<br>            data = dictionary<br>        except:<br>            print(f&quot;\u001b[31;1mError: Invalid response: {url}\u001b[0m&quot;)<br>            print(response.status_code)<br>            print(response.text)<br>            data = [{&quot;Error&quot;: &quot;Invalid response&quot;, &quot;Url&quot;: url}]<br>   <br>    # Save the date of birth in the list<br>    dob_list.append(data)<br>    return dob_list<br><br># saving data to a file<br>try: <br>    with open(f&quot;{output_file_name_DatesOfBirth}&quot;, &quot;w&quot;, encoding=&quot;utf-8&quot;, newline=&#39;&#39;) as fw:<br>        first_row = True<br>        for i in range(0,len(links_todo)):<br>            url = links_todo[i]    <br>            DataA = get_DateOfBirth(url)<br>            if not DataA:<br>                continue<br>            for listA in DataA:<br>                if first_row:<br>                    first_row = False<br>                    headers = [&quot;Url&quot;, &quot;DateOfBirth&quot;, &quot;Error&quot;]<br>                    writer = csv.DictWriter(fw, fieldnames=headers)<br>                    writer.writeheader()       <br>            writer.writerow(listA)        <br># the code will be executed even if the user interrupts its execution (which sometimes takes hours):<br>except KeyboardInterrupt:<br>    print(&quot;Interrupted by user&quot;)     <br><br>print(f&quot;\u001b[33mThe name of the output file is: {output_file_name_DatesOfBirth}\u001b[0m&quot;) # yellow</pre><h3>3) Statistics correlation calculations</h3><p>See the code without width limitation on my <a href="https://github.com/IvetaKuncova/ESPORT/tree/master/03%20correlation%20statistics%20-%20esport%20players">GitHub</a>.</p><p>Detail descriptions and pictures about these statistics are in the E-sport/part 4: Analyzing the number of players. Here is just the Python script.</p><pre># From Jupyter notebook<br><br>import pandas as pd<br>import seaborn as sns<br>from scipy import stats<br><br># Load file<br>data = pd.read_csv(&quot;SDM_player_gdp_pop_int.csv&quot;)<br># Data type settings<br>data = pd.DataFrame(data)<br>data[&quot;GPI_CNT_PLAYER_ID&quot;] = data[&quot;GPI_CNT_PLAYER_ID&quot;].astype(int)<br>data[&quot;GPI_CNT_PLAYERS_ON_1MIL_POP&quot;] = data[&quot;GPI_CNT_PLAYERS_ON_1MIL_POP&quot;].astype(float)<br>data[&quot;GPI_AVG_GDP_PER_CAPITA&quot;] = data[&quot;GPI_AVG_GDP_PER_CAPITA&quot;].astype(float)<br>data[&quot;GPI_AVG_POPULATION&quot;] = data[&quot;GPI_AVG_POPULATION&quot;].astype(float)<br>data[&quot;GPI_AVG_POPULATION_AGED_15TO29&quot;] = data[&quot;GPI_AVG_POPULATION_AGED_15TO29&quot;].astype(float)<br>data[&quot;GPI_AVG_SHARE_OF_INDIVIDUALS_USING_INTERNET&quot;] = data[&quot;GPI_AVG_SHARE_OF_INDIVIDUALS_USING_INTERNET&quot;].astype(float)<br># Text columns must be excluded<br>data.drop([&quot;GPI_COUNTRY&quot;,&quot;GPI_CONTINENT&quot;], axis=&#39;columns&#39;, inplace=True)<br><br># Rename columns<br>data = data.rename(columns={&quot;GPI_CNT_PLAYER_ID&quot;: &quot;No. of players&quot;, &quot;GPI_CNT_PLAYERS_ON_1MIL_POP&quot;: &quot;No. of players/mil. inhabitants&quot;, &quot;GPI_AVG_GDP_PER_CAPITA&quot;: &quot;Avg. GDP per capita&quot;, &quot;GPI_AVG_POPULATION&quot;: &quot;Avg. population&quot;, &quot;GPI_AVG_POPULATION_AGED_15TO29&quot;: &quot;Avg. population aged 15-29 years&quot;, &quot;GPI_AVG_SHARE_OF_INDIVIDUALS_USING_INTERNET&quot;: &quot;Avg. perc. of inhabitants using the Internet&quot;})<br># Print the first records<br>print(data.head())<br><br>sns.scatterplot(data=data, x=&quot;Avg. population&quot;, y=&quot;No. of players&quot;, color=&quot;blue&quot;)<br>sns.scatterplot(data=data, x=&quot;Avg. population aged 15-29 years&quot;, y=&quot;No. of players&quot;, color=&quot;blue&quot;)<br>sns.scatterplot(data=data, x=&quot;Avg. GDP per capita&quot;, y=&quot;No. of players/mil. inhabitants&quot;, color=&quot;blue&quot;)<br>sns.scatterplot(data=data, x=&quot;Avg. perc. of inhabitants using the Internet&quot;, y=&quot;No. of players/mil. inhabitants&quot;, color=&quot;blue&quot;)<br><br># Normal distribution test:<br># Normal distribution is always tested for one column of the table.<br># If the p-value is less than a certain pre-set threshold (0.05), then the data do not come from a normal distribution.<br>print(stats.normaltest(data[&quot;No. of players&quot;]))<br>print(stats.normaltest(data[&quot;No. of players/mil. inhabitants&quot;]))<br>print(stats.normaltest(data[&quot;Avg. GDP per capita&quot;]))<br>print(stats.normaltest(data[&quot;Avg. population&quot;]))<br>print(stats.normaltest(data[&quot;Avg. population aged 15-29 years&quot;]))<br>print(stats.normaltest(data[&quot;Avg. perc. of inhabitants using the Internet&quot;]))<br><br>## FINDING THE CORRELATION VALUE<br># Statistic - the higher it is the stronger is the correlation<br>print(stats.kendalltau(data[&quot;Avg. population&quot;], data[&quot;No. of players&quot;]))<br>print(stats.kendalltau(data[&quot;Avg. perc. of inhabitants using the Internet&quot;], data[&quot;No. of players/mil. inhabitants&quot;]))<br>print(stats.kendalltau(data[&quot;Avg. GDP per capita&quot;], data[&quot;No. of players/mil. inhabitants&quot;]))<br>print(stats.kendalltau(data[&quot;Avg. population aged 15-29 years&quot;], data[&quot;No. of players&quot;]))</pre><p>My <a href="https://github.com/IvetaKuncova/ESPORT"><strong>GitHub</strong></a>, my <a href="https://public.tableau.com/app/profile/iveta.kuncova/vizzes"><strong>Tableau Public</strong></a><br><strong>Next part:</strong> <a href="https://medium.com/@vtkncv/e0de520948ce">E-sport/part 3: Keboola, SQL and data model</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=acb60fb6d58b" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[E-sport/part 1: Project Plan and Preparation]]></title>
            <link>https://medium.com/@vtkncv/e-sport-part-1-project-plan-and-preparation-98b5178845b5?source=rss-029ab3d9933f------2</link>
            <guid isPermaLink="false">https://medium.com/p/98b5178845b5</guid>
            <category><![CDATA[project-plan]]></category>
            <dc:creator><![CDATA[IvetaKuncova]]></dc:creator>
            <pubDate>Wed, 14 Feb 2024 09:50:54 GMT</pubDate>
            <atom:updated>2024-02-16T09:43:04.663Z</atom:updated>
            <content:encoded><![CDATA[<p># TimePlan #SourceOfData #DivisionOfLabor</p><p><strong>Previous part: </strong><a href="https://medium.com/@vtkncv/e-sport-data-analysis-project-summary-e7b64cd37c84">E-sport data analysis project: Summary</a><br><strong>Next part: </strong><a href="https://medium.com/@vtkncv/e-sport-part-2-python-acb60fb6d58b">E-sport/part 2: Python</a><br>My <a href="https://github.com/IvetaKuncova/ESPORT"><strong>GitHub</strong></a>, my <a href="https://public.tableau.com/app/profile/iveta.kuncova/vizzes"><strong>Tableau Public</strong></a></p><p><em>This is my first data project. I am describing my steps and the experience I gained. It’s part of my education in Data Analysis at </em><a href="https://www.czechitas.cz/kurzy/digitalni-akademie-data"><em>Czechitas’s “Digital Academy: Data” </em></a><em>300-hour intensive course.</em></p><p><strong>Table of Contents:</strong><br>- <a href="#896c">Time Plan</a><br>- <a href="#0dc8">Source of Data</a><br>- <a href="#7ee6">Division of Labor</a></p><h4><strong>Project Goals:</strong></h4><p>- Apply SQL, Python, Visualisations etc. in practice<br>- Individual and teamwork in data analysis<br>- Team <a href="https://medium.com/@ivanaiveta/e-sport-nen%C3%AD-jenom-hobby-7feb22905bae">Blog </a>for 10 minutes reading in czech (not this one)<br>- 3-minute presentation</p><h3>Time Plan:</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*sY_RCyzT-lQsaJadau4pEQ.png" /></figure><p>There were some deadlines and events, which should be considered at the Czechitas Academy. It was a partnership project (but here I am describing only my part of the project), therefore I needed to find a project partner (<a href="https://www.linkedin.com/in/ivana-rezlerova/">Ivana Rezlerova</a>), with whom we chose a theme (E-sport), two mentors (<a href="https://www.linkedin.com/in/petr-holik/">Petr Holik</a> and <a href="https://www.linkedin.com/in/filip-lavacca-851319237/">Filip Lavacca</a>), to look for sources of data and possible hypotheses to investigate. Team Blog in Czech you can find <a href="https://medium.com/@ivanaiveta/e-sport-nen%C3%AD-jenom-hobby-7feb22905bae">here</a>.</p><h3>Chosen theme: E-sport</h3><h3>Source of data: EsportsEarnings.com</h3><p><em>Incredible database about e-sport Players, Games, Tournaments and Prize money. It is a community-driven resource based on freely available public information (yes, it is not 100 % reliable, data cleansing will be necessary). It contains data from 1996 to the present (September 2023). These pages also provide public APIs for downloading their data.</em></p><figure><a href="https://www.esportsearnings.com/"><img alt="" src="https://cdn-images-1.medium.com/max/861/1*YfQofu0DGDdg8UEL5xNqhg.png" /></a><figcaption><a href="https://www.esportsearnings.com/">EsportsEarnings.com</a></figcaption></figure><p>At first, I made <a href="https://github.com/IvetaKuncova/ESPORT/blob/master/01%20python/API/API_columns.xlsx">an overview table in Excel</a> with all columns for each API to see if one API output can be linked to another one. It turned out APIs are linkable, which means I can connect e.g. data about a player or team with data about a tournament. It was possible to continue with these datasets.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*BJM2U5bEaQ4K5OXBl0hP1Q.png" /></figure><h4>Secondary Source: <a href="https://ourworldindata.org/">OurWorldInData.org</a></h4><p>For correlation statistics about players in countries I used these three sources of data below. They are all divided into countries and years ca 1990–2021.</p><ul><li><a href="https://ourworldindata.org/grapher/gdp-per-capita-worldbank">GDP per capita</a></li><li><a href="https://ourworldindata.org/population-growth">Population Growth</a></li><li><a href="https://ourworldindata.org/grapher/share-of-individuals-using-the-internet">Share of the population using the Internet</a></li></ul><h3>Division of Labor</h3><p>The division of labor depended on the amount of time each of us had. I was working 7 hours a day on work days. My project partner Ivana was working about 6 hours a week because she was employed at that time. This means <strong>85 % of the project was my responsibility</strong> because I had more time to dedicate to it. I<strong>n this Blog, I am presenting only my part of this project.</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*MJkxo--M9Ono0X_E-3bNFQ.png" /><figcaption>*All the Python scripts I am presenting here (or on GitHub) are my work, also contributed some of her own. It means we had two different scripts (mine and Ivana’s) for APIs 8, 9 and 10. It was not so difficult for me to create it by adjusting other my scripts for other APIs, because APIs were similar. We used both variants of these scripts for the downloading.</figcaption></figure><p>My <a href="https://github.com/IvetaKuncova/ESPORT"><strong>GitHub</strong></a>, my <a href="https://public.tableau.com/app/profile/iveta.kuncova/vizzes"><strong>Tableau Public</strong></a><br><strong>Next part:</strong> <a href="https://medium.com/@vtkncv/e-sport-part-2-python-acb60fb6d58b">E-sport/part 2: Python</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=98b5178845b5" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>