<?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 Sam Bennett on Medium]]></title>
        <description><![CDATA[Stories by Sam Bennett on Medium]]></description>
        <link>https://medium.com/@samjgbennett?source=rss-24adbb3b5072------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*mBwNGfqn3n9ONyUkA6rvJQ.png</url>
            <title>Stories by Sam Bennett on Medium</title>
            <link>https://medium.com/@samjgbennett?source=rss-24adbb3b5072------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Mon, 23 Nov 2026 09:50:08 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@samjgbennett/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[UnderDog]]></title>
            <link>https://medium.com/@samjgbennett/unveiling-underdog-4851ed70ed92?source=rss-24adbb3b5072------2</link>
            <guid isPermaLink="false">https://medium.com/p/4851ed70ed92</guid>
            <category><![CDATA[mobile-app-development]]></category>
            <category><![CDATA[learning-to-code]]></category>
            <category><![CDATA[dogs]]></category>
            <category><![CDATA[technology]]></category>
            <dc:creator><![CDATA[Sam Bennett]]></dc:creator>
            <pubDate>Tue, 30 Dec 2025 18:52:37 GMT</pubDate>
            <atom:updated>2026-01-02T15:02:53.415Z</atom:updated>
            <content:encoded><![CDATA[<h3>Creating an app to help dogs get adopted.</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Xih6moBo0pzk_rM-6lsSNw.png" /></figure><p>My girlfriend has recently been obsessed with getting a dog and for fun she would go onto a dog adoption website and search through the website and show me whenever she found a ‘really good boy’. I gave this a go on her phone, and it turned out to be a lot of fun when you love dogs as much as we do. However, I found most of the websites themselves to be slightly clunky and required some time to setup requirements and filter before scrolling. I just wanted to scroll. It might be easy to disparage the current dog adoption websites, but I actually think some are reasonably good and work reasonably well. My one problem with them was that they weren’t simple, quick or convenient to use — I also thought an app would be a better interface for the gamification aspect I desired.</p><p>I’ve had this idea for a while where I wanted to see if I could hijack the doomscroll mechanism many of us have developed in the aid of a good cause — it seemed to me this dog adoption app is the perfect way to implement this. However, by the time I had decided this, I’d just started a new job and moved to London and therefore let the idea mull whilst I got my life a bit more settled. However, as we got closer to Christmas and New Years I kept finding myself thinking more about how I would implement this project. Coincidentally, I had a few weekends free and days off around Christmas which would be the perfect way to spend the festive season.</p><p>I’m conscious that I should’ve explained what I’ve made before I’m three paragraphs deep so here it goes. I collated many dog adoption shelters dogs into one place where the user can scroll, like and view information about different dogs. The user can then ‘fetch’ the dog from the original adoption website where the adoption websites handle the actual adopting of dogs. This app essentially makes the matching of prospective owners with dogs available more efficient with a dog-first approach to matching rather than a shelter-focused approach, hence giving smaller rescue centres more visibility and the prospective owner a “low barrier to entry” way to find a dog. My sister has just finished training to be a vet and her insight from working at vet practises is that UnderDog has the opportunity to help smaller centres with technical challenges, consequently I added the ability for a charity to add their own dogs to the app (once the charity has been verified by me manually) so hopefully I can further highlight the good work they are doing whilst simultaneously improving the app.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*HU0dBn0ANIpcnl5fqcmP6w.png" /></figure><p>For my job, I have done some UI implementation for different tools, so I figured that development of an app couldn’t be much more sophisticated. It turns out it most certainly can. It was apparent that app development had a significant learning curve, however my guess was that this was likely to be front-loaded and that once I understood how all the terms and applications for development fit together then I could utilise my previous coding and UI understanding to fill in the gaps. This ended up being a reasonable assumption, and thinking back, the slight overconfidence on my part spurred me on to get ‘stuck in’. In addition, the fact that I wanted the simplicity of the app to be a feature I assumed that this project was achievable after a bit more reading and tutorial watching.</p><p>Luckily, as with many programming challenges, many people have thought about similar problems to those I was encountering and solutions were well-documented. This led me to decide that the skills I needed were learnable, and it turned out that the project wasn’t conceptually difficult to implement. The issue was mostly that the tools I used(e.g Dart, Firebase and Flutter) just needed some time to get used to.</p><p>As soon as I was able to get the first real dog onto my screen, any frustration with bugs in the code disappeared. Seeing this dog&#39;s actual face changed everything. His name is Aladdin he is a 7 year old ‘goofy boy’ who ‘treasures his toys and treats’. Instantly, he got added to my liked dogs and has remained there ever since. If this app could help Aladdin get adopted, then this whole project would be a massive success. (I do want him myself but unfortunately my flat doesn’t allow pets).</p><p>As I am writing this, I have finished the first version of UnderDog — although this is certainly not perfect at the moment, I think the current application can benefit some furry friends and therefore I am going to release to the app store as soon as I’ve come to some data agreements with UK dog shelters.</p><p>You can follow the journey of UnderDog and download it soon on iOS and Android. If you know a shelter that would benefit by being included, reach out to <a href="/service/mailto:underdogapp.contact@gmail.com">underdogapp.contact@gmail.com</a> and I can allow them to add dogs easily.</p><p>… And yes a feline counterpart is coming soon. NineLives is my current idea for the name but open to ideas.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=4851ed70ed92" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Pricing Basket Options with Monte Carlo]]></title>
            <link>https://medium.com/@samjgbennett/pricing-basket-options-with-monte-carlo-684ec1444088?source=rss-24adbb3b5072------2</link>
            <guid isPermaLink="false">https://medium.com/p/684ec1444088</guid>
            <dc:creator><![CDATA[Sam Bennett]]></dc:creator>
            <pubDate>Sun, 09 Feb 2025 18:44:08 GMT</pubDate>
            <atom:updated>2025-02-09T18:44:08.430Z</atom:updated>
            <content:encoded><![CDATA[<p>Pricing Basket European, Asian and Lookback Call options using Monte Carlo Simulation</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/696/1*O3VQBbSo6dsIzEfrubgKaw.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*fAmCj5x01VUSz533Ey41dA.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*XSCm1dJP8OScjTr6u8wfwA.png" /></figure><pre>def Naive_MC_GBM(S0, T, r, sigma, Nsteps, Npaths, Var_Cov):<br>    &quot;&quot;&quot;<br>    Perform naive Monte Carlo simulation of Geometric Brownian Motion (GBM).<br>    <br>    Parameters:<br>        S0 : Initial spot prices for each asset.<br>        T : Time to maturity in years.<br>        r : Risk-free interest rate.<br>        sigma : Volatility for each asset.<br>        Nsteps : Number of time steps (e.g., 260 for daily steps over 1 years for 3 years).<br>        Npaths : Number of paths for Monte Carlo.<br><br>    Returns:<br>        t : Time grid.<br>        S : 3D array of simulated daily closing prices (assets , time steps , paths).<br>    &quot;&quot;&quot;<br>    <br>    NBasket = len(S0)  # Number of assets<br>    t, dt = np.linspace(0, T, Nsteps + 1, retstep=True) #Creating a time grid<br>    S = np.zeros((NBasket, Nsteps + 1, Npaths)) # Creating a 3D array of simulated daily closing prices<br><br>    # Set initial prices across all paths<br>    for m in range(NBasket):<br>        S[m, 0, :] = S0[m]<br><br>    L = np.linalg.cholesky(Var_Cov) #Cholesky decomposition of Σ matrix<br>    <br>    # Simulate paths<br>    for n in range(Nsteps):<br>        Z = rng.normal(size = (NBasket, Npaths)) #Z ~ N(0,1)<br>        Y = np.sqrt(dt) * (L @ Z)  #Define a kxk matrix for Brownian increments<br>        for m in range(NBasket):<br>            S[m, n + 1, :] = S[m, n, :] * (1 + r*dt + sigma[m] * Y[m,:]) # Monte Carlo simulation<br><br>    return t, S</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*qIu0fLVFRIqqWA9hJXX5Kw.png" /></figure><pre>#Computing European call, Asian Call and Lookback Call options prices<br><br>t, S = Naive_MC_GBM(S0, T, r, sigma, Nsteps, Npaths, Var_Cov)<br><br>K = 100 <br><br>#European Call<br>B_T = np.mean(S[:, -1, :], axis=0)  # Basket price at maturity<br><br>f_ST_Euro = np.exp(-r * T) * np.maximum(B_T - K, 0)  # Payoff<br>V_Euro =  np.mean(f_ST_Euro) #Price<br>CI_Euro = 1.96 * np.std(f_ST_Euro) / np.sqrt(Npaths) #Condidence interval<br><br># Asian call option<br>B_mean = np.mean(np.mean(S, axis=1), axis=0)  # Mean value of the basket over the life of the option<br>f_ST_Asian = np.exp(-r * T) * np.maximum(B_mean - K, 0)  # Payoff<br>V_Asian =  np.mean(f_ST_Asian) #Price<br>CI_Asian = 1.96 * np.std(f_ST_Asian) / np.sqrt(Npaths)<br><br># Lookback call option<br>B_min = np.min(np.mean(S, axis=1), axis=0)  # Minimum value of the basket over the life of the option<br>f_ST_Lookback = np.exp(-r * T) * np.maximum(B_T - B_min, 0)<br>V_Lookback = np.mean(f_ST_Lookback)<br>CI_Lookback = 1.96 * np.std(f_ST_Lookback) / np.sqrt(Npaths)<br><br># Display results<br>print(f&quot;European Call Option Price: {V_Euro:.2f} ± {CI_Euro:.5f}&quot;)<br>print(f&quot;Asian Call Option Price: {V_Asian:.2f} ± {CI_Asian:.5f}&quot;)<br>print(f&quot;Lookback Call Option Price: {V_Lookback:.2f} ± {CI_Lookback:.5f}&quot;)</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*i3iH1krlxuUPtF4QLMNF5g.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*KBa4H83L1uab_iXIvGqCGQ.png" /></figure><pre>#Antithetic GBM<br><br>def Naive_MC_GBM_ant(S0, T, r, sigma, Nsteps, Npaths, Var_Cov):<br>    &quot;&quot;&quot;<br>    Perform naive Monte Carlo simulation of Geometric Brownian Motion (GBM).<br>    <br>    Parameters:<br>        S0 : Initial spot prices for each asset.<br>        T : Time to maturity in years.<br>        r : Risk-free interest rate.<br>        sigma : Volatility for each asset.<br>        Nsteps : Number of time steps (e.g., 260 for daily steps over 1 years for 3 years).<br>        Npaths : Number of paths for Monte Carlo.<br><br>    Returns:<br>        t : Time grid.<br>        S : 3D array of simulated daily closing prices (assets , time steps , paths).<br>    &quot;&quot;&quot;<br>    <br>    NBasket = len(S0)  # Number of assets<br>    t, dt = np.linspace(0, T, Nsteps + 1, retstep=True)<br>    S_p = np.zeros((NBasket, Nsteps + 1, Npaths))<br>    <br>    S_m = np.zeros((NBasket, Nsteps + 1, Npaths))<br><br>    # Set initial prices across all paths<br>    for m in range(NBasket):<br>        S_p[m, 0, :] = S0[m]<br>        S_m[m, 0, :] = S0[m]<br><br>    L = np.linalg.cholesky(Var_Cov)<br>    <br>    # Simulate paths<br>    for n in range(Nsteps):<br>        Z = rng.normal(size = (NBasket, Npaths))<br>        Y = L @ Z<br>        dW = np.sqrt(dt) * rng.normal(size=(NBasket, Npaths))  # Brownian increments for each asset<br>        for m in range(NBasket):<br>            S_p[m, n + 1, :] = S_p[m, n, :] * (1 + r*dt + sigma[m] * Y[m,:] * dW[m,:])<br>            S_m[m, n + 1, :] = S_m[m, n, :] * (1 + r*dt - sigma[m] * Y[m,:] * dW[m,:])<br><br>    return t, S_p, S_m</pre><pre>#Antithetic calculations<br><br>#Computing European call, Asian Call and Lookback Call options prices<br><br>t, S_p, S_m = Naive_MC_GBM_ant(S0, T, r, sigma, Nsteps, Npaths, Var_Cov)<br><br>K = 100 <br><br>#European Call<br>B_T_p = np.mean(S_p[:, -1, :], axis=0)  # Basket price at maturity<br>f_ST_Euro_p = np.exp(-r * T) * np.maximum(B_T_p - K, 0)  # Payoff<br><br>B_T_m = np.mean(S_m[:, -1, :], axis=0)  # Basket price at maturity<br>f_ST_Euro_m = np.exp(-r * T) * np.maximum(B_T_m - K, 0)  # Payoff<br><br>Z_Euro = 0.5*(f_ST_Euro_p + f_ST_Euro_m)<br><br>V_Euro_ant =  np.mean(Z_Euro) #Price<br>CI_Euro_ant = 1.96 * np.std(Z_Euro) / np.sqrt(Npaths) #Condidence interval<br><br><br># Asian call option<br>B_mean_p = np.mean(np.mean(S_p, axis=1), axis=0)  # Mean value of the basket over the life of the option<br>f_ST_Asian_p = np.exp(-r * T) * np.maximum(B_mean_p - K, 0)  # Payoff<br><br>B_mean_m = np.mean(np.mean(S_m, axis=1), axis=0)  # Mean value of the basket over the life of the option<br>f_ST_Asian_m = np.exp(-r * T) * np.maximum(B_mean_m - K, 0)  # Payoff<br><br>Z_Asian = 0.5*(f_ST_Asian_p + f_ST_Asian_m)<br><br>V_Asian_ant =  np.mean(Z_Asian) #Price<br>CI_Asian_ant = 1.96 * np.std(Z_Asian) / np.sqrt(Npaths)<br><br><br><br># Lookback call option<br>B_min_p = np.min(np.mean(S_p, axis=1), axis=0)  # Minimum value of the basket over the life of the option<br>f_ST_Lookback_p = np.exp(-r * T) * np.maximum(B_T_p - B_min_p, 0)<br><br>B_min_m = np.min(np.mean(S_m, axis=1), axis=0)  # Minimum value of the basket over the life of the option<br>f_ST_Lookback_m = np.exp(-r * T) * np.maximum(B_T_m - B_min_m, 0)<br><br>Z_Lookback = 0.5*(f_ST_Lookback_p + f_ST_Lookback_m)<br><br>V_Lookback_ant = np.mean(Z_Lookback)<br>CI_Lookback_ant = 1.96 * np.std(Z_Lookback) / np.sqrt(Npaths)<br><br># Display results<br>print(f&quot;European Call Option Price: {V_Euro_ant:.2f} ± {CI_Euro_ant:.5f}&quot;)<br>print(f&quot;Asian Call Option Price: {V_Asian_ant:.2f} ± {CI_Asian_ant:.5f}&quot;)<br>print(f&quot;Lookback Call Option Price: {V_Lookback_ant:.2f} ± {CI_Lookback_ant:.5f}&quot;)</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*W7QY_i4R5zq4z5lZGonqjA.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*rudfeaNbJR1pmnDlKeZavw.png" /></figure><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=684ec1444088" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Trading Triumphs: My Journey to finishing 4th in the UK and Top 0.8% Globally in Algo Trading]]></title>
            <link>https://medium.com/@samjgbennett/trading-triumphs-my-journey-to-finishing-4th-in-the-uk-and-top-0-8-globally-in-algo-trading-0248f862ec0b?source=rss-24adbb3b5072------2</link>
            <guid isPermaLink="false">https://medium.com/p/0248f862ec0b</guid>
            <category><![CDATA[algorithmic-trading]]></category>
            <category><![CDATA[trading]]></category>
            <category><![CDATA[mathematical-modeling]]></category>
            <category><![CDATA[challenge]]></category>
            <category><![CDATA[personal-development]]></category>
            <dc:creator><![CDATA[Sam Bennett]]></dc:creator>
            <pubDate>Sat, 04 May 2024 09:48:35 GMT</pubDate>
            <atom:updated>2024-05-11T11:16:54.314Z</atom:updated>
            <content:encoded><![CDATA[<h3>Trading Triumphs: My Journey to finishing 4th in the UK and Top 0.8% Globally in an Algorithmic Trading Challenge</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*F9cNEUsQJZ9VZfgCtG9XFw.png" /></figure><p>This all started when my friend Costas came to me with this idea to compete in an international quant trading competition named IMC Prosperity. I was immediately drawn to the challenge after watching the quirky promotional video featuring a parrot talking about different commodities on an archipelago. As a stats undergrad with a background in competitive algorithmic challenges, this was an exciting opportunity to test my skills and work on an interesting project with my mates.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*p8Zf751migrISARiInXdPg.png" /></figure><p>Initially, I felt a bit out of my depth. The team consisted of high-level mathematicians and two software engineers for large financial institutions, so naturally I felt my familiarity with terminology and trading would require significant improvement before and during the competition. The team really helped me rapidly improve my skills, through constant iterations, testing and discussing our algos.</p><p>Before the competition, in order to boost my skills, I immersed myself in as much research and practical application of trading algorithms as possible. I experimented with several statistical models from my university lectures, such as the Gaussian Process model with a periodic kernel, which seemed ideally suited for seasonal data prediction.</p><p>Although the competition was talented, which saw participation from 9,139 teams including prestigious universities like Cambridge and Stanford, my team in particular were amazing, the level of rigour and culture of hard work created the most high-performance group I had ever been a part of. The level of focus and raw intelligence in my team mates further pushed me to adopt their practises and strive to better myself to contribute meaningfully for towards our final algorithm.</p><p>The IMC Prosperity competition was structured uniquely, with each of its five rounds demanding distinct skills — from arbitrage and statistical prediction to pairs trading. Each round concluded with a ‘Manual trade’ in the form of a mathematical optimisation problem where teams bid in complex probabilistic scenarios. These rounds were intellectually demanding and required deep understanding and innovative approaches to trading algorithms.</p><p>The ‘Manual Trade’ in particular developed an additional level of rigour to my mathematical solutions in which I had to be a confident enough in my work to argue my case against brilliant mathematicians within the team.</p><p>A cornerstone of our strategy for algorithmic trading was our structure of development, backtesting, discussion and refining of various trading strategies. These included market-making, sophisticated statistical predictions, cross-exchange arbitrage, and options arbitrage leveraging the Black-Scholes model. In particular, a custom fair pricing model that we developed became crucial to our strategy and was integral to our performance in every round.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*6MMIF7ffZ3aShjBp-0Sxog.png" /></figure><p>Our teamwork and relentless effort paid off spectacularly. We ranked 4th in the UK and 74th globally out of 9,139 teams, placing us in the top 0.8% internationally. This achievement was particularly satisfying given the scale and the caliber of the competition.</p><p>However, the journey was not without its challenges. In the final 2 rounds I did what I could but struggled to contribute as meaningfully as I would have wanted due to having to sit my university exams, which also applied to other members of the team, therefore possibly hindering our final round performance despite amazing work from them.</p><p>We narrowly missed out on the prizes awarded to the top 25 internationally. Perhaps if exams hadn’t got in the way our team might have been able to earn the prizes provided by IMC, although I believe we are in the ideal position to earn top 10 next year. I’m sure we will be missing all the late-night discord calls until then.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*xo-vpHWWSxRFCrExNNBtzQ.png" /></figure><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=0248f862ec0b" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Uncovering Political Insider Trading using code: A Deep Dive with Selenium Scraping]]></title>
            <link>https://medium.com/@samjgbennett/uncovering-political-insider-trading-using-code-a-deep-dive-with-selenium-scraping-c4560d47229b?source=rss-24adbb3b5072------2</link>
            <guid isPermaLink="false">https://medium.com/p/c4560d47229b</guid>
            <category><![CDATA[selenium]]></category>
            <category><![CDATA[web-scraping]]></category>
            <category><![CDATA[trading]]></category>
            <category><![CDATA[python]]></category>
            <category><![CDATA[trading-bot]]></category>
            <dc:creator><![CDATA[Sam Bennett]]></dc:creator>
            <pubDate>Mon, 26 Jun 2023 16:43:41 GMT</pubDate>
            <atom:updated>2023-06-27T19:38:23.716Z</atom:updated>
            <content:encoded><![CDATA[<h3>Exploiting Political Insider Trading using code: A Deep Dive with Selenium Scraping</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/684/1*bK_FwN9uUuG1nKFD84wjeQ.png" /></figure><p>Yesterday, I stumbled upon a fascinating YouTube video by Johnny Harris. It shed light on an intriguing subject — the trading habits of US politicians. These trades, often informed by insider knowledge, seemed to be a hidden facet of political life. The tone of the video and the articles Harris referenced stirred up a sense of unfairness in me. I couldn’t help but wonder, could there be a way to find the trades they are making?</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/379/1*rx6bSOGySyxHTne0d4FXLQ.png" /></figure><p>This quest led me to the STOCK Act, a law passed by Obama in 2012. This act mandates that the trading activities of congress members be documented and disclosed to the public — ie. to me.</p><p>Driven by this thought, I delved into the U.S. House of Representatives’ Office of the Clerk database. After some time navigating this vast reservoir of information, I concluded that these trade records could be extracted using web scraping. The journey towards a more transparent trading landscape had just begun. Despite this, it’s important to tread cautiously when considering web scraping. Not all websites condone this practice and it’s crucial to respect the site’s robots.txt file, privacy policies, and terms of service. Breaching these could lead to legal implications and it’s always best to seek permission where necessary. In this project I was unable to find the robots.txt file and thus decided to just carry on, however, I would warn others against this practice and seek legal advice (however as a student I cannot personally afford this.)</p><p>Starting on this project, I initially thought to use Beautiful Soup, a tool that had been instrumental in my past work, such as the project I shared on Medium: <a href="https://medium.com/me/stats/post/880b02069e46.">https://medium.com/me/stats/post/880b02069e46.</a> However, the complexity of this task soon revealed itself to be beyond what Beautiful Soup could handle.</p><p>Recognizing this, I made a strategic shift in my approach. I decided to learn and use Selenium, a more advanced tool seemingly better suited for the intricacies of this task. Thus, the project turned into not only an exploration of trade records but also a journey of expanding my technical skills.</p><p>The initial phase of the project involved navigating to the U.S. House of Representatives’ Office of the Clerk database and locating the search box. The snippet of code below illustrates this initial step.</p><pre>from selenium import webdriver<br>from selenium.webdriver.common.keys import Keys<br>from selenium.webdriver.chrome.service import Service<br>from selenium.webdriver.chrome.options import Options<br>import time<br>import pickle  # To save and load the last top URL<br><br><br>options= Options()<br>options.add_experimental_option(&quot;detach&quot;,True)<br><br><br># Initialize the Chrome Driver<br>driver = webdriver.Chrome(service=Service(&#39;location of chromedriver),options=options)  # Update this path<br><br># Open the webpage<br>driver.get(&quot;https://disclosures-clerk.house.gov/PublicDisclosure/FinancialDisclosure&quot;)<br><br>Search_reports = driver.find_element(&quot;xpath&quot;,<br>                                 &quot;//a[text()=&#39;Search Reports&#39;]&quot;) <br><br>Search_reports.click()<br><br>time.sleep(2)<br><br># Find the search box (replace &#39;search_box&#39; with the actual name)<br>search_box = driver.find_element(&quot;xpath&quot;,<br>                                 &quot;//input[@name=&#39;LastName&#39;]&quot;) &#39;search_box&#39;<br><br>names = [&#39;Pelosi&#39;,&#39;Greene&#39;,&#39;Khanna&#39;] # Politicians used</pre><p>After the initial setup, I moved on to the main part of the task. My goal was to target specific politicians — those mentioned in the Johnny Harris video and whose data was available in the U.S. House of Representatives’ Office of the Clerk database. I developed a for loop to automate this process. The code enters the politician’s name in the search box, sorts the search results to display the newest trades first, and identifies the Periodic Transaction Reports.</p><pre>import requests<br>from PyPDF2 import PdfMerger<br>import time<br>import os<br><br>for name in names:<br>    # Enter the search string<br><br>    search_box.clear()<br>    search_box.send_keys(name)<br><br>    # Submit the search<br>    search_box.send_keys(Keys.RETURN)<br><br>    # Wait for the page to load<br>    time.sleep(2)<br><br>    # Click the &#39;Filing Year&#39; column twice<br>    #filing_year_column = driver.find_element(&#39;Filing Year&#39;)  # Update &#39;filing_year_column&#39;<br>    filing_year_column = driver.find_element(&quot;xpath&quot;,<br>                                            &quot;//th[text()=&#39;Filing Year&#39;]&quot;)<br>    filing_year_column.click()<br>    time.sleep(1)<br>    filing_year_column.click()<br><br>    # Wait for the page to load<br>    time.sleep(2)<br><br>    reports = driver.find_elements(&quot;xpath&quot;,<br>                                    &quot;//a[contains(@href, &#39;/public_disc/ptr-pdfs&#39;)]&quot;) </pre><p>My original idea was to output all the trades as text in the terminal, however when showing my parents what I had been doing for the last 3 hours, they seemed much more interested in the pdf being generated than simply just text, thus I decided that for each politician I would simply download and merge their Periodic Transaction Reports from the last 2 years into a single pdf for each politician. The code snippet below illustrates the setup for this process. I included a feature to check if new trades have been completed, determining if re-downloading all PDFs is necessary. This check was implemented using the Pickle module, as suggested by ChatGPT.</p><pre>def download_pdf(url, destination):<br>        response = requests.get(url)<br>        with open(destination, &#39;wb&#39;) as output_file:<br>            output_file.write(response.content)<br><br>    # Initialize a PDF merger<br>    merger = PdfMerger()<br><br>    # List to keep track of downloaded PDF file paths<br>    pdf_file_paths = []<br><br>    # Try to load the last top URL from a file<br>    try:<br>        with open(&#39;last_top_url.pkl&#39;, &#39;rb&#39;) as file:<br>            last_top_url = pickle.load(file)<br>    except FileNotFoundError:<br>        last_top_url = None  # If the file doesn&#39;t exist, set the last top URL to None<br><br>    # Get the top URL from the current run<br>    current_top_url = reports[0].get_attribute(&#39;href&#39;)<br><br>    # If the top URL hasn&#39;t changed, exit the script<br>    if current_top_url == last_top_url:<br>        print(&#39;No new PDFs have been added.&#39;)<br>        driver.quit()<br>        exit()<br><br>    # If the top URL has changed, save it for the next run<br>    with open(&#39;last_top_url.pkl&#39;, &#39;wb&#39;) as file:<br>        pickle.dump(current_top_url, file)</pre><p>Next, I wrote a for loop to open all the downloaded PDFs and create a merged document of all trades for each politician from the past two years. The code snippet below demonstrates this.</p><pre># Loop over each report link<br>    for i, report in enumerate(reports):<br>        # Click the link<br>        report.click()<br>        <br>        # Switch to the new tab<br>        driver.switch_to.window(driver.window_handles[1])<br>        <br>        # Get the URL of the PDF<br>        url = driver.current_url<br><br>        # Download the PDF<br>        destination = f&#39;folder_location/{name}{i}.pdf&#39;  # replace with your path<br>        download_pdf(url, destination)<br>        <br>        # Add the PDF to the merger<br>        merger.append(destination)<br><br>        # Add the file path to the list<br>        pdf_file_paths.append(destination)<br>        <br>        # Close the current tab<br>        driver.close()<br>        <br>        # Switch back to the original tab<br>        driver.switch_to.window(driver.window_handles[0])<br>        <br>        # Wait a bit before the next download<br>        time.sleep(2)<br><br><br>   final_destination = f&#39;merged_pdf_name/{name}.pdf&#39;<br><br>    # Merge all the PDFs into one<br>    merger.write(final_destination)  # replace with your path<br>    merger.close()<br>    # Delete all downloaded PDFs<br>    for pdf_file_path in pdf_file_paths:<br>        os.remove(pdf_file_path)<br><br># Close the browser<br>driver.quit()</pre><p>The next steps — if ethical and legal — are to feed the trades into ChatGPT and to use its web browsing feature to identify links between the politician and companies traded; this is to identify any trades in which they may have additional information or if any of the trades oppose any of their public statements. Once the stocks have been filtered, a trading bot could be tested that copies the trades that remain after filtration. However, as aforementioned although this would be an interesting exercise, I am unsure about the ethical validity of this plan.</p><p>Looking ahead, there are intriguing possibilities to explore, provided they fall within ethical and legal boundaries. One such prospect is to utilize the capabilities of ChatGPT, specifically its web browsing feature. The idea is to determine any potential connections between the politicians and the companies they’ve traded with. The goal is twofold: to discover if any trades were conducted based on privileged information, and to highlight if any trades contradict their public statements.</p><p>Once these filters are applied, we’re left with a distilled list of trades. These could potentially serve as the blueprint for a trading bot, which could mimic the remaining trades. Using my previous projects,e.g <a href="https://medium.com/@samjgbennett/predicting-financial-market-prices-with-xgboost-and-kalman-filters-strategy-5d9c801bceea">https://medium.com/@samjgbennett/predicting-financial-market-prices-with-xgboost-and-kalman-filters-strategy-5d9c801bceea</a>, it probably wouldn’t take too much time to create a bot that operates based on the trading habits of politicians.</p><p>However, I must reiterate my reservations. While this exercise could be insightful, it raises questions about its ethical implications about whether this is useful for the world or fun. For me, I enjoy the mathematical and statistical challenge of trading more than a cool trick that generated income by copying others. As with anything, it has also been better coded and documented by some kids on TikTok. The TikToks targeting Nancy Pelosi&#39;s finances specifically are now infamous amongst those in the finance meme community.</p><p>And thus, my journey into the world of political stock trading ended. A project that started with a video and a sense of curiosity had blossomed into a complex web scraping operation. From learning a new tool like Selenium to creating a system that automatically fetches, downloads, and consolidates two years of political trade data — the journey had been both challenging and rewarding.</p><p>As I scrolled through the final PDFs, I felt a sense of accomplishment. The PDFs were more than just documents; they were windows into a world of information previously hidden behind layers of complexity.</p><p>This project was not just about creating a tool to monitor political trades. It was about making information more accessible, about shedding light for myself on the opaque world of political trading — something that yesterday I had no idea had even existed.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=c4560d47229b" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Algorithmic Stock Trading with XGBoost and Kalman Filters – Strategy]]></title>
            <link>https://medium.com/@samjgbennett/predicting-financial-market-prices-with-xgboost-and-kalman-filters-strategy-5d9c801bceea?source=rss-24adbb3b5072------2</link>
            <guid isPermaLink="false">https://medium.com/p/5d9c801bceea</guid>
            <category><![CDATA[investing]]></category>
            <category><![CDATA[finance]]></category>
            <category><![CDATA[math]]></category>
            <category><![CDATA[technology]]></category>
            <category><![CDATA[programming]]></category>
            <dc:creator><![CDATA[Sam Bennett]]></dc:creator>
            <pubDate>Mon, 06 Mar 2023 21:50:51 GMT</pubDate>
            <atom:updated>2023-03-07T17:11:10.643Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*jFjxXBv-7aQc2VHVdTaFxA@2x.jpeg" /><figcaption>Algorithm paper trading on OANDA</figcaption></figure><p>Ever since I learnt about the biases in human thinking in my first statistics class I have been aware that decisions people make are rarely logical and most of the time veer into illogical. In order to mitigate against this in my own life, I have found created statistical models very useful. In this article, I would like to share my exploration of following a passion of mine and writing a stock trading algorithm to remove the bias in my own stock trading. My partner for this project was <a href="https://medium.com/u/e795fdc80aca">Tom Miller</a>, please read his article about the use of indicators and more from our stock trading project.</p><blockquote><strong>Model Choice</strong></blockquote><p>In my previous project of building a football betting algorithm, I found that XGBoost was highly precise and accurate machine learning model thus seemed natural that this would be the backbone of my stock prediction algorithm. I also attempted to use other algorithms such as neural networks, SVM and EMD however these didn’t seem to be as profitable using my simulations. Wanting to reduce noise in my training data, I started by fitting linear models to data to find coefficients that would start to represent the proportion of the current price that is determined by previous time steps. In this modelling, it seemed that 99% of the current price can be determined by the previous two time points. I labelled this process ‘Markov’ due to its similarities to Markov chains however using the previous two points to describe the current price point rather than only the previous one.</p><pre>lr = np.linalg.lstsq(data_close[[‘lag_1&#39;,’lag_2&#39;]],data_close[‘close’], rcond=None)[0]<br>print(&quot;lr&quot;)<br>print(lr)<br><br>data_close[‘Markov’] = np.dot(data_close[[‘lag_1&#39;,’lag_2&#39;]],lr)<br><br>fig, ax = plt.subplots()<br># Plot the first dataset<br>ax.plot(data_close[&#39;close&#39;] , label=&#39;actual&#39;)<br>ax.plot(data_close[&#39;Markov&#39;],label=&#39;Markov&#39;)<br>ax.legend(loc=&quot;upper left&quot;)<br>plt.show()</pre><p>I planned that I could create a machine learning algorithm by shifting the time points back one for the training data and the test data being unshifted (ideally this would be able to predict the price movement given the model is accurate enough).</p><pre>#Define target and features<br>X_train = train_data[[&#39;lag_1&#39;,&#39;lag_2&#39;]]<br>y_train = train_datax[&#39;close&#39;]<br>X_test = test_data[[&#39;lag_1&#39;,&#39;lag_2&#39;]]<br>y_test = test_datax[&#39;close&#39;]    <br>#Standard Scaler<br>X_train = X_train.apply(lambda x: (x - x.mean()) / (x.std()))<br>X_test = X_test.apply(lambda x: (x - x.mean()) / (x.std()))<br></pre><blockquote><strong>Smoothing</strong></blockquote><p>As this is attempting to predict the future, large amounts of noise will be involved and accuracy will be low. I believed that if the general trend of the stock movement can be modelled then smoothing as seen below using Kalman Filters and Savgol filters can decrease some of the louder noise involved.</p><pre>import xgboost as xgb<br># Define classifier<br>classifier = xgb.XGBRegressor(random_state=30)<br><br># Train classifier<br>classifier.fit(X_train, y_train)<br><br># Test classifier<br>y_pred = classifier.predict(X_test)<br>y_pred = y_pred.flatten()<br><br>combined = pd.DataFrame(dict(actual=y_test, XGBoost=y_pred))<br><br>from scipy.signal import savgol_filter<br><br>data[&#39;smooth&#39;] = savgol_filter(data[&#39;XGBoost&#39;],window_length=3, polyorder=2)<br><br>#data[&#39;smooth&#39;] = savgol_filter(data[&#39;smooth&#39;],window_length=5, polyorder=3)<br>import numpy as np<br>import numpy as np<br>from pykalman import KalmanFilter<br><br># Define the observation matrix, which is taken as an identity matrix in this example<br>observation_matrix = np.identity(1)<br><br># Estimate the initial state mean and initial state covariance based on historical data<br>initial_state_mean = np.mean(data[&#39;smooth&#39;])<br>initial_state_covariance = np.cov(data[&#39;smooth&#39;])<br><br># Define the transition matrix, which assumes a linear relationship between the state at time t and t-1<br>transition_matrix = np.array([[1]])<br><br># Define the process noise covariance and observation noise covariance, which are assumed to be diagonal matrices with small values in this example<br>process_noise_covariance = np.array([[1e-5]])<br>observation_noise_covariance = np.array([[1e-3]])<br><br># Create a KalmanFilter object<br>kf = KalmanFilter(<br>    transition_matrices=transition_matrix,<br>    observation_matrices=observation_matrix,<br>    initial_state_mean=initial_state_mean,<br>    initial_state_covariance=initial_state_covariance,<br>    #process_noise_covariance=process_noise_covariance<br>)<br><br>#Fit the Kalman filter to the financial data<br>filtered_state_means, filtered_state_covariances = kf.filter(data[&#39;smooth&#39;])<br>data[&#39;Kalman&#39;] = pd.DataFrame(filtered_state_means, index=data[&#39;smooth&#39;].index)<br><br># Create a figure and an axis<br>fig, ax = plt.subplots()<br># Plot the first dataset<br>ax.plot(data[&#39;close&#39;] , label=&#39;actual&#39;)<br><br>ax2 = ax.twinx()<br><br>#ax2.plot(data[&#39;ma3XGBoost&#39;],&#39;k&#39;,label=&#39;ma3XGBoost&#39;)<br>ax2.plot(data[&#39;smooth&#39;],&#39;c&#39;,label=&#39;smooth&#39;)<br><br>ax3 = ax.twinx()<br>ax3.plot(data[&#39;Kalman&#39;],&#39;m&#39;, label=&#39;Kalman filter&#39;)<br>#ax2.plot(data[&#39;fourier&#39;],&#39;m&#39;,label=&#39;fourier&#39;)<br><br>plt.title(&#39;Stock Movement&#39;)<br>ax.legend()<br>ax2.legend(loc=&#39;upper left&#39;)<br>ax3.legend(loc=&#39;lower left&#39;)<br>plt.show()<br></pre><blockquote><strong>Splitting</strong></blockquote><p>When the code runs it uses starts by collecting data from the time period specified (more on this in an article I will write on collecting &amp; cleaning stock data). Then splits the most recent day of price data for test data (10%) whilst the other 90% is for training the machine learning model. We then run the algorithm specified above.</p><blockquote><strong>Trading Indicators &amp; Simulation</strong></blockquote><p>My trading indicators were based on the idea that the general trend of my XGBoost generated graph was useful so a derivative and second derivative trading indicator model was used. At certain values (based on trial and error to achieve maximum profit) of the derivative, we would have our buy long and short signal as well as a complimentary sell signal. Using the test data I wrote a simulation to work out the profit that would be achieved, the trading costs I incorporated were those of a micro ES contract just to allow me to standardise my simulations.</p><pre>#Backtesting<br><br>#data[‘Gradient’] = data[‘XGBoost’] - data[‘XGBoost’].shift(1)<br>data[‘Gradient’] = data[‘Kalman’] - data[‘Kalman’].shift(1)<br>data[‘2Gradient’] = data[‘Kalman’] - data[‘Kalman’].shift(2)<br>data[‘SecondDeriv’] = data[‘Gradient’] - data[‘Gradient’].shift(1)<br><br>data[‘hour’] = data.index.hour<br>data[‘Trading’] = np.where(np.logical_and(data[‘hour’] &gt;= 10,data[‘hour’] &lt; 16),1,0)<br>#buy when gradient &gt; 0.2, sell if gradient &lt; 0 and buy = True<br><br>#Long Trades<br>#data[‘trades_L’] = np.where(np.logical_and(0.13&lt;data[‘Gradient’],data[‘Gradient’]&lt;0.18),1,0)<br><br>&quot;&quot;&quot;Current best strategies:<br><br>#1 - ES<br>data[‘trades_Buy_L’] = np.where(np.logical_and(data[‘SecondDeriv’]&lt;-0.03,data[‘Gradient’]&gt;0.04),1,0)<br>data[‘trades_Sell_L’] = np.where(np.logical_and(data[‘SecondDeriv’]&gt;-0.01,data[‘Gradient’]&lt;0.03),-1,0)<br><br>&quot;&quot;&quot;<br><br>data[‘trades_Buy_L’] = np.where(data[‘Trading’]==1, np.where(np.logical_and(data[‘SecondDeriv’]&lt;-0.03, data[‘Gradient’]&gt;0.02),1,0), 0)<br>data[‘trades_Sell_L’] = np.where(data[‘Trading’]==1, np.where(np.logical_and(data[‘SecondDeriv’]&gt;-0.01, data[‘Gradient’]&lt;0),-1,0), 0)<br><br>#Short Trades<br><br>data[‘trades_Buy_S’] = np.where(data[‘Trading’]==1, np.where(np.logical_and(data[‘SecondDeriv’]&gt;0.03, data[‘Gradient’]&lt;-0.04),1,0), 0)<br>data[‘trades_Sell_S’] = np.where(data[‘Trading’]==1, np.where(np.logical_and(data[‘SecondDeriv’]&lt;0.01, data[‘Gradient’]&gt;-0.03),-1,0), 0)<br><br><br>#Bet where we have RF is greater than previous point<br><br>data[‘Holding_L’] = np.where(data[‘trades_Buy_L’] == 1, 1, np.where(data[‘trades_Sell_L’] == -1, 0, np.nan))<br>data[‘Holding_L’].fillna(method=’ffill’, inplace=True)<br>data[‘prev_holding_L’] = data[‘Holding_L’].shift(1)<br><br>data[‘Holding_S’] = np.where(data[‘trades_Buy_S’] == 1, 1, np.where(data[‘trades_Sell_S’] == -1, 0, np.nan))<br>data[‘Holding_S’].fillna(method=’ffill’, inplace=True)<br>data[‘prev_holding_S’] = data[‘Holding_S’].shift(1)<br><br><br>#Calculating where trades are made<br>data[‘change_L’] = np.where((data[‘Holding_L’] == 1) &amp; (data[‘prev_holding_L’] == 0), 1, np.where((data[‘Holding_L’] == 0) &amp; (data[‘prev_holding_L’] == 1), -1, 0))<br>data[‘change_S’] = np.where((data[‘Holding_S’] == 1) &amp; (data[‘prev_holding_S’] == 0), 1, np.where((data[‘Holding_S’] == 0) &amp; (data[‘prev_holding_S’] == 1), -1, 0))<br><br># Generate trades, we trade if over a sufficient number<br><br>hold_mask_L = data[‘change_L’] == 1<br>hold_mask_S = data[‘change_S’] == 1<br><br># Create a boolean array for when the holding is 0<br>not_hold_mask_L = data[‘change_L’] == -1<br>not_hold_mask_S = data[‘change_S’] == -1<br><br>&quot;&quot;&quot; Plotting &quot;&quot;&quot;<br># Plot the Close values in green when holding is 1<br>plt.plot(data[hold_mask_L].index, data[hold_mask_L][‘close’], ‘g.’, label=’Bought_L’,markersize=10)<br><br>plt.plot(data[hold_mask_S].index, data[hold_mask_S][‘close’], ‘k.’, label=’Bought_S’,markersize=10)<br><br># Plot the Close values in red when holding is 0<br>plt.plot(data[not_hold_mask_L].index, data[not_hold_mask_L][‘close’], ‘r.’, label=’Sold_L’,markersize=10)<br><br>plt.plot(data[not_hold_mask_S].index, data[not_hold_mask_S][‘close’], ‘m.’, label=’Sold_S’,markersize=10)<br><br>plt.plot(data[‘close’], label= ‘Close’, dashes=[3, 1])<br><br># Add a legend to the plot<br>plt.legend()<br><br><br><br>#Calculation of profit<br>data[‘profit_L’] = data[‘Holding_L’] * (data[‘close’] - data[‘close’].shift(1))<br>profit_L = data[‘profit_L’].sum()<br>   <br>data[‘profit_S’] = data[‘Holding_S’] * (data[‘close’].shift(1)-data[‘close’])<br>profit_S = data[‘profit_S’].sum()<br>data[‘cumprofit’] = data[‘profit_S’].cumsum() + data[‘profit_L’].cumsum()<br><br>Long_profit = data[‘profit_L’].sum()*50<br>Short_profit = data[‘profit_S’].sum()*50<br><br>print(&quot;Long Profit multiplier&quot;,data[‘profit_L’].sum())<br>print(&quot;Short Profit multiplier&quot;,data[‘profit_S’].sum())<br>print(&quot;Long Profit&quot;,Long_profit)<br>print(&quot;Short Profit&quot;,Short_profit)<br><br><br>#data.to_csv(&quot;UnFunctioned_V1.1.csv&quot;)<br>Number_of_trades_L = (data[‘trades_Buy_L’].sum())<br>Number_of_trades_S = (data[‘trades_Buy_S’].sum())<br>print(&quot;Number of trades (Long)&quot;,Number_of_trades_L)<br>print(&quot;Number of trades (Short)&quot;,Number_of_trades_S)<br><br>Trading_costs_micro = (Number_of_trades_L+Number_of_trades_S)*0.25<br><br>Total_profit = (Long_profit + Short_profit) - Trading_costs_micro<br>print(&quot;Profit&quot;,Total_profit)<br><br></pre><p>The image below shows the performance of the profit gained from the simulation in the days specified. V1 is the algorithm specified above still with the Savgol filter but without the Kalman Filter. The values on the left are trading with Microsoft stock and the values on the right are trading with ES futures. TP represent the total profit.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/585/1*p0vqn30LSVLs4iZkoo43tg@2x.jpeg" /><figcaption>Simulated profits when running the algorithm based on my simulation</figcaption></figure><blockquote><strong>External Simulation</strong></blockquote><p>After this, I have, connected my code to OANDA using the free API for paper trading and am collecting results over a longer period to establish the effectiveness of the trading algorithm. A snippet of the code can be seen below, using external simulation software allows me to truly validate the algorithm not only on a simulation I created.</p><pre><br>    #Sell<br><br>    if signal == 1:<br><br>        #mo is market order<br><br>        mo = MarketOrderRequest(instrument=&quot;SPX500_USD&quot;, units=-1, takeProfitOnFill=TakeProfitDetails(price=TPSell).data, stopLossOnFill=StopLossDetails(price=SLSell).data)<br><br>        r = orders.OrderCreate(accountID, data=mo.data)<br><br>        rv = client.request(r)<br><br>        print(rv) #just to see that order has passed<br><br>    #Buy<br><br>    elif signal == 2:<br><br>        mo = MarketOrderRequest(instrument=&quot;SPX500_USD&quot;, units=1, takeProfitOnFill=TakeProfitDetails(price=TPBuy).data, stopLossOnFill=StopLossDetails(price=SLBuy).data)<br><br>        r = orders.OrderCreate(accountID, data=mo.data)<br><br>        rv = client.request(r)<br><br>        print(rv)<br><br><br><br>#trading_job()<br><br><br><br>scheduler = BlockingScheduler()<br><br>scheduler.add_job(trading_job, &#39;cron&#39;, day_of_week=&#39;mon-fri&#39;, hour=&#39;10-17&#39;,start_date=&#39;2022-02-13 10:00:00&#39;, timezone=&#39;Europe/London&#39;)#minute=&#39;1,16,31,46&#39;<br><br>scheduler.start()<br><br></pre><p>Once, it seems apparent that the coding algorithm is viable and not susceptible to large losses (due to gambler’s ruin etc) it will be time to connect the algorithm to a broker and trade with real funds, starting with ES futures and then expanding.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=5d9c801bceea" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[BUILDING A FOOTBALL NEURAL NET]]></title>
            <link>https://medium.com/@samjgbennett/building-a-football-neural-net-b2daa49151d2?source=rss-24adbb3b5072------2</link>
            <guid isPermaLink="false">https://medium.com/p/b2daa49151d2</guid>
            <category><![CDATA[neural-networks]]></category>
            <category><![CDATA[football]]></category>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[epl]]></category>
            <category><![CDATA[ai]]></category>
            <dc:creator><![CDATA[Sam Bennett]]></dc:creator>
            <pubDate>Sat, 13 Aug 2022 14:18:58 GMT</pubDate>
            <atom:updated>2022-08-13T14:25:47.512Z</atom:updated>
            <content:encoded><![CDATA[<p>CREATING A HOMEMADE NEURAL NET FOR FOOTBALL USING MATH AND YOUTUBE</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*NhIZyHW2lafL5SZIX53EPg.png" /></figure><p>For me it seemed that the use of Tensorflow and Pytorch to build neural network seemed too detatched from the math for me to gain a deep understanding of what my neural net is actually doing. I have always favoured a contructivist ‘ground up’ approach to learning and for me it seemed that the optimum way to learn about neural nets through this project was to dive in with the math.</p><p>My mission was relatively simple: try and create a neural network that had a predictive accuracy of around 0.65 as a base for choosing the winners of EPL matches, from reading papers this accuracy is similar to a gradient boosting or RBF SVM approach for the same problem.</p><p>Above we can see my plan to implement this network, I have decided to use a relatively simple n-&gt;10-&gt;10-&gt;2-&gt;1 neural net and then flesh this out when I believe it is required to increase the accuracy. I have chosen to use the ELU activation function as my nodes seemed to die (got to a point where there was no longer learning) when using the industry standard of ReLU due to the zeroing of negative values in practise.</p><p>My next idea is to test out a one-hot encoding system for converting the 3rd layer to ‘y_hat’ and perhaps a soft-max function for converting the values in the 3rd layer to probabilities.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=b2daa49151d2" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[WEB SCRAPING FOOTBALL DATA]]></title>
            <link>https://medium.com/@samjgbennett/web-scraping-football-880b02069e46?source=rss-24adbb3b5072------2</link>
            <guid isPermaLink="false">https://medium.com/p/880b02069e46</guid>
            <category><![CDATA[football-betting]]></category>
            <category><![CDATA[web-scraping]]></category>
            <category><![CDATA[football]]></category>
            <category><![CDATA[beautifulsoup]]></category>
            <dc:creator><![CDATA[Sam Bennett]]></dc:creator>
            <pubDate>Tue, 09 Aug 2022 14:38:10 GMT</pubDate>
            <atom:updated>2022-08-09T14:41:02.711Z</atom:updated>
            <content:encoded><![CDATA[<p>GATHERING FOOTBALL DATA FROM THE INTERNET USING PYTHON</p><p>09/08/22</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*EBj8jSoMzb31Y7vXlhupvg.png" /></figure><p>For me this was a crucical first step in my journey to create a half-decent football prediction neural network. According to Yaser S. Abu-Mostafa(Professor of Electrical Engineering and Computer Science) to get a proper result you must have data for <strong>at-least 10 times the degree of freedom. </strong>This means if you have 3 weights you should have 30 units of data. Long story short I needed data and lots of it.</p><p><strong>What did I use?</strong></p><p>My website choice to obtain the data from was ‘FBREF’, this is becuase it’s the same website used in ‘Web Scraping Football Matches From the EPL With Python [part 1 of 2]’ YouTube video just in case I needed any help. I would highly reccomend watching this video before starting any projects as for me it was invaluable. In my case I used BeautifulSoup as this seemed to be most popular python library that people used on YouTube. I also used Pandas as creating a dataFrame from the data would help me clean it later. Also uses requests library for its .get function.</p><p><strong>What data did I plan to use?</strong></p><p>I started with EPL results from the last two seasons as this is data which is overtly relevant for predictions and I am most familar with the EPL personally, unfortunately being a Man United fan myself :(. I figured I can first get this to a reasonable level before I started to expand to more years and more leagues.</p><p><strong>Code plan</strong></p><p>My step-by-step plan is below for how I scraped. For me using BeautifulSoup was alien however after a while some patterns emerge with further research. The key things steps to using BeautifulSoup seem to be:</p><ol><li>Creating a partial url varibable, this is should take you to the full stats table.</li><li>Then creating an empty list which we will add to later, e.g all_matches = []</li><li>Create a for loop that loops through the years you want and uses .get(partial_url) to visit the website.</li><li>We then use BeautifulSoup to select a table, we find its name by inspecting the website on the table to find its name in the website code</li><li>We then will .find_all(‘a’) in the html to find all &lt;a&gt;, as it seems this is where the good stuff is kept. We want squads data.</li><li>Then get the team_urls using a for loop or vectorised code to complete the partial url using a for loop.</li><li>Now for loop through the team_urls and repreat steps 5&amp;6 but in this case obtaining shooting data.</li><li>Important to add breaks using time.sleep() from the time library as this will ensure you don’t get blocked from the website and they will not get overrun with requests.</li></ol><p>We will now clean the data as explained in my ‘CLEANING EPL DATA’ article.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=880b02069e46" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>