<?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 Ricardo André on Medium]]></title>
        <description><![CDATA[Stories by Ricardo André on Medium]]></description>
        <link>https://medium.com/@ricardoandreom?source=rss-cb92fec91650------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*3tdbfGvDjv2dc0AxnJidpA.png</url>
            <title>Stories by Ricardo André on Medium</title>
            <link>https://medium.com/@ricardoandreom?source=rss-cb92fec91650------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Sat, 28 Nov 2026 14:00:59 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@ricardoandreom/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[A Low-Risk Strategic Investment Journey]]></title>
            <link>https://medium.com/@ricardoandreom/a-low-risk-strategic-investment-journey-45902448144a?source=rss-cb92fec91650------2</link>
            <guid isPermaLink="false">https://medium.com/p/45902448144a</guid>
            <category><![CDATA[dollar-cost-averaging]]></category>
            <category><![CDATA[financial-planning]]></category>
            <category><![CDATA[portfolio]]></category>
            <category><![CDATA[finance]]></category>
            <category><![CDATA[investing]]></category>
            <dc:creator><![CDATA[Ricardo André]]></dc:creator>
            <pubDate>Tue, 30 Jan 2024 22:42:41 GMT</pubDate>
            <atom:updated>2024-01-30T22:45:14.195Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/375/1*W5EzK2LOWJ4ihkuzdDOoaw.png" /><figcaption>just illustrative</figcaption></figure><p>Living in a financially uncertain world can be challenging, but having a solid investment strategy can be the key to building a secure financial future. In this article, I will share my investment journey, highlighting a low-risk approach I adopted to achieve my financial goals.</p><h4>Clear financial objectives</h4><p>From the outset, I set clear long-term financial goals. This includes building a portfolio that can withstand market fluctuations and provide consistent growth over time.</p><h4>Essential diversification</h4><p>Diversification is the backbone of my strategy. I chose to invest in various sectors, including technology, semiconductors, energy, oil, healthcare, REITs, and food. This approach aims to mitigate risks associated with specific sectors, providing balance to my portfolio.</p><h3>Dollar Cost Averaging (DCA)—Smoothing the path to success</h3><p>Dollar Cost Averaging (DCA) is an investment technique designed to reduce market volatility, providing a consistent and disciplined approach. By investing a fixed amount regularly, regardless of the asset’s price at that moment, investors buy more shares when prices are low and fewer when they are high. This results in an average cost per share over time, smoothing short-term market fluctuations. DCA does not require precise predictions about market movements, allowing investors to benefit from the power of time and consistency, which is particularly effective for those seeking long-term wealth while minimizing the impact of normal market fluctuations.</p><h4>Consistent monthly investments with DCA</h4><p>The choice of Dollar Cost Averaging (DCA) has been crucial. Investing monthly between 30 and 40% of the available funds after covering essential expenses provides a disciplined approach and helps smooth market fluctuations. Also, this particular monthly investment amount ensures my commitment to portfolio growth without sacrificing the quality of life in the present.</p><h4>Investing in selected assets</h4><p>My portfolio includes not only individual stocks but also ETFs (lower risk than most stocks), representing different areas of interest. From artificial intelligence to gold, including the traditional SP500 and MSCI World, each asset was chosen based on careful analysis.</p><h4>Flexibility in allocation</h4><p>A distinctive feature of my strategy is the flexibility in asset allocation. Unlike maintaining fixed and equitable percentages across all sectors, I adjust the distribution based on my perceptions of growth potential and desired exposure to risk in each sector. This approach allows me to capitalize on emerging opportunities and mitigate specific risks by adapting the portfolio to market conditions. This flexibility adds a strategic dimension, combining intuition and rationality in the ongoing quest for a robust and dynamic portfolio.</p><h4>The power of compound interest in long-term strategies</h4><p>Given the long-term nature of my approach, it’s worth noting that compound interest will play a significant role in the monetary growth of my portfolio. As the power of compounding quietly works its magic, reinvesting returns and generating earnings on the previous gains, the potential for exponential growth becomes evident.</p><h4>Tangible results</h4><p>In almost a year, my strategy has yielded a commendable 18% return. This performance attests to the effectiveness of a low-risk, long-term investment approach.</p><h4>Conclusion</h4><p>Building a solid financial future is a journey that requires patience, discipline, and a well-defined strategy. My experience shows that it is possible to achieve significant returns with a low-risk, long-term focus. By adapting my strategy to the circumstances, I am confident that I am building a secure path to financial prosperity.</p><p><strong>Final disclaimer: </strong><em>This article reflects my personal experience and does not constitute financial advice. Always consult a financial professional and do your own analysis before making significant investment decisions.</em></p><p><em>If you enjoyed my article and feel like giving a little something back, feel free to give it a round of claps</em> 👏 or <em>buy me a virtual coffee :), link </em><a href="https://ko-fi.com/ricardoandreom"><strong><em>here</em></strong></a><em>.</em></p><p>Your support is greatly appreciated!</p><p>Follow me and my content on:<br><a href="https://www.linkedin.com/in/ricardoandreom/"><strong>Linkedin</strong></a><strong><br></strong><a href="https://public.tableau.com/app/profile/ricardoandreom/vizzes/"><strong>Tableau</strong></a><strong><br></strong><a href="https://ricardoandreom.github.io/ricardo_portfolio_page/"><strong>Portfolio page</strong></a><strong> <br></strong><a href="https://twitter.com/HspaceAnalytics"><strong>Football analytics Twitter</strong></a><strong><br></strong><a href="https://www.instagram.com/halfspace_analytics/"><strong>Football analytics Instagram</strong></a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=45902448144a" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[How to web scrape using BeautifulSoup]]></title>
            <link>https://medium.com/@ricardoandreom/how-to-web-scrape-using-beautifulsoup-3abfd90435b5?source=rss-cb92fec91650------2</link>
            <guid isPermaLink="false">https://medium.com/p/3abfd90435b5</guid>
            <category><![CDATA[business-analysis]]></category>
            <category><![CDATA[data]]></category>
            <category><![CDATA[data-science]]></category>
            <category><![CDATA[business-strategy]]></category>
            <category><![CDATA[web-scraping]]></category>
            <dc:creator><![CDATA[Ricardo André]]></dc:creator>
            <pubDate>Tue, 21 Nov 2023 22:57:54 GMT</pubDate>
            <atom:updated>2023-11-21T22:57:54.736Z</atom:updated>
            <content:encoded><![CDATA[<h3>A Practical Guide for Extracting Data</h3><h4>Introduction</h4><p>The internet contains a wealth of useful information that is frequently hidden within the depths of web pages. Web scraping is a powerful technique that enables us to access this data automatically and transform it into usable knowledge for analysis or decision-making.<br><strong>In this tutorial, we’ll look at how to use Python, or more precisely, a library called BeautifulSoup, to perform web scraping on Amazon, one of the world’s largest e-commerce sites.</strong></p><h4>Why is web scraping important?</h4><p>Consider having access to information about product prices, consumer reviews, and market trends that is dispersed across multiple web pages. Web scraping allows you to collect, consolidate, and structure data for further analysis. This method is critical for gaining valuable insights in areas such as market analysis, competitor research, and price monitoring.</p><h4>Web scraping challenges</h4><ol><li><strong>Identifying the correct HTML elements</strong><br>Web scraping involves identifying the correct HTML elements, such as divs and classes, that contain the desired data. Websites frequently update their structures, change class names, or use dynamic content, making it challenging to pinpoint the specific elements required for scraping.<br>Also note that these changes can disrupt the scraping process as the previously identified elements might no longer exist or may have been altered, causing the scraper to fail.</li><li><strong>Header</strong><br>When scraping data from websites, using a header in your requests is crucial. The header will simulate a browser visit, making the request appear more legitimate. Websites often expect requests to come from browsers and might block those that don’t, so providing a header increases the chances of a successful scrape.</li><li><strong>Blocks and Requests</strong><br>Websites may include mechanisms to prevent excessive scraping. <br>They may use techniques such as IP blocking or rate limiting to limit the number of requests from a specific IP address or user.<br>These restrictions are usually put in place to keep the website from becoming overloaded with traffic or to keep their data from being scraped extensively without permission.<br>To avoid being blocked, scrapers must adhere to these constraints and consider techniques such as rotating IP addresses or implementing delays between requests.</li></ol><h3>Web scrape code implementation</h3><p>Let us now put all of this theory into practice. My idea was to create a web scrape that would extract information about the products that appeared when we searched for a product on Amazon and then use the data for whatever purpose we saw necessary.</p><p>Let’s see the code explained below.</p><pre># libraries <br>from bs4 import BeautifulSoup<br>import requests<br>import pandas as pd<br>import numpy as np</pre><p>The variables created below are defining the product to be searched, the number of pages to scrape, the base URL to access result pages, and request headers to simulate a browser.<br>In this case, we will take a look into watches available in Amazon. ‘Relogio’ is a portuguese word that means in english ‘watch’.</p><pre>product = &#39;relogio&#39;<br>num_pages_to_scrape = 5<br>base_url = &#39;https://www.amazon.es/-/pt/s?k=&#39; + product + &#39;&amp;page=&#39;<br>headers = {&#39;User-Agent&#39;: &#39;Chrome/58.0.3029.110&#39;}</pre><p>For each product found, we will extract the description, brand, price, rating, and delivery information.</p><h4><strong>Requests</strong></h4><p>For each page, we make an HTTP request using requests.get() and retrieve the HTML content. This HTML is parsed with BeautifulSoup, and specific HTML elements containing the desired data are located.</p><h4><strong>Data extraction</strong></h4><p>Within the loop, we search for HTML elements containing information like product description, brand, price, rating, and delivery information. Methods like find() and get_text() are used to extract content from these elements. <br>To apply the find methods, you will need the inspect the page HTML code. Try to follow the next three images and understand the code.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*eMqe4-nFE54M0izUE5w45Q.png" /><figcaption><strong>Open the page you want to webscrape and click ‘Inspect’</strong></figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*RZHT9I5SSo9lyrLQhsPeEQ.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*rXMq9zKhNrjNIK092ZeqHw.png" /><figcaption><strong>Finding HTML elements</strong></figcaption></figure><p><strong>Data Organization</strong><br>The extracted data is stored in lists corresponding to each category (descriptions, brands, prices, etc.). These lists are then consolidated into a dictionary called data, which is later transformed into a pandas DataFrame.</p><pre>df_final = pd.DataFrame()<br><br>for page_num in range(2, num_pages_to_scrape + 1):<br>    url = base_url + str(page_num)<br>    response = requests.get(url, headers=headers)<br>    soup = BeautifulSoup(response.content, &#39;html.parser&#39;)<br><br>    products = soup.find_all(&#39;div&#39;, {&#39;class&#39;: &#39;sg-col-inner&#39;})<br><br>    descriptions = []<br>    brands = []<br>    prices = []<br>    ratings = []<br>    delivery_infos = []<br><br>    product_data_format =[]<br><br>    for product in products:<br><br>        description_element = product.find(&#39;h2&#39;, {&#39;class&#39;: &#39;a-size-mini a-spacing-none a-color-base s-line-clamp-2&#39;})<br>        brand_element = product.find(&#39;h2&#39;, {&#39;class&#39;: &#39;a-size-mini s-line-clamp-1&#39;})<br>        price_element = product.find(&#39;span&#39;, {&#39;class&#39;: &#39;a-price&#39;})<br>        rating_element = product.find(&#39;i&#39;, {&#39;class&#39;: &#39;a-icon a-icon-star-small a-star-small-4-5 aok-align-bottom&#39;})<br>        delivery_element = product.find(&#39;div&#39;, {&#39;class&#39;: &#39;a-row a-size-base a-color-secondary s-align-children-center&#39;})<br><br>        brand = brand_element.get_text().strip() if brand_element else np.nan<br>        description = description_element.get_text().strip() if description_element else np.nan<br>        price = price_element.get_text().strip() if price_element else np.nan<br>        rating = rating_element.get_text().strip() if rating_element else np.nan<br>        delivery_info = delivery_element.get_text().strip() if delivery_element else np.nan<br><br>        descriptions.append(description)<br>        brands.append(brand)<br>        prices.append(price)<br>        ratings.append(rating)<br>        delivery_infos.append(delivery_info)<br><br>    data = {<br>        &#39;Description&#39;: descriptions,<br>        &#39;Brand&#39;: brands,<br>        &#39;Price&#39;: prices,<br>        &#39;Rating&#39;: ratings,<br>        &#39;Delivery Info&#39;: delivery_infos<br>         }<br><br>    df = pd.DataFrame(data)<br>    df_final = pd.concat([df_final, df])<br><br></pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*E06xbGmSgg5tL9g-qiNsJA.png" /></figure><p><strong>Data cleaning and formatting: </strong><br>Post-extraction, the clean_process_data() function is applied to clean and format the resulting dataframe. This includes removing rows with excessive missing values, extracting rating and price numbers, and creating a column indicating if delivery is free.</p><pre>def clean_process_data(df, product):<br>  df[&#39;Product&#39;] =  product<br>  nan_count = df.isnull().sum(axis=1)<br>  df = df[nan_count &lt;= 3]<br>  df[&#39;Rating&#39;] = df[&#39;Rating&#39;].str.extract(r&#39;(\d+\.\d+)&#39;, expand=False)<br>  df[&#39;Price&#39;] = df[&#39;Price&#39;].str.extract(r&#39;(\d+,\d+)&#39;, expand=False)<br>  df[&#39;Delivery_is_free&#39;] = df[&#39;Delivery Info&#39;].str.contains(&#39;GRÁTIS&#39;, case=False, na=False)<br>  df[&#39;Delivery_is_free&#39;] = df[&#39;Delivery_is_free&#39;].map({True: &#39;Yes&#39;}).fillna(&#39;No&#39;)<br>  df = df[[&#39;Product&#39;, &#39;Brand&#39;, &#39;Description&#39;, &#39;Price&#39;, &#39;Rating&#39;, &#39;Delivery Info&#39;, &#39;Delivery_is_free&#39;]]<br><br>  return df<br><br># cleaning and process the df_final<br>df = clean_process_data(df_final, &#39;Relogio&#39;)</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*B7-fOjX1Ptr-Wenw2qhiDA.png" /><figcaption><strong>Output of our extraction cleaned and processed</strong></figcaption></figure><p>There are still some null values, but the dataset is way better than the first one, allowing us to now extract some insights.</p><h3>Wrap-Up</h3><p>After data collection and organization, we have a structured dataset about products ready for analysis. We can explore the information, conduct statistical analysis, create visualizations, or store the data for future reference.</p><p>I hope this tutorial was useful in understanding web scraping and its practical applications. Experiment with different websites to learn more about this fascinating technique!</p><p><em>If you enjoyed my article and feel like giving a little something back, feel free to give it a round of claps</em> 👏 or <em>buy me a virtual coffee :), link </em><a href="https://ko-fi.com/ricardoandreom"><strong><em>here</em></strong></a><em>.</em></p><p>Your support is greatly appreciated!</p><p>Follow me and my content on:<br><a href="https://www.linkedin.com/in/ricardoandreom/"><strong>Linkedin</strong></a><strong><br></strong><a href="https://public.tableau.com/app/profile/ricardoandreom/vizzes/"><strong>Tableau</strong></a><strong><br></strong><a href="https://ricardoandreom.github.io/ricardo_portfolio_page/"><strong>Portfolio page</strong></a><strong><br></strong><a href="https://twitter.com/HspaceAnalytics"><strong>Football analytics Twitter</strong></a><strong><br></strong><a href="https://www.instagram.com/halfspace_analytics/"><strong>Football analytics Instagram</strong></a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=3abfd90435b5" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Player Scouting Recommender System]]></title>
            <link>https://medium.com/@ricardoandreom/player-scouting-recommendation-system-a77dc3a75790?source=rss-cb92fec91650------2</link>
            <guid isPermaLink="false">https://medium.com/p/a77dc3a75790</guid>
            <category><![CDATA[sports-analytics]]></category>
            <category><![CDATA[football-analytics]]></category>
            <category><![CDATA[math]]></category>
            <category><![CDATA[data-science]]></category>
            <category><![CDATA[football]]></category>
            <dc:creator><![CDATA[Ricardo André]]></dc:creator>
            <pubDate>Wed, 15 Nov 2023 16:59:29 GMT</pubDate>
            <atom:updated>2023-11-17T13:04:04.443Z</atom:updated>
            <content:encoded><![CDATA[<h4>Introduction</h4><p>When it comes to football, a team’s ability to recognize new potential is critical to its success. Using web scraping and a similarity model, I attempted to create a player scouting suggestion based on a player name input.</p><h4>Real-Time Web Scraping</h4><p>The foundation of my project lies in real-time metric collection for all players in the top 5 leagues (excluding goalkeepers) from <a href="https://fbref.com/en/">FBREF</a>. In order to achieve this, I put in place a web scraping engine that gathers data in real-time and presents a comprehensive view of every player’s performance. These metrics go beyond simple traditional numbers, they include things like play efficacy and influence, technical skills, and more.</p><h4>Scaling and Principal Component Analysis</h4><p>After gathering the data, I recognized the need to streamline the information for effective analysis. I implemented standard scaling to normalize the data and employed a dimensionality reduction technique, namely PCA.</p><p>Without normalizing the data, larger-scale features can dominate, skewing the analysis and perhaps resulting in erroneous representations of the data’s main components.</p><p>PCA was employed to reduce the dimensionality of the player feature space. This not only speeds up computation but also captures the most significant aspects of player performance. By retaining the principal components, the system retains the essence of the data while mitigating the curse of dimensionality.</p><h4>Used features</h4><p>Shot Creation Actions<br>Aerial Duels Won%<br>Performance Fouls<br>Crosses<br>Recoveries<br>npxG<br>npxG/Shot’<br>Shots on target<br>Passes completed<br>% Passes completed<br>Key passes<br>xA<br>Passes into final 1/3<br>Long passes attempted<br>Progressive passes<br>Tackles + Interceptions<br>Blocks shots<br>Clearances<br>Take-Ons attempted<br>Take-Ons successful %<br>Carries into penalty area<br>Passes received<br>Progressive passes received<br>Progressive carries</p><p>All metrics are extracted per 90&#39;.</p><h4>Measuring Player Similarity with Cosine Similarity</h4><p>The core of my system is the construction of a player similarity model using cosine similarity. We can now begin to compute the player similarities between the players now that we have the data.</p><p>The cosine similarity is a mathematical measure that calculates the cosine of the angle between two vectors. In this context, these vectors represent the multidimensional feature space encapsulating various player attributes. What makes cosine similarity particularly powerful is its ability to capture not only the magnitude but also the orientation of vectors, providing a nuanced similarity score, offering a comprehensive understanding of how closely players align in terms of playing style.</p><p>To compute similarities, we start by calculating a distance matrix containing Euclidean distances between player data transformed by PCA.</p><p>Then, we apply the following math to this distance matrix and that’s it.</p><p><strong><em>D(A,B) </em></strong>denotes the distance between player A and B<br><em> </em><strong><em>S(A,B) </em></strong>denotes the similarity between player A and B</p><p><strong><em>S(A,B) = 1 / (1 + D(A,B))</em></strong></p><h4>Example — Cosine similarity interpretation</h4><p>Consider two players, A and B. If the cosine similarity between their feature vectors is high, it indicates a close alignment in their playing styles. Conversely, a lower cosine similarity suggests differences in their approaches to the game. This nuanced understanding allows teams to make informed decisions about player acquisitions, ensuring a better fit within the team’s dynamics.</p><h4>Application Workflow</h4><p>The application I developed is intuitive and user-friendly. Users simply input a player’s name into the system, and within seconds, they receive a list of the most similar players. You can also filter the results by league and maximum age. This allows for a detailed understanding of how closely players match in terms of playing style, facilitating informed decision-making during a possible scouting process.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*RUOGpDqFRH-kRImtYs--gw.png" /><figcaption><strong>App layout</strong></figcaption></figure><h4>Final Considerations</h4><p>In a world driven by technology, the fusion of data and sports is transforming how we understand and explore the potential of football players. My tool represents a bold step in this direction, highlighting the importance of embracing innovation to achieve success in the competitive landscape of modern football. As we move forward, it is exciting to contemplate what the future holds for the intersection of sports and technology.</p><h4>If you want to use the app, click <a href="https://player-similarities.streamlit.app/">here</a>. Feedbacks are welcome!!!</h4><p>Really hope you enjoyed your reading and find it useful!!! :)</p><p><em>If you enjoyed my article and feel like giving a little something back, feel free to give it a round of claps</em> 👏 or <em>buy me a virtual coffee :), link </em><a href="https://ko-fi.com/ricardoandreom"><strong><em>here</em></strong></a><em>.</em></p><p>Your support is greatly appreciated!</p><p>Follow me and my content on:<br><a href="https://www.linkedin.com/in/ricardoandreom/"><strong>Linkedin</strong></a><strong><br></strong><a href="https://public.tableau.com/app/profile/ricardoandreom/vizzes/"><strong>Tableau</strong></a><strong><br></strong><a href="https://ricardoandreom.github.io/ricardo_portfolio_page/"><strong>Portfolio page</strong></a><strong><br></strong><a href="https://twitter.com/HspaceAnalytics"><strong>Football analytics Twitter</strong></a><strong><br></strong><a href="https://www.instagram.com/halfspace_analytics/"><strong>Football analytics Instagram</strong></a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=a77dc3a75790" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[How to create a Scatter Plot with Club Badges using Python]]></title>
            <link>https://medium.com/@ricardoandreom/creating-a-scatter-plot-with-club-badges-using-python-27d4a05d9582?source=rss-cb92fec91650------2</link>
            <guid isPermaLink="false">https://medium.com/p/27d4a05d9582</guid>
            <category><![CDATA[soccer-analytics]]></category>
            <category><![CDATA[football-analytics]]></category>
            <category><![CDATA[football]]></category>
            <category><![CDATA[data-visualization]]></category>
            <category><![CDATA[data-science]]></category>
            <dc:creator><![CDATA[Ricardo André]]></dc:creator>
            <pubDate>Thu, 19 Oct 2023 23:43:12 GMT</pubDate>
            <atom:updated>2023-10-27T09:36:52.712Z</atom:updated>
            <content:encoded><![CDATA[<h3>Introduction</h3><p>In this tutorial we will create a scatter plot with club badges using Python. What sets this tutorial apart is our use of club badges as markers, adding a personalized touch to the visual representation of data. Note that this will be a beginners tutorial. <br>We’ll focus on Premier League teams’ Expected Goals (xG) and Expected Goals Against (xGA) metrics.</p><p>By the end of this tutorial, you’ll not only have a stunning visualization but also a versatile technique that you can apply to various other metrics and datasets.</p><h3>Prerequisites</h3><p>Please make sure you have the necessary libraries installed:</p><pre>import pandas as pd<br>import matplotlib.pyplot as plt<br>from matplotlib.offsetbox import OffsetImage, AnnotationBboxpyt</pre><p>You can install these libraries using the following command on your cmd:</p><pre>pip install pandas matplotlib</pre><h3>Step 1: Data Preparation</h3><p>Our first step is to gather the data. We’ll be using a CSV file containing crucial metrics for each Premier League team. Specifically, we’re interested in ‘Squad’, ‘MP’ (Matches Played), ‘Pts’ (Points), ‘xGA’ (Expected Goals Against), ‘xG’ (Expected Goals), and ‘xGD’ (Expected Goal Difference).</p><p>If you don’t know where to gather football data, <a href="https://fbref.com/en/"><strong>fbref</strong></a> is a good place to start and explore!</p><pre># read the dataset<br>df = pd.read_csv(&#39;prem_table.csv&#39;, usecols=[&#39;Squad&#39;,&#39;MP&#39;,&#39;Pts&#39;,&#39;xGA&#39;,&#39;xG&#39;,&#39;xGD&#39;])<br># computing metrics per 90<br>df[&#39;xG/90&#39;] = df[&#39;xG&#39;] / df[&#39;MP&#39;]<br>df[&#39;xGA/90&#39;] = df[&#39;xGA&#39;] / df[&#39;MP&#39;]<br>df[&#39;xGD/90&#39;] = df[&#39;xGD&#39;] / df[&#39;MP&#39;]<br>df[&#39;Points/90&#39;] = df[&#39;Pts&#39;] / df[&#39;MP&#39;]<br><br>df</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/931/1*Byes0RGwI2f6_SnwXILPLA.png" /></figure><p>The next step is adding a column to your dataset that contains file paths to club badges. Step-by-step explanation:</p><ol><li><strong>Create a Club Badge Path Column: </strong>This means you’ll be adding a new column to your dataset.</li><li><strong>Download the Club Badges: </strong>You need to obtain the images of the club badges from a source, possibly from the internet or any other location where they are available.</li><li><strong>Name the Images:</strong> Each badge image needs to be named after the corresponding team’s name in the ‘Squad’ column. For example, if a team is named ‘Manchester United’ in your dataset, the badge image file should also be named ‘Manchester United.png’ (or whatever format the images are in).</li></ol><p>So, essentially, you’re ensuring that each team in your dataset has a corresponding badge image with the same name as the team’s name. This way, you can easily link the team to its badge in your visualization code.</p><pre># creating a club badge path column for each team<br>df[&#39;path&#39;] = df[&#39;Squad&#39;] + &#39;.png&#39;<br>df</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*dAG9Q4OGPYDWN3HKa3Gmgw.png" /></figure><h3>Step 2: Adding Club Badges</h3><p>To add a unique flair to our visualization, we define a function getImage(path) that reads and resizes the club badges.</p><pre>def getImage(path):<br>    return OffsetImage(plt.imread(path), zoom=.05, alpha=1)</pre><h3>Step 3: Plotting Club Badges</h3><p>With our badges ready, we create the initial scatter plot and overlay the club badges. This combination of data and visual elements will make our plot both informative and visually appealing.</p><pre># Set background colour<br>bgcol = &#39;#fafafa&#39;<br><br># Create initial plot<br>fig, ax = plt.subplots(figsize=(9, 6), dpi=120)<br>fig.set_facecolor(bgcol)<br>ax.set_facecolor(bgcol)<br>ax.scatter(df[&#39;xG/90&#39;], df[&#39;xGA/90&#39;], c=bgcol)<br><br># Change plot spines<br>ax.spines[&#39;right&#39;].set_visible(False)<br>ax.spines[&#39;top&#39;].set_visible(False)<br>ax.spines[&#39;left&#39;].set_color(&#39;#ccc8c8&#39;)<br>ax.spines[&#39;bottom&#39;].set_color(&#39;#ccc8c8&#39;)<br><br># Change ticks<br>plt.tick_params(axis=&#39;x&#39;, labelsize=12, color=&#39;#ccc8c8&#39;)<br>plt.tick_params(axis=&#39;y&#39;, labelsize=12, color=&#39;#ccc8c8&#39;)<br><br><br>for index, row in df.iterrows():<br>    ab = AnnotationBbox(getImage(row[&#39;path&#39;]), (row[&#39;xG/90&#39;], row[&#39;xGA/90&#39;]),<br>                        frameon=False)<br>    ax.add_artist(ab)</pre><h3>Step 4: Adding Average Lines</h3><p>For context, we add average lines for xG and xGA. This will help viewers quickly gauge how each team compares to the league averages.</p><pre>plt.hlines(df[&#39;xG/90&#39;].mean(), df[&#39;xGA/90&#39;].min(), df[&#39;xGA/90&#39;].max(), color=&#39;#c2c1c0&#39;)<br>plt.vlines(df[&#39;xG/90&#39;].mean(), df[&#39;xGA/90&#39;].min(), df[&#39;xG/90&#39;].max(), color=&#39;#c2c1c0&#39;)</pre><h3>Step 5: Adding Text and Labels</h3><p>With the visual elements in place, we add the finishing touches. A descriptive title, axis labels, and acknowledgments for the data source and creator enhance the plot’s professionalism.</p><pre>plt.title(&#39;xG vs xGA Premier League teams&#39;, fontsize=12)<br>plt.ylabel(&#39;xGA/90&#39;, fontsize=10)<br>plt.xlabel(&#39;xG/90&#39;, fontsize=10)<br>fig.text(.76, 0.0, &#39;Made by @ricardoandreom\nData from Fbref&#39;, size=7, fontweight=&#39;bold&#39;)</pre><p><strong>Whole code to create the scatter plot:</strong></p><pre># Set background colour<br>bgcol = &#39;#fafafa&#39;<br><br># Create initial plot<br>fig, ax = plt.subplots(figsize=(9, 6), dpi=120)<br>fig.set_facecolor(bgcol)<br>ax.set_facecolor(bgcol)<br>ax.scatter(df[&#39;xG/90&#39;], df[&#39;xGA/90&#39;], c=bgcol)<br><br># Change plot spines<br>ax.spines[&#39;right&#39;].set_visible(False)<br>ax.spines[&#39;top&#39;].set_visible(False)<br>ax.spines[&#39;left&#39;].set_color(&#39;#ccc8c8&#39;)<br>ax.spines[&#39;bottom&#39;].set_color(&#39;#ccc8c8&#39;)<br><br># Change ticks<br>plt.tick_params(axis=&#39;x&#39;, labelsize=12, color=&#39;#ccc8c8&#39;)<br>plt.tick_params(axis=&#39;y&#39;, labelsize=12, color=&#39;#ccc8c8&#39;)<br><br># Plot badges<br>def getImage(path):<br>    return OffsetImage(plt.imread(path), zoom=.05, alpha = 1)<br><br>for index, row in df.iterrows():<br>    ab = AnnotationBbox(getImage(row[&#39;path&#39;]), (row[&#39;xG/90&#39;], row[&#39;xGA/90&#39;]),<br>                        frameon=False)<br>    ax.add_artist(ab)<br><br># Add average lines<br>plt.hlines(df[&#39;xG/90&#39;].mean(), df[&#39;xGA/90&#39;].min(), df[&#39;xGA/90&#39;].max(), color=&#39;#c2c1c0&#39;)<br>plt.vlines(df[&#39;xG/90&#39;].mean(), df[&#39;xGA/90&#39;].min(), df[&#39;xG/90&#39;].max(), color=&#39;#c2c1c0&#39;)<br><br>##### Text<br><br>## Title &amp; comment<br>plt.title(&#39;xG vs xGA Premier League teams&#39;,fontsize=12)<br># Axis labels<br>plt.ylabel(&#39;xGA/90&#39;,fontsize=10)<br>plt.xlabel(&#39;xG/90&#39;,fontsize=10)<br>#fig.text(.48,.85,&quot;Data per 90&#39;&quot;,size=7, fontweight=&#39;bold&#39;)<br>fig.text(.76,0.0,&#39;Made by @ricardoandreom\nData from Fbref&#39;, size=7,<br>         fontweight=&#39;bold&#39;)<br><br>## Mean average lines labels<br>fig.text(.54,.4,&#39;Avg xGA/90&#39;, size=8, color=&#39;#c2c1c0&#39;)<br>fig.text(.41,.17,&#39;Avg xG/90&#39;, size=8, color=&#39;#c2c1c0&#39;,rotation=90)<br><br># Save plot<br>plt.savefig(&#39;PL_xGxGA.png&#39;, dpi=500, bbox_inches = &quot;tight&quot;)</pre><h3><strong>Output</strong></h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*itFNvxsA53nAE675sSM2-A.png" /></figure><h4>Looks great, right? Now, it’s your turn!</h4><p>By combining data visualization with club badges, we’ve created a visually appealing scatter plot that provides insights into Premier League teams’ performance. This technique can be extended to other metrics and datasets and off course other teams, allowing for creative and informative visualizations in various domains also apart from football.</p><p>Really hope you enjoyed your reading and find it useful!!! :)</p><p><em>If you enjoyed my article and feel like giving a little something back, feel free to buy me a virtual coffee :), link </em><a href="https://ko-fi.com/ricardoandreom"><strong><em>here</em></strong></a><em>.</em></p><p>Follow me and my content on:<br><a href="https://www.linkedin.com/in/ricardoandreom/"><strong>Linkedin</strong></a><strong><br></strong><a href="https://public.tableau.com/app/profile/ricardoandreom/vizzes/"><strong>Tableau</strong></a><strong><br></strong><a href="https://ricardoandreom.github.io/ricardo_portfolio_page/"><strong>Portfolio page</strong></a><strong><br></strong><a href="https://twitter.com/HspaceAnalytics"><strong>Football analytics Twitter</strong></a><strong><br></strong><a href="https://www.instagram.com/halfspace_analytics/"><strong>Football analytics Instagram</strong></a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=27d4a05d9582" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Poisson distribution to predict match results]]></title>
            <link>https://medium.com/@ricardoandreom/poisson-distribution-to-predict-match-results-c4032dcef949?source=rss-cb92fec91650------2</link>
            <guid isPermaLink="false">https://medium.com/p/c4032dcef949</guid>
            <category><![CDATA[data-science]]></category>
            <category><![CDATA[poisson-distribution]]></category>
            <category><![CDATA[soccer-analytics]]></category>
            <category><![CDATA[football-analytics]]></category>
            <category><![CDATA[soccer]]></category>
            <dc:creator><![CDATA[Ricardo André]]></dc:creator>
            <pubDate>Mon, 16 Oct 2023 23:17:05 GMT</pubDate>
            <atom:updated>2023-11-22T00:37:55.942Z</atom:updated>
            <content:encoded><![CDATA[<h3>Context</h3><p>Events in football, such as goals and corners, often seem to occur in a seemingly random and unpredictable manner. However, behind this apparent chaos lies a probability distribution that governs these occurrences—the Poisson distribution.</p><p>In probability theory and statistics, the <strong>Poisson distribution</strong> is a discrete probability distribution that expresses the probability of a given number of events occurring in a fixed interval of time or space if these events occur with a known constant mean rate (<em>lambda</em>) and independently of the time since the last event.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/894/1*FFCxrnkOyI13apRT7H4v3A.png" /></figure><p>In this context, the <em>lambda</em> will represent the average rate of goals, and we need to assume that the number of goals scored in a match is independent of time.</p><p>With the popularity of betting games increasing in recent years, <strong>how about attempting to predict some match results using Python?</strong></p><p>In this article, I’ll present a fundamental approach, inspired by <strong>David Sheelan’s</strong> blog and <strong>Soccermatics</strong>, on how to use the Poisson distribution to predict match results.<br>We’ll dive into some details and assess the model’s performance, ultimately addressing the question of whether the number of goals scored by each team can be approximated by a Poisson distribution.</p><p>But before we embark on model creation, result prediction, and validation, we need the data. So, let’s retrieve the data from the previous Liga Portugal season. You can find and extract the data<strong> </strong><a href="https://www.football-data.co.uk/portugalm.php"><strong>here</strong></a>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/907/1*4eeyjC1Zz5ps8z0yNEtj6Q.png" /></figure><p>Once we’ve gathered the necessary data, we need to establish a test data set. Given that there are a total of 18 teams competing in Liga Portugal, we removethe last 9 rows to simulate predictions for the final matchday. Now, our focus shifts towards determining the average goals scored both at home and away.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/501/1*x9C5XPgfZvHMmhWYndztgw.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/385/1*yF8sIrs7aOlAnLIpULxFvQ.png" /></figure><p>For soccer enthusiasts, this outcome comes as no surprise. On average, home teams tend to score more goals than their opponents.</p><p>Additionally, let’s explore the example below to help in your comprehension of the code and gather some insights.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/433/1*GZ1IsX2oMyf5ayBIZdwVTQ.png" /></figure><p>This output tells us that the probability of the home team scoring one goal is 34.51%, while there is a 19.7% chance of the away team scoring two goals.</p><p>Let’s now visualize the number of goals per match compared to the number of goals per match predicted by the Poisson model, for both the home and away sides.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/760/1*aB9ssb3IfD0YQ7T--NkVVg.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*VUxnWDhnKbUujNHmps4PoQ.png" /></figure><p>The bars represent the actual number of goals in the Liga Portugal 2022/23 season and the lines illustrate our Poisson-calculated values.</p><p>It’s really interesting to see how closely the lines align with the actual distribution. As mentioned earlier, the Poisson distribution proves to be a valuable approach for making such predictions. Let’s continue with our analysis.</p><h3>Predict a match of the Liga Portugal</h3><p>We’ve observed that the calculated average number of goals in average fits the real distribution. Now the next question now is how can we predict the amount of goals for a match? We are going to use Poission Regression for that.</p><p>Let’s try a match between Porto and Benfica.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/583/1*3rMOQf5TuEABlbOrutfG_Q.png" /></figure><p>The formula (highlighted in blue) is modeling the relationship between the number of goals and other explanatory variables using a Poisson regression model.<br>Essentially, the model is attempting to understand how the probability of scoring goals is influenced by whether the team is playing at home (home), as well as by the specific teams involved (team and opponent).</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/450/1*RnAAj2ZFJCAynzXqhO1eUA.png" /></figure><p>Let’s analyse this general poisson regression model. The number of observations is 594 (33 matchdays for 18 teams).</p><h4>How to interpret this output?</h4><p>All the coefficients and estimations are referenced in relation to the Intercept line (baseline rate).<br>The last row, ‘home 0.2813’, underscores the significance of home advantage, leading us to conclude once again that home teams tend to score more goals than away teams.<br>The team coefficient for Porto is 0.7047, indicating that Porto scores more goals than average teams. A lower coefficient suggests that a team scores fewer goals on average. On the other side, the opponent coefficient for Benfica is -0.5531, indicating that Benfica tends to concede fewer goals than an average team.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/732/1*wcdTQq3bwMqFE_VUHvVxLg.png" /><figcaption>Porto vs Benfica — simulation result</figcaption></figure><p>In this simulation, I obtained a draw (1–1) for Porto vs Benfica. <br>The result is indeed quite satisfactory. However, if you persist in simulating outcomes for these teams, you may encounter some rather improbable results. This stands as one of the limitations of this model.</p><p>The sample size is relatively small (with each team playing at most 19 home/away games) and this can lead to significant variations in the accuracy of this approximation, particularly in the earlier stages of the season when teams have played fewer games.</p><p>Let’s proceed to simulate the final round of Liga Portugal 2022/23, following the previous methods.</p><h3>Predict the final round of Liga Portugal 2022/23</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/681/1*6V_Fs0TCtN9QeCGcL0AKkA.png" /></figure><p>In the code above, first we obtain a dataframe with the predictions and then we compute the columns the columns that tells us if the prediction leads us to win a 1x2 prediction and if got a match result exactly.</p><p>In the above code, initially, we generate a dataframe containing the predictions. Then, we calculate the columns that that tells us if the prediction leads us to win a 1x2 bet and if it accurately matches the final result. Below, is the our final output with the predictions for the final round of Liga Portugal 2022/23.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1005/1*3Th2Cj2hRR8_FDAgywAxqw.png" /></figure><p>I’d say that is quite surprising that we achieved an exact 33% accuracy in match results and an impressive 66% accuracy in 1x2 predictions. These outcomes are exceptionally favorable, especially considering our basic approach.</p><p>Aditionally, note that our predictions were limited to a single match, and it happened to fall on the final matchday. Typically, this specific day tends to be less predictable due to some teams already having secured their final standings. This can result in reduced motivation and, consequently, weaker performances.</p><p>Taking all this into account, I think our predictions turned out to be remarkably accurate. It’s worth noting that building on this foundation, it may be worthwhile to explore more sophisticated models in the future.</p><p>Really hope you enjoyed your reading and find it useful!!! :)</p><p><em>If you enjoyed my article and feel like giving a little something back, feel free to give it a round of claps</em> 👏 or <em>buy me a virtual coffee :), link </em><a href="https://ko-fi.com/ricardoandreom"><strong><em>here</em></strong></a><em>.</em></p><p>Your support is greatly appreciated!</p><p>Follow me and my content on:<br><a href="https://www.linkedin.com/in/ricardoandreom/"><strong>Linkedin</strong></a><strong><br></strong><a href="https://public.tableau.com/app/profile/ricardoandreom/vizzes/"><strong>Tableau</strong></a><strong><br></strong><a href="https://ricardoandreom.github.io/ricardo_portfolio_page/"><strong>Portfolio page</strong></a><strong><br></strong><a href="https://twitter.com/HspaceAnalytics"><strong>Football analytics Twitter</strong></a><strong><br></strong><a href="https://www.instagram.com/halfspace_analytics/"><strong>Football analytics Instagram</strong></a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=c4032dcef949" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Who could be Benzema’s replacement & successor at Real Madrid?]]></title>
            <link>https://medium.com/@ricardoandreom/who-could-be-benzemas-replacement-successor-at-real-madrid-8c902d77a39d?source=rss-cb92fec91650------2</link>
            <guid isPermaLink="false">https://medium.com/p/8c902d77a39d</guid>
            <category><![CDATA[football]]></category>
            <category><![CDATA[scouting]]></category>
            <category><![CDATA[data-analysis]]></category>
            <category><![CDATA[real-madrid]]></category>
            <category><![CDATA[machine-learning]]></category>
            <dc:creator><![CDATA[Ricardo André]]></dc:creator>
            <pubDate>Sun, 07 May 2023 17:06:40 GMT</pubDate>
            <atom:updated>2023-10-19T22:16:21.849Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*1zL0pNIoo7O75XlpaowuuA.jpeg" /></figure><p>Real Madrid is going through a phase of renewing its squad and very well so far with the signings for the next decade of <strong>Militão</strong>, <strong>Tchouaméni, Camavinga, Vinicius and Rodrigo. </strong>However<strong>, </strong>one of the positions that still needs to be filled is the striker position, where <strong>Karim Benzema has been the undisputed protagonist</strong>.</p><p>As a personal project, I decided to use my experience in data analysis and machine learning to help Real Madrid find the ideal successor for Benzema.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*T6whZNOLS5gOoWKw-Ja5jA.jpeg" /></figure><h4>Real Madrid’s recruitment policy in recent seasons</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*AGAITsEeYd6RI3Bc_z4p0g.jpeg" /></figure><p>First, I analyzed Real Madrid’s recruitment policy since the 2019/20 season. Noticed that the money spent on players per season is 116.5 million euros, and the <strong>money spent per signing is 38.8 million euros</strong>.<br><strong>25% of signings were made for free</strong>. Excluding free signings, only two players (<strong>Areola</strong> and <strong>Hazard</strong>) over the age of 24 were signed, and the <strong>average age of signings was 22 years old.</strong></p><h4>Signing requisites</h4><p>I think we all agree that both Areola and specially Hazard (inflating the average money spent per due to his 100M transfer fee) were good signings.In my point of view, there is no interesting forwards running out of contract, so I think that won’t be an option summer window to replace Benzema.</p><p>Based on this analysis,<strong> I decided to search for players with a maximum age of 25 years and a market value below 80 million euros</strong>, using a machine learning model I developed.</p><h4>Process</h4><p>After applying the model to Benzema, I obtained a list of the 14 most similar players with the levels of similarity in Top-5 Leagues.</p><p>In order to create this model, I collected data from FBref and organized it through web scraping. Next, I applied principal component analysis (PCA) to reduce the dimensionality of the data features, which allowed me to cluster the players based on their characteristics. Finally, I measured the level of similarity between the clusters using the Euclidean distance between their points.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*rdMlX3YLD_YqBGBBRZ3g-g.jpeg" /></figure><p>Now, let’s a look a the profiles of the most similar players to Benzema through radar charts and other relevant information.</p><h3>Report</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*vzzxLvhLLzZC3q21FZKfww.jpeg" /></figure><p>Kylian Mbappe is a French forward who is widely regarded as one of the best players in world football. His explosive pace and dribbling ability make him a nightmare for defenders to deal with. Mbappe’s finishing is also highly impressive, with his coolness and composure in front of goal. Additionally, he has a high level of work rate and tactical intelligence, which allows him to contribute defensively as well as offensively.</p><p>Mbappe is an old Real Madrid dream but the problem is the high price associated.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*vSqd_A7evWJue0ED97GcZA.jpeg" /></figure><p>Ademola Lookman is an Nigerian forward who can play as both a winger and a striker. He is a technically gifted player with excellent ball control and dribbling ability. He possesses a blistering turn of pace and is capable of beating defenders in one-on-one situations. He has a keen eye for goal and is capable of scoring from distance. He is also a hard worker who is willing to track back and contribute defensively.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*aQ0TIzm922_NeI43zokjQg.jpeg" /></figure><p>Christopher Nkunku is known for his technical ability, vision, and creativity on the ball.</p><p>Christopher Nkunku is a French atacking midfielder who possesses excellent technical ability and creativity. He is an intelligent player who can operate in a variety of positions, including central midfield, attacking midfield, and on the wings. Nkunku’s passing range is exceptional, with the ability to play incisive through balls and create chances for his teammates. He is also a hard worker who is willing to contribute defensively and press the opposition. While his finishing is not a particular strength, he is still a dangerous player who can contribute to his team’s attacking play.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*70HHDYuQEyJTk9O3PEaUfQ.jpeg" /></figure><p>Donyell Malen is a Dutch forward with an eye for goal. His sharp movements and clinical finishing make him a constant threat in the final third. He possesses impressive speed and agility, allowing him to create separation from defenders and get in behind the backline. Malen is also comfortable on the ball and has the ability to beat his man with a dribble. While his defensive work rate is not exceptional, he can still contribute to pressing and harrying the opposition.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*L8TdCm0mPAkcEVGZY1JMSQ.jpeg" /></figure><p>Darwin Nunez is a Uruguayan forward who possesses a rare combination of strength, skill, and pace. His powerful physique allows him to hold off defenders and win aerial duels, while his dribbling ability and close control make him a danger in one-on-one situations. Nunez is also an excellent finisher, with a keen eye for goal and good instincts in the box.</p><p>Off the ball, Núñez is a hard-working player who contributes to his team’s pressing and defensive efforts. He is willing to track back and help out in defense, making him a valuable asset both in attack and defense.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*EbHFFk8iZr1Ahlyd17-4kA.jpeg" /></figure><p>Moussa Diaby is a French forward who possesses impressive speed and dribbling ability. He is a dynamic player who can operate anywhere across the front line, and his ability to create space and get in behind defenders makes him a constant threat on the counter-attack. Diaby is also an excellent passer, with good vision and creativity in the final third. While his finishing can be inconsistent at times, he is still a dangerous player who can contribute to his team’s attacking play.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*8TzR9ohM0xcwBaAEBoO97A.jpeg" /></figure><p>Jonathan David is a Canadian forward who possesses a wide range of attacking qualities. He is a versatile player who can play anywhere across the front line, and his pace and dribbling ability make him a constant threat on the counter-attack. David is also an excellent finisher, with a keen eye for goal and good instincts in the box. Additionally, he is a hard worker who is willing to contribute defensively and press the opposition.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*uh-LvC3XIXM3MllM_ssR7g.jpeg" /></figure><p>Rafael Leão is a Portuguese forward who possesses a rare combination of speed, power, and technical ability. His pace makes him a constant threat on the counter-attack, while his dribbling skills and close control allow him to take on defenders in one-on-one situations. Leão is also an excellent finisher, with a powerful shot and good instincts in the box. While his defensive work rate is not exceptional, he can still contribute to pressing and harrying the opposition.</p><p>Leão is seen as a player with immense potential to become one of the best players in the world.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ld0Um9Y6mo070PrFwOj7Fw.jpeg" /></figure><p>Højlund is a powerful center forward with excellent ball-striking ability and movement. He is comfortable playing in a variety of roles, including as an isolated lone forward or as part of a strike pairing with an AM behind. He possesses impressive footwork and close control for a player of his height and uses these skills to create separation from defenders and take shots on goal. Hojlund is also an extremely hard worker who presses eagerly and constantly.</p><p>Hojlund is not far from being a finished product and has the potential to become a ruthless finisher in front of goal and one of the best strikers in Europe.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ghSy0DyWnT1N3z9dUmUUXw.jpeg" /></figure><p>Amine Gouiri is a French forward who primarily operates as a striker but can also play on the wings. He is a technically gifted player who possesses excellent ball control and dribbling skills. He has a keen eye for goal and is a natural finisher, capable of scoring from a variety of positions. He is a tireless worker who is always looking to press and win the ball back for his team.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*8Cik_DdlO4pG4zbWqYcodQ.jpeg" /></figure><p>Kolo Muani is a French forward who plays primarily as a central striker. He is a strong, powerful player who uses his physicality to great effect on the field. He is an excellent dribbler who is comfortable taking on defenders and has a keen eye for goal. He is also an intelligent player who is able to make clever runs to create space for himself and his teammates.</p><h3>Signings non-suggested by model</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*bS4JHZtYp3xD9HZJi98ApQ.jpeg" /></figure><p>Kai Havertz is a German attacking midfielder who is known for his versatility, technical ability, and vision. He is equally adept at playing as a number 10 or on either wing. His height and physique make him a formidable presence on the field, and he is an excellent dribbler who is comfortable with the ball at his feet. He has excellent vision and passing ability and is capable of unlocking defenses with his incisive through balls. He also possesses a lethal shot and is a threat from distance.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*LMRKJxprxdtzQVDXwX-WHw.jpeg" /></figure><p>Gabriel Jesus is a Brazilian striker who possesses a lethal combination of technical ability, speed, and finishing prowess. He has the versatility to play as both a central striker and a wide attacker. He is known for his excellent movement off the ball, making intelligent runs to exploit gaps in opposition defenses. His close control is excellent, and he is capable of dribbling past defenders with ease. He is also a tireless worker who is willing to track back and contribute defensively.</p><h3>Final choices</h3><p>Based on the prerequisites, the role of Benzema &amp; player profiles, and market limitations, I have selected these five players for consideration.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*V8304EalIMPfbKmXH3ft8g.jpeg" /></figure><p>Hope that you find some of this players interesting to replace Benzema in the future. Who would be your choices? Do you have different names?</p><p>Hope you enjoyed your reading!!!</p><p><em>If you enjoyed my article and feel like giving a little something back, feel free to buy me a virtual coffee :), link </em><a href="https://ko-fi.com/ricardoandreom"><strong><em>here</em></strong></a><em>.</em></p><p>Follow me and my content on :<br><a href="https://www.linkedin.com/in/ricardoandreom/"><strong>Linkedin</strong></a><strong><br></strong><a href="https://public.tableau.com/app/profile/ricardoandreom/vizzes/"><strong>Tableau</strong></a><strong><br></strong><a href="https://ricardoandreom.github.io/ricardo_portfolio_page/"><strong>Portfolio page</strong></a><strong><br></strong><a href="https://twitter.com/HspaceAnalytics"><strong>Football analytics Twitter</strong></a><strong><br></strong><a href="https://www.instagram.com/halfspace_analytics/"><strong>Football analytics Instagram</strong></a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=8c902d77a39d" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[How to scrape and personalize data from FBref with Python: A guide to unlocking Football Insights]]></title>
            <link>https://medium.com/@ricardoandreom/how-to-scrape-and-personalize-data-from-fbref-with-python-a-guide-to-unlocking-football-insights-7e623607afca?source=rss-cb92fec91650------2</link>
            <guid isPermaLink="false">https://medium.com/p/7e623607afca</guid>
            <category><![CDATA[python-webscraping]]></category>
            <category><![CDATA[football-analytics]]></category>
            <category><![CDATA[football]]></category>
            <category><![CDATA[data-visualization]]></category>
            <category><![CDATA[data-analysis]]></category>
            <dc:creator><![CDATA[Ricardo André]]></dc:creator>
            <pubDate>Thu, 06 Apr 2023 17:16:39 GMT</pubDate>
            <atom:updated>2023-11-22T00:58:38.537Z</atom:updated>
            <content:encoded><![CDATA[<p>Football enthusiasts around the world are always on the hunt for new ways to explore and analyze the game. Fortunately, <a href="https://fbref.com/en/"><strong>FBref</strong></a> provides a wealth of open-source data that can be scraped and analyzed to unlock valuable insights.</p><p>In this article, we will demonstrate how to scrape league and player statistics tables from FBref using Pandas (a Python library). By leveraging HTML tables, we’ll show you how to extract and customize this data to better understand the game and players.</p><p>First of all, we need to identify what table of FBREF we want to scrape. Let’s try scraping Top-5 league player data. If you explore FBref you’ll find this data in this <a href="https://fbref.com/en/comps/Big5/gca/players/Big-5-European-Leagues-Stats"><strong>link</strong></a><strong>: </strong><a href="https://fbref.com/en/comps/Big5/gca/players/Big-5-European-Leagues-Stats">https://fbref.com/en/comps/Big5/gca/players/Big-5-European-Leagues-Stats</a></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*JAilmkXq3p0tb1PuwtsDxQ.png" /><figcaption>fbref table</figcaption></figure><p>Let’s start the code. To extract data from an HTML table using Python, we can use the “Pandas” library. First, we import this library and then provide the URL for the table inside the pd.read_html() function.</p><pre># libraries<br>import pandas as pd<br><br># fbref table link<br>url_df = &#39;https://fbref.com/en/comps/Big5/gca/players/Big-5-European-Leagues-Stats#stats_gca&#39;<br><br>df = pd.read_html(url_df)<br>df</pre><p>As shown below, the format of the scraped table can be difficult to work with and interpret.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/924/1*hssngL1-OUha1_jE9Z91wQ.png" /><figcaption>df</figcaption></figure><p>Let’s now extract the table at index [0] and voilà.</p><pre>df = pd.read_html(url_df)[0]<br>df.head()</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ro9_92NLrNxS94g0dZHuMQ.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/867/1*K-alICsj7LvyAa6p5E7o6A.png" /><figcaption>df and df.info()</figcaption></figure><p>Our primary objective has been achieved. We have successfully scraped the data. However, the resulting dataframe has a multi-index, and our task is to remove this multi-index, create new headers, and slightly modify the dataframe.</p><pre># creating a data with the same headers but without multi indexing<br>df.columns = [&#39; &#39;.join(col).strip() for col in df.columns]<br><br>df = df.reset_index(drop=True)<br>df.head()</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*CKPXNc9vOp-uTjsSo8WnAQ.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/913/1*fqFfXPUduOrJTW-U4zVOLw.png" /><figcaption>df and df.info()</figcaption></figure><p>Look at <strong>df.info()</strong> and how the structure of the dataframe is different now.</p><p>Let’s now rename some columns, removing the ‘level_0’s.</p><pre># creating a list with new names<br>new_columns = []<br>for col in df.columns:<br>  if &#39;level_0&#39; in col:<br>      new_col = col.split()[-1]  # takes the last name<br>  else:<br>      new_col = col<br>  new_columns.append(new_col)<br><br># rename columns<br>df.columns = new_columns<br>df = df.fillna(0)<br><br>df.head()</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*exd-OtYSYqosuS_527tHGw.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1000/1*UM91jtoTEI6K5EJtqKXk8g.png" /></figure><p>If you take a look at the DataFrame at this point, you may notice that the ‘Age’ column appears to be in an unusual format.</p><p>Additionally, the ‘Pos’ (position) column sometimes contains multiple positions for players who are able to play efficiently in more than one position. To address these issues, I will split the ‘Pos’ column into two separate columns, one for the primary position and another for a secondary position if one exists.</p><p>I also think that the format of the ‘Nation’ and ‘Comp’ (competition) columns could be improved. Therefore, I will make some changes to the DataFrame to address these issues and make it more readable.</p><pre>df[&#39;Age&#39;] = df[&#39;Age&#39;].str[:2]<br>df[&#39;Position_2&#39;] = df[&#39;Pos&#39;].str[3:]<br>df[&#39;Position&#39;] = df[&#39;Pos&#39;].str[:2]<br>df[&#39;Nation&#39;] = df[&#39;Nation&#39;].str.split(&#39; &#39;).str.get(1)<br>df[&#39;League&#39;] = df[&#39;Comp&#39;].str.split(&#39; &#39;).str.get(1)<br>df[&#39;League_&#39;] = df[&#39;Comp&#39;].str.split(&#39; &#39;).str.get(2)<br>df[&#39;League&#39;] = df[&#39;League&#39;] + &#39; &#39; + df[&#39;League_&#39;]<br>df = df.drop(columns=[&#39;League_&#39;, &#39;Comp&#39;, &#39;Rk&#39;, &#39;Pos&#39;,&#39;Matches&#39;])<br><br>df[&#39;Position&#39;] = df[&#39;Position&#39;].replace({&#39;MF&#39;: &#39;Midfielder&#39;, &#39;DF&#39;: &#39;Defender&#39;, &#39;FW&#39;: &#39;Forward&#39;, &#39;GK&#39;: &#39;Goalkeeper&#39;})<br>df[&#39;Position_2&#39;] = df[&#39;Position_2&#39;].replace({&#39;MF&#39;: &#39;Midfielder&#39;, &#39;DF&#39;: &#39;Defender&#39;,<br>                                                 &#39;FW&#39;: &#39;Forward&#39;, &#39;GK&#39;: &#39;Goalkeeper&#39;})<br>df[&#39;League&#39;] = df[&#39;League&#39;].fillna(&#39;Bundesliga&#39;)</pre><p>Finally, we have arrived at our and improved dataset, which is now ready to be used for creating valuable football insights and analysis.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*j8CcbIKAU6ygyBVpfcTEyg.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/535/1*o_CgjY9v00raOxFDBjTzVQ.png" /></figure><p>Did you like the final result? Will it be useful for you? Hope so :))</p><p>Really hope you enjoyed your reading and find it useful!!! :)</p><p><em>If you enjoyed my article and feel like giving a little something back, feel free to give it a round of claps</em> 👏 or <em>buy me a virtual coffee :), link </em><a href="https://ko-fi.com/ricardoandreom"><strong><em>here</em></strong></a><em>.</em></p><p>Your support is greatly appreciated!</p><p>Follow me and my content on:<br><a href="https://www.linkedin.com/in/ricardoandreom/"><strong>Linkedin</strong></a><strong><br></strong><a href="https://public.tableau.com/app/profile/ricardoandreom/vizzes/"><strong>Tableau</strong></a><strong><br></strong><a href="https://ricardoandreom.github.io/ricardo_portfolio_page/"><strong>Portfolio page</strong></a><strong><br></strong><a href="https://twitter.com/HspaceAnalytics"><strong>Football analytics Twitter</strong></a><strong><br></strong><a href="https://www.instagram.com/halfspace_analytics/"><strong>Football analytics Instagram</strong></a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=7e623607afca" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Uncovering Manchester City’s Center-Backs chameleonic back line of 4]]></title>
            <link>https://medium.com/@ricardoandreom/uncovering-manchester-citys-center-backs-chameleonic-back-line-of-4-4fbfcc401679?source=rss-cb92fec91650------2</link>
            <guid isPermaLink="false">https://medium.com/p/4fbfcc401679</guid>
            <category><![CDATA[data-visualization]]></category>
            <category><![CDATA[football]]></category>
            <category><![CDATA[manchester-city]]></category>
            <category><![CDATA[football-analytics]]></category>
            <category><![CDATA[premier-league]]></category>
            <dc:creator><![CDATA[Ricardo André]]></dc:creator>
            <pubDate>Thu, 06 Apr 2023 11:20:38 GMT</pubDate>
            <atom:updated>2023-10-19T22:17:01.498Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/450/1*-7TTovdvC4HvadASqeQTCA.png" /><figcaption>4 CBs line-up vs Liverpool</figcaption></figure><p><strong>A lot of people were caught by surprise, but with Guardiola every idea cannot be disregarded easily. If he believes it will work eventually!!</strong></p><p>Everyone is talking about Manchester City due to the fact that in recent games, Manchester City has been playing with four center-backs, which is quite unusual in modern football where attacking full-backs are often the norm. However, City’s results speak for themselves, and they have been performing exceptionally well.</p><p>In their recent game, Manchester City employed a defensive formation with a back line of three players. This involved moving Stones from his usual position as a right-back to a pivotal midfield role. City’s opponent for this match was Liverpool, king of gegenpressing.</p><p>To counteract this, City utilized a tactic of creating passing triangles in their build-up play, which eventually allowed Stones to find enough space to make a crucial switch out to Mahrez. It was at this moment that the threat to Liverpool’s defense began to mount.</p><p>Very important for this all to work are the CBs, Rodri and Stones. If they don’t move the ball accurately and quickly, none of this will work.</p><p>These excellent perfomances are only possible with CBs with different profiles and strenghts so, I’d like to share with you the radar chart profiles of each of City’s center-backs, highlighting their individual strengths and contributions to the team’s success.</p><p>Let’s see the CB’s radar charts and take closer look at what makes each of these defenders such an essential part of City’s defensive system.</p><h3>John Stones: The Unconventional Midfielder</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*MlnkDYjqLvJxFiloJFc-XQ.png" /></figure><h3>Ruben Dias: The Rock at the Back</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*qe6u_KVJq3c7dG-qdrpmFg.png" /></figure><h3>Akanji: The Tactical Genius in Defense</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*QGesLYVNKlPOTCUBYlc6Bw.png" /></figure><h3>Nathan Ake: The Versatile Wall</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*QMzKb-OFpUwh6zezKusHoA.png" /></figure><p>In conclusion, it is undeniable that Manchester City has a formidable center-back line-up. Each of them possessing unique strengths and attributes that complement one another perfectly, resulting in the necessary harmony required for effective build-up play and defensive solidity. From Stones’ ability to operate as an unconventional midfielder, to Dias’ rock-solid presence at the back, and the versatility and adaptability of Ake and Akanji, and not forgetting Laporte’s elegant defending, it is clear that City has a well-rounded and dynamic defensive unit. It is no wonder that they have been performing so well, and it will be interesting to see how they continue to fare as the season progresses.</p><p>Hope you enjoyed your reading!!!</p><p><em>If you enjoyed my article and feel like giving a little something back, feel free to buy me a virtual coffee :), link </em><a href="https://ko-fi.com/ricardoandreom"><strong><em>here</em></strong></a><em>.</em></p><p>Follow me and my content on :<br><a href="https://www.linkedin.com/in/ricardoandreom/"><strong>Linkedin</strong></a><strong><br></strong><a href="https://public.tableau.com/app/profile/ricardoandreom/vizzes/"><strong>Tableau</strong></a><strong><br></strong><a href="https://ricardoandreom.github.io/ricardo_portfolio_page/"><strong>Portfolio page</strong></a><strong><br></strong><a href="https://twitter.com/HspaceAnalytics"><strong>Football analytics Twitter</strong></a><strong><br></strong><a href="https://www.instagram.com/halfspace_analytics/"><strong>Football analytics Instagram</strong></a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=4fbfcc401679" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[How can we describe a team’s style of play?]]></title>
            <link>https://medium.com/@ricardoandreom/how-can-we-describe-a-teams-style-of-play-b14ff359d803?source=rss-cb92fec91650------2</link>
            <guid isPermaLink="false">https://medium.com/p/b14ff359d803</guid>
            <category><![CDATA[soccer]]></category>
            <category><![CDATA[data-science]]></category>
            <category><![CDATA[scouting]]></category>
            <category><![CDATA[football]]></category>
            <category><![CDATA[python]]></category>
            <dc:creator><![CDATA[Ricardo André]]></dc:creator>
            <pubDate>Wed, 23 Nov 2022 01:13:24 GMT</pubDate>
            <atom:updated>2023-11-22T00:35:50.640Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*hcHl0_0wSlvfa-ed8F7n6A.png" /><figcaption><strong>Arsenal profile</strong></figcaption></figure><p>In this article, I’ll try to describe the style of play of some of the Top-5 league teams. For that, I used data from <a href="https://fbref.com/en/">Fbref</a> and <a href="https://analytics.soccerment.com/">Soccerment</a>, websites that allow us to scrape very interesting football data.</p><p>A team’s style of play is something difficult to characterize since each person sees football in a different way, interprets it differently, and likes different things. So I’ll start by explaining what I’m going to consider for my game-style profile model.</p><p>To characterize a team’s style of play, I will calculate the following metrics:</p><ul><li>Defensive height</li><li>Directness</li><li>Tempo</li><li>Field tilt %</li><li>Possession</li><li>Pressing resistance</li><li>Pressing intensity</li><li>Dribbling</li><li>Set-pieces</li><li>Air duels</li><li>Crossing</li></ul><p>which I will explain their calculation and context later on.</p><p>From the metrics available in FBREF and Soccerment, let’s see which metrics I considered useful and included in my initial dataset to describe a team style of play.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/622/1*GOOVECPHXxnXl7Qks5EH0A.png" /><figcaption><strong>Initial dataframe information</strong></figcaption></figure><p>After loading the data, I calculated the metrics as follows. All the metrics are per 90&#39;.</p><pre>def process_data(df):<br>  df_style_of_play[&#39;Team&#39;] = df[&#39;Squad&#39;]<br>  df_style_of_play[&#39;Pressing Intensity&#39;] = df[&#39;PPDA&#39;]<br>  df_style_of_play[&#39;Pressing Resistance&#39;] = df[&#39;OPPDA&#39;]<br>  df_style_of_play[&#39;Possession&#39;] = df[&#39;Avg Possession%&#39;]<br>  df_style_of_play[&#39;Field tilt %&#39;] = df[&#39;Field_tilt%&#39;]<br>  df_style_of_play[&#39;Tempo&#39;] = df[&#39;Attempted passes/90&#39;]*100/df[&#39;Touches/90&#39;]<br>  df_style_of_play[&#39;Directness&#39;] = df[&#39;PrgDist&#39;]*100/df[&#39;TotDist&#39;]<br>  df[&#39;%tackles_def3rd&#39;] = df[&#39;Tackles def3rd/90&#39;] / (df[&#39;Tackles def3rd/90&#39;] + df[&#39;Tackles mid3rd/90&#39;] + df[&#39;Tackles final3rd/90&#39;]) <br>  df[&#39;%tackles_mid3rd&#39;] = df[&#39;Tackles mid3rd/90&#39;] / (df[&#39;Tackles def3rd/90&#39;] + df[&#39;Tackles mid3rd/90&#39;] + df[&#39;Tackles final3rd/90&#39;]) <br>  df[&#39;%tackles_final3rd&#39;] = df[&#39;Tackles mid3rd/90&#39;] / (df[&#39;Tackles def3rd/90&#39;] + df[&#39;Tackles mid3rd/90&#39;] + df[&#39;Tackles final3rd/90&#39;]) <br>  df_style_of_play[&#39;Defensive height&#39;] = (df[&#39;%tackles_def3rd&#39;]*16.5*1.1) + (df[&#39;%tackles_mid3rd&#39;]*49.5*1.1) + (df[&#39;%tackles_final3rd&#39;]*82.5*1.1) <br>  df_style_of_play[&#39;Crossing&#39;] = df[&#39;CrsPA/90&#39;]<br>  df_style_of_play[&#39;Air duels&#39;] = df[&#39;Aerials Lost&#39;] + df[&#39;Aerials Won&#39;] <br>  df_style_of_play[&#39;Set Pieces&#39;] = df[&#39;SCA from dead balls&#39;]<br>  df_style_of_play[&#39;Dribbling&#39;] = df[&#39;Dribbles Attempted/90&#39;] / df[&#39;Touches/90&#39;]<br><br>  return df_style_of_play<br><br>df_style_of_play = process_data(df)</pre><h4>Pressing Intensity and Pressing Resistance</h4><p>For <strong>pressing intensity</strong> and<strong> pressing resistance</strong>, I considered passes per defensive action <strong>(PPDA)</strong> and opposition passes per defensive action (<strong>OPPDA</strong>) to describe these metrics, respectively. I would say that the pressing intensity and resistance are not highly correlated with successful strategies but surely give us some ideas of the team’s style of play.<br>In this case, <strong>PPDA can give us a certain indication of a team’s intent to win the ball back, and OPPDA give us an idea of how vulnerable a team is to the opponent’s pressure</strong>.</p><h4>Field tilt — Territorial dominance</h4><p><strong>Field tilt %</strong> is a metric for showing territorial dominance between teams, considering possession only in the final third. This way, we can <strong>measure a team’s dominance and attacking mindset</strong>.<br>Note that it was only the metric I loaded from Soccerment.</p><h4>Tempo</h4><p>The formula for calculating my tempo metric is <strong>attempted passes / touches</strong>. This measure somehow tells us the rhythm that the teams print in the game, and that is something that varies a lot from team to team and from style to style.</p><h4>Directness</h4><p>The idea behind this metric is to assess how direct teams progress with the ball. There are teams that play in a more lateral way and others that play in a more vertical way. Which one is better? It always depends, but surely it’s a good detail to describe a team’s style of play.</p><h4>Possession</h4><p>Here is the basic average possession %, it’s always an indicator of how much a team feels comfortable with a ball and how much they value it.</p><h4>Defensive height</h4><p>The defensive height is a concept that is very difficult to define, and even more so with the data available on Fbref.<br>It is interesting to try to understand if a team prefers a style of play with a lower, medium, or high defensive block.</p><p>I started to calculate the proportion of tackles in the defensive 3rd, mid-3rd, and offensive 3rd of the total tackles. Let’s now explain what&#39;s behind my formula for this metric.<br>I considered that the pitch has 110 meters of length. Dividing 110 by 3, we obtain 36.66. So the defensive 3rd goes from 0 to 36.66, the mid 3rd goes from 36.66 to 73.32, and then the offensive 3rd goes from 73.32 to 100. Then I calculated the mid-value for each 3rd, and after some roundings, I used the formula present in the code.</p><h4>How much do teams rely on air duels, set pieces, and dribbling?</h4><p>The idea behind the rest of the metrics I considered is to get a sense of how much teams rely on air duels, set pieces, and dribbling.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*nFJ3Zp9E7e8WuT_QiU6VbA.png" /></figure><p>The first big step in the creation of the dataframe to describe a team’s style of play is completed. If you pay attention to the dataframe, you’ll see that some need to be normalized, and that’s what we did later on.</p><pre>def data_normalization(df):<br>  columns = [&#39;Dribbling&#39;, &#39;Set Pieces&#39;, &#39;Air duels&#39;, <br>             &#39;Crossing&#39;, &#39;Air duels&#39;, &#39;Pressing Resistance&#39;]<br>  <br>  for column in columns:<br>    df[column] = (df[column]*100) / (df[column].max())<br><br>  df[&#39;Pressing Intensity&#39;] = (df[&#39;Pressing Intensity&#39;].min()*100) / (df[&#39;Pressing Intensity&#39;])<br><br>  return df_style_of_play<br><br>df_style_of_play = data_normalization(df_style_of_play)</pre><p>The idea here was to divide each column (metric) by the maximum value of the corresponding column to obtain a number between 0 and 1, and then multiply by 100.</p><p>Regarding the pressing intensity normalization, it was a little bit different. In normal conditions, after a team regains possession, they want to keep the ball and not get rid of it. Therefore, the teams should be looking for lower values of OPPDA, i.e., lower pressing resistance values that are not normalized. So in order to get a value indicator of a good pressing resistance, we need to compare the team’s OPPDA with the minimum value of OPPDA and that’s what I did, converting the values in order to vary between 0 and 100.</p><p><strong>Note that the values in the dataset are not indicators of better or worse strategies. Football is very unpredictable and variable, and that’s why this sport is so magical! This data only gives us an idea of the team’s style of play.</strong></p><p>Finally, here’s the head of my style of play dataframe, with all metrics normalized and ready to make some visualizations.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*XGtw2BOOsi6T9AZKlFwNBg.png" /></figure><p>The next and final step is producing the radar chart of some teams to represent their style of play in a more attractive and insightful way.</p><p>Let’s check out the following gif with some style of play profile comparisons from some of the best teams in Europe.</p><h3>Results</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/960/1*P5n0WoqEr9X0Y1jnEzYYJA.gif" /></figure><p>What do you think of this style of play profile? Any curious radar chart?</p><p>I won’t say much about the results obtained in the radar charts, I’ll let you say if it makes sense compared to reality.<br>I’ll just say that I found it curious that Union Berlin’s radar was so full, they depend a lot on crosses and aerial duels, and taking into account the great season they’re having, it’s very interesting to get these results.</p><p>On the other hand, everyone, or at least me, was expecting Liverpool to have a great season, but in the Premier League, they are really disappointing. However, it’s very interesting to see that, looking at their profile radars, they are still somehow competing with Manchester City, who are still in the race for all competitions and doing well overall.<br>What is not working out well with Jürgen Klopp&#39;s pupils this season in the Premier League?</p><p>I hope you enjoyed your reading!!!</p><p><em>If you enjoyed my article and feel like giving a little something back, feel free to buy me a virtual coffee :), link </em><a href="https://ko-fi.com/ricardoandreom"><strong><em>here</em></strong></a><em>.</em></p><p>Follow me and my content on:<br><a href="https://www.linkedin.com/in/ricardoandreom/"><strong>Linkedin</strong></a><strong><br></strong><a href="https://public.tableau.com/app/profile/ricardoandreom/vizzes/"><strong>Tableau</strong></a><strong><br></strong><a href="https://ricardoandreom.github.io/ricardo_portfolio_page/"><strong>Portfolio page</strong></a><strong><br></strong><a href="https://twitter.com/HspaceAnalytics"><strong>Football analytics Twitter</strong></a><strong><br></strong><a href="https://www.instagram.com/halfspace_analytics/"><strong>Football analytics Instagram</strong></a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=b14ff359d803" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Football scouting — Players level of similarity]]></title>
            <link>https://medium.com/@ricardoandreom/football-scouting-players-level-of-similarity-88c40fb6e77e?source=rss-cb92fec91650------2</link>
            <guid isPermaLink="false">https://medium.com/p/88c40fb6e77e</guid>
            <category><![CDATA[data-science]]></category>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[scouting]]></category>
            <category><![CDATA[euclidean-distance]]></category>
            <category><![CDATA[football]]></category>
            <dc:creator><![CDATA[Ricardo André]]></dc:creator>
            <pubDate>Mon, 21 Nov 2022 12:39:36 GMT</pubDate>
            <atom:updated>2023-11-22T00:50:56.981Z</atom:updated>
            <content:encoded><![CDATA[<h3>Euclidian similarity between players</h3><h4>How similar is a player relatively to another?</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/516/1*6r2W3g-JyS2LTFFtWressg.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*rVVoLIduaLfushfW.png" /></figure><p>In football, one of the biggest challenges for the team management and coaching staff is choosing and finding a good replacement for a player who is leaving.</p><p>A lot of things can happen to an apparent wonderful and perfect signing, and everything goes wrong, but we can minimize that risk using data, and that’s what I’m trying to do here. Let’s see how!</p><p>The starting point of this scouting method will be an <a href="https://medium.com/@ricardoandreom/k-means-for-player-clustering-2d-3d-22df7d12f1a9">article</a> I wrote before that I advise you to read to understand the concept properly.</p><p>In this <a href="http://K-means is able to find relationships in data and create groups of similar characteristics.">article</a>, I used an <strong>unsupervised machine learning </strong><a href="https://www.javatpoint.com/k-means-clustering-algorithm-in-machine-learning"><strong>K-means</strong></a><strong> algorithm to find relationships in data and create groups of similar characteristics.</strong></p><p>In this case, I applied the K-means algorithm to the Premier League defenders in order to get an output with groups of similar defenders.</p><p>Once I have the cluster groups, I calculate the level of similarity between each of the players, building a <a href="https://en.wikipedia.org/wiki/Euclidean_distance_matrix">Euclidean similarity matrix</a> for the players in my model.<br>The goal is to input the name of a player (present in the data) and receive a table with the names of the players and their level of similarity in relation to the given input.<br>If we consider that we have a good model behind all this, we are probably going to get a good replacement for our input player.</p><p>So let’s work on it! Let’s go to the code.</p><p>I copied the reduced df from the code of the previous article to work on it and create a similarity matrix.</p><pre>reduced1 = reduced.copy()</pre><p>Now, let’s create the similarity matrixes.<br>I created first a euclidian distance matrix, and then through this one I also created a level similarity matrix.<br>By changing the values in &#39;cluster_list&#39;, we want to see the clusters represented in the matrixes. In this case, all clusters are represented.</p><pre>cluster_list = [0,1,2,3,4,5,6]<br>reduced1 = reduced1[reduced1[&#39;cluster&#39;].isin(cluster_list)]<br><br>distance_matrix = pd.DataFrame(index=reduced1[&#39;name&#39;], columns=reduced1[&#39;name&#39;])<br><br>distance_matrix = pd.DataFrame(index=reduced_sim[&#39;Player&#39;], columns=reduced_sim[&#39;Player&#39;])<br>    for i in range(len(distance_matrix)):<br>        x_i = reduced_sim.iloc[i, 0]<br>        y_i = reduced_sim.iloc[i, 1]<br>        for j in range(len(distance_matrix)):<br>            x_j = reduced_sim.iloc[j, 0]<br>            y_j = reduced_sim.iloc[j, 1]<br>            distance_matrix.iloc[i, j] = np.sqrt((x_i - x_j) ** 2 + (y_i - y_j) ** 2)<br><br>max_euc_dist = list(distance_matrix.max())<br>sim_matrix = pd.DataFrame(index=reduced1[&#39;name&#39;], columns=reduced1[&#39;name&#39;])<br>for i in range(len(distance_matrix)):<br>   for j in range(len(distance_matrix)):<br>      sim_matrix.iloc[i,j] = ((max_euc_dist[i] - distance_matrix.iloc[i,j])*100 / max_euc_dist[i]) </pre><p>Now that we have created the matrixes, let’s see a fraction of the euclidian similarity matrix with conditional formatting.<br>The redder cells are the least similar players, and the greener cells are the most similar.</p><h3>Similarity matrix</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*w2TWRXYu9CO6QHW68lwRLw.png" /><figcaption><strong>Euclidian similarity matrix</strong></figcaption></figure><p><strong>How do I interpret this table?</strong> For example, according to my k-means model, Trent Alexander-Arnold has a level of similarity of % 38.52 with Matty Cash. The levels of similarity in this table are between 0 and 100.</p><p>This table will definitely help to get our main man replaced!</p><h4><strong>Most similar players</strong></h4><p>The next step was writing a code that returns me the most similar players according to my model after I give a player name as an input. For example, in the case below, I looked for the most similar players to Diogo Dalot, and that&#39;s what I got.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*W3ogcEMJWdeKAbouNQOQ1Q.png" /><figcaption><strong>Top 6 similar players to Diogo Dalot</strong></figcaption></figure><p>Now that we have everything set and done, let’s observe our outputs in a more colorful way. We are going to take a look at some of the clusters in my <a href="https://medium.com/@ricardoandreom/k-means-for-player-clustering-2d-3d-22df7d12f1a9">article</a> mentioned before.</p><h3>Conclusions</h3><p><strong>Player level of similarities inside clusters</strong></p><h4>Cluster 5: Offensive, progressive and very good technical Full-backs</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*L-Gkq57U7pqr54x6535PDw.png" /><figcaption><strong>Cluster 5 (FBs) euclidian similarity distance</strong></figcaption></figure><h4>Cluster 4: Representation of a small set of the top center backs in the league</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/972/1*BNlD7OW0kQ5j81kQCoqYxg.png" /><figcaption><strong>Cluster 4 (CBs)</strong></figcaption></figure><h4>Who are the most similar players to TAA, Cancelo, and James? (best 3 RB’s in my opinion)</h4><p>They are all great, but I think we agree they have a very different profile, so I think it’s interesting to see which players are most similar to each one of these players.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/580/1*y7VekOSkmMtwPDZajsOBAw.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/457/1*Pq7yc6JMcYpYq89FQuDidg.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/420/1*GnYbwV0T0ttMO4D-UHwCkA.png" /></figure><p>What do you think? Did you expect something similar to these outputs?</p><p>For me personally, the name of Nouri being present here at the top of this table is a bit of a surprise, but it also emphasizes the fact that he is having a great season so far.</p><p>It’s interesting to observe that the style of play at Manchester seems to affect the level of similarities between Manchester City players. If you look at Cancelo&#39;s similarities, you’ll find three teams that are not even full-backs. On the other hand, if you observe the TAA table, no teammate shows up, and regarding Reece James, only Cucurella appears as a top-level similarity teammate.</p><p>Now it&#39;s time to assess the top CB’s similarities.</p><h4>Who are the most similar players to Virgil van Dijk, Thiago Silva and Ruben Dias?</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/456/1*if2B8_L8NdvDunbmaRxrFQ.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/432/1*vyXn2VfVSGJ753_0fUu9CQ.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/412/1*9B9kPRxFLWvd684Xr3i_-g.png" /></figure><h4>Who are the most similar players to Lisandro Martínez and William Saliba?</h4><p>Saliba is not in the cluster that is classified as the top CB’s in the league, but the fact that he is the most similar player to Virgil van Dijk says a lot about his performance this season so far in the PL. A special and key player for Arsenal.</p><p>Once again, the Manchester City style of play seems to affect the level of similarity between players. Guardiola must be working very well and implementing his ideas very well.</p><p>More level similarity tables for two of the big signings of the season...</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/439/1*Few7fkV7eNJcfyVq6D7vbA.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/415/1*XcKJImc-SRVxoBHLdm8IEA.png" /></figure><p>Here it’s curious to observe that Martínez, despite being 1,75 m tall, has a high level of similarities with strong physically active players. Yeah.. football is mostly played with the brain!</p><p><strong>Would you use this model in your scouting? Did you expect these results? Were there surprises?</strong> Remember that the amount of data considered is not very significant yet, and that’s a lacuna for sure.<br>However, I think it was enough to get some interesting insights about some of the defenders in PL.</p><p>I hope you enjoyed your reading!!!</p><p><em>If you enjoyed my article and feel like giving a little something back, feel free to buy me a virtual coffee :), link </em><a href="https://ko-fi.com/ricardoandreom"><strong><em>here</em></strong></a><em>.</em></p><p>Follow me and my content on:<br><a href="https://www.linkedin.com/in/ricardoandreom/"><strong>Linkedin</strong></a><strong><br></strong><a href="https://public.tableau.com/app/profile/ricardoandreom/vizzes/"><strong>Tableau</strong></a><strong><br></strong><a href="https://ricardoandreom.github.io/ricardo_portfolio_page/"><strong>Portfolio page</strong></a><strong><br></strong><a href="https://twitter.com/HspaceAnalytics"><strong>Football analytics Twitter</strong></a><strong><br></strong><a href="https://www.instagram.com/halfspace_analytics/"><strong>Football analytics Instagram</strong></a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=88c40fb6e77e" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>