<?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 Felix Morales on Medium]]></title>
        <description><![CDATA[Stories by Felix Morales on Medium]]></description>
        <link>https://medium.com/@fmoralcaballero?source=rss-b9f12041089a------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*aq-dcws1ckpUyTgLj4Jd2Q.png</url>
            <title>Stories by Felix Morales on Medium</title>
            <link>https://medium.com/@fmoralcaballero?source=rss-b9f12041089a------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Sat, 05 Dec 2026 02:15:05 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@fmoralcaballero/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[“Nothing happened here.” Where is “here”?]]></title>
            <link>https://medium.com/@fmoralcaballero/nothing-happened-here-where-is-here-14f290f0f139?source=rss-b9f12041089a------2</link>
            <guid isPermaLink="false">https://medium.com/p/14f290f0f139</guid>
            <dc:creator><![CDATA[Felix Morales]]></dc:creator>
            <pubDate>Mon, 12 Oct 2026 17:06:57 GMT</pubDate>
            <atom:updated>2026-10-12T17:06:57.666Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*GIi1CKbOTvlhsqw_" /><figcaption>Photo by <a href="https://unsplash.com/@sheflincoln?utm_source=medium&amp;utm_medium=referral">Shefali Lincoln</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p>On October 9, an earthquake centered on the Azuero Peninsula shook Panama. The images went around the world, and messages of support came with them.</p><p>What I did not expect were the replies from some Panamanians in the comments. Some could be summed up like this: “Those images are exaggerated. That happened out in the interior; here in the capital we’re fine.” (In Panama, “the interior” is everything outside the capital.) To those who expressed concern for Panama, others replied that there was no reason to worry, that we have a good building code here, and that we are not Colombia or Venezuela. And in case anyone still had doubts: relax, everyone, the Canal is still running.</p><p>I understand the relief of confirming that you are okay, that your family is okay, and that your house is still standing. What I struggle to understand is how we went from that relief to talking as if all of Panama had come out unscathed. Because when we say “nothing happened here,” who are we including in that “here”?</p><p>Two things worry me. The first is that those comments talk as if the affected areas were not part of Panama. The second is complacency: puffing out our chests over damage that was minimal, and that, on top of that, was only minimal in one part of the country.</p><h3>Something did happen</h3><p>Let’s start with the basics. The preliminary report from Panama’s National Civil Protection System (SINAPROC), as of 6:30 PM on October 10, listed 840 damaged homes (including ten completely destroyed in Chiriquí), 419 schools with damage, and 29 people with minor injuries (<a href="https://www.tvn-2.com/nacionales/temblor-panama-800-casas-afectadas_1_2265477.html">TVN</a>, in Spanish). That same day, the government declared a state of emergency (<a href="https://www.telemetro.com/nacionales/sismo-panama-gobierno-declara-estado-emergencia-terremoto-75-n6094734">Telemetro</a>).</p><p>Behind those numbers are real places. For a while, Tonosí could only be reached by air, and one person had to be rescued from the rubble of a church (<a href="https://www.eltiempo.com/mundo/latinoamerica/sistema-de-falla-azuero-sona-esto-se-sabe-de-la-estructura-geologica-detras-del-fuerte-terremoto-de-magnitud-7-7-en-panama-y-sus-mas-de-100-replicas-3592711">El Tiempo</a>). In Los Santos, Herrera, and Veraguas, some communities were cut off (<a href="https://www.laestrella.com.pa/panama/nacional/terremoto-en-panama-causa-27-heridos-y-danos-en-viviendas-hospitales-y-escuelas-JA26376719">La Estrella</a>). Those numbers stand for families whose homes were damaged or lost and for towns left with no way out.</p><p>However, that same report listed no deaths and no missing persons.</p><p>Thank God. There is a great deal to be grateful for in that absence of reported deaths. Still, the families whose homes were destroyed need somewhere to live. Those whose homes were damaged still need to know whether they can go back.</p><p>For anyone who lost their home, something did happen.</p><h3>Making Panamanians in the interior invisible</h3><p>I am from Panama City, and I grew up in Chiriquí. These comments remind me of a feeling I had when I studied Panamanian history in school: it often seemed like we were learning the history of Panama City. And the rest of the country? Fine, thanks.</p><p>With the earthquake, I saw the same thing again. Since no building fell in the capital, some people concluded that the images were exaggerated.</p><p>Exaggerated for whom?</p><p>Whatever the intentions of those who wrote those comments, the effect is the same: the conversation ends up centered on reassuring the world about the capital, while the losses of other communities fade into the background. The experience of one part of the country ends up standing in for everyone’s. So are the people of the interior invisible?</p><p>Let me be clear: Panama does not end at the capital.</p><p>The same goes for the Canal. It makes sense to report on whether it is operating; its importance to the country is obvious. What I question is using that news to close the books on the national toll, as if it also answered the needs of those who lost their homes or were cut off.</p><h3>Our own strong arm and intellect saved us</h3><p>The other idea that has been repeated is how much merit there is in Panama having a building code that accounts for earthquakes of this magnitude, one that has been strictly enforced for recent structures. This has also been repeated alongside comparisons with Colombia and Venezuela, which apparently also have building codes that account for earthquakes, codes that are not faithfully followed. I fear that, true as these facts may be, we are guilty of arrogance.</p><p>Credit where credit is due: without that building code, and without enforcing it, Panama City would surely have suffered greater damage.</p><p>However, we need to put things in perspective: the epicenter was not in the capital. It was about 200 km (some 125 miles) from Panama City and about the same distance from David, two of the most populated areas in the country.</p><p>That matters more than it seems. The same earthquake does not shake every place equally. Intensity is usually greater near the epicenter and decreases with distance, although it also depends on soil conditions and other features of the event. The <a href="https://earthquake.usgs.gov/data/dyfi/background.php">USGS explains this difference between an earthquake’s magnitude and the intensity felt at each location</a>.</p><p>Can we take for granted that we would have fared the same with the epicenter near Panama City? I don’t think so. The USGS estimates an earthquake’s impact from three things: how strongly the ground shakes, how many people are exposed, and how vulnerable the buildings are (<a href="https://earthquake.usgs.gov/data/pager/faq.php">USGS</a>). With the epicenter near the capital, the first two would have shot up, and only the third works in our favor (where the code is enforced).</p><p>What I mean is that the absence of major damage in Panama City cannot be explained entirely by human merit: a good part of why the capital came out well was its distance from the epicenter.</p><p>The other issue is comparing our scenario, real or hypothetical, with that of Colombia or Venezuela. However, I question why we make this comparison at all.</p><p>Certainly, comparing experiences in order to learn can be useful; that is what technical reports and the lessons of each disaster are for. What strikes me as lacking in empathy is using the suffering of other countries to feel superior. Competing over which earthquake had the greater magnitude, or boasting that we fared better, does nothing for those who are trying to recover.</p><p>Who are we helping with that? Our ego?</p><p>We can acknowledge what we did well without using other people’s suffering to beat our chests. And to anyone who writes “Pray for Panama,” we can simply thank them for their solidarity. There is no need to answer as if admitting that people in the interior need help called our capacity as a country into question.</p><h3>What we did well, and what we can do better: not being complacent</h3><p>I would rather that relief led us to understand better what happened: what worked, what failed, and what could have ended much worse.</p><p>That last part seems especially important to me. There is a term for these: close calls, situations in which a serious consequence could have occurred if the circumstances had been slightly different. We need to learn from them too.</p><p>Let me illustrate: imagine you are crossing the street and a car brushes right past you. Fortunately, nothing happens to you. However, the difference between that “nothing happened to me” and a trip to the hospital was a matter of inches, and you did not decide those inches. If the scene repeats itself, you might not be so lucky.</p><p>One account that deserves that kind of scrutiny is that of the Hotel Dos Continentes in Penonomé. EFE documented the collapse of the rear of the building and gathered the testimony of a person on site, who explained that the way the shaking unfolded had given the occupants time to get out. <a href="https://efe.com/mundo/2026-10-10/panama-edificaciones-colapsan-terremoto/">Here is EFE’s report</a> (in Spanish).</p><p>That testimony raises questions that matter beyond the immediate outcome. What made it possible to get out? Which conditions helped, and which might not be repeated? What would need to be fixed so that the occupants’ safety did not depend on having the same amount of time again?</p><p>The account alone does not answer those questions. That is precisely why they are worth investigating. There was a collapse, and understanding what made the evacuation possible may be as important as understanding why the structure failed.</p><p>The same applies to the broader picture of the earthquake. We must identify what protected us thanks to preparation and what depended on favorable circumstances. If a serious consequence was avoided this time, we cannot assume it will be avoided again. The prudent course is to review our vulnerabilities and fix them before they cause greater damage. We cannot choose where or when the next earthquake will strike; we can, however, make decisions about the conditions in which it will find us. That is what studying close calls is for: acting without waiting for the worst to happen.</p><h3>What is up to us</h3><p>The priority is helping those who need to recover, and whatever we learn should guide the rebuilding from now on. We would have learned very little if the whole conversation stayed on why certain buildings in the capital held up, without including how to better protect the communities that suffered the greatest losses. Those of us who came out relatively well have reasons to be grateful; let us show that gratitude by standing with those affected and by taking seriously what still needs to improve. Because if we are humble, we can recognize that even the best plans can go wrong (this time, things went better for one part of the country than for another).</p><p>An earthquake like this may not happen again in the lifetime of many of us. However, the decisions we make now may affect those who do have to face one later. Learning is worth it, even if its benefits never reach us personally. Because each of us is here for more than ourselves: we are here for those who come after us.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=14f290f0f139" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[“Aquí no pasó nada”. ¿Aquí dónde?]]></title>
            <link>https://medium.com/@fmoralcaballero/aqu%C3%AD-no-pas%C3%B3-nada-aqu%C3%AD-d%C3%B3nde-89c11a77c16a?source=rss-b9f12041089a------2</link>
            <guid isPermaLink="false">https://medium.com/p/89c11a77c16a</guid>
            <category><![CDATA[disaster-response]]></category>
            <category><![CDATA[seismology]]></category>
            <category><![CDATA[earthquake]]></category>
            <category><![CDATA[panama]]></category>
            <dc:creator><![CDATA[Felix Morales]]></dc:creator>
            <pubDate>Mon, 12 Oct 2026 16:54:21 GMT</pubDate>
            <atom:updated>2026-10-12T16:57:06.558Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*1Vhe5zoT2SRJM5U3" /><figcaption>Photo by <a href="https://unsplash.com/@jensaber?utm_source=medium&amp;utm_medium=referral">Jens Aber</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p>El 9 de octubre, un terremoto con epicentro en la península de Azuero sacudió Panamá. Las imágenes le dieron la vuelta al mundo, y con ellas llegaron los mensajes de apoyo.</p><p>Lo que no esperaba era la respuesta de algunos panameños en los comentarios. Algunos podrían resumirse así: “<em>Esas imágenes son exageradas. Eso fue allá en el interior; aquí en la capital estamos bien</em>”. A quienes expresaban preocupación por Panamá, otros les respondían que n<em>o había por qué preocuparse, que aquí tenemos un buen código de construcción y que no somos Colombia ni Venezuela. </em>Y por si quedaban dudas, <em>tranquilos todos, el Canal sigue operativo.</em></p><p>Entiendo el alivio de comprobar que uno está bien, que su familia está bien y que su casa sigue en pie. Lo que me cuesta entender es cómo pasamos de ese alivio a hablar como si todo Panamá hubiera salido ileso. Porque, cuando decimos “aquí no pasó nada”, ¿a quiénes estamos incluyendo en ese “aquí”?</p><p>Me preocupan dos cosas. La primera es que esos comentarios hablan como si las zonas afectadas no fueran parte de Panamá. La segunda es la complacencia: sacar pecho por daños que fueron mínimos, y que además solo fueron mínimos en una parte del país.</p><h4>Sí pasó algo</h4><p>Empecemos por lo básico: El balance preliminar del Sistema Nacional de Protección Civil (SINAPROC) con corte al 10 de octubre, a las 6:30 PM, registraba <strong>840 viviendas afectadas (entre ellas, diez destruidas por completo en Chiriquí), y 419 centros educativos con daños y 29 personas con lesiones menores </strong>(<a href="https://www.tvn-2.com/nacionales/temblor-panama-800-casas-afectadas_1_2265477.html">TVN</a>). Ese mismo día, el Gobierno declaró estado de emergencia (<a href="https://www.telemetro.com/nacionales/sismo-panama-gobierno-declara-estado-emergencia-terremoto-75-n6094734">Telemetro</a>).</p><p>Detrás de esas cifras hay lugares concretos. A Tonosí, por un tiempo, solo se podía llegar por aire, y hubo que rescatar a una persona de entre los escombros de una iglesia (<a href="https://www.eltiempo.com/mundo/latinoamerica/sistema-de-falla-azuero-sona-esto-se-sabe-de-la-estructura-geologica-detras-del-fuerte-terremoto-de-magnitud-7-7-en-panama-y-sus-mas-de-100-replicas-3592711">El Tiempo</a>). En Los Santos, Herrera y Veraguas hubo comunidades que quedaron incomunicadas (<a href="https://www.laestrella.com.pa/panama/nacional/terremoto-en-panama-causa-27-heridos-y-danos-en-viviendas-hospitales-y-escuelas-JA26376719">La Estrella</a>). En esas cifras hay familias con la casa dañada o perdida y pueblos que se quedaron sin cómo salir.</p><p>Pero en ese mismo balance no había fallecidos ni desaparecidos.</p><p>Gracias a Dios. Hay muchísimo que agradecer en esa ausencia de muertes reportadas. Pero las familias con casas destruidas siguen necesitando dónde vivir. Quienes tienen sus viviendas dañadas todavía necesitan saber si pueden regresar a ellas.</p><p>Para quien perdió su casa, sí pasó algo.</p><h4>Haciendo invisibles a los panameños del interior</h4><p>Soy capitalino y me crié en Chiriquí. Estos comentarios me recuerdan una sensación que tenía cuando estudiaba historia de Panamá en el colegio: muchas veces parecía que estábamos aprendiendo la historia de la ciudad de Panamá. ¿Y el resto del país? Bien, gracias.</p><p>Con el terremoto volví a ver lo mismo. Como en la capital no se cayó ningún edificio, hubo quien concluyó que las imágenes eran exageradas.</p><p>¿Exageradas para quién?</p><p>Sea cual sea la intención de quienes escribieron esos comentarios, el efecto es el mismo: La conversación termina centrada en tranquilizar al mundo sobre la capital, mientras las pérdidas de otras comunidades quedan en segundo plano. La experiencia de una parte del país acaba convertida en el balance de todos. ¿O sea que la gente del interior es invisible?</p><p>Que quede claro: Panamá no se acaba en la capital.</p><p>Lo mismo pasa con el Canal. Tiene sentido informar sobre su funcionamiento; su importancia para el país es evidente. Lo que cuestiono es usar esa noticia para dar por cerrado el balance nacional, como si respondiera también a las necesidades de quienes perdieron su casa o quedaron incomunicados.</p><h4>Nuestro propio brazo fuerte e intelecto nos salvó</h4><p>La otra idea que se ha repetido es el mérito que tiene que Panamá tenga un código de construcción que contemple sismos de esta magnitud, y que haya sido de estricto cumplimiento para estructuras recientes. Esto se ha repetido también con comparaciones con Colombia y Venezuela, que al parecer también tiene códigos de construcción que contemplan sismos, pero que no se siguen fielmente. Me temo que dentro de lo cierto de estos hechos, se está pecando de arrogancia.</p><p>Al César lo que es del César: De no tener dicho código de construcción, y de no cumplirlo, seguramente la ciudad de Panamá habría tenido daños mayores.</p><p>Pero hay que poner las cosas en perspectiva: el epicentro no fue en la capital. Quedó a unos 200 km de la ciudad de Panamá y otro tanto de David, dos de las zonas más pobladas del país.</p><p>Eso importa más de lo que parece. Un mismo sismo no sacude todos los lugares por igual. La intensidad suele ser mayor cerca del epicentro y disminuir con la distancia, aunque también depende de las condiciones del suelo y de otras características del evento. El <a href="https://earthquake.usgs.gov/data/dyfi/background.php">USGS explica esa diferencia entre la magnitud de un sismo y la intensidad que se experimenta en cada lugar</a>.</p><p>¿Podemos dar por hecho que nos habría ido igual con el epicentro cerca de la ciudad de Panamá? Yo creo que no. El USGS estima el impacto de un sismo con tres cosas: cuánto sacude, cuánta gente está expuesta y qué tan vulnerables son las construcciones (<a href="https://earthquake.usgs.gov/data/pager/faq.php">USGS</a>). Con el epicentro cerca de la capital, las dos primeras se habrían disparado, y solo la tercera juega a nuestro favor (donde el código se cumple).</p><p><strong>Lo que quiero decir es que no toda la ausencia de daños mayores en la ciudad de Panamá se explica por méritos humanos: buena parte de que la capital saliera bien librada fue la distancia al epicentro.</strong></p><p>El otro aspecto es comparar nuestro escenario, real o hipotético, con el de Colombia o Venezuela. Pero cuestiono la razón por la cual hacemos esta comparación.</p><p>Ciertamente el comparar experiencias para aprender puede servir. Para eso existen los informes técnicos y las lecciones de cada desastre. Lo que me parece de poca empatía es utilizar el sufrimiento de otros países para sentirnos superiores. Ponernos a competir por cuál terremoto tuvo mayor magnitud, o presumir que a nosotros nos fue mejor, no ayuda a quienes están tratando de recuperarse.</p><p>¿A quién ayudamos con eso? ¿A nuestro ego?</p><p>Podemos reconocer lo que hicimos bien sin usar el sufrimiento ajeno para darnos golpes de pecho. Y a quien nos escribe “Pray for Panama” podemos agradecerle la solidaridad. No hace falta responderle como si reconocer que hay personas en el interior que necesitan ayuda pusiera en duda nuestra capacidad como país.</p><h4>Lo que hicimos bien, y podemos hacer mejor: No ser complacientes.</h4><p>Yo preferiría que ese alivio nos llevara a entender mejor lo ocurrido: qué funcionó, qué falló y qué pudo haber terminado mucho peor.</p><p>Esto último me parece especialmente importante. En inglés se habla de <em>close calls</em>: los “casi”, esas situaciones en las que una consecuencia grave pudo haberse producido si las circunstancias hubieran sido ligeramente distintas. También hay que aprender de ellas.</p><p>Lo ejemplifico así: imagínense que van cruzando la calle y un carro les pasa rozando. Afortunadamente, no les pasa nada. Pero la diferencia entre ese “no me pasó nada” y una visita al hospital fue de centímetros, y esos centímetros no los decidieron ustedes. Si se repite la escena, capaz no corren con la misma suerte.</p><p>Un relato que merece esa mirada es el del Hotel Dos Continentes, en Penonomé. EFE documentó el colapso de su parte posterior y recogió el testimonio de una persona en el lugar que explicó que la secuencia de la sacudida había dado tiempo a los ocupantes para desalojar. <a href="https://efe.com/mundo/2026-10-10/panama-edificaciones-colapsan-terremoto/">Así lo recoge la nota de EFE</a>.</p><p>Ese testimonio permite plantear preguntas que importan más allá del resultado inmediato. ¿Qué facilitó la salida? ¿Qué condiciones ayudaron y cuáles podrían no repetirse? ¿Qué habría que corregir para que la seguridad de los ocupantes no dependiera de disponer otra vez del mismo tiempo?</p><p>El relato no responde por sí solo esas preguntas. Precisamente por eso vale la pena investigarlas. Hubo un colapso, y entender qué permitió evacuar puede ser tan importante como entender por qué falló la estructura.</p><p>Lo mismo aplica al balance más amplio del terremoto. Debemos identificar qué nos protegió gracias a la preparación y qué dependió de circunstancias favorables. Si una consecuencia grave se evitó esta vez, no podemos asumir que volverá a evitarse. Lo prudente es revisar las vulnerabilidades y corregirlas antes de que produzcan daños mayores. Porque nosotros no podemos escoger dónde ni cuándo ocurrirá el próximo sismo, pero sí podemos tomar decisiones sobre las condiciones en las que nos encontrará. Para eso sirve estudiar también los “casi”: para actuar sin esperar a que ocurra lo peor.</p><h4>Lo que nos toca</h4><p>La prioridad es ayudar a quienes necesitan recuperarse, y lo que aprendamos debe orientar desde ahora la reconstrucción. <strong>Sería muy poco lo aprendido si toda la conversación se quedara en por qué resistieron ciertos edificios de la capital, sin incluir cómo proteger mejor a las comunidades que sufrieron las mayores pérdidas</strong>. Quienes salimos relativamente bien tenemos motivos para agradecer; demostremos ese agradecimiento acompañando a los afectados y tomando en serio lo que falta por mejorar. Porque si somos humildes, podemos reconocer que aun con los mejores planes las cosas pueden salir mal (esta vez, a una parte del país le salieron mejor que a otra).</p><p>Puede que un terremoto así no vuelva a ocurrir en la vida de muchos de nosotros. Pero las decisiones que tomemos ahora pueden afectar a quienes sí tengan que enfrentarlo después. Vale la pena aprender, aunque los beneficios de hacerlo no nos toquen personalmente. Porque uno no está aquí solamente por uno, sino por los que vienen después.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=89c11a77c16a" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Panamá no necesita encontrar culpables: necesita desarrollar más talento]]></title>
            <link>https://medium.com/@fmoralcaballero/panam%C3%A1-no-necesita-encontrar-culpables-necesita-desarrollar-m%C3%A1s-talento-a27d974493d3?source=rss-b9f12041089a------2</link>
            <guid isPermaLink="false">https://medium.com/p/a27d974493d3</guid>
            <dc:creator><![CDATA[Felix Morales]]></dc:creator>
            <pubDate>Mon, 29 Jun 2026 14:11:04 GMT</pubDate>
            <atom:updated>2026-06-29T14:11:04.770Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*0M3XekO5-A68VNS6" /><figcaption>Photo by <a href="https://unsplash.com/@lucidistortephoto?utm_source=medium&amp;utm_medium=referral">Alfonso Scarpa</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p>Ya terminó la participación de Panamá en el Mundial 2026, y creo que vale la pena hablar de lo que pasó con un poco más de calma.</p><p>Entiendo perfectamente la frustración. Panamá perdió sus tres partidos, no pudo anotar un solo gol, y para los que estábamos ilusionados con esta Copa del Mundo, eso duele. Duele más todavía cuando uno siente que el equipo no salió a esconderse, que no fue simplemente superado de principio a fin. Al contrario: hubo momentos en los que Panamá compitió, generó, presionó y dejó la sensación de que estaba cerca de algo más.</p><p>Yo tuve la dicha de ir al partido contra Ghana. Para mí fue un sueño hecho realidad ver un partido de Mundial en vivo, y sobre todo ver a la selección de mi país. Pero salí del estadio con una sensación amarga. No porque Panamá no hubiese competido, sino precisamente porque compitió. Porque durante muchos tramos hizo cosas bien, pero al llegar al área rival parecía que faltaba algo. Faltaba claridad. Faltaba gol.</p><p>Y cuando vi el partido de nuevo, ya por televisión, esa sensación se reforzó. Panamá sí llegó al área rival. Pero en el fútbol, lamentablemente, competir bien no siempre alcanza. Puedes hacer muchas cosas correctamente durante 80 o 90 minutos y aun así irte con las manos vacías por un detalle, o una jugada aislada.</p><p>Por eso me preocupa un poco la forma en que hemos reaccionado como país. Porque entiendo la rabia, pero hemos dejado que nuestra rabia se transforme en una búsqueda desesperada de culpables. En redes sociales, muchos han decidido que el problema se resume en José Fajardo. Otros han decidido que todo es culpa de Thomas Christiansen y su lista. Y aunque toda crítica futbolística es válida, creo que esa explicación es demasiado fácil.</p><p>Para mí, el problema de fondo es otro.</p><h3><strong>Nivel en la ofensiva</strong></h3><p>Con mucho amor, y sin intención de ofender a nadie: a esta generación de Panamá le falta nivel individual de tres cuartos de cancha hacia adelante. O quizás, para decirlo con más precisión: esta generación, que probablemente es la que mejor fútbol colectivo ha jugado en la historia de la selección mayor masculina de Panamá, no tiene en ataque el mismo nivel de talento que tuvieron otras generaciones.</p><p>Y esto no significa que en Panamá no haya talento. Me parece increíble que uno tenga que aclararlo, pero lo aclaro: decir que a esta generación le falta talento ofensivo diferencial no es decir que “en Panamá no hay talento”. Eso sería absurdo. Lo que estoy diciendo es algo mucho más normal en el fútbol: los países tienen ciclos. Hay generaciones que producen delanteros, mediapuntas y jugadores desequilibrantes de un perfil muy alto, y hay generaciones que destacan más por otras cosas. España tuvo una generación dorada irrepetible con Xavi, Iniesta, Busquets, Villa, Torres, Ramos, Puyol, Casillas y compañía. Después tuvo que reconstruirse. Alemania, Italia, Chile, Colombia, Costa Rica: todos los países pasan por momentos donde una generación sube el techo competitivo, y luego vienen otras que tienen virtudes distintas. Eso es parte natural del fútbol.</p><p>En el caso de Panamá, hubieron nombres muy importantes en la delantera: Julio y Jorge Dely Valdés, Luis Tejada, Blas Pérez, Gabriel Torres, entre otros. Jugadores que, cada uno en su contexto, podían resolver partidos de formas que hoy nos hacen falta. Esta generación actual tiene muchas virtudes, pero no tiene ese mismo tipo de pegada.</p><h3><strong>Lo que logró (y no logró) Christiansen</strong></h3><p>Y aquí es donde, para mí, aparece el gran mérito de Thomas Christiansen.</p><p>Christiansen nos hizo creer que Panamá podía jugar al fútbol, presionar alto para recuperar el balón en área rival, tener personalidad con la pelota, proponer, competirle de tú a tú a selecciones con más nombre. Nos cambió el chip.</p><p>Durante muchos años, Panamá parecía una selección condenada a esperar, a correr detrás del balón, a resistir. Con Christiansen, Panamá se volvió un equipo que, incluso cuando no tenía los mejores talentos individuales del campo, lograba imponer su idea de juego. Eso no es poca cosa.</p><p>De hecho, creo que una de las razones por las que esta falta de gol no nos había hecho tanto daño antes es precisamente porque el sistema de Christiansen lograba generar muchas situaciones. Cuando un equipo no tiene un delantero que te meta una de cada dos, necesita crear más. Necesita compensar la falta de contundencia con volumen, presión, recuperación alta y presencia constante en campo rival.</p><p>Y en la CONCACAF, Panamá fue relativamente exitoso jugando así. Lo vimos con una nueva final de Copa Oro. Lo vimos llegando a la final de la CONCACAF Nations League. Lo vimos cuando esta generación de Panamá le ha ganado frecuentemente a la “generación dorada” de los Estados Unidos. Una generación estadounidense con jugadores en ligas importantes como Pulisic, Balogun, Sergiño Dest y compañía. Eso habla del buen trabajo. Habla de una idea. Habla de un equipo que creció muchísimo.</p><p>Pero también habla de un equipo que, cuando llega al máximo nivel, se topa con su propio techo.</p><p>Y ese techo, hoy, parece estar en el ataque.</p><h3><strong>¿Se equivocó Christiansen con la lista de jugadores?</strong></h3><p><strong>Adalberto Carrasquilla es irreemplazable</strong></p><p>Panamá extrañó muchísimo a Coco. Eso me parece indiscutible. Es el que mejor conecta la defensa con el ataque, el que puede recibir bajo presión, girar, romper líneas y darle un poco más de claridad al equipo cuando el partido se pone pesado. Con Carrasquilla en cancha, probablemente Panamá habría creado mejores ocasiones. Tal vez habría encontrado mejores pases en tres cuartos de cancha. Tal vez el equipo habría sufrido menos para transformar posesión y presión en verdadero peligro.</p><p>Pero ahí está justamente el problema: Carrasquilla no jugó.</p><p>Y como no jugó, mucha gente dice: <em>“Entonces, ¿para qué lo llevaron? ¿Por qué no llevaron a otro?”</em></p><p>Esa pregunta es válida. Pero también hay que ser honestos con la respuesta: Panamá no tiene un pozo de talento tan profundo como para pensar que reemplazar a Carrasquilla era simplemente cambiar una pieza por otra. Carrasquilla no era un jugador más en la lista. Era, posiblemente, el jugador más irremplazable del equipo.</p><p>Entonces sí, llevarlo lesionado hizo la decisión más riesgosa. Pero no necesariamente significa que había una alternativa claramente mejor. Porque cuando uno dice <em>“hubieran llevado a otro”</em>, la pregunta seria es: <em>¿a quién? ¿Y ese jugador de verdad habría cambiado el nivel del equipo? ¿O simplemente estamos imaginando una versión idealizada de alguien que no estuvo?</em></p><p>Ese es mi problema con muchos análisis después del Mundial. Están construidos sobre hipótesis muy convenientes. <em>“Si jugaba Carrasquilla.” “Si llevaban a Kadir.” “Si Fajardo no era titular.” “Si Christiansen hacía esto otro.”</em></p><p>Puede ser. Todo puede ser. Pero no me parece tan claro que esas alternativas fueran obviamente mejores dada la situación. Carrasquilla era irremplazable, y los demás nombres entran en el terreno de lo hipotético. Y cuando el talento disponible no es abundante, muchas decisiones terminan siendo más dolorosas que decisivas: cualquier camino tenía problemas.</p><p><strong>Los delanteros que tenemos son los que son</strong></p><p>Por eso creo que las críticas contra Fajardo, aunque entendibles desde la frustración, muchas veces parten de una premisa equivocada: la idea de que Christiansen tenía una alternativa claramente superior y simplemente no quiso usarla. Yo no veo eso tan claro.</p><p>Si uno mira los números de los delanteros actuales de Panamá, el panorama no es tan simple. Entre los atacantes disponibles, Ismael Díaz y José Fajardo aparecen entre los que tienen mejores promedios goleadores con la selección. Ismael ronda los 0.29 goles por partido; Fajardo ronda los 0.24. No son números de élite histórica, claro. Están por debajo de lo que ofrecieron figuras como Luis Tejada (0.4), Blas Pérez (0.34) o los Dely Valdés (0.41). Pero el punto es precisamente ese: los demás delanteros actuales tampoco tienen un registro claramente superior, al menos desde el punto de vista de efectividad goleadora.</p><p>En otras palabras: los delanteros que hay son los que hay.</p><p>Y sé que muchos van a decir: <em>“¿Y Kadir Barría?”</em></p><p>Ese es un caso importante, porque entiendo perfectamente por qué causa ilusión. Es joven, juega en Botafogo, ya tuvo momentos llamativos, y el simple hecho de estar compitiendo en Brasil siendo adolescente tiene muchísimo mérito. Nadie debería negar su potencial. Al contrario: Kadir puede ser una pieza importantísima para el futuro de Panamá.</p><p>Pero una cosa es tener futuro, y otra cosa es ser, hoy, la solución inmediata para una selección mayor en un Mundial.</p><p>Kadir causó sensación por sus primeros goles con Botafogo y por lo que representa: un delantero joven, panameño, jugando en una liga poderosa. Pero cuando uno mira su producción reciente con el primer equipo del Botafogo en el 2026 (0 goles, 2 asistencias, 19 partidos), todavía no estamos hablando de un jugador que esté goleando de forma sostenida. Ha tenido minutos, ha mostrado cosas, ha sumado experiencia, pero todavía está en proceso de consolidación.</p><p>Entonces, cuestionar a Christiansen como si hubiese dejado fuera a un delantero hecho y derecho, probado, claramente superior a todos los demás, me parece injusto. Kadir tiene mucho futuro, pero futuro no es lo mismo que presente. En un Mundial, el entrenador suele inclinarse por jugadores con más madurez competitiva, más recorrido en el proceso, y más conocimiento del grupo.</p><p>Podemos discutir si Kadir debió ir como apuesta. Podemos discutir si su perfil habría servido como revulsivo. Esa discusión es válida. Pero decir que Panamá no anotó goles simplemente porque no fue Kadir me parece una exageración.</p><p>Lo mismo pasa con la crítica a Fajardo. Claro que se puede criticar a un delantero que no marca. Claro que se le puede exigir más. Pero otra cosa es convertirlo en símbolo de todo lo malo. Fajardo no es el único responsable de que Panamá no haya anotado. El gol no depende solamente del nueve. Depende de cómo llegan los centros, de cuántas ventajas se generan, de la calidad del último pase, de la toma de decisiones de los extremos, de los mediocampistas que pisan área, de los laterales, de la pelota parada, etc.</p><p>El problema de Panamá no fue un solo jugador. Fue la falta de nivel en el último tercio.</p><h3><strong>Lo que no (y sí) necesita el fútbol panameño</strong></h3><p>Y eso no se arregla insultando a Fajardo en redes sociales. No se arregla diciendo <em>“si hubieran llevado a fulano”</em>. No se arregla fingiendo que había una solución mágica en la banca o fuera de la convocatoria.</p><p>A veces el fútbol es más cruel que eso. A veces el equipo hace casi todo lo que puede hacer, y aun así no alcanza. A veces la diferencia entre una narrativa y otra son centímetros. Un cabezazo que entra en lugar de pegar en el travesaño. Un rebote que cae en tus pies en lugar de caerle al defensa. Un remate que se abre un poco menos. Si una de esas jugadas entra, tal vez hoy no estaríamos hablando de fracaso, sino de orgullo, de evolución.</p><p>Pero como la pelota no entró, buscamos culpables.</p><p>Y yo creo que ahí tenemos que tener cuidado.</p><p>Si queremos que Panamá siga creciendo, necesitamos analizar mejor. Necesitamos poder decir dos cosas al mismo tiempo: que el equipo compitió bien y que le faltó calidad arriba. Que Christiansen hizo un gran trabajo y que pudo haberse equivocado en decisiones puntuales. Que Fajardo no tuvo un buen Mundial, pero que tampoco había un delantero claramente superior esperando afuera. Que Kadir Barría ilusiona, pero que todavía está en desarrollo. Que Panamá ha avanzado muchísimo, pero que avanzar no significa que ya estamos listos para competir de igual a igual con selecciones que llevan décadas produciendo jugadores en ligas top.</p><p>Para mí, la gran lección de este Mundial no es que Panamá necesita gritar más, insultar más o cambiar todo por rabia. La lección es que Panamá necesita desarrollar más talento.</p><p>Necesitamos que más jugadores jóvenes salgan temprano. Que compitan en mejores ligas. Que los clubes de Panamá formen atacantes más completos. Que aparezcan más jugadores capaces de decidir partidos en el último tercio. Que no tengamos que poner toda la esperanza en un solo muchacho de 18 años.</p><p>Y también necesitamos paciencia. No paciencia conformista, sino paciencia inteligente. Paciencia para entender procesos. Paciencia para separar el análisis de la frustración. Paciencia para exigir sin destruir.</p><p>A este grupo hay que agradecerle. Nos llevó a finales de Nations League, a una final de Copa Oro, a otro Mundial, y nos dio probablemente el mejor fútbol que ha jugado Panamá a nivel de selección mayor masculina. Eso no se debe borrar porque el Mundial terminó con tres derrotas y cero goles.</p><p>¿Duele? Sí.</p><p>¿Hay cosas que criticar? También.</p><p>Pero no confundamos crítica con linchamiento, ni análisis con buscar chivos expiatorios.</p><h3><strong>Lo que debe quedarse en Panamá: La fe y la ambición</strong></h3><p>Sobre si Christiansen debe seguir o no, eso le tocará decidirlo a la federación, y cada fanático tendrá su opinión.</p><p>Yo solo diría esto: si viene otro entrenador, o si Christiansen continúa, Panamá necesita a alguien que tenga capacidad, sí, pero también fe. La fe que de seguro Christiansen tuvo que tener para convencer a los jugadores y al país de que se podía jugar bien al fútbol. Lo que significa que también tuvo fe en el jugador panameño, a pesar de las limitaciones estructurales.</p><p>Fe en una idea. Fe en que podemos jugar con ambición. Fe en que no tenemos que volver a sentirnos pequeños.</p><p>Porque si algo nos dejó Christiansen, más allá de nombres y resultados, fue eso: la sensación de que Panamá podía jugar. De que Panamá podía competir con personalidad. De que Panamá podía intentar algo más grande.</p><h3><strong>Lo que sigue</strong></h3><p>Ahora el siguiente paso no es destruir lo construido. El siguiente paso es desarrollar el talento que nos falta para que, la próxima vez que Panamá llegue a un Mundial y compita bien, también tenga cómo transformar esas ocasiones en goles.</p><p>Con más calma. Con más mente fría. Y, sobre todo, con más amor por el proceso.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=a27d974493d3" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Predicting the 2026 FIFA World Cup with data science]]></title>
            <link>https://medium.com/@fmoralcaballero/predicting-the-2026-fifa-world-cup-with-data-science-b49ed1229d5c?source=rss-b9f12041089a------2</link>
            <guid isPermaLink="false">https://medium.com/p/b49ed1229d5c</guid>
            <category><![CDATA[soccer-analytics]]></category>
            <category><![CDATA[data-science]]></category>
            <category><![CDATA[soccer]]></category>
            <category><![CDATA[fifa-world-cup]]></category>
            <category><![CDATA[elo-rating-system]]></category>
            <dc:creator><![CDATA[Felix Morales]]></dc:creator>
            <pubDate>Sun, 14 Jun 2026 16:12:24 GMT</pubDate>
            <atom:updated>2026-06-14T22:11:58.184Z</atom:updated>
            <content:encoded><![CDATA[<h4>A full-tournament forecast using Elo ratings, FIFA’s new 48-team format, and a few lessons learned since my Qatar 2022 simulation.</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*DiLcWQNXgrMm0G0E" /><figcaption>Photo by <a href="https://unsplash.com/@fznsr_?utm_source=medium&amp;utm_medium=referral">Fauzan Saari</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p>The World Cup has kicked off in Mexico, Canada, and the United States. And yes, I’m excited for it because:</p><ol><li>Panama made it to the second-ever World Cup in great fashion, and seem poised to get their first points after a point-less debut in 2018.</li><li>Argentina, my title-contending favorite team, seems poised to win it again, with this one being Lionel Messi’s last World Cup.</li><li>I managed to get tickets for one game! It will be a dream come true to at least make it to one game, especially since FIFA’s ticket-pricing strategy was quite a threat to this dream.</li></ol><p>But as usual, I am also incapable of just watching a soccer tournament without asking a dangerous question:</p><blockquote>What would happen if we simulated the whole thing?</blockquote><p>So, this is my latest installment in a personal tradition: forecasting international soccer tournaments with data science. I previously did this for the <a href="https://morales-felix.github.io/Qatar-2022-FIFA-World-Cup-simulation/">2022 World Cup</a> and for <a href="https://medium.com/@fmoralcaballero/predicting-the-winner-of-copa-america-2024-with-data-science-85bac848a2b7">Copa America 2024</a> (<a href="https://medium.com/@fmoralcaballero/predicting-the-winner-of-copa-america-2024-with-data-science-part-2-b0be0b132f30">in two parts</a>). The basic idea is still the same: use Elo ratings as a measure of team strength, simulate matches many times, and see which teams most often make it to particular stages.</p><p>But this version is different in many ways, some due to the expanded 48-team format for this World Cup, others due to improvements in my own skills/understanding and in the tooling available (specifically, Codex).</p><p><strong>The TL;DR version</strong></p><p>After running 100,000 full-tournament simulations, these were the most frequently winning teams:</p><p>1. <strong>Spain:</strong> Champion in 13,788 out of 100,000 simulations(13.8%)</p><p>2. <strong>Argentina:</strong> 12,865 out of 100,000 (12.9%)</p><p>3. <strong>France:</strong> 7979 out of 100,000 (8.0%)</p><p>4. <strong>Brazil: </strong>6465 out of 100,000 (6.5%)</p><p>5. <strong>England:</strong> 5389 out of 100,000 (5.4%)</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Ci75SLXWrQjMaSwY3T7Cqw.png" /><figcaption>Top 10 teams by probability of winning the 2026 FIFA World Cup. I intentionally left the x-axis scale a little long to illustrate the scale of the uncertainty in forecasting the champion at the beginning of the tournament. The error bars correspond to the standard error.</figcaption></figure><p>This does not mean the model is “predicting” that Spain will win in the way a pundit might make a single pick. A true World Cup forecast should be probabilistic. If the favorite is at 14% probability, that does not mean the favorite is weak. It means the tournament is hard, both for teams to win, and for forecasters to… forecast.</p><p>And part of this is by design: The FIFA World Cup format is a machine designed to convert small edges into either ecstasy or heartbreak. Which is a romantic way of saying that such a format allows for a good dose of randomness to happen due to seeding, the group stage draw, and a path-dependent single-elimination knockout stage format. Which of course makes for highly-entertaining soccer!</p><p>But how can one go about forecasting such a tournament? Read on for a full description of what went on.</p><p>No patience for reading? You can find the GitHub repo for this project here: <a href="https://github.com/morales-felix/FIFA-World-Cup-2026-simulation">https://github.com/morales-felix/FIFA-World-Cup-2026-simulation</a></p><p><strong>What Elo is doing here</strong></p><p>The model uses national team ratings from <a href="https://eloratings.net/">eloratings.net</a>, which were fetched right before the first match on June 11, 2026.</p><p>I still consider these ratings as one of the best public sources for international soccer team strength. Elo ratings began in chess, which is an individual game, but the fundamental idea translates well to team sports: teams gain rating points when they outperform expectations and lose rating points when they underperform expectations.</p><p>For a match between two teams, the rating difference implies an expected probability of winning or losing. A much stronger team might be expected to win often against a weaker team (say, win 7 games out of 10 played against such a team), and evenly matched teams would be expected to win, lose, or tie some (perhaps win around 5 out of 10 games). This means that, as our intuition dictates, a weaker team can still have a way to win, but the way becomes harder the more lopsided the matchup is.</p><p>My implementation uses Elo in three places: (1) to calculate match-result probabilities, (2) to update ratings after each simulated match, and (3) to help break ties when simulated group-stage teams are otherwise level.</p><p>However, there is one simplification worth stating clearly: The official <a href="https://eloratings.net/">World Football Elo</a> method adjusts rating changes using goal difference. But I do not simulate exact scorelines, only whether the home team in a match wins, draws, or loses. That means I treat a one-goal win and a four-goal win the same for Elo updating. While I considered simulating goal difference, I decided against it for now: adding precision to a model is not the same as making it better.</p><p><strong>What changed from my 2022 and 2024 simulations?</strong></p><p><strong>1. The bracket is now part of the simulation</strong></p><p>The expanded World Cup format is not just bigger. It is more path-dependent.</p><p>In the old 32-team format, each group sent two teams to the round of 16, and the bracket was mostly easy to define ahead of time. In the 2026 format, the eight best third-place teams also advance. That creates a need to define how to match up these 32 teams that are expected to participate in this new Round of 32.</p><p>FIFA defined a bit of a complicated method to decide these matchups in a <a href="https://digitalhub.fifa.com/m/636f5c9c6f29771f/original/FWC2026_regulations_EN.pdf">table in Annex C of the 2026 tournament regulations</a>. Briefly, it is based on which set of best eight third-placed teams actually advance, which creates an explosion of possible combinations (495, to be exact). I wrote code to parse the downloaded PDF and use the correct matchup assignment for each simulated tournament.</p><p>This might sound like a technical footnote. It is not. With a tournament format like the one used in the FIFA World Cup, the shape of the bracket is an integral part of a forecast. This is because a team’s probability of becoming World Cup champion depends not only on its own strength, but also on whether it lands in a brutal section of the bracket or catches a more forgiving path.</p><p><strong>2. One simulation now means one full tournament</strong></p><p>My earlier approach first simulated the group stage, and then took the average group stage result to simulate the knockout stage separately. That was understandable because the original use case was filling out a bracket at my workplace with prizes for separate group and knockout stage predictions. But statistically, it is not ideal.</p><p>If you simulate the group stage many times, collapse it into an “average” group stage run, and then simulate one bracket based on that average, you are conditioning the knockout stage on a representative group stage result. But the real-life tournament does not happen in the average (that’d be boring). It rather happens with a mix of teams performing as expected, others overperforming, and others underperforming.</p><p>This year’s simulation instead does the following in one go:</p><p>1. Start with pre-tournament Elo ratings.</p><p>2. Simulate every group-stage match.</p><p>3. Update Elo ratings after each simulated match.</p><p>4. Rank teams within each group.</p><p>5. Select the top two teams plus the eight best third-place teams.</p><p>6. Build the knockout bracket using FIFA’s rules.</p><p>7. Simulate the knockout stage through the final.</p><p>8. Record how far every team went.</p><p>Repeat that 100,000 times, and the forecast becomes a summary of many possible tournaments rather than one typical tournament.</p><p>This is the biggest methodological improvement in the project.</p><p><strong>3. Tie-breaker rules</strong></p><p>Because I am not simulating scorelines, I cannot perfectly implement FIFA’s full group-stage tie-breaker procedure. The real rules include head-to-head points, head-to-head <em>goal difference</em>, head-to-head <em>goals scored</em>, overall <em>goal difference</em>, <em>goals scored</em>, <em>fair play points</em>, and FIFA rankings.</p><p>But I can do better than random ordering.</p><p>In this simulation, group ranking is decided by:</p><p>1. simulated group points</p><p>2. head-to-head points among teams tied on points</p><p>3. Elo rating at the start of the tournament</p><p>4. random fallback only if still exactly tied</p><p>For the best third-place teams, the simulation uses:</p><p>1. simulated group points</p><p>2. Elo rating at the start of the tournament</p><p>3. random fallback only if still exactly tied</p><p>This is not a perfect replica of FIFA’s rules, but it is a reasonable approximation given that the model does not simulate goal difference or goals scored.</p><p><strong>The simulation setup</strong></p><p>You can find the GitHub repository here: <a href="https://github.com/morales-felix/FIFA-World-Cup-2026-simulation">https://github.com/morales-felix/FIFA-World-Cup-2026-simulation</a></p><p>The data inputs are simple:</p><p>- <strong>data/roster.csv:</strong> the 48 teams, their groups, and their starting Elo ratings</p><p>- <strong>data/matches.csv</strong>: the 72 group-stage matches in schedule order</p><p>- <strong>FWC26_regulations_EN.pdf</strong>: FIFA’s tournament regulations</p><p>The core simulation lives in <strong>src/world_cup_simulator.py</strong>, and the full-tournament notebook is <strong>simulating_full_tournament.ipynb</strong>.</p><pre>third_place_matchups = parse_annex_c_matchups(&quot;FWC26_regulations_EN.pdf&quot;)<br><br>result = simulate_2026_tournament(<br>    &quot;data/matches.csv&quot;,<br>    &quot;data/roster.csv&quot;,<br>    third_place_matchups<br>)</pre><p>Under the hood, <strong>simulate_2026_tournament</strong> runs the group stage, ranks the groups, builds the bracket, simulates the knockout stage, and returns team-level and bracket-level results.</p><p><strong>Group-stage forecast</strong></p><p>The group stage is where the expanded format changes the psychology of the tournament. Finishing first obviously still matters, especially if you get matched against a third-place team (which depends on which teams qualify through this route). Finishing second is usually safe. Finishing third puts your fate partly in the hands of teams in other groups. But many others, <a href="https://www.natesilver.net/p/whats-your-teams-path-to-the-world">Nate Silver included</a>, have called this group stage format an exercise in “participation trophies” since it allows 32 out of 48 teams to advance. I’ll let you be the judge:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*yPQJ3oZ6Ao67j6w1UasjkQ.png" /><figcaption>This figure shows expected group-stage points, with the 2.5th to 97.5th percentile simulation range for each team. The dot is the average. The line shows how wide the team’s plausible range is.</figcaption></figure><p>While the above figure might suggest that anything goes, there are some patterns that can be discerned by it:</p><ol><li>Groups that are easier to forecast have mean and uncertainty bars that look staggered. These include Group A, E, and L. Specially Group L. But other groups have mean number of points very close to each other, and uncertainty bars that pretty much span the entire possible range of points (0 to 9). Chiefly among those groups, Group D and Group J, which have very close mean points among those finishing 2nd, 3rd, and 4th. Others, like groups C and I, have very close mean points among those finishing 2nd and 3rd. One could consider these as the “Groups of Death”, due to how closely contested they seem to be. They will surely be from the perspective of each of the teams involved.</li><li>There are groups with very clear favorites to win the group: Group H (Spain), J (Argentina), and perhaps I (France).</li><li>I actually do not buy that Canada will win its group. This is a curious result since I did not add home-field advantage to my implementation of the Elo rating model (and home-field advantage has been quantified to be <a href="https://www.natesilver.net/p/pele-methodology">less of a factor in modern soccer</a>).</li></ol><p>Perhaps another view of this group stage simulation might shed more light:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*kIWdrOwtnagFYN1adBdL3Q.png" /><figcaption>Heatmap of the probability each team has to end up 1st place in the group (i.e., win the group), 2nd place, 3rd place, or simply advance to the next stage. Advancing to the next stage implies having either: won the group, end up 2nd place, or be among the top eight out of twelve 3rd place finishers.</figcaption></figure><p>The above heatmap does confirm that the battle for who wins Group B will be the interesting one, and that Spain and Argentina are clear favorites to win their groups. Suffice to say that if they do not win their groups, all hell breaks loose with regards to this forecast!</p><p>It also looks likethat <strong>Group D is The Group of Death</strong>: Everybody has more than 50% chance of advancing to the Round of 32, with this group having the smallest difference in chances of advancing (87% — 51% = 36%) between the most and least likely to advance.</p><p>From Panama’s perspective, the forecast is optimistic about their chances of achieving their goal for this World Cup: Earn their first points in a FIFA World Cup, and perhaps through a first win in a FIFA World Cup. The forecast is pretty confident that Panama can achieve this through a top eight third-place finish!</p><p><strong>The knockout-stage forecast</strong></p><p>The knockout stage is where the forecast becomes less intuitive, more subject to randomness, and therefore more interesting. It is a single-elimination tournament, akin to <a href="https://en.wikipedia.org/wiki/NCAA_Division_I_men%27s_basketball_tournament#Format">March Madness</a>.</p><p>One consequence of this is that the strongest team is not always the team with the best path to win the World Cup. Specifically, even if two teams have similar Elo ratings, one of them can have a higher probability of winning the World Cup than the other. This is because, even assuming that both teams win their groups, only one of them has path in which they encounter an evenly-matched opponent in the final match, as opposed to the quarterfinal or semifinal match.</p><p>You might remember that the top-line forecast is that Spain and Argentina are the top contenders for this FIFA World Cup according to this simulation. Here’s a breakdown of probabilities of ending at each stage in the knockout round:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*G3vndtksQ6GRCd5eA6R2xA.png" /></figure><p>This stage ladder is a great way to show the forecast. For each top contender, it reports the probability of reaching the round of 32, 16, quarterfinals, semifinals, final, and winning the World Cup. This makes the forecast less binary, and allows for nuances like a team not being the most likely champion but being more likely to reach the quarterfinals than the most likely champion (like Argentina).</p><p>One thing to note is that regardless of the 48-team tournament, this World Cup is going to be a fairly contested one: The top 5 contenders add up to 46% probability of winning the World Cup, and the top 10 account for 66% probability of winning. This is in contrast to my <a href="https://medium.com/@fmoralcaballero/predicting-the-winner-of-copa-america-2024-with-data-science-part-2-b0be0b132f30">Copa America 2024 and Euro 2024 simulations</a>, where Spain and Argentina alone accounted for close to 50% of the probability (although those were estimated with an already-defined bracket).</p><p>However, true soccer fans might wonder why Spain and Argentina have such close probabilities of winning (13% or 14%, while France is a relatively far third contender (8%). Perhaps a view of the most likely bracket can illustrate what is going on.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*beKVw4cZ_a7caLOh_dSDSw.png" /></figure><p>By most likely bracket, I mean the the round of 32 matchups I’m displaying correspond to the most likely group stage results (top-two finishers, and top eight third-placed teams) across 100k simulations. Further, each team that advances to the next round is the most likely to do so in that particular matchup.</p><p>Something is immediately apparent: Spain and Argentina sit on opposite paths to the final. In other words, they would only play each other in the final match. They also happen to be the top two teams in the world according to their pre-tournament <a href="https://eloratings.net/2026_World_Cup_start">Elo ratings</a>, with Spain having 2157 points and Argentina 2115. These facts explain why Spain and Argentina top the World Cup winning odds in my simulated 100k tournaments.</p><p>However, I should point out that this is not what I would predict will happen. These specific odds of winning the World Cup are contingent upon Spain and Argentina winning their groups. And even more importantly, the above entire bracket is contingent upon all of its teams finishing in their forecasted positions within their groups. It is a very brittle scenario, with almost any deviation potentially resulting in France, Brazil, or England (OK, maybe not England) becoming a top-two contender.</p><p>While that makes the knockout stage a much tougher thing to forecast, it is what makes the tournament very exciting! Starting with the group stage, any deviation from expectation will throw this most-likely bracket to the trash can. And I am looking forward to seeing that happen!</p><p><strong>Deeper technical notes</strong></p><p>Hopefully after reading this you are left with a sense of increased uncertainty (and therefore, excitement), rather than increased certainty. Otherwise, I failed at my job.</p><p>But there are two kinds of uncertainty when building forecasts such as these, and one subtle improvement over my older posts is that I now separate them.</p><p>The first is simulation uncertainty: the error introduced because I only ran a finite number of simulations. But with 100,000 simulations, I can reduce this source of uncertainty enough for a blog forecast.</p><p>What I cannot reduce is the second kind of uncertainty: real-life soccer. This is actual range of outcomes the tournament could produce across stadiums in Mexico, Canada, and the United States. That is what the simulation is meant to capture and what I hoped to convey with all of the above charts.</p><p>However, I could presumably reduce that uncertainty with models that capture more information from the real world.</p><p>The model I used knows team strength through Elo. It knows the tournament format. It knows the schedule. It knows that group-stage results change future Elo ratings. It knows that the 2026 bracket depends on the set of third-place teams that qualify. But it does not know injuries, starting lineups, tactical setups, travel fatigue, squad rotation, refereeing, weather, vibes, or the emotional burden of being England in a penalty shootout…</p><p>It also does not simulate goal difference.</p><p>But that’s exactly why it is difficult yet exciting to do these forecasting exercises on short tournaments such as the FIFA World Cup!</p><p><strong>So who wins?</strong></p><p>After 100k simulations, the model’s top title contenders are:</p><p>Spain</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*Ikpi42_wpILpsRU1" /><figcaption>Photo by <a href="https://unsplash.com/@zelladun?utm_source=medium&amp;utm_medium=referral">Fachry Zella Devandra</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p>Argentina</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*UIUsJcDZ5DFmQB-r" /><figcaption>Photo by <a href="https://unsplash.com/@disfruta_cafe?utm_source=medium&amp;utm_medium=referral">Diego Castañeda</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p>And I’ll introduce my personal bias into this, and say that I am perfectly happy to see either of them win it all!</p><p><strong>Final thoughts</strong></p><p>I started doing these simulations because of a workplace bracket challenge. That is still the spirit of the project: passion for soccer, and for following my curiosity.</p><p>But this version is also a much better forecast than the one I built for Qatar 2022.</p><p>The most important change is conceptual: I am no longer simulating a group stage and then simulating a bracket as a separate exercise. I am simulating entire tournaments. That lets uncertainty propagate naturally: A weird group-stage result can create a weird bracket, which then creates weird knockout stage paths.</p><p>There will be at least one team that will break this simulation. Somebody will become a national hero.</p><p>And that is exactly what the World Cup is made of.</p><p>Want to give this simulation a try? Want to improve upon it? Here’s the GitHub repository: <a href="https://github.com/morales-felix/FIFA-World-Cup-2026-simulation">https://github.com/morales-felix/FIFA-World-Cup-2026-simulation</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=b49ed1229d5c" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Uncovering ARDS with Data Science: An Algorithm That Finds a Life-Threatening Syndrome]]></title>
            <link>https://medium.com/@fmoralcaballero/ards-a-common-deadly-syndrome-thats-easy-to-miss-23f3b4b837d3?source=rss-b9f12041089a------2</link>
            <guid isPermaLink="false">https://medium.com/p/23f3b4b837d3</guid>
            <category><![CDATA[ards-diagnosis]]></category>
            <category><![CDATA[health-informatics]]></category>
            <category><![CDATA[data-science]]></category>
            <category><![CDATA[ai-in-healthcare]]></category>
            <dc:creator><![CDATA[Felix Morales]]></dc:creator>
            <pubDate>Fri, 08 Aug 2025 23:38:17 GMT</pubDate>
            <atom:updated>2025-08-14T00:19:47.119Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*mclka_N_9EqWuWt8" /><figcaption>Photo by <a href="https://unsplash.com/@cdc?utm_source=medium&amp;utm_medium=referral">CDC</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p>I just recently had a cool AI in Healthcare paper <a href="https://doi.org/10.1038/s41467-025-61418-5">published in Nature Communications</a>!</p><p>Did I hear you say: “What is it about?”</p><p>Keep reading ;)</p><h3>The Problem</h3><p>Acute Respiratory Distress Syndrome (ARDS) is a severe lung condition that affects <strong>about 10% of ICU patients</strong> and kills over <strong>40% of them</strong>. In ARDS, fluid floods the lungs’ air sacs, causing low oxygen levels in the blood (hypoxemia) and often requiring a ventilator. Treating ARDS properly (for example with low tidal-volume ventilation or prone positioning) can save lives, but many ARDS cases go <strong>unrecognized </strong>by doctors. This is partly because doctors in a busy ICU must sift through lab results, chest X-rays, other doctors’ notes, and echo reports to make the diagnosis, and this “information overload” often leads to missed cases.</p><p>In short, ARDS is common and dangerous, but hard to diagnose consistently. Researchers have therefore sought ways to <strong>automate</strong> the diagnosis.</p><p>In a new <a href="https://doi.org/10.1038/s41467-025-61418-5">study</a>, we built an <a href="https://github.com/amarallab/ARDS_diagnosis">open-source pipeline</a> that mimics the standard ARDS criteria (the <em>Berlin Definition</em>) and flags likely ARDS cases using electronic health record (EHR) data. By doing so, our algorithm can help catch ARDS that busy physicians might miss.</p><h3><strong>The Berlin Definition: ARDS step-by-step</strong></h3><p>To diagnose ARDS, doctors use the <strong>Berlin Definition</strong> (established in 2012 and updated in 2023), which is like a checklist of criteria to evaluate to diagnose ARDS. In practice, this means asking a series of questions about each ventilated patient:</p><ul><li><strong>Is there hypoxemia?</strong> The blood oxygen (PaO₂) to inspired oxygen (FiO₂) ratio must be ≤300 mm Hg <em>while on a ventilator with PEEP ≥5 cm H₂O</em> (in other words, oxygen levels are low <em>despite</em> significant ventilator support).</li><li><strong>Are there bilateral lung infiltrates on imaging?</strong> The chest X-ray or CT should show <em>opacities on both sides of the chest</em>, consistent with pulmonary edema (in other words, there’s fluid in <em>both</em> lungs).</li><li><strong>Is there any known ARDS risk factor?</strong> Classic triggers for this fluid accumulation in the lungs include <strong>pneumonia, sepsis, aspiration</strong>, trauma, pancreatitis, and others.</li><li><strong>If we can’t find a known ARDS risk factor, can we rule out heart failure?</strong> Fluid in both lungs must not be exclusively be due to “cardiogenic origin,” meaning that heart failure can’t be the only explanation for fluid in both lungs. So, if we couldn’t find a risk factor, we must make sure there isn’t any heart failure either.</li></ul><p>Putting it all together: ARDS is defined by <strong>(1)</strong> a low PaO₂/FiO₂ ratio (≤300), AND <strong>(2)</strong> bilateral pulmonary opacities on imaging, AND <strong>(3a)</strong> a known risk factor present, OR <strong>(3b)</strong> no evidence of heart failure. Meeting these steps means the patient has ARDS.</p><p>Figuring out each piece requires looking at different types of data: lab numbers, radiology reports, doctors’ notes, and echo reports. This process looks straightforward on paper, but hopefully you can see that it is <strong>time-consuming </strong>in real time. In fact, many studies have shown that physicians often <strong>under-diagnose (or at the very least, under-treat) ARDS!</strong></p><h3>Automating ARDS Diagnosis with a Data Pipeline</h3><p>Our new study builds a <strong>computational pipeline</strong> that automatically runs through these Berlin steps using data from the ICU chart. In a way, it replaces each manual check with a programmatic one. The pipeline takes as input all ventilated ICU encounters meeting basic criteria (adult and intubated patient) and then applies filters in sequence — mimicking how the Berlin Definition would <em>adjudicate</em> ARDS. Importantly, it’s <strong>open-source, trained on multiple hospitals’ data, and tested on a public dataset (MIMIC-III)</strong>, making the process transparent and reproducible.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/325/1*emEhElNmUNoaZkU6iwIYrg.png" /><figcaption>The ARDS diagnosis pipeline applies the Berlin Definition step by step. Starting from all ventilated ICU patients, it first checks oxygenation (PaO₂/FiO₂), then analyzes chest imaging reports for bilateral infiltrates, then scans physician notes for ARDS risk factors, and finally examines echo reports to exclude heart failure.</figcaption></figure><p>At each step, we used different software and data science tools:</p><ul><li><strong>Step 1: Hypoxemia filter.</strong> The pipeline requires that the patient had at least one PaO₂/FiO₂ ≤ 300 mm Hg <em>after</em> intubation. This is a logical check done in structured data (blood gas records), without needing machine learning or AI. Patients who never reach this hypoxemia threshold are dropped out from consideration.</li><li><strong>Step 2: Bilateral infiltrates.</strong> The pipeline next checks if there’s <strong>bilateral opacities</strong> <strong>within 48 hours</strong> of a hypoxemia event<strong>. </strong>This is a very important step! To decide if imaging shows bilateral opacities, the pipeline parses the <em>radiology reports</em>. These free-text reports (X-ray or CT impressions) are fed into an <strong>interpretable machine learning model</strong> (specifically an XGBoost classifier), which was trained on ~12 thousand labeled reports where critical care doctors had marked “yes” or “no” to bilateral infiltrates. Essentially, the model learns keywords and phrases (“pulmonary edema,” “bilateral effusions,” etc.) that predict whether the report describes opacities. In testing, this XGBoost model performed quite well: it achieved an <strong>area under the ROC curve (AUROC) of 0.88</strong> on held-out data. The model’s probabilities are then thresholded to decide yes/no for “bilateral infiltrates.”</li><li><strong>Step 3: ARDS risk factors.</strong> The pipeline next checks if <em>at least one</em> ARDS risk factor is mentioned in the chart within 7 days of hypoxemia. To do this, it analyzes the doctors’ notes. First, a set of <strong>regular expressions</strong> (keyword patterns) scans each note for terms like “pneumonia,” “sepsis,” “aspiration,” etc. However, we used XGBoost to improve detection of pneumonia, since there was enough training data to make this approach work for that risk factor. In practice, the pipeline flags a risk factor if it either matches a regex for any of the risk factors, or if the pneumonia ML model probability is high. For reference, the pneumonia model had an AUROC around <strong>0.88 </strong>on held-out data.</li><li><strong>Step 4: Excluding heart failure.</strong> Finally, the pipeline asks whether heart failure might explain the opacities if it couldn’t find a single risk factor. It combs through doctors’ notes, echocardiogram reports and lab data for evidence of cardiogenic edema. The algorithm looks for structured indicators like <strong>low ejection fraction (&lt;40%)</strong>, signs of cardiopulmonary bypass, dilated left atrium/ventricle, hypertrophy, or grade II–III diastolic dysfunction. These features are extracted via regex (the echo reports are quite standardized) and numeric thresholds. A single elevated BNP (brain natriuretic peptide) can also trigger a “cardiac” flag.</li></ul><p>If such cardiac findings are present <em>without any ARDS risk factors</em>, the pipeline concludes the issue is likely heart failure, not ARDS, and labels the case negative. Otherwise, if all previous filters passed (steps 1 to 3), the pipeline declares <strong>ARDS-positive</strong>.</p><p>By chaining these steps, the pipeline effectively <strong>encodes the Berlin Definition</strong> into software. Unlike a single black-box model, which would match a set of features with a “yes” or “no” ARDS label, this structured approach lets clinicians see <strong>which</strong> Berlin Definition criterion was met or not. What’s more, we can also give a view of which words moved the machine learning models to flag “yes” or “no” at each step.</p><h3>Performance of the Pipeline</h3><p>As my advisor said in a talk:</p><blockquote>How did it do? FANTASTIC! Otherwise I wouldn’t be giving a talk about it!</blockquote><p>I can say the same, but about the fact that we got it published, and that I’m writing to you about it in this post!</p><p>In the held-out MIMIC-III test set (which was sample of 100 ICU cases, roughly balanced in their ARDS status), the pipeline achieved maximum of <strong>93.5% sensitivity</strong> (true positive rate) and a minimum 7.2<strong>% false positive rate</strong> (~93% specificity) for ARDS. In other words, it caught over 93% of true ARDS cases while mistakenly flagging only about 7% of non-ARDS patients (depending on the probability threshold choice for the Bilateral Infiltrates model).</p><p>For context, doctors only documented ARDS in the chart in ~22.6% of those cases, so the automated tool vastly outperformed routine charting. But that’s a cheap shot, so we also asked an internal medicine doctor to review those cases as well. This doctor’s sensitivity was 83% (but their specificity was ~96%)!</p><p>The key point is that this automated Berlin Definition drastically <strong>improves ARDS recognition</strong> over usual practice. For reference, even the best doctor recognition rates reported in studies (~78% in the LUNG SAFE study) are below what the pipeline achieved.</p><h3>Reflections: Interpretability, Labels, and Reproducibility</h3><blockquote>For more about this rant/discussion, and to also learn more about these results, check out my <a href="https://youtu.be/RF7M1gC1beU">talk at the Institute for Artificial Intelligence in Medicine (Northwestern University)</a>!</blockquote><p>A question that we obviously get is “Why didn’t you use large language models?” This pipeline illustrates how we have a <strong>different philosophy</strong> in the use of machine learning for medical applications. Rather than throwing a black-box model at the data, we kept transparency (interpretable models) and domain knowledge (we automated a clinical guideline) at the forefront of our design choices. Furthermore, we deliberately chose classifiers that output <em>probabilities</em> rather than hard predictions, which means physicians can adjust the probability thresholds to balance missing cases against false alarms as they deem appropriate. Finally, because the models are simpler (trees and regex) they can be versioned, explained, and validated — all crucial for gaining <strong>clinician trust</strong>.</p><p>And I want to harp on this aspect: this project highlights a contrast with many AI efforts that hunt for hidden patterns. It instead <strong>encodes known structure</strong>. The Berlin Definition is a well-established decision tree, and we built a computational tool that could apply it accurately, swiftly, and <strong>reliably</strong>. We show that the pipeline can do the three of these, while plenty of evidence shows that even the best trained humans for this task (i.e., critical care doctors) cannot do the three simultaneously.</p><p>Now, ARDS criteria could change, and it has changed recently. That means the pipeline would need an update. But such an update would be clear to potential users, which would not be the case if we pursued a black-box approach to this pipeline. I would even submit that it wouldn’t be clear to us either.</p><p>Building the system did require <strong>heavy human effort</strong> behind the scenes. Thousands of radiology reports and notes had to be labeled by experts for model training. Echo reports were annotated for cardiac findings as well. This upfront “chart review” is laborious, but it paid off in a robust algorithm. In that sense, the work was part data science, part traditional clinical study. The end result, however, is a fully <em>open-source</em> pipeline with code on <a href="https://github.com/amarallab/ARDS_diagnosis">GitHub</a>, making it reproducible and extensible. Because it was validated on MIMIC-III, future researchers or hospitals can <strong>benchmark</strong> themselves against this pipeline.</p><p>In summary, this work shows how data science can augment clinical care by faithfully implementing a diagnostic algorithm. The pipeline may serve as a quality assurance tool (flagging missed cases in retrospective reviews) or, with further work, as a real-time alert system. It dramatically reduces under-recognition of ARDS and does so with high transparency.</p><p>Thanks for reading! :)</p><h3>Links:</h3><p>Paper: <a href="https://doi.org/10.1038/s41467-025-61418-5">https://doi.org/10.1038/s41467-025-61418-5</a></p><p>GitHub: <a href="https://github.com/amarallab/ARDS_diagnosis">https://github.com/amarallab/ARDS_diagnosis</a></p><p>Talk: <a href="https://youtu.be/RF7M1gC1beU">https://youtu.be/RF7M1gC1beU</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=23f3b4b837d3" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Build a SMART on FHIR App using Python’s Flask and OAuthLib]]></title>
            <link>https://medium.com/@fmoralcaballero/building-a-smart-on-fhir-application-with-pythons-flask-and-oauthlib-1217a49d1529?source=rss-b9f12041089a------2</link>
            <guid isPermaLink="false">https://medium.com/p/1217a49d1529</guid>
            <category><![CDATA[fhir]]></category>
            <category><![CDATA[oauth2]]></category>
            <category><![CDATA[healthit]]></category>
            <category><![CDATA[smartonfhir]]></category>
            <category><![CDATA[app-development]]></category>
            <dc:creator><![CDATA[Felix Morales]]></dc:creator>
            <pubDate>Tue, 03 Dec 2024 04:24:19 GMT</pubDate>
            <atom:updated>2024-12-12T16:14:58.712Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*uzv5zRVd8O2oU5OC" /><figcaption>Photo by <a href="https://unsplash.com/@lukechesser?utm_source=medium&amp;utm_medium=referral">Luke Chesser</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p>Imagine you’re a healthcare developer tasked with creating a web application for clinicians. This app would pull real-time patient data like height, blood pressure, and cholesterol levels from an Electronic Health Record (EHR) system. To achieve this, your app must comply with the <a href="https://hl7.org/fhir/smart-app-launch/app-launch.html"><strong>SMART on FHIR</strong></a> standard, an interoperability protocol designed for secure access to <a href="https://hl7.org/fhir/">FHIR (Fast Healthcare Interoperability Resources)</a> APIs using OAuth 2.0.</p><p>SMART on FHIR provides a robust way to authenticate apps within EHRs, enabling developers to focus on innovative healthcare solutions while ensuring patient data security and privacy.</p><h3>The Problem</h3><p>While there are SMART on FHIR <a href="https://docs.smarthealthit.org/">tutorials</a> out there, they mostly focus on client-side JavaScript/Node.js libraries. There is a lack of online resources for developers interested in using a server-side, Python Flask implementation. That’s not to say they don’t exist: SMART Health IT has developed the <a href="https://docs.smarthealthit.org/client-py/">FHIRClient</a> Python library, and include a nice <a href="https://github.com/smart-on-fhir/client-py/blob/main/demos/flask/flask_app.py">demo app</a> to showcase its functionality. However, this library abstracts away crucial implementation details. This level of abstraction might be helpful for seasoned developers but can leave beginners confused.</p><h3>The Solution</h3><p>This tutorial walks you through creating a SMART on FHIR application using Python’s <a href="https://flask.palletsprojects.com/en/stable/"><strong>Flask</strong></a> framework and <a href="https://oauthlib.readthedocs.io/en/latest/"><strong>OAuthLib</strong></a> library. By using OAuthLib, we simplify the SMART on FHIR authorization workflow into comprehensible steps, allowing you to understand the “how” and “why” behind each step.</p><p>We’ll build a simple app that (1) runs locally, (2) launches from the <a href="https://launch.smarthealthit.org/">SMART Health IT sandbox</a>, and (3) retrieves and displays the following FHIR resources for a patient:</p><ul><li><strong>Patient</strong>: First name, last name, date of birth.</li><li><strong>Observation</strong>: Height, blood pressure, HDL, and LDL.</li></ul><p>The goal is to demystify the authorization workflow, which is the initial barrier to creating SMART on FHIR apps.</p><h3>Let’s Get Started!</h3><h3>Step 1: Clone the demo app GitHub repo</h3><p>First, fork the <a href="https://github.com/morales-felix/SMART-on-FHIR-Python-app">GitHub repo</a> containing the app we’ll explore in this tutorial. Then, clone the forked repo to your local machine, and navigate to the project directory:</p><pre>git clone https://github.com/morales-felix/SMART-on-FHIR-Python-app.git<br>cd SMART-on-FHIR-Python-app</pre><h3>Step 2: Install dependencies</h3><p>Create a fresh environment (Python &gt;=3.7 but &lt; 3.10 strongly recommended), and run the following:</p><pre>python -m venv venv<br>source venv/bin/activate  # On Windows use `venv\Scripts\activate`<br>pip install -r requirements.txt</pre><h3>Step 3: Set Up the Flask App</h3><p>Next, create a Flask app skeleton with the following structure:</p><pre>from flask import Flask, request, redirect, render_template<br>from oauthlib.oauth2 import WebApplicationClient<br>import requests<br>import json<br><br>#####################################################################################<br># Defining application credentials for OAuth 2.0<br>CLIENT_ID = &quot;client-id&quot;<br>BASE_URL = &quot;https://launch.smarthealthit.org/v/r4/fhir&quot;<br># See https://hl7.org/fhir/smart-app-launch/scopes-and-launch-context.html<br># For EHR launch, the scope should be &quot;launch&quot;, not &quot;launch/patient&quot;<br>SCOPES = (<br>    &quot;patient/Patient.rs patient/Observation.rs launch offline_access openid fhirUser&quot;<br>)<br>REDIRECT_URI = &quot;http://localhost:4201/fhir-app/&quot;<br>#####################################################################################<br><br>app = Flask(__name__)<br>client = WebApplicationClient(CLIENT_ID)  # OAuth client<br>cookie = {}  # Temporary storage for token</pre><blockquote><strong>Note</strong>: When deploying an app to production or working on serious development projects, never include credentials directly in your code. Instead, store them in a configuration file and ensure the file is excluded from version control, such as by using .gitignore. In this example, the credentials are not sensitive, so they are included in the script for convenience.</blockquote><h3>Pause: Understanding OAuth 2.0 and SMART on FHIR</h3><p>OAuth 2.0 is an authorization framework that enables third-party apps to access resources on behalf of a user. It consists of these key steps:</p><ol><li><strong>Authorization Request</strong>: The app directs the user to the authorization server (EHR in our case) to request access.</li><li><strong>Authorization Grant</strong>: The server returns an authorization code upon user approval.</li><li><strong>Access Token Request</strong>: The app exchanges the code for an access token.</li><li><strong>Access Resource</strong>: The app uses the token to request resources from the FHIR API.</li></ol><p>SMART on FHIR builds on OAuth 2.0 by adding healthcare-specific extensions, such as <a href="https://hl7.org/fhir/smart-app-launch/1.0.0/scopes-and-launch-context/">scopes for accessing FHIR resources</a> and launch context for <a href="https://hl7.org/fhir/smart-app-launch/app-launch.html#launch-app-ehr-launch">EHR-embedded apps</a>. In particular, EHR-embedded apps launch with a user already logged into the EHR system, slightly altering the flow of the authorization request and grant process.</p><p>If you are visual learner, this sequence diagram from Cerner’s <a href="https://engineering.cerner.com/smart-on-fhir-tutorial/">tutorial</a> may help clarify the steps (follow the arrows from left to right, moving downward):</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1004/1*4it59dQbKLg_6WkOw8Xt7g.png" /><figcaption>Sequence of SMART on FHIR authorization steps in an EHR launch</figcaption></figure><p>In summary, a SMART on FHIR app launched in “EHR” mode receives parameters needed to prepare an authorization request to the authorization server. Once approved, the app obtains an authorization token, which it exchanges for an API access token. With this token, the app can make API calls to access FHIR data.</p><p>We’ll write code to handle each of these steps!</p><h3>Step 4: Implementing the SMART on FHIR Workflow</h3><h4>1. <a href="https://hl7.org/fhir/smart-app-launch/app-launch.html#retrieve-well-knownsmart-configuration">Retrieve SMART Configuration</a></h4><p>Unlike the diagram above, this demo app fetches metadata about the authorization and token endpoints as soon as it is served:</p><pre>smart_config_url = f&quot;{BASE_URL}/.well-known/smart-configuration&quot;<br>response = requests.get(<br>    smart_config_url, headers={&quot;Accept&quot;: &quot;application/fhir+json&quot;}<br>).json()<br>authorization_uri = response[&quot;authorization_endpoint&quot;]<br>token_uri = response[&quot;token_endpoint&quot;]</pre><p>While this step could be performed after launch, it must be completed before requesting authorization. The app needs this metadata to know where to request authorization and access tokens.</p><h4>2. <a href="https://hl7.org/fhir/smart-app-launch/app-launch.html#launch-app-ehr-launch">Handling app launch</a></h4><p>When a user launches the app, the EHR system initiates the authorization process by calling the launch URL you registered with the <a href="https://launch.smarthealthit.org/">SMART Health IT sandbox</a>. This URL will include the launch and iss parameters. For this tutorial, the launch URL should be <a href="http://localhost:4201/,">http://localhost:4201</a>/ since the app is being served locally:</p><pre>@app.route(&quot;/&quot;, methods=[&quot;GET&quot;, &quot;POST&quot;])<br>@app.route(&quot;/index.html&quot;, methods=[&quot;GET&quot;, &quot;POST&quot;])<br>def index():<br>    &quot;&quot;&quot;<br>    This is the method the EHR client will trigger upon launch.<br>    It will redirect to the authorization page.<br>    &quot;&quot;&quot;<br><br>    # Retrieve the launch parameters from the query string<br>    launch_token = request.args.get(&quot;launch&quot;, &quot;&quot;)<br>    iss = request.args.get(&quot;iss&quot;, &quot;&quot;)<br><br>    assert (<br>        iss == BASE_URL<br>    ), f&quot;&quot;&quot;ISS link is {iss}, but the app&#39;s registered link is {BASE_URL}<br>    (these should match, otherwise there might be a security vulnerability). Please validate.&quot;&quot;&quot;<br><br>    cookie[&quot;launch_token&quot;] = launch_token<br><br>    return redirect(&quot;/authorize&quot;)</pre><p>The @app.route(“/”, methods=[“GET&quot;, “POST”]) decorator triggers this function upon launch, specifying which URL the function should handle. The function extracts the launch token and iss parameters using the request.args.get() method, verifies that the iss parameter matches the BASE_URL set earlier (a critical security check), and then redirects to the authorization process.</p><h4>3. <a href="https://hl7.org/fhir/smart-app-launch/app-launch.html#obtain-authorization-code">Authorization Request</a></h4><p>The previous function redirects to this one via the @app.route(“/authorize”, methods=[“GET&quot;, “POST”]) decorator:</p><pre>@app.route(&quot;/authorize&quot;)<br>def authorization():<br>    &quot;&quot;&quot;<br>    This method prepares an authorization request<br>    to the authorization server with the necessary parameters.<br>    &quot;&quot;&quot;<br>    <br>    import uuid<br><br>    # Generate a state<br>    cookie[&quot;state&quot;] = uuid.uuid4().hex<br><br>    # Prepare request for authorization server<br>    auth_url = client.prepare_request_uri(<br>        uri=authorization_uri,<br>        redirect_uri=REDIRECT_URI,<br>        launch=cookie[&quot;launch_token&quot;],  # Necessary for EHR launch<br>        scope=SCOPES,<br>        state=cookie[&quot;state&quot;],<br>        aud=BASE_URL  # This is a key difference between OAuth 2.0 and SMART on FHIR<br>    )<br><br>    # Hit the auth server with built-in parameters<br>    return redirect(auth_url)</pre><p>As described in the docstring, this function prepares the authorization request using the client.prepare_request_uri() method from OAuthLib. This method appends the specified parameters to the authorization_uri, and redirects to the resulting URL, effectively sending the request to the authorization server.</p><blockquote><strong>Note</strong>: Think of this step as filling out a form and submitting it. Therefore, it’s crucial to ensure every parameter is correct — double-check everything!</blockquote><p>At this stage, the process is handed off to the authorization server, which will either grant or deny authorization.</p><h4>4. <a href="https://hl7.org/fhir/smart-app-launch/app-launch.html#obtain-access-token">Obtain Access Token</a></h4><p>If the app is granted authorization, the authorization server will call the redirect URL you registered with the <a href="https://launch.smarthealthit.org/">SMART Health IT sandbox</a>. This registered URL must match the one specified in your Python script; otherwise, the process will fail — double-check this! The redirect URL called by the authorization server will include an authorization code, which is needed to prepare an access token request:</p><pre>@app.route(&quot;/fhir-app/&quot;, methods=[&quot;GET&quot;, &quot;POST&quot;])<br>def callback():<br>    &quot;&quot;&quot;<br>    This method will handle the callback from the authorization server.<br>    It will then request an access token from the token server.<br>    &quot;&quot;&quot;<br><br>    try:<br>        # Prepare request for token server.<br>        # This method already does a strict state checking behind the scenes<br>        # (aka, checks that the state returned by the auth server is the same that the client gave)<br>        token_url, headers, body = client.prepare_token_request(<br>            token_url=token_uri,<br>            authorization_response=request.url,<br>            redirect_url=REDIRECT_URI,<br>            state=cookie[&quot;state&quot;],<br>            include_client_id=True,  # This is another SMART-specific aspect, in case of a public client<br>        )<br><br>        # Send post request to token endpoint<br>        token_response = requests.post(token_url, headers=headers, data=body)<br>        cookie[&quot;token&quot;] = token_response.json()<br><br>        # Add token to the client object so that it can be used later<br>        client.parse_request_body_response(json.dumps(token_response.json()))<br><br>    except Exception:<br>        error_message = (<br>            &quot;An error occured when the application tried to obtain an access token.&quot;<br>        )<br>        return render_template(&quot;error.html&quot;, error=error_message)<br><br>    return redirect(&quot;/render_data&quot;)</pre><p>The first part of the function mirrors the previous one by preparing another request. However, OAuthLib provides a specialized method, client.prepare_token_request(), for this purpose. This method handles more complexity than the earlier client.prepare_request_uri() method.</p><p>The authorization code is extracted from the redirect URL passed by the authorization server to our app. We retrieve it by passing request.url to the authorization_response parameter.</p><p>Once the access token request is prepared, the function uses the Requests library to send it to the token server. If approved, the server returns an API access token, <strong>fully authorizing the app</strong>. The function then proceeds with the rest of the app’s logic.</p><blockquote><strong>Note</strong>: The access token grants the app specific permissions to make API requests, limited by the SCOPES parameter defined earlier in the script. For example, this app only has read access to the Patient and Observation FHIR resources associated with the patient it was launched for.</blockquote><h3>Step 5: Access FHIR Resources and do stuff</h3><p>With <a href="https://hl7.org/fhir/smart-app-launch/app-launch.html#access-fhir-api">access to the requested data</a>, you can now pursue your use case or explore new possibilities. Here’s a snippet showing how this demo app processes data from the Patient and Observation FHIR resources:</p><pre>@app.route(&quot;/render_data&quot;, methods=[&quot;GET&quot;, &quot;POST&quot;])<br>def render_data():<br>    &quot;&quot;&quot;<br>    This method will render the data obtained from FHIR.<br>    &quot;&quot;&quot;<br>    <br>    import concurrent.futures<br><br>    with concurrent.futures.ThreadPoolExecutor() as executor:<br>        # Submit API calls as tasks to the executor<br>        future_patient = executor.submit(_get_patient_data, cookie[&quot;token&quot;])<br>        future_height = executor.submit(_get_height, cookie[&quot;token&quot;])<br>        future_bp = executor.submit(_get_bp, cookie[&quot;token&quot;])<br>        future_hdl = executor.submit(_get_hdl, cookie[&quot;token&quot;])<br>        future_ldl = executor.submit(_get_ldl, cookie[&quot;token&quot;])<br><br>        # Wait for all tasks to complete<br>        concurrent.futures.wait(<br>            [future_patient, future_height, future_bp, future_hdl, future_ldl]<br>        )<br><br>        # Get results from completed tasks<br>        try:<br>            first_name, last_name, dob = future_patient.result()<br>            height = future_height.result()<br>            systolic_bp, diastolic_bp = future_bp.result()<br>            hdl = future_hdl.result()<br>            ldl = future_ldl.result()<br><br>            records = {<br>                &quot;Name&quot;: first_name + &quot; &quot; + last_name,<br>                &quot;Date of Birth&quot;: dob,<br>                &quot;Height&quot;: height,<br>                &quot;Systolic BP&quot;: systolic_bp,<br>                &quot;Diastolic BP&quot;: diastolic_bp,<br>                &quot;HDL&quot;: hdl,<br>                &quot;LDL&quot;: ldl,<br>            }<br><br>            return render_template(&quot;render_data.html&quot;, data=records)<br><br>        except Exception as error:<br>            raise ValueError(<br>                f&quot;Found the following error when rendering data: {error}&quot;<br>            ) from error</pre><p>This function leverages internal helper functions prefixed with _get_, each designed to extract specific data elements. These helper functions are executed concurrently using concurrent.futures for efficiency. Once the data is retrieved, the function renders the results in an HTML template.</p><p>For more details on how the data elements are extracted, refer to the full ehr_launch.py <a href="https://github.com/morales-felix/SMART-on-FHIR-Python-app/blob/main/ehr_launch.py">script</a>.</p><h3>Conclusion</h3><p>Congratulations! You’ve built a simple SMART on FHIR application using Flask and OAuthLib. This tutorial demonstrated how to:</p><ol><li>Launch the app with SMART on FHIR.</li><li>Handle OAuth 2.0 authorization steps.</li><li>Access FHIR resources.</li></ol><p>Feel free to adapt this code to your specific use case. If you have questions, drop them in the comments below!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=1217a49d1529" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Los “planes de gobierno” presentados por candidatos a presidente son inútiles]]></title>
            <link>https://medium.com/@fmoralcaballero/los-planes-de-gobierno-presentados-por-candidatos-a-presidente-son-in%C3%BAtiles-25a61a8740ef?source=rss-b9f12041089a------2</link>
            <guid isPermaLink="false">https://medium.com/p/25a61a8740ef</guid>
            <category><![CDATA[ramblings]]></category>
            <category><![CDATA[política]]></category>
            <category><![CDATA[elecciones-2019]]></category>
            <category><![CDATA[panamá]]></category>
            <category><![CDATA[opinión]]></category>
            <dc:creator><![CDATA[Felix Morales]]></dc:creator>
            <pubDate>Tue, 15 Oct 2024 23:00:11 GMT</pubDate>
            <atom:updated>2024-10-16T13:10:47.027Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*EAdTs4iW5OMugI5w" /><figcaption>Photo by <a href="https://unsplash.com/@mbrunacr?utm_source=medium&amp;utm_medium=referral">Miguel Bruna</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p><em>Esto lo escribí entre marzo y mayo de 2019, cuando Panamá celebraba elecciones generales.</em></p><p>La publicación de los “planes de gobierno” de los candidatos a la presidencia de Panamá ha generado reacciones a favor y en contra en redes sociales. Sin embargo, quienes observan y analizan estas reacciones notarán que no se centran en propuestas específicas (lo que supongo es el propósito de publicar dichos planes), sino en la supuesta falta de un plan detallado por parte del candidato independiente Ricardo Lombana. Personalmente, al leer brevemente cada documento, me sorprendió que Lombana quisiera distanciarse incluso en este aspecto. Curioso por las reacciones que esto generaría, no me decepcionó el espectáculo en redes (mejor que pagar Netflix).</p><p>Muchas opiniones carecen del espíritu de debate democrático y parecen más propaganda política o puro espectáculo. La crítica más común es: <strong>“Se debe llegar a la presidencia con un plan de trabajo, no a improvisar”</strong>. Aunque esta idea suena razonable, es engañosa, ya que <strong>los documentos largos presentados por todos los candidatos NO son planes en el sentido estricto de la palabra.</strong></p><p>Un plan, según definiciones de diccionario, es <strong>“un conjunto de pasos propuestos, donde se detalla el tiempo y los recursos necesarios para cada paso, cuya realización apunte a la consecución de un objetivo”</strong>. Bajo esta definición, uno esperaría que los planes de gobierno describieran secuencialmente los pasos a seguir, con detalles sobre recursos y cronogramas. Te invito a revisar los documentos presentados y comprobar que <strong>ninguno cumple con esta definición básica.</strong></p><p>Es cierto que los documentos largos incluyen antecedentes y análisis de problemas, lo que indica que los candidatos entienden la situación del país. Pero eso no convierte esos documentos en “planes”. Si tienes dudas, consulta la definición mencionada. Otro argumento podría ser que al menos los demás candidatos desglosan sus propuestas en objetivos generales y específicos, mientras que Lombana presentó solo una lista de promesas. Entonces, <em>¿cómo es que voy a criticar a los candidatos de partidos por sus documentos detallados y defender a Lombana por un documento escueto</em>? La respuesta es simple: por muy largos y detallados que sean, todos los documentos presentan solo <em>qué</em> se quiere lograr, sin describir la <em>secuencia</em> de pasos para lograrlo. Según la definición, todos son listas de deseos para Santa Claus. Dividir las propuestas en generales y específicas no cambia esa esencia.</p><p>Si ninguno de estos documentos es un plan de gobierno, <strong>¿qué son entonces?</strong> En política, estos documentos tienen el objetivo de presentar la postura del candidato sobre los problemas más apremiantes del país y los principios en los que basarán sus soluciones. Esto es lo que en inglés se llama una “plataforma política”. Un ejemplo sería que un candidato considere el embarazo juvenil como un problema urgente y proponga resolverlo a través de instituciones religiosas en lugar de educación sexual, reflejando así una postura conservadora.</p><p>Bajo esta definición, los documentos de los candidatos cumplen con su función. El ejemplo más evidente (y tal vez el único; sospechosamente todos los candidatos coinciden sobre cuales son los problemas más importantes, y en como resolverlos) es la atención al cambio de la Constitución, donde difieren en cómo proceder (mediante dos Asambleas, o mediante una Asamblea Constituyente). Estas diferencias reflejan el valor que cada candidato le otorga al tema de la corrupción, y permiten a los votantes tomar decisiones informadas. Lo lamentable es que, en lugar de generar un debate sobre estas diferencias, el foco ha sido criticar a un candidato por no llenar páginas con verborrea inútil.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=25a61a8740ef" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Predicción del Campeón de la Copa América 2024 con Ciencia de Datos — Parte 2]]></title>
            <link>https://medium.com/@fmoralcaballero/predicci%C3%B3n-del-campe%C3%B3n-de-la-copa-am%C3%A9rica-2024-con-ciencia-de-datos-parte-2-169163756c35?source=rss-b9f12041089a------2</link>
            <guid isPermaLink="false">https://medium.com/p/169163756c35</guid>
            <category><![CDATA[copa-america]]></category>
            <category><![CDATA[soccer-analytics]]></category>
            <category><![CDATA[data-science]]></category>
            <category><![CDATA[soccer]]></category>
            <category><![CDATA[elo-rating]]></category>
            <dc:creator><![CDATA[Felix Morales]]></dc:creator>
            <pubDate>Fri, 05 Jul 2024 01:37:20 GMT</pubDate>
            <atom:updated>2024-07-05T01:47:02.476Z</atom:updated>
            <content:encoded><![CDATA[<h3>Predicción del Campeón de la Copa América 2024 con Ciencia de Datos — Parte 2</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*W7yMt_AZNLurmacU" /><figcaption>Photo by <a href="https://unsplash.com/@arianzesan?utm_source=medium&amp;utm_medium=referral">Zesan H.</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p>En mi <a href="https://medium.com/@fmoralcaballero/predicting-the-winner-of-copa-america-2024-with-data-science-85bac848a2b7">publicación anterior</a>, simulé toda la <a href="https://es.wikipedia.org/wiki/Copa_Am%C3%A9rica_2024">Copa América 2024</a> utilizando el <a href="https://es.wikipedia.org/wiki/Clasificaci%C3%B3n_Elo_del_f%C3%BAtbol_mundial">sistema de clasificación Elo</a> para estimar el nivel de las selecciones nacionales, pronosticando que Argentina ganaría el torneo. También mencioné que sería mejor simular la fase de eliminación directa justo después de la fase de grupos, ya que el puntaje Elo reflejaría de manera más precisa el nivel de las selecciones nacionales para ese entonces.</p><p>Ahora que la fase de grupos de la Copa América 2024 ha terminado y la fase de eliminación directa comienza hoy (4 de julio de 2024) con Argentina enfrentándose a Ecuador, es el momento perfecto para:</p><ul><li>Evaluar cómo se desempeñó mi simulación original para la fase de grupos.</li><li>Ejecutar una simulación actualizada para la fase de eliminación directa.</li><li>Hacer la predicción final de quién será el campeón de la Copa América 2024.</li></ul><h3>¿Cómo se desempeñó mi simulación de la fase de grupos?</h3><p>Aquí están los resultados de la simulación:</p><pre>| Grupo | Selección      | Media de puntos| Intervalo de confianza del 99% | <br>|-------|----------------|----------------|--------------------------------|<br>|-------|----------------|----------------|--------------------------------|<br>|   A   | Argentina      |      6.76      |          6.52 - 7.05           |<br>|   A   | Chile          |      3.55      |          3.11 - 3.96           |<br>|   A   | Perú           |      3.05      |          2.74 - 3.53           |<br>|   A   | Canadá         |      2.65      |          2.27 - 3.03           |<br>|-------|----------------|----------------|--------------------------------|<br>|   B   | Ecuador        |      5.75      |          5.24 - 6.12           |<br>|   B   | México         |      4.59      |          4.06 - 4.98           |<br>|   B   | Venezuela      |      3.38      |          2.99 - 3.92           |<br>|   B   | Jamaica        |      2.32      |          1.92 - 2.70           |<br>|-------|----------------|----------------|--------------------------------|<br>|   C   | Uruguay        |      6.71      |          6.29 - 7.14           |<br>|   C   | Estados Unidos |      4.71      |          4.31 - 5.30           |<br>|   C   | Panamá         |      2.88      |          2.48 - 3.32           |<br>|   C   | Bolivia        |      1.83      |          1.42 - 2.18           |<br>|-------|----------------|----------------|--------------------------------|<br>|   D   | Colombia       |      6.69      |          6.34 - 7.20           |<br>|   D   | Brasil         |      5.38      |          5.06 - 5.72           |<br>|   D   | Paraguay       |      2.68      |          2.33 - 3.06           |<br>|   D   | Costa Rica     |      1.45      |          1.23 - 1.77           |</pre><p>La tabla anterior muestra los equipos ordenados por la media aritmética de puntos que obtuvieron en 100 rondas de simulación (cada ronda consistiendo de 100 simulaciones). También incluye el intervalo de confianza del 99% para estos puntos, lo que indica la incertidumbre. Utilicé estos intervalos de confianza para determinar si podía predecir con confianza si un equipo terminaría 1°, 2°, 3° o 4° en su grupo. Específicamente, si los intervalos de confianza de los puntos simulados de dos equipos se superponían, no haría una predicción entre ellos.</p><p>Esto es lo que mencioné respecto a estos resultados en mi publicación anterior:</p><blockquote>En el Grupo A, Argentina debería quedar primero de grupo fácilmente. Sin embargo, aunque Chile tiene una ventaja clara sobre Perú, no es definitiva, ya que los intervalos de confianza entre los dos se superponen. Canadá definitivamente debería terminar en último lugar.</blockquote><blockquote>En el Grupo B, definitivamente debería ser: Ecuador, México, Venezuela y Jamaica. No hay superposición en los intervalos de confianza, y si observamos el nivel de los equipos, está claro que Ecuador encabeza el grupo. Aunque diría que este es el grupo más débil… el puntaje Elo promedio (que es una forma de estimar el nivel) de este grupo es el más bajo de todos los grupos.</blockquote><blockquote>En el Grupo C, definitivamente debería ser: Uruguay, Estados Unidos, Panamá y Bolivia. Panamá podría, en el mejor de los casos obtener una victoria contra Bolivia, tal como en la Copa América 2016 (cuando jugó contra los finalistas Argentina y Chile).</blockquote><blockquote>En el Grupo D, definitivamente debería ser: Colombia, Brasil, Paraguay, Costa Rica.</blockquote><p>Y aquí están los resultados reales de la fase de grupos (lo que de verdad pasó):</p><pre>| Grupo | Selección      | Puntos | <br>|-------|----------------|--------|<br>|-------|----------------|--------|<br>|   A   | Argentina      |    9   |<br>|   A   | Canadá         |    4   |<br>|   A   | Chile          |    2   |<br>|   A   | Perú           |    1   |<br>|-------|----------------|--------|<br>|   B   | Venezuela      |    9   |<br>|   B   | Ecuador        |    4   |<br>|   B   | México         |    4   |<br>|   B   | Jamaica        |    0   |<br>|-------|----------------|--------|<br>|   C   | Uruguay        |    9   |<br>|   C   | Panamá         |    6   |<br>|   C   | Estados Unidos |    3   |<br>|   C   | Bolivia        |    0   |<br>|-------|----------------|--------|<br>|   D   | Colombia       |    7   |<br>|   D   | Brasil         |    5   |<br>|   D   | Costa Rica     |    3   |<br>|   D   | Paraguay       |    0   |</pre><p>Hay varias maneras de evaluar estos resultados, algunas más favorables a la simulación que otras. Aquí hay tres evaluaciones diferentes que puedes elegir:</p><p><strong>Evaluación 1: De aquellas selecciones que la simulaci</strong>ó<strong>n arrojó que definitivamente pasar</strong>í<strong>an a la siguiente ronda, ¿cu</strong>á<strong>les realmente avanzaron?</strong></p><p>La simulación pronosticó con certeza:</p><ul><li>Grupo A: Argentina (CIERTO)</li><li>Grupo B: Ecuador (CIERTO), México (FALSO)</li><li>Grupo C: Uruguay (CIERTO), Estados Unidos (FALSO)</li><li>Grupo D: Colombia (CIERTO), Brasil (CIERTO)</li></ul><p>Esto resulta en 5 de 7 selecciones que fueron pronosticadas correctamente, aproximadamente un 71.4% de acierto. También jugué a lo seguro con el Grupo A y no hice una predicción sobre cual selección terminaría en segundo lugar.</p><p><strong>Evaluación 2: De aquellas selecciones cuyas posiciones en el grupo fueron pronosticadas con certeza, ¿cu</strong>á<strong>les realmente se ubicaron así?</strong></p><p>La simulación predijo con certeza:</p><ul><li>Grupo A: 1. Argentina (CIERTO)</li><li>Grupo B: 1. Ecuador (FALSO), 2. México (FALSO), 3. Venezuela (FALSO), 4. Jamaica (FALSO)</li><li>Grupo C: 1. Uruguay (CIERTO), 2. Estados Unidos (FALSO), 3. Panamá (FALSO), 4. Bolivia (CIERTO)</li><li>Grupo D: 1. Colombia (CIERTO), 2. Brasil (CIERTO), 3. Paraguay (FALSO), 4. Costa Rica (FALSO)</li></ul><p>Esto da como resultado que 5 de 13 equipos fueron pronosticados correctamente, aproximadamente un 38.5% de acierto. Añadiendo que predije incorrectamente que Canadá terminaría último, la precisión baja a 5 de 14, o 35.7%.</p><p>Esta evaluación es severa, ya que una predicción incorrecta automáticamente acarrea otra que también es incorrecta. La siguiente evaluación es más indulgente en ese aspecto.</p><p><strong>Evaluación 3: ¿Qué posiciones relativas de los equipos se predijeron correctamente?</strong></p><p>Esta evaluación observa las ubicaciones individuales de los equipos dentro de sus grupos:</p><ul><li>Grupo A: Argentina ubicándose por encima de las otras tres selecciones (CIERTO, CIERTO, CIERTO)</li><li>Grupo A: Chile ubicándose por encima de Canadá (FALSO)</li><li>Grupo B: Ecuador ubicándose por encima de las otras tres selecciones (CIERTO, CIERTO, CIERTO)</li><li>Grupo B: México ubicándose por encima de Venezuela y Jamaica (FALSO, CIERTO)</li><li>Grupo B: Venezuela ubicándose por encima de Jamaica (CIERTO)</li><li>Grupo C: Uruguay ubicándose por encima de las otras tres selecciones (CIERTO, CIERTO, CIERTO)</li><li>Grupo C: Estados Unidos ubicándose por encima de Panamá y Bolivia (FALSO, CIERTO)</li><li>Grupo C: Panamá ubicándose por encima de Bolivia (CIERTO)</li><li>Grupo D: Colombia ubicándose por encima de las otras tres selecciones (CIERTO, CIERTO, CIERTO)</li><li>Grupo D: Brasil ubicándose por encima de Paraguay y Costa Rica (CIERTO, CIERTO)</li><li>Grupo D: Paraguay cubicándose por encima de Costa Rica (FALSO)</li></ul><p>Sumando todas las predicciones correctas e incorrectas, tenemos 17 predicciones correctas de 22 hechas con certeza, aproximadamente un 77.3% de acierto.</p><p><strong>¿Que predice la simulaci</strong>ó<strong>n sobre la fase de eliminación directa?</strong></p><p>La diferencia clave entre simular una fase de grupos y una fase de eliminación directa es que en una fase de grupos sabemos todos los partidos que ocurrirán en dicha fase. En contraste, en una fase de eliminación directa solamente conocemos la primera ronda de partidos (en este caso, los cuartos de final).</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*eKVoO9e12mu-LDwvvLB2kQ.png" /><figcaption>La llave de la Copa América 2024</figcaption></figure><p>Para abordar esto, simulé cada uno de los partidos de la ronda de eliminacion directa y repetí la simulación 10,000 veces para poder aplicar estadística.</p><p>Lo hice de la siguiente forma.</p><p><strong>Preparando el ambiente de trabajo</strong></p><p>Primero, necesitamos importar las librerías necesarias y configurar las condiciones iniciales para nuestra simulación.</p><pre>import numpy as np<br>import pandas as pd<br>import csv<br>from tqdm import tqdm<br>from joblib import Parallel, delayed<br>from src.copa_america_simulator import *</pre><p>También necesitamos preparar algunos datos. Específicamente, necesitamos una lista de las selecciones que participarán en la fase de eliminación directa de la Copa América 2024 junto con sus puntajes Elo al término de la fase de grupos. Preparé un archivo CSV con esta información.</p><pre>| Selección | Puntaje Elo |<br>|-----------|-------------|<br>| Argentina |     2144    |<br>| Colombia  |     2030    |<br>| Uruguay   |     2027    |<br>| Brasil    |     2021    |<br>| Ecuador   |     1853    |<br>| Venezuela |     1826    |<br>| Panamá    |     1747    |<br>| Canadá    |     1741    |</pre><p>Además, creé otro archivo CSV con los partidos de la fase de eliminación directa.</p><pre>| Patido |   Local   | Visitante | Avanza | Al partido | Penaltis? |    Etapa     |<br>|--------|-----------|-----------|--------|------------|-----------|--------------|      <br>|   0    | Argentina | Ecuador   |        |     4      |           |   cuartos    |<br>|   1    | Venezuela | Canadá    |        |     4      |           |   cuartos    |<br>|   2    | Uruguay   | Brasil    |        |     5      |           |   cuartos    |<br>|   3    | Colombia  | Panamá    |        |     5      |           |   cuartos    |<br>|   4    |           |           |        |     6      |           |    semis     |<br>|   5    |           |           |        |     6      |           |    semis     |<br>|   6    |           |           |        |     7      |           |    final     |<br>|   7    |           |           |        |     7      |           | tercer lugar |</pre><p><strong>Scripts en Python</strong></p><p>Primero, definí una función para simular un partido de la fase de eliminación directa. Esta función lee un partido cualuiera y genera el resultado en un formato consistente con los archivos CSV de la fase de eliminación directa mencionados anteriormente.</p><pre>def simulate_playoff_game(game, ternary=True):<br>    &quot;&quot;&quot;<br>    Simulates a single game in the knockout stage<br>    &quot;&quot;&quot;<br><br>    import numpy as np<br><br>    home = game[&quot;elo_prob_home&quot;]<br>    away = 1 - game[&quot;elo_prob_home&quot;]<br>    tie = 0<br><br>    # Simulating game proper<br>    wildcard = random.uniform(0, 1)<br><br>    # Concoction to go from binary probabilities to ternary<br>    # 50-50% should translate into 1/3, 1/3, 1/3 (even split of probability space)<br>    # With increasing lopsidedness (e.g. 75-25%), the stronger team should see increased win probability,<br>    # and the weaker team should see decreased win probability. And in terms of ties, that also should decrease<br>    # as lopsidedness increases, but I assume that at a lower rate than weaker team win probability.<br>    if ternary:<br>        if home &gt; 0 and home &lt; 1:<br>            home_odds = home / away<br>            tie_odds = 1<br>            away_odds = 1 - abs(home - 0.5) * 2<br><br>            home_odds1 = (home / away) / min(away_odds, tie_odds, home_odds)<br>            tie_odds1 = 1 / min(away_odds, tie_odds, home_odds)<br>            away_odds1 = (1 - abs(home - 0.5) * 2) / min(away_odds, tie_odds, home_odds)<br><br>            home = home_odds1 / (home_odds1 + tie_odds1 + away_odds1)<br>            tie = tie_odds1 / (home_odds1 + tie_odds1 + away_odds1)<br>            away = away_odds1 / (home_odds1 + tie_odds1 + away_odds1)<br><br>        elif home == 0:<br>            tie = 0<br>            away = 1<br><br>        elif home == 1:<br>            tie = 0<br>            away = 0<br><br>        else:<br>            raise ValueError(&quot;Probabilities must be floats between 0 and 1, inclusive&quot;)<br>    else:<br>        pass<br><br>    if wildcard &gt;= 0 and wildcard &lt; away:<br>        return game[&quot;away_team&quot;], game[&quot;home_team&quot;], 0, False<br><br>    if wildcard &gt;= away and wildcard &lt; away + tie and ternary:<br>        # Simulating outcome of a penalty shootout. I assume it is a coin-toss. An advancing team is needed.<br>        teams = [game[&quot;away_team&quot;], game[&quot;home_team&quot;]]<br>        advances = np.random.choice(teams)<br>        teams.remove(advances)<br>        return advances, teams[0], 0.5, True<br><br>    if wildcard &gt;= away + tie and wildcard &lt;= 1:<br>        return game[&quot;home_team&quot;], game[&quot;away_team&quot;], 1, False</pre><p>Luego, escribí una función para simular una ronda de eliminación directa completa.</p><pre>def simulate_playoffs(games, teams, ternary=True):<br>    &quot;&quot;&quot;<br>    Simulates the entire knockout stage<br>    &quot;&quot;&quot;<br><br>    for game in games:<br>        team1, team2 = teams[game[&quot;home_team&quot;]], teams[game[&quot;away_team&quot;]]<br><br>        # Home field advantage is B.S. in modern soccer<br>        elo_diff = team1[&quot;rating&quot;] - team2[&quot;rating&quot;]<br><br>        # This is the most important piece<br>        game[&quot;elo_prob_home&quot;] = 1.0 / (math.pow(10.0, (-elo_diff / 400.0)) + 1.0)<br><br>        # If game was played, maintain team Elo ratings<br>        if game[&quot;advances&quot;] == &quot;&quot; or game[&quot;loses&quot;] == &quot;&quot;:<br><br>            game[&quot;advances&quot;], game[&quot;loses&quot;], game[&quot;result_home&quot;], game[&quot;penalties&quot;] = (<br>                simulate_playoff_game(game, ternary)<br>            )<br><br>            # Elo shift based on K<br>            shift = 50.0 * (game[&quot;result_home&quot;] - game[&quot;elo_prob_home&quot;])<br><br>            # Apply shift<br>            team1[&quot;rating&quot;] += shift<br>            team2[&quot;rating&quot;] -= shift<br><br>        # This is to populate quarterfinals and the such depending on previous rounds&#39; results<br>        next_stage = int(game[&quot;to_match&quot;])<br><br>        if next_stage &lt; 6:<br><br>            if games[next_stage][&quot;home_team&quot;] == &quot;&quot;:<br>                games[next_stage][&quot;home_team&quot;] = game[&quot;advances&quot;]<br>            else:<br>                games[next_stage][&quot;away_team&quot;] = game[&quot;advances&quot;]<br><br>        elif next_stage == 6:<br>            if games[next_stage][&quot;home_team&quot;] == &quot;&quot;:<br>                games[next_stage][&quot;home_team&quot;] = game[&quot;advances&quot;]<br>            else:<br>                games[next_stage][&quot;away_team&quot;] = game[&quot;advances&quot;]<br><br>            if games[next_stage + 1][&quot;home_team&quot;] == &quot;&quot;:<br>                games[next_stage + 1][&quot;home_team&quot;] = game[&quot;loses&quot;]<br>            else:<br>                games[next_stage + 1][&quot;away_team&quot;] = game[&quot;loses&quot;]<br><br>        else:<br>            pass</pre><p>Finalmente, repetí la simulación 10,000 veces:</p><pre>n = 10000<br>playoff_results_teams = []<br>playoff_results_stage = []<br><br>for i in tqdm(range(n)):<br>    overall_result_teams = dict()<br>    overall_result_stage = dict()<br>    games = read_games(&quot;data/playoff_matches1.csv&quot;)<br>    teams = {}<br>    <br>    for row in [<br>        item for item in csv.DictReader(open(&quot;data/playoff_roster1.csv&quot;))]:<br>        teams[row[&#39;team&#39;]] = {<br>            &#39;name&#39;: row[&#39;team&#39;],<br>            &#39;rating&#39;: float(row[&#39;rating&#39;])<br>            }<br>    <br>    simulate_playoffs(games, teams, ternary=True)<br>    <br>    playoff_pd = pd.DataFrame(games)<br>    <br>    # This is for collecting results of simulations per team<br>    for key in teams.keys():<br>        overall_result_teams[key] = collect_playoff_results(<br>            key,<br>            playoff_pd<br>            )<br>    playoff_results_teams.append(overall_result_teams)<br>    <br>    # Now, collecting results from stage-perspective<br>    overall_result_stage[&#39;whole_bracket&#39;] = playoff_pd[&#39;advances&#39;].to_list()<br>    overall_result_stage[&#39;Semifinals&#39;] = playoff_pd.loc[playoff_pd[&#39;stage&#39;] == &#39;quarterfinals&#39;, &#39;advances&#39;].to_list()<br>    overall_result_stage[&#39;Final&#39;] = playoff_pd.loc[playoff_pd[&#39;stage&#39;] == &#39;semifinals&#39;, &#39;advances&#39;].to_list()<br>    overall_result_stage[&#39;third_place_match&#39;] = playoff_pd.loc[playoff_pd[&#39;stage&#39;] == &#39;semifinals&#39;, &#39;loses&#39;].to_list()<br>    overall_result_stage[&#39;fourth_place&#39;] = playoff_pd.loc[playoff_pd[&#39;stage&#39;] == &#39;third_place&#39;, &#39;loses&#39;].to_list()[0]<br>    overall_result_stage[&#39;third_place&#39;] = playoff_pd.loc[playoff_pd[&#39;stage&#39;] == &#39;third_place&#39;, &#39;advances&#39;].to_list()[0]<br>    overall_result_stage[&#39;second_place&#39;] = playoff_pd.loc[playoff_pd[&#39;stage&#39;] == &#39;final&#39;, &#39;loses&#39;].to_list()[0]<br>    overall_result_stage[&#39;Champion&#39;] = playoff_pd.loc[playoff_pd[&#39;stage&#39;] == &#39;final&#39;, &#39;advances&#39;].to_list()[0]<br>    overall_result_stage[&#39;match4&#39;] = list(playoff_pd.loc[4, [&#39;home_team&#39;, &#39;away_team&#39;]])<br>    overall_result_stage[&#39;match5&#39;] = list(playoff_pd.loc[5, [&#39;home_team&#39;, &#39;away_team&#39;]])<br>    <br>    playoff_results_stage.append(overall_result_stage)</pre><p>Recopilé los resultados de estas simulaciones en playoff_results_teamsy playoff_results_stage. Para esta publicación, estamos más interesados en los datos de playoff_results_stage.</p><p><strong>¿Y los resultados?</strong></p><p>Veamos las cosas partido por partido.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*eKVoO9e12mu-LDwvvLB2kQ.png" /></figure><p>Tenemos a Argentina vs. Ecuador y Venezuela vs. Canadá:</p><pre># Este es un partido de semifinal<br>results_stage[&#39;match4&#39;].value_counts()</pre><pre>[Argentina, Venezuela]   5489<br>[Argentina, Canadá]      3316<br>[Ecuador, Venezuela]      737<br>[Ecuador, Canadá]         458</pre><p>La distribución de los posibles enfrentamientos para el primer partido de semifinales muestra que el enfrentamiento más probable es Argentina vs. Venezuela. Sin embargo, vamos a indagar un poco más:</p><ul><li>Argentina avanza a las semifinales en 8,816 de 10,000 simulaciones. Personalmente, apostaría a que Argentina avanza a las semifinales.</li><li>Venezuela avanza a las semifinales en 6,226 de 10,000 simulaciones. Esta predicción es mucho más difícil.</li></ul><p>Me arriesgaré y pronosticaré que esta semifinal será Argentina vs. Venezuela.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*t6cF6GHnIeNYRT_IEUgZNg.png" /></figure><p>A continuación, tenemos a Uruguay vs. Brasil y Colombia vs. Panamá:</p><pre># Este es un partido de semifinal<br>results_stage[&#39;match5&#39;].value_counts()</pre><pre>[Uruguay, Colombia]    4422<br>[Brasil, Colombia]     4288<br>[Brasil, Panamá]        659<br>[Uruguay, Panamá]       631</pre><p>Con Colombia avanzando en 8,710 de 10,000 simulaciones, podemos estar seguros de que Colombia llegará a las semifinales.</p><p>En cuanto a Uruguay vs. Brasil… 🔥 Este partido ni siquiera debería ser pronosticado, debe ser disfrutado. La historia entre estos dos países, tanto dentro como fuera de la cancha, hace de este EL partido del torneo. 🔥</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Jm2CnX7UtY95gCfPaTlkEg.png" /></figure><p><strong>¿Cuál es el partido de la final más probable?</strong></p><p>Ahora que me he acobardado y he evitado predecir el partido entre Uruguay y Brasil, respondamos una pregunta más fácil:</p><pre>results_stage[&#39;Final&#39;].value_counts()</pre><pre>[Argentina, Colombia]    3427<br>[Argentina, Uruguay]     2276<br>[Argentina, Brasil]      2231<br>[Venezuela, Colombia]     368<br>...</pre><p>Si tuviera que apostar, apostaría a que la final se jugará entre Argentina y Colombia. El problema es que las otras dos posibilidades provienen del partido entre Uruguay y Brasil, y juntas, son más probables que el enfrentamiento entre Argentina y Colombia.</p><p>Lo único que puedo decir con confianza es que Argentina es el finalista más probable (8,072 de 10,000 simulaciones tienen a Argentina como finalista).</p><p>Además…</p><h3><strong>¿Quién se coronar</strong>á<strong> campeón?</strong></h3><pre>results_stage[&#39;Champion&#39;].value_counts()</pre><pre>Argentina       5423<br>Colombia        1570<br>Uruguay         1053<br>Brasil           999<br>Venezuela        441<br>Ecuador          332<br>Canadá           160<br>Panamá            22</pre><p>¿Quién más? 😉</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*d81-7yb93HSc8-UJ" /><figcaption>Photo by <a href="https://unsplash.com/@disfruta_cafe?utm_source=medium&amp;utm_medium=referral">Diego Castañeda</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p>En serio, casi la mitad de las simulaciones muestran a Argentina ganando la Copa América 2024. Esto puede explicarse por el camino relativamente más fácil de Argentina hacia la final, ya que no enfrentará a ninguno de las otras 3 selecciones más fuertes hasta llegar a la final. Mientras tanto, estas 3 selecciones fuertes se enfrentarán entre sí antes de llegar a la final.</p><p>Así, las simulaciones muestran probabilidades diluidas para estas otras selecciones, mientras que el resto de las probabilidades se consolidan alrededor de Argentina.</p><p>Sin embargo, para todos los fanáticos del fútbol, esto no significará que Argentina será campeón fácilmente. Cada partido de la fase de eliminación directa debe jugarse, y un camino fácil a la final no garantiza la victoria en la final. Una vez que Argentina finalmente le toque enfrentarse a Colombia, Uruguay o Brasil, todo puede pasar.</p><h3>Conclusión</h3><p>El fútbol a menudo es llamado “El Deporte Más Hermoso del Mundo”, y cada vez que uso ciencia de datos y técnicas estadísticas para pronosticar partidos, me recuerda lo hermosamente impredecible que es. Aunque el fútbol no es completamente impredecible, la aleatoriedad en el fútbol lo hace altamente entretenido:</p><ul><li>Estadísticamente, esperaba que Ecuador venciera a Venezuela, pero la expulsión de Eder Valencia del partido debido a una jugada imprudente dejó a Ecuador con un jugador menos durante la mayor parte del partido. Esto aumentó la tasa de fatiga del equipo, llevándolos a la derrota.</li><li>Una situación similar ocurrió en el partido entre Estados Unidos y Panamá. Tim Weah perdió la compostura, golpeó a Roderick Miller y fue justamente expulsado. En consecuencia, Estados Unidos perdió un partido que necesitaba ganar para que las simulaciones y las expectativas estadísticas se alinearan con la realidad. Porque las estadísticas predijeron que Uruguay vencería a Estados Unidos, y ESO sí se convirtió en realidad.</li><li>¿Y qué hay de esos partidos donde un equipo que hace bastantes disparos a gol (pero sin anotar) pierde ante un equipo que solo hace un buen disparo (y anota)? Nuestro deseo innato de justicia se desencadena en tales situaciones, especialmente si apoyas a uno de los dos equipos.</li></ul><p>¡No dudes en opinar y comentar a qué equipo apoyas en la Copa América 2024! Recuerda que también puedes explorar esta simulación clonando mi repositorio en <a href="https://github.com/morales-felix/Copa-America-2024-simulation">GitHub</a>.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=169163756c35" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Predicting the Winner of Copa America 2024 with Data Science — Part 2]]></title>
            <link>https://medium.com/@fmoralcaballero/predicting-the-winner-of-copa-america-2024-with-data-science-part-2-b0be0b132f30?source=rss-b9f12041089a------2</link>
            <guid isPermaLink="false">https://medium.com/p/b0be0b132f30</guid>
            <category><![CDATA[soccer]]></category>
            <category><![CDATA[copa-america]]></category>
            <category><![CDATA[soccer-analytics]]></category>
            <category><![CDATA[data-science]]></category>
            <category><![CDATA[elo-rating]]></category>
            <dc:creator><![CDATA[Felix Morales]]></dc:creator>
            <pubDate>Thu, 04 Jul 2024 22:14:53 GMT</pubDate>
            <atom:updated>2024-07-05T01:46:37.287Z</atom:updated>
            <content:encoded><![CDATA[<h3>Predicting the Winner of Copa America 2024 with Data Science — Part 2</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*hLx_Q9IhnAHhPidX" /><figcaption>Photo by <a href="https://unsplash.com/@arianzesan?utm_source=medium&amp;utm_medium=referral">Zesan H.</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><blockquote>¿Prefieres leer en español? Haz clic <a href="https://medium.com/@fmoralcaballero/predicci%C3%B3n-del-campe%C3%B3n-de-la-copa-am%C3%A9rica-2024-con-ciencia-de-datos-parte-2-169163756c35">aquí</a> para leer el artículo en español.</blockquote><p>In my <a href="https://medium.com/@fmoralcaballero/predicting-the-winner-of-copa-america-2024-with-data-science-85bac848a2b7">previous post</a>, I simulated the entire <a href="https://en.wikipedia.org/wiki/2024_Copa_Am%C3%A9rica">Copa America 2024</a> tournament using the <a href="https://en.wikipedia.org/wiki/World_Football_Elo_Ratings">Elo rating system</a> to measure team strength, predicting Argentina as the winner. I also mentioned that it would be better to simulate the knockout stage after the group stage since the Elo ratings would more accurately reflect the teams’ strengths by then.</p><p>Now that the Copa America 2024 group stage is over and the knockout stage begins today (July 4, 2024) with Argentina facing Ecuador, it’s the perfect time to:</p><ul><li>Evaluate how my original simulation performed for the group stage.</li><li>Run an updated simulation for the knockout stage.</li><li>Make the final call on who will be the Copa America 2024 champion!</li></ul><h3>How did my group-stage simulation perform?</h3><p>You be the judge! 😉</p><p>Here are the simulation results:</p><pre>| Group | Team          | Mean points | 99% confidence interval | <br>|-------|---------------|-------------|-------------------------|<br>|-------|---------------|-------------|-------------------------|<br>|   A   | Argentina     |    6.76     |       6.52 - 7.05       |<br>|   A   | Chile         |    3.55     |       3.11 - 3.96       |<br>|   A   | Peru          |    3.05     |       2.74 - 3.53       |<br>|   A   | Canada        |    2.65     |       2.27 - 3.03       |<br>|-------|---------------|-------------|-------------------------|<br>|   B   | Ecuador       |    5.75     |       5.24 - 6.12       |<br>|   B   | Mexico        |    4.59     |       4.06 - 4.98       |<br>|   B   | Venezuela     |    3.38     |       2.99 - 3.92       |<br>|   B   | Jamaica       |    2.32     |       1.92 - 2.70       |<br>|-------|---------------|-------------|-------------------------|<br>|   C   | Uruguay       |    6.71     |       6.29 - 7.14       |<br>|   C   | United States |    4.71     |       4.31 - 5.30       |<br>|   C   | Panama        |    2.88     |       2.48 - 3.32       |<br>|   C   | Bolivia       |    1.83     |       1.42 - 2.18       |<br>|-------|---------------|-------------|-------------------------|<br>|   D   | Colombia      |    6.69     |       6.34 - 7.20       |<br>|   D   | Brazil        |    5.38     |       5.06 - 5.72       |<br>|   D   | Paraguay      |    2.68     |       2.33 - 3.06       |<br>|   D   | Costa Rica    |    1.45     |       1.23 - 1.77       |</pre><p>The table above shows teams sorted by the average number of points they earned across 100 simulation rounds (each round consisting of 100 runs). It also includes the 99% confidence interval for these points to indicate uncertainty. I used these confidence intervals to determine whether I could confidently predict if a team would finish 1st, 2nd, 3rd, or 4th in their group. Specifically, if the confidence intervals of two teams’ simulated points overlapped, I would not make a prediction between them.</p><p>Here is what I stated regarding these results in my previous post:</p><blockquote>- Group A should see Argentina easily top the group. However, while Chile has a clear edge over Peru, it’s not definitive since the confidence intervals between the two overlap. Canada should definitely end up in last place.</blockquote><blockquote>- Group B should definitely be: Ecuador, Mexico, Venezuela and Jamaica. No overlap in confidence intervals, and if we look at their team strengths, it’s clear the Ecuador tops the group. Although I would say this is the sleeper group… lower team strength of the tournament overall.</blockquote><blockquote>- Group C should definitely be: Uruguay, United States, Panama, and Bolivia. Panama might at best get a win against Bolivia, just like the 2016 Copa America (when it drew against eventual finalists Argentina and Chile).</blockquote><blockquote>- Group D should definitely be: Colombia, Brazil, Paraguay, Costa Rica.</blockquote><p>And here are the actual group stage results:</p><pre>| Group | Team          | Points | <br>|-------|---------------|--------|<br>|-------|---------------|--------|<br>|   A   | Argentina     |    9   |<br>|   A   | Canada        |    4   |<br>|   A   | Chile         |    2   |<br>|   A   | Peru          |    1   |<br>|-------|---------------|--------|<br>|   B   | Venezuela     |    9   |<br>|   B   | Ecuador       |    4   |<br>|   B   | Mexico        |    4   |<br>|   B   | Jamaica       |    0   |<br>|-------|---------------|--------|<br>|   C   | Uruguay       |    9   |<br>|   C   | Panama        |    6   |<br>|   C   | United States |    3   |<br>|   C   | Bolivia       |    0   |<br>|-------|---------------|--------|<br>|   D   | Colombia      |    7   |<br>|   D   | Brazil        |    5   |<br>|   D   | Costa Rica    |    3   |<br>|   D   | Paraguay      |    0   |</pre><p>There are several ways to evaluate these results, some more favorable to the simulation than others. Here are three different evaluations:</p><p><strong>Evaluation 1: Which teams that were definitely predicted to advance to the knockout stage actually advanced?</strong></p><p>The simulation predicted with certainty:</p><ul><li><strong>Group A</strong>: Argentina (TRUE)</li><li><strong>Group B</strong>: Ecuador (TRUE), Mexico (FALSE)</li><li><strong>Group C</strong>: Uruguay (TRUE), United States (FALSE)</li><li><strong>Group D</strong>: Colombia (TRUE), Brazil (TRUE)</li></ul><p>This results in 5 out of 7 teams called correctly, approximately 71.4% correct. I also played it safe with Group A and did not call the second place.</p><p><strong>Evaluation 2: Which teams that were definitely predicted to place in their respective positions actually placed as such?</strong></p><p>The simulation predicted with certainty:</p><ul><li><strong>Group A</strong>: 1. Argentina (TRUE)</li><li><strong>Group B</strong>: 1. Ecuador (FALSE), 2. Mexico (FALSE), 3. Venezuela (FALSE), 4. Jamaica (FALSE)</li><li><strong>Group C</strong>: 1. Uruguay (TRUE), 2. United States (FALSE), 3. Panama (FALSE), 4. Bolivia (TRUE)</li><li><strong>Group D</strong>: 1. Colombia (TRUE), 2. Brazil (TRUE), 3. Paraguay (FALSE), 4. Costa Rica (FALSE)</li></ul><p>This results in 5 out of 13 teams called correctly, approximately 38.5% correct. Adding that I incorrectly predicted Canada would finish last, the accuracy drops to 5 out of 14, or 35.7%.</p><p>This evaluation is strict since one incorrect prediction affects others in the group. The next evaluation is more lenient.</p><p><strong>Evaluation 3: Which relative team positions were predicted correctly?</strong></p><p>This evaluation looks at individual team placements within their groups:</p><ul><li><strong>Group A</strong>: Argentina placing higher than everyone else (TRUE, TRUE, TRUE)</li><li><strong>Group A</strong>: Chile placing higher than Canada (FALSE)</li><li><strong>Group B</strong>: Ecuador placing higher than everyone else (TRUE, FALSE, TRUE)</li><li><strong>Group B</strong>: Mexico placing higher than Venezuela and Jamaica (FALSE, TRUE)</li><li><strong>Group B</strong>: Venezuela placing higher than Jamaica (TRUE)</li><li><strong>Group C</strong>: Uruguay placing higher than everyone else (TRUE, TRUE, TRUE)</li><li><strong>Group C</strong>: United States placing higher than Panama and Bolivia (FALSE, TRUE)</li><li><strong>Group C</strong>: Panama placing higher than Bolivia (TRUE)</li><li><strong>Group D</strong>: Colombia placing higher than everyone else (TRUE, TRUE, TRUE)</li><li><strong>Group D</strong>: Brazil placing higher than Paraguay and Costa Rica (TRUE, TRUE)</li><li><strong>Group D</strong>: Paraguay placing higher than Costa Rica (FALSE)</li></ul><p>Adding up all the correct and incorrect predictions, we have 17 correct predictions out of 22 made with certainty, approximately 77.3%.</p><h3>How will the knockout stage play out?</h3><p>The key difference between simulating a group stage and a knockout stage is that in a group stage, we know all the matches that will occur. In contrast, in a knockout stage, we only know the first round of matches.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*7RrcWiconvLZq_eBQwKBfQ.png" /><figcaption>Copa America 2024 bracket</figcaption></figure><p>To tackle this, I simulated each knockout stage game and repeated this knockout stage simulation 10,000 times to gather comprehensive statistics.</p><p>Here’s how I did it.</p><h4>Setting Up the Environment</h4><p>First, we need to import the necessary libraries and set up the initial conditions for our simulation.</p><pre>import numpy as np<br>import pandas as pd<br>import csv<br>from tqdm import tqdm<br>from joblib import Parallel, delayed<br>from src.copa_america_simulator import *</pre><p>We also need to prepare some data. Specifically, we need a roster of the teams in the Copa America 2024 knockout stage along with their Elo ratings after the group stage. I prepared a CSV file with this information.</p><pre>| Team      | Elo rating |<br>|-----------|------------|<br>| Argentina |    2144    |<br>| Colombia  |    2030    |<br>| Uruguay   |    2027    |<br>| Brazil    |    2021    |<br>| Ecuador   |    1853    |<br>| Venezuela |    1826    |<br>| Panama    |    1747    |<br>| Canada    |    1741    |</pre><p>Additionally, I created another CSV file with the knockout stage matchups.</p><pre>| Match | Home Team | Away Team | Advances | To Match | Penalties? |     Stage     |<br>|-------|-----------|-----------|----------|----------|------------|---------------|      <br>|   0   | Argentina | Ecuador   |          |    4     |            | quarterfinals |<br>|   1   | Venezuela | Canada    |          |    4     |            | quarterfinals |<br>|   2   | Uruguay   | Brazil    |          |    5     |            | quarterfinals |<br>|   3   | Colombia  | Panama    |          |    5     |            | quarterfinals |<br>|   4   |           |           |          |    6     |            |  semifinals   |<br>|   5   |           |           |          |    6     |            |  semifinals   |<br>|   6   |           |           |          |    7     |            |     final     |<br>|   7   |           |           |          |    7     |            |  third place  |</pre><h4>Python scripts</h4><p>First, I defined a function to simulate a knockout-stage match. This function reads a given match and outputs the results in a format consistent with the knockout-stage CSV files mentioned above.</p><pre>def simulate_playoff_game(game, ternary=True):<br>    &quot;&quot;&quot;<br>    Simulates a single game in the knockout stage<br>    &quot;&quot;&quot;<br><br>    import numpy as np<br><br>    home = game[&quot;elo_prob_home&quot;]<br>    away = 1 - game[&quot;elo_prob_home&quot;]<br>    tie = 0<br><br>    # Simulating game proper<br>    wildcard = random.uniform(0, 1)<br><br>    # Concoction to go from binary probabilities to ternary<br>    # 50-50% should translate into 1/3, 1/3, 1/3 (even split of probability space)<br>    # With increasing lopsidedness (e.g. 75-25%), the stronger team should see increased win probability,<br>    # and the weaker team should see decreased win probability. And in terms of ties, that also should decrease<br>    # as lopsidedness increases, but I assume that at a lower rate than weaker team win probability.<br>    if ternary:<br>        if home &gt; 0 and home &lt; 1:<br>            home_odds = home / away<br>            tie_odds = 1<br>            away_odds = 1 - abs(home - 0.5) * 2<br><br>            home_odds1 = (home / away) / min(away_odds, tie_odds, home_odds)<br>            tie_odds1 = 1 / min(away_odds, tie_odds, home_odds)<br>            away_odds1 = (1 - abs(home - 0.5) * 2) / min(away_odds, tie_odds, home_odds)<br><br>            home = home_odds1 / (home_odds1 + tie_odds1 + away_odds1)<br>            tie = tie_odds1 / (home_odds1 + tie_odds1 + away_odds1)<br>            away = away_odds1 / (home_odds1 + tie_odds1 + away_odds1)<br><br>        elif home == 0:<br>            tie = 0<br>            away = 1<br><br>        elif home == 1:<br>            tie = 0<br>            away = 0<br><br>        else:<br>            raise ValueError(&quot;Probabilities must be floats between 0 and 1, inclusive&quot;)<br>    else:<br>        pass<br><br>    if wildcard &gt;= 0 and wildcard &lt; away:<br>        return game[&quot;away_team&quot;], game[&quot;home_team&quot;], 0, False<br><br>    if wildcard &gt;= away and wildcard &lt; away + tie and ternary:<br>        # Simulating outcome of a penalty shootout. I assume it is a coin-toss. An advancing team is needed.<br>        teams = [game[&quot;away_team&quot;], game[&quot;home_team&quot;]]<br>        advances = np.random.choice(teams)<br>        teams.remove(advances)<br>        return advances, teams[0], 0.5, True<br><br>    if wildcard &gt;= away + tie and wildcard &lt;= 1:<br>        return game[&quot;home_team&quot;], game[&quot;away_team&quot;], 1, False</pre><p>Next, I wrote a function to simulate the entire knockout round by iterating over every game.</p><pre>def simulate_playoffs(games, teams, ternary=True):<br>    &quot;&quot;&quot;<br>    Simulates the entire knockout stage<br>    &quot;&quot;&quot;<br><br>    for game in games:<br>        team1, team2 = teams[game[&quot;home_team&quot;]], teams[game[&quot;away_team&quot;]]<br><br>        # Home field advantage is B.S. in modern soccer<br>        elo_diff = team1[&quot;rating&quot;] - team2[&quot;rating&quot;]<br><br>        # This is the most important piece<br>        game[&quot;elo_prob_home&quot;] = 1.0 / (math.pow(10.0, (-elo_diff / 400.0)) + 1.0)<br><br>        # If game was played, maintain team Elo ratings<br>        if game[&quot;advances&quot;] == &quot;&quot; or game[&quot;loses&quot;] == &quot;&quot;:<br><br>            game[&quot;advances&quot;], game[&quot;loses&quot;], game[&quot;result_home&quot;], game[&quot;penalties&quot;] = (<br>                simulate_playoff_game(game, ternary)<br>            )<br><br>            # Elo shift based on K<br>            shift = 50.0 * (game[&quot;result_home&quot;] - game[&quot;elo_prob_home&quot;])<br><br>            # Apply shift<br>            team1[&quot;rating&quot;] += shift<br>            team2[&quot;rating&quot;] -= shift<br><br>        # This is to populate quarterfinals and the such depending on previous rounds&#39; results<br>        next_stage = int(game[&quot;to_match&quot;])<br><br>        if next_stage &lt; 6:<br><br>            if games[next_stage][&quot;home_team&quot;] == &quot;&quot;:<br>                games[next_stage][&quot;home_team&quot;] = game[&quot;advances&quot;]<br>            else:<br>                games[next_stage][&quot;away_team&quot;] = game[&quot;advances&quot;]<br><br>        elif next_stage == 6:<br>            if games[next_stage][&quot;home_team&quot;] == &quot;&quot;:<br>                games[next_stage][&quot;home_team&quot;] = game[&quot;advances&quot;]<br>            else:<br>                games[next_stage][&quot;away_team&quot;] = game[&quot;advances&quot;]<br><br>            if games[next_stage + 1][&quot;home_team&quot;] == &quot;&quot;:<br>                games[next_stage + 1][&quot;home_team&quot;] = game[&quot;loses&quot;]<br>            else:<br>                games[next_stage + 1][&quot;away_team&quot;] = game[&quot;loses&quot;]<br><br>        else:<br>            pass</pre><p>I then repeated this simulation 10,000 times:</p><pre>n = 10000<br>playoff_results_teams = []<br>playoff_results_stage = []<br><br>for i in tqdm(range(n)):<br>    overall_result_teams = dict()<br>    overall_result_stage = dict()<br>    games = read_games(&quot;data/playoff_matches1.csv&quot;)<br>    teams = {}<br>    <br>    for row in [<br>        item for item in csv.DictReader(open(&quot;data/playoff_roster1.csv&quot;))]:<br>        teams[row[&#39;team&#39;]] = {<br>            &#39;name&#39;: row[&#39;team&#39;],<br>            &#39;rating&#39;: float(row[&#39;rating&#39;])<br>            }<br>    <br>    simulate_playoffs(games, teams, ternary=True)<br>    <br>    playoff_pd = pd.DataFrame(games)<br>    <br>    # This is for collecting results of simulations per team<br>    for key in teams.keys():<br>        overall_result_teams[key] = collect_playoff_results(<br>            key,<br>            playoff_pd<br>            )<br>    playoff_results_teams.append(overall_result_teams)<br>    <br>    # Now, collecting results from stage-perspective<br>    overall_result_stage[&#39;whole_bracket&#39;] = playoff_pd[&#39;advances&#39;].to_list()<br>    overall_result_stage[&#39;Semifinals&#39;] = playoff_pd.loc[playoff_pd[&#39;stage&#39;] == &#39;quarterfinals&#39;, &#39;advances&#39;].to_list()<br>    overall_result_stage[&#39;Final&#39;] = playoff_pd.loc[playoff_pd[&#39;stage&#39;] == &#39;semifinals&#39;, &#39;advances&#39;].to_list()<br>    overall_result_stage[&#39;third_place_match&#39;] = playoff_pd.loc[playoff_pd[&#39;stage&#39;] == &#39;semifinals&#39;, &#39;loses&#39;].to_list()<br>    overall_result_stage[&#39;fourth_place&#39;] = playoff_pd.loc[playoff_pd[&#39;stage&#39;] == &#39;third_place&#39;, &#39;loses&#39;].to_list()[0]<br>    overall_result_stage[&#39;third_place&#39;] = playoff_pd.loc[playoff_pd[&#39;stage&#39;] == &#39;third_place&#39;, &#39;advances&#39;].to_list()[0]<br>    overall_result_stage[&#39;second_place&#39;] = playoff_pd.loc[playoff_pd[&#39;stage&#39;] == &#39;final&#39;, &#39;loses&#39;].to_list()[0]<br>    overall_result_stage[&#39;Champion&#39;] = playoff_pd.loc[playoff_pd[&#39;stage&#39;] == &#39;final&#39;, &#39;advances&#39;].to_list()[0]<br>    overall_result_stage[&#39;match4&#39;] = list(playoff_pd.loc[4, [&#39;home_team&#39;, &#39;away_team&#39;]])<br>    overall_result_stage[&#39;match5&#39;] = list(playoff_pd.loc[5, [&#39;home_team&#39;, &#39;away_team&#39;]])<br>    <br>    playoff_results_stage.append(overall_result_stage)</pre><p>I collected the results of these simulations in playoff_results_teams and playoff_results_stage. For this post, we are more interested in the data from playoff_results_stage.</p><p><strong>What do we get?</strong></p><p>Let’s unfold the results match by match.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*7RrcWiconvLZq_eBQwKBfQ.png" /></figure><p>We have Argentina vs. Ecuador and Venezuela vs. Canada:</p><pre># This is a semifinal match<br>results_stage[&#39;match4&#39;].value_counts()</pre><pre>[Argentina, Venezuela]   5489<br>[Argentina, Canada]      3316<br>[Ecuador, Venezuela]      737<br>[Ecuador, Canada]         458</pre><p>The distribution of possible semifinal matchups shows that the most likely matchup is Argentina vs. Venezuela. However, let’s break it down further:</p><ul><li>Argentina advances to the semifinals in 8,816 out of 10,000 simulations. I would personally bet on Argentina advancing to the semifinals.</li><li>Venezuela advances to the semifinals in 6,226 out of 10,000 simulations. This prediction is much tougher.</li></ul><p>I’ll go out on a limb and predict it will be Argentina vs. Venezuela.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*IJCWSS1WjcTxoiZt1tf1wg.png" /><figcaption>First semifinal</figcaption></figure><p>Next, we have Uruguay vs. Brazil and Colombia vs. Panama:</p><pre># This is a semifinal match<br>results_stage[&#39;match5&#39;].value_counts()</pre><pre>[Uruguay, Colombia]    4422<br>[Brazil, Colombia]     4288<br>[Brazil, Panama]        659<br>[Uruguay, Panama]       631</pre><p>With Colombia advancing in 8,710 out of 10,000 simulations, we can be confident that Colombia will make it to the semifinals.</p><p>As for Uruguay vs. Brazil… 🔥 This match shouldn’t even be predicted — it should be enjoyed. The history between these two countries, both on and off the soccer field, makes this THE match of the tournament. 🔥</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*6jJa6jSOugqzwsI4j0sG8Q.png" /></figure><p><strong>What’s the most likely final match?</strong></p><p>Now that I’ve chickened out of predicting the Uruguay vs. Brazil game, let’s answer an easier question:</p><pre>results_stage[&#39;Final&#39;].value_counts()</pre><pre>[Argentina, Colombia]    3427<br>[Argentina, Uruguay]     2276<br>[Argentina, Brazil]      2231<br>[Venezuela, Colombia]     368<br>...</pre><p>If I had to bet, I’d bet on the final being played between Argentina and Colombia. The problem is that the other two possibilities come from the Uruguay vs. Brazil game, and taken together, they are more likely than the Argentina vs. Colombia matchup.</p><p>All I can confidently say is that Argentina is the most likely finalist (8,072 out of 10,000 simulations as a finalist).</p><p>Also…</p><h3><strong>Who will be crowned champion?</strong></h3><pre>results_stage[&#39;Champion&#39;].value_counts()</pre><pre>Argentina       5423<br>Colombia        1570<br>Uruguay         1053<br>Brazil           999<br>Venezuela        441<br>Ecuador          332<br>Canada           160<br>Panama            22</pre><p>Who else? 😉</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*gJZ6VtzFY_86zZXP" /><figcaption>Photo by <a href="https://unsplash.com/@disfruta_cafe?utm_source=medium&amp;utm_medium=referral">Diego Castañeda</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p>In all seriousness, almost half of the simulations show Argentina winning the Copa America 2024. This can be explained by Argentina’s relatively easier path to the final, avoiding the top 3 strongest teams until then. Meanwhile, the other 3 strong contenders will face each other before the final.</p><p>Thus, the simulations show dispersed probabilities for the other teams, while consolidating around Argentina.</p><p>However, for all soccer enthusiasts, this doesn’t mean Argentina will easily win the trophy. Each knockout stage match must be played, and an easy path to the final won’t guarantee victory. Once Argentina faces either Colombia, Uruguay, or Brazil, all bets are off.</p><h3>Conclusion</h3><p>Soccer is often called “The Beautiful Game,” and every time I use data science and statistical techniques to forecast matches, I’m reminded of how beautifully unpredictable it is. While not entirely unpredictable, the randomness in soccer makes it highly entertaining:</p><ul><li>Ecuador was predicted to beat Venezuela, but Eder Valencia’s expulsion from the game due to a reckless play left Ecuador with one less player for most of the match. This increased the team’s fatigue rate, leading to their loss.</li><li>A similar situation occurred in the United States vs. Panama game. Tim Weah lost his cool, punched Roderick Miller, and was justifiably sent off. Consequently, the United States lost a match they needed to win for the simulations and statistical expectations to align with reality. Because statistics predicted Uruguay would beat the United States, and THAT became reality.</li><li>And what about those matches where a team that played brilliantly and took numerous great shots on goal (but didn’t score) loses to a team that only generated one good shot (and scored)? Our innate desire for fairness is triggered in such situations, especially if you support one of the teams.</li></ul><p>Feel free to share your thoughts and let me know which team you’re rooting for in Copa America 2024! Remember that you can also play around with this simulation by forking/cloning my <a href="https://github.com/morales-felix/Copa-America-2024-simulation">GitHub repo</a>.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=b0be0b132f30" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Predicting the Winner of Copa America 2024 with Data Science — Part 1]]></title>
            <link>https://medium.com/@fmoralcaballero/predicting-the-winner-of-copa-america-2024-with-data-science-85bac848a2b7?source=rss-b9f12041089a------2</link>
            <guid isPermaLink="false">https://medium.com/p/85bac848a2b7</guid>
            <category><![CDATA[sports]]></category>
            <category><![CDATA[simulation]]></category>
            <category><![CDATA[data-science]]></category>
            <category><![CDATA[elo-rating]]></category>
            <category><![CDATA[soccer]]></category>
            <dc:creator><![CDATA[Felix Morales]]></dc:creator>
            <pubDate>Sun, 23 Jun 2024 21:26:47 GMT</pubDate>
            <atom:updated>2024-07-04T21:37:31.698Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*h6LQKqzQ6LaU-fCQ" /><figcaption>Photo by <a href="https://unsplash.com/@viennachanges?utm_source=medium&amp;utm_medium=referral">Vienna Reyes</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p>The Copa America 2024 is underway in the United States, and yes, I am excited! This is the oldest still-running continental soccer (football, if you are that kind of person) competition in the world. And I am excited since my two national teams play in this tournament: My home country, Panama, and my favorite top national team, Argentina (which is the current champion).</p><p>But I am also a data scientist, and I can’t simply watch games without a little statistics chip in my shoulder! The excitement of simulating a tournament like Copa America 2024, using the Elo rating system, is something I couldn’t resist.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*b_AD8TdRF4a2-HUb" /><figcaption>Photo by <a href="https://unsplash.com/@roman_lazygeek?utm_source=medium&amp;utm_medium=referral">Roman Mager</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><h4>The Elo rating system?</h4><p>And yes, I said the Elo rating system. It was initially devised for chess, but has become a popular method for ranking teams in various sports, including soccer. To the point that FIFA actually uses a variant of this system for its own <a href="https://inside.fifa.com/fifa-world-ranking/men">rankings</a> (I personally believe the ranking at <a href="http://eloratings.net/">eloratings.net</a> is the gold standard for international soccer, not FIFA’s).</p><p>It works by calculating the relative strength of teams based on their game results. If you’d like to learn more about the Elo rating system, there’s plenty of material online to learn more. For an intro, read <a href="https://medium.com/purple-theory/what-is-elo-rating-c4eb7a9061e0">this blog post</a>, and for a soccer-specific intro, see <a href="https://eloratings.net/about">here</a> for international soccer and <a href="http://clubelo.com/">here</a> for European club soccer.</p><p>In this blog post, I’ll walk you through the Jupyter notebook I created to simulate the Copa America 2024 using the Elo rating system. This simulation aims to predict which team might emerge as the champion by running multiple iterations of the tournament and analyzing the results.</p><p>This simulation uses Elo ratings from eloratings.net to measure team strength and update it after each simulated game. The Elo implementation is based on <a href="https://github.com/morales-felix/nfl-elo-game">FiveThirtyEight’s NFL forecasting game</a>.</p><p>Do you simply want to dive into the code? Fork my GitHub repo <a href="https://github.com/morales-felix/Copa-America-2024-simulation">here</a>.</p><h4>Setting Up the Environment</h4><p>First, we need to import the necessary libraries and set up the initial conditions for our simulation:</p><pre>import numpy as np<br>import pandas as pd<br>import csv<br>from tqdm import tqdm<br>from joblib import Parallel, delayed<br>from src.copa_america_simulator import *</pre><p>We also need to set up some data. First, we need to define the roster of teams that will play this tournament, alongside with their Elo rating before the start of the tournament. In this case, I prepared a csv file with this information:</p><pre>| Group | Team          | Elo rating |<br>|-------|---------------|------------|<br>|-------|---------------|------------|<br>|  A    | Argentina     |    2144    |<br>|  A    | Peru          |    1744    |<br>|  A    | Chile         |    1725    |<br>|  A    | Canada        |    1721    |<br>|-------|---------------|------------|<br>|  B    | Ecuador       |    1876    |<br>|  B    | Mexico        |    1791    |<br>|  B    | Venezuela     |    1725    |<br>|  B    | Jamaica       |    1642    |<br>|-------|---------------|------------|<br>|  C    | Uruguay       |    1992    |<br>|  C    | United States |    1790    |<br>|  C    | Panama        |    1698    |<br>|  C    | Bolivia       |    1592    |<br>|-------|---------------|------------|<br>|  D    | Brazil        |    2028    |<br>|  D    | Colombia      |    2015    |<br>|  D    | Paraguay      |    1710    |<br>|  D    | Costa Rica    |    1620    |</pre><p>I will also define another csv file with the actual group matches:</p><pre>| Group | Date | Home Team      | Away Team      |<br>|-------|------|----------------|----------------|<br>| A     | 1    | Argentina      | Canada         |<br>| A     | 2    | Peru           | Chile          |<br>| B     | 3    | Mexico         | Jamaica        |<br>| B     | 4    | Ecuador        | Venezuela      |<br>| C     | 5    | United States  | Bolivia        |<br>| C     | 6    | Uruguay        | Panama         |<br>| D     | 7    | Brazil         | Costa Rica     |<br>| D     | 8    | Colombia       | Paraguay       |<br>| A     | 9    | Chile          | Argentina      |<br>| A     | 10   | Peru           | Canada         |<br>| B     | 11   | Venezuela      | Mexico         |<br>| B     | 12   | Ecuador        | Jamaica        |<br>| C     | 13   | Panama         | United States  |<br>| C     | 14   | Uruguay        | Bolivia        |<br>| D     | 15   | Paraguay       | Brazil         |<br>| D     | 16   | Colombia       | Costa Rica     |<br>| A     | 17   | Argentina      | Peru           |<br>| A     | 18   | Canada         | Chile          |<br>| B     | 19   | Mexico         | Ecuador        |<br>| B     | 20   | Jamaica        | Venezuela      |<br>| C     | 21   | United States  | Uruguay        |<br>| C     | 22   | Bolivia        | Panama         |<br>| D     | 23   | Brazil         | Colombia       |<br>| D     | 24   | Costa Rica     | Paraguay       |</pre><h4><strong>Simulation Function</strong></h4><p>I defined a function to simulate the group stage of the tournament. This function reads the team rosters and match schedules from CSV files and then uses the Elo ratings to simulate match outcomes.</p><pre>def run_group_stage_simulation(n, j):<br>    &quot;&quot;&quot;<br>    Run a simulation of the group stage of the Copa America<br>    &quot;&quot;&quot;<br>    <br>    teams_pd = pd.read_csv(&quot;data/roster.csv&quot;)<br>    <br>    for i in range(n):<br>        games = read_games(&quot;data/matches.csv&quot;)<br>        teams = {}<br>    <br>        for row in [<br>            item for item in csv.DictReader(open(&quot;data/roster.csv&quot;))<br>            ]:<br>            teams[row[&#39;team&#39;]] = {<br>                &#39;name&#39;: row[&#39;team&#39;],<br>                &#39;rating&#39;: float(row[&#39;rating&#39;]),<br>                &#39;points&#39;: 0<br>                }<br>    <br>        simulate_group_stage(<br>            games,<br>            teams,<br>            ternary=True<br>            )<br>    <br>        collector = []<br>        for key in teams.keys():<br>            collector.append(<br>                {&quot;team&quot;: key,<br>                 f&quot;simulation{i+1}&quot;: teams[key][&#39;points&#39;]}<br>            )<br><br>        temp = pd.DataFrame(collector)<br>        teams_pd = pd.merge(teams_pd, temp)<br>    <br>    sim_cols = [<br>        a for a in teams_pd.columns if &quot;simulation&quot; in a]<br>    teams_pd[<br>        f&quot;avg_pts_{j+1}&quot;<br>        ] = teams_pd[sim_cols].mean(axis=1)<br>    not_sim = [<br>        b for b in teams_pd.columns if &quot;simulation&quot; not in b]<br>    simulation_result = teams_pd[not_sim]<br>    <br>    return simulation_result</pre><p>However, the above function is mainly there to enable parallelization using the joblib package. In order words, this function is mostly there to enable multiple runs of the simulation at once. But the “simulation” is really done by the simulate_group_stage function:</p><pre>def simulate_group_stage(games, teams, ternary=True):<br>    &quot;&quot;&quot;<br>    Simulates the entire group stage<br>    &quot;&quot;&quot;<br><br>    for game in games:<br>        team1, team2 = teams[game[&quot;home_team&quot;]], teams[game[&quot;away_team&quot;]]<br><br>        # Home field advantage is BS<br>        elo_diff = team1[&quot;rating&quot;] - team2[&quot;rating&quot;]<br><br>        # This is the most important piece, where we set my_prob1 to our forecasted probability<br>        game[&quot;elo_prob_home&quot;] = 1.0 / (math.pow(10.0, (-elo_diff / 400.0)) + 1.0)<br><br>        # If game was played, maintain team Elo ratings<br>        if game[&quot;result_home&quot;] == &quot;&quot;:<br><br>            game[&quot;result_home&quot;] = simulate_group_stage_game(game, ternary)<br><br>            # Elo shift based on K<br>            shift = 50.0 * (game[&quot;result_home&quot;] - game[&quot;elo_prob_home&quot;])<br><br>            # Apply shift<br>            team1[&quot;rating&quot;] += shift<br>            team2[&quot;rating&quot;] -= shift<br><br>            # Apply points<br>            if game[&quot;result_home&quot;] == 0:<br>                team1[&quot;points&quot;] += 0<br>                team2[&quot;points&quot;] += 3<br>            elif game[&quot;result_home&quot;] == 0.5:<br>                team1[&quot;points&quot;] += 1<br>                team2[&quot;points&quot;] += 1<br>            else:<br>                team1[&quot;points&quot;] += 3<br>                team2[&quot;points&quot;] += 0</pre><p>And the simulate_group_stage function uses another function simulate each game, “cleverly” called simulate_group_stage_game</p><pre>def simulate_group_stage_game(game, ternary=True):<br>    &quot;&quot;&quot;<br>    Simulates a single game in the group stage<br>    &quot;&quot;&quot;<br><br>    home = game[&quot;elo_prob_home&quot;]<br>    away = 1 - game[&quot;elo_prob_home&quot;]<br>    tie = 0<br><br>    # Simulating game proper<br>    wildcard = random.uniform(0, 1)<br><br>    # Concoction to go from binary probabilities to ternary<br>    if ternary:<br>        if home &gt; 0 and home &lt; 1:<br>            home_odds = home / away<br>            tie_odds = 1<br>            away_odds = 1 - abs(home - 0.5) * 2<br><br>            home_odds1 = (home / away) / min(away_odds, tie_odds, home_odds)<br>            tie_odds1 = 1 / min(away_odds, tie_odds, home_odds)<br>            away_odds1 = (1 - abs(home - 0.5) * 2) / min(away_odds, tie_odds, home_odds)<br><br>            home = home_odds1 / (home_odds1 + tie_odds1 + away_odds1)<br>            tie = tie_odds1 / (home_odds1 + tie_odds1 + away_odds1)<br>            away = away_odds1 / (home_odds1 + tie_odds1 + away_odds1)<br><br>        elif home == 0:<br>            tie = 0<br>            away = 1<br><br>        elif home == 1:<br>            tie = 0<br>            away = 0<br><br>        else:<br>            raise ValueError(&quot;Probabilities must be floats between 0 and 1, inclusive&quot;)<br>    else:<br>        pass<br><br>    if wildcard &gt;= 0 and wildcard &lt; away:<br>        return 0<br><br>    if wildcard &gt;= away and wildcard &lt; away + tie and ternary:<br>        return 0.5<br><br>    if wildcard &gt;= away + tie and wildcard &lt;= 1:<br>        return 1</pre><p>Now, before we go any further, I’d like to make some notes on this Elo implementation:</p><ul><li>Per eloratings.net, the K constant is set to 50 as the Copa America is a continental competition.</li><li>Probabilities given by the Elo rating system are binary. As you can see in the code, I came up with a workaround to convert binary probabilities to ternary probabilities given that soccer admits three outcomes after a match (win, tie, lose).</li><li>I did not simulate score lines. Rather, I simply used probabilities to decide whether a team would win, tie, or lose. As such, I did not use the goal difference multiplier specified in eloratings.net.</li><li>I’ll be happy to talk about the workaround, but I wouldn’t take it as gospel. There might be ways to do this, but I did not research it. Wanted to have fun, not produce an academic-paper-worthy method, nor a sellable product.</li></ul><h4><strong>Running the Simulations</strong></h4><p>And then, the simulation is orchestrated by the following lines of code:</p><pre># Reads in the matches and teams as dictionaries and proceeds with that data type<br>n = 100 # How many simulations to run<br>m = 100 # How many simulation results to collect<br><br>roster_pd = Parallel(n_jobs=5)(<br>    delayed(run_group_stage_simulation)(<br>        n, j) for j in tqdm(range(m)))<br><br>for t in tqdm(range(m)):<br>    if t == 0:<br>        roster = pd.merge(<br>            roster_pd[t],<br>            roster_pd[t+1]<br>            )<br>    elif t &gt;= 2:<br>        roster = pd.merge(<br>            roster,<br>            roster_pd[t]<br>            )<br>    else:<br>        pass</pre><h4><strong>Group Stage Results</strong></h4><p>Let’s check out the results for the Copa America 2024!</p><pre>roster[not_sim].sort_values(<br>    by=[<br>        &#39;group&#39;,<br>        &#39;avg_sim_pts&#39;<br>        ],<br>    ascending=False<br>    )</pre><pre>| Group | Team          | Mean points | 99% confidence interval |<br>|-------|---------------|-------------|-------------------------|<br>|-------|---------------|-------------|-------------------------|<br>|   A   | Argentina     |    6.76     |       6.52 - 7.05       |<br>|   A   | Chile         |    3.55     |       3.11 - 3.96       |<br>|   A   | Peru          |    3.05     |       2.74 - 3.53       |<br>|   A   | Canada        |    2.65     |       2.27 - 3.03       |<br>|-------|---------------|-------------|-------------------------|<br>|   B   | Ecuador       |    5.75     |       5.24 - 6.12       |<br>|   B   | Mexico        |    4.59     |       4.06 - 4.98       |<br>|   B   | Venezuela     |    3.38     |       2.99 - 3.92       |<br>|   B   | Jamaica       |    2.32     |       1.92 - 2.70       |<br>|-------|---------------|-------------|-------------------------|<br>|   C   | Uruguay       |    6.71     |       6.29 - 7.14       |<br>|   C   | United States |    4.71     |       4.31 - 5.30       |<br>|   C   | Panama        |    2.88     |       2.48 - 3.32       |<br>|   C   | Bolivia       |    1.83     |       1.42 - 2.18       |<br>|-------|---------------|-------------|-------------------------|<br>|   D   | Colombia      |    6.69     |       6.34 - 7.20       |<br>|   D   | Brazil        |    5.38     |       5.06 - 5.72       |<br>|   D   | Paraguay      |    2.68     |       2.33 - 3.06       |<br>|   D   | Costa Rica    |    1.45     |       1.23 - 1.77       |</pre><p>You can see that:</p><p>- Group A should see Argentina easily top the group. However, while Chile has a clear edge over Peru, it’s not definitive since the confidence intervals between the two overlap. Canada should definitely end up in last place.</p><p>- Group B should definitely be: Ecuador, Mexico, Venezuela and Jamaica. No overlap in confidence intervals, and if we look at their team strengths, it’s clear the Ecuador tops the group. Although I would say this is the sleeper group… lower team strength of the tournament overall.</p><p>- Group C should definitely be: Uruguay, United States, Panama, and Bolivia. Panama might at best get a win against Bolivia, just like the 2016 Copa America (when it drew against eventual finalists Argentina and Chile).</p><p>- Group D should definitely be: Colombia, Brazil, Paraguay, Costa Rica.</p><p>(Honestly, this is a bit of a boring forecasting/prediction exercise. I guess the European Championship is more exciting…).</p><p>Now that we have decided which teams will make it to the playoffs, let’s simulate those and see who we predict to win the Copa America 2024!</p><h4><strong>Simulating knockout stage</strong></h4><p>The knockout stage is where it gets truly interesting. Using the results from the group stage simulations, I simulated the knockout rounds to predict the overall winner of the tournament.</p><pre>n = 10000<br>playoff_results_teams = []<br>playoff_results_stage = []<br><br>for i in tqdm(range(n)):<br>    overall_result_teams = dict()<br>    overall_result_stage = dict()<br>    games = read_games(&quot;data/playoff_matches.csv&quot;)<br>    teams = {}<br>    <br>    for row in [<br>        item for item in csv.DictReader(open(&quot;data/playoff_roster.csv&quot;))]:<br>        teams[row[&#39;team&#39;]] = {<br>            &#39;name&#39;: row[&#39;team&#39;],<br>            &#39;rating&#39;: float(row[&#39;rating&#39;])<br>            }<br>    <br>    simulate_playoffs(games, teams, ternary=True)<br>    <br>    playoff_pd = pd.DataFrame(games)<br>    <br>    # This is for collecting results of simulations per team<br>    for key in teams.keys():<br>        overall_result_teams[key] = collect_playoff_results(<br>            key,<br>            playoff_pd<br>            )<br>    playoff_results_teams.append(overall_result_teams)<br>    <br>    # Now, collecting results from stage-perspective<br>    overall_result_stage[&#39;whole_bracket&#39;] = playoff_pd[&#39;advances&#39;].to_list()<br>    overall_result_stage[&#39;Semifinals&#39;] = playoff_pd.loc[playoff_pd[&#39;stage&#39;] == &#39;quarterfinals&#39;, &#39;advances&#39;].to_list()<br>    overall_result_stage[&#39;Final&#39;] = playoff_pd.loc[playoff_pd[&#39;stage&#39;] == &#39;semifinals&#39;, &#39;advances&#39;].to_list()<br>    overall_result_stage[&#39;third_place_match&#39;] = playoff_pd.loc[playoff_pd[&#39;stage&#39;] == &#39;semifinals&#39;, &#39;loses&#39;].to_list()<br>    overall_result_stage[&#39;fourth_place&#39;] = playoff_pd.loc[playoff_pd[&#39;stage&#39;] == &#39;third_place&#39;, &#39;loses&#39;].to_list()[0]<br>    overall_result_stage[&#39;third_place&#39;] = playoff_pd.loc[playoff_pd[&#39;stage&#39;] == &#39;third_place&#39;, &#39;advances&#39;].to_list()[0]<br>    overall_result_stage[&#39;second_place&#39;] = playoff_pd.loc[playoff_pd[&#39;stage&#39;] == &#39;final&#39;, &#39;loses&#39;].to_list()[0]<br>    overall_result_stage[&#39;Champion&#39;] = playoff_pd.loc[playoff_pd[&#39;stage&#39;] == &#39;final&#39;, &#39;advances&#39;].to_list()[0]<br>    overall_result_stage[&#39;match4&#39;] = list(playoff_pd.loc[4, [&#39;home_team&#39;, &#39;away_team&#39;]])<br>    overall_result_stage[&#39;match5&#39;] = list(playoff_pd.loc[5, [&#39;home_team&#39;, &#39;away_team&#39;]])<br>    <br>    playoff_results_stage.append(overall_result_stage)</pre><p>Who wins this tournament?</p><pre>results_stage[&#39;Champion&#39;].value_counts(normalize=True)</pre><pre>Argentina        0.5527<br>Colombia         0.1459<br>Brazil           0.1133<br>Uruguay          0.0936<br>Ecuador          0.0591<br>Mexico           0.0174<br>Chile            0.0116<br>United States    0.0064</pre><p>Well, who else? My dear and beloved Argentina is the team most likely to win this Copa America. In ten thousand simulations of the playoffs, it ends up as champion in more than half of them!</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*5w_BsJgfMBYP7_kO" /><figcaption>Photo by <a href="https://unsplash.com/@disfruta_cafe?utm_source=medium&amp;utm_medium=referral">Diego Castañeda</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p>Now, bear in mind that I am running this playoff simulation assuming that these will be the teams that make it to the playoffs. Also, I am using the Elo ratings prior to the start of the tournament, which isn’t the most ideal choice given that these ratings will adjust to the results of the group stage games. As such, ratings at the end of the group stage would be a much better reflection of the teams’ true strength than ratings prior to the start of the tournament. So, I’d wait until the group stage is over to offer you a more realistic simulation of the playoffs!</p><h4><strong>Conclusion</strong></h4><p>The results of the simulation give us a probabilistic view of the potential outcomes of the Copa America 2024. While no model can predict the future with certainty, the Elo rating system provides a robust framework for understanding the relative strengths of the teams and making informed predictions.</p><p>Using data science techniques to simulate and analyze soccer tournaments not only enhances our understanding of the game but also adds an extra layer of excitement as we eagerly await the real-world outcomes. Whether you’re a data enthusiast or a soccer fan, I hope this simulation inspires you to explore the fascinating world of sports analytics.</p><p>Feel free to share your thoughts and let me know which team you’re rooting for in Copa America 2024! Remember that you can also play around with this simulation by forking/cloning my <a href="https://github.com/morales-felix/Copa-America-2024-simulation">GitHub repo</a>.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=85bac848a2b7" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>