<?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 Jhalyl Mason on Medium]]></title>
        <description><![CDATA[Stories by Jhalyl Mason on Medium]]></description>
        <link>https://medium.com/@JhalylM?source=rss-b4aded07cd68------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*MkwliUBRH9yemQyhrucTLA@2x.jpeg</url>
            <title>Stories by Jhalyl Mason on Medium</title>
            <link>https://medium.com/@JhalylM?source=rss-b4aded07cd68------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Tue, 01 Dec 2026 20:13:16 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@JhalylM/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[The Art and Science of Strategic Thinking]]></title>
            <link>https://blog.gopenai.com/the-art-and-science-of-strategic-thinking-9d16b91aa229?source=rss-b4aded07cd68------2</link>
            <guid isPermaLink="false">https://medium.com/p/9d16b91aa229</guid>
            <category><![CDATA[relationships]]></category>
            <category><![CDATA[business]]></category>
            <category><![CDATA[psychology]]></category>
            <category><![CDATA[game-theory]]></category>
            <category><![CDATA[life]]></category>
            <dc:creator><![CDATA[Jhalyl Mason]]></dc:creator>
            <pubDate>Thu, 06 Nov 2025 01:00:22 GMT</pubDate>
            <atom:updated>2025-11-06T06:35:33.485Z</atom:updated>
            <content:encoded><![CDATA[<p><strong><em>What Game Theory teaches us about Trust, Risk, and Human Nature</em></strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Lf8pqD59J0BmGLYc4q4rdw.png" /></figure><h4>Introduction</h4><p>Every day, whether aware of it or not, we play several games.</p><p>Not the kinds with boards or screens, but the subtle games of action and consequence that define our lives. Each time we negotiate salaries or prices, split responsibilities, make promises, or decide whom we should trust, we’re playing. Each choice is a move that helps shape the overall outcome.</p><p><strong><em>Strategic thinking</em></strong> is the skill we use when navigating these choices. It’s part intuition/part logic, and requires us to attempt to understand how our actions affect others, and how theirs affect us in return. For decades, mathematicians, economists, and psychologists have tried to map this complex process through the lens of <strong><em>Game Theory</em></strong><em>.</em></p><p>But game theory isn’t just about mathematics or economics. Beneath all of the equations lies a deep exploration of human nature: why we cooperate, why we compete, and how we learn to trust.</p><h4>The Science: How Game Theory Models Decision-Making</h4><p>The encyclopedia Brittanica defines game theory as the “branch of applied mathematics that provides tools for analyzing situations in which parties, called players, make decisions that are interdependent”. To put it simply, <strong>game theory</strong> is the <strong>mathematical study of interaction and strategy.</strong></p><p>At its core, game theory starts with a simple premise: in any situation involving multiple decision-makers (or “players”), each one tries to choose the strategy that gives the best possible payoff, while assuming everyone else is doing the same.</p><p>This logic leads to a powerful concept known as the <strong>Nash equilibrium</strong>, named after mathematician John Nash. It describes a point where no player can improve their outcome by changing their strategy alone. In other words, everyone’s current choices are optimal given everyone else’s choices.</p><p>One of the most famous illustrations of this is the <strong>Prisoner’s Dilemma</strong>. Two suspects are arrested and questioned separately. Each must decide whether to stay silent or betray the other. If both stay silent, they get light sentences (think a slap on the wrist). If one betrays and the other stays silent, the betrayer goes free while the other takes the full punishment (think long prison terms). If both betray, both suffer moderately. Rationally, betrayal seems to be the safest for each individual; it’s the only option that has the possibility of total freedom. Yet if both choose this option, they are both left worse off than if they had trusted each other and stayed silent.</p><p>This paradox captures a fundamental tension in human life: <strong>acting in our individual self-interest can sometimes harm us collectively</strong>. Logic alone isn’t always enough to win the “game.”</p><h4>The Art: The Human Side</h4><p>If the science of strategic thinking lies in logic, then the art lies in empathy.</p><p>Real people are not robots calculating payoffs; we have our own unique histories, emotions, and biases. We trust, forgive, retaliate, and sometimes make decisions that defy strict rationality.</p><p>That’s where <strong>behavioral game theory</strong> steps in. It examines how real humans, with all of our imperfections, actually play these “games”. For instance, in experiments where one player divides a sum of money and the other can accept or reject the offer, people tend to consistently reject “unfair” splits, even when it means losing money themselves. Justice and pride tend to be surprisingly powerful forces in the human decision making process.</p><p>Strategic thinking, then, is not just about cold calculation; it also involves understanding the motives, emotions, and perceptions of others. In business negotiations, relationships, and politics alike, success often depends just as much on empathy as it does on intellect.</p><h4>Trust and Risk in the Game of Life</h4><p>At first thought, trust may seem like a purely moral virtue, but it also serves as a strategic move.</p><p>In repeated interactions (what game theorists call <strong>iterated games)</strong> reputation becomes like a form of currency. Cooperation in one round can encourage more in the next. The legendary “Tit-for-Tat” strategy, popularized by political scientist Robert Axelrod, demonstrated this beautifully: start the game with cooperation, subsequently mirror your partner’s previous move each round (if they betray you first then you do the same on the next given opportunity, same with cooperation) and forgive quickly (after retaliating for betrayal, do not hold grudges or betray again unless the other does so first). Over time, this simple formula outperformed more aggressive or deceptive strategies at the same task.</p><p>Why? Because <strong>trust</strong>, once established, <strong>compounds</strong>. It reduces uncertainty around future events and enables mutually beneficial outcomes that competition alone can’t achieve.</p><p>Think about partnerships in business, alliances in diplomacy, or teamwork in organizations. The risk of being betrayed is always there, but refusing to trust at all leads to stagnation. <strong>Progress often requires vulnerability</strong> and a leap of faith that the other side won’t exploit your openness.</p><p>Of course, <strong>trust can be broken</strong>. Once lost, it shifts the “game” <strong>entirely</strong>, creating cycles of <strong>suspicion</strong> and <strong>retaliation</strong>. But the potential rewards of cooperation (such as shared growth, innovation, and stability) can often outweigh some of the risks.</p><h4>What Game Theory Reveals About Human Nature</h4><p>Perhaps the most profound lesson gained from game theory is this: humans are <em>not</em> purely rational, but our tendency to seek fairness and cooperation is itself an evolved strategy.</p><p>From an evolutionary perspective, cooperation allowed early societies to survive and flourish. Groups that trusted and shared resources outperformed those that didn’t. Certain “moral” instincts, such as empathy, reciprocity, and even guilt, may have developed as mechanisms to sustain that cooperation.</p><p>In complex societies, we still rely on these instincts. We form networks of trust in families, communities, and institutions. We create laws and norms to punish betrayal and reward honesty. In essence, we’ve built entire civilizations on the logic of trust.</p><p>Game theory, in stripping human behavior down to mathematical simplicity, paradoxically highlights our complexity. It shows that while we’re inherently capable of selfishness, we’re also wired for collaboration. Even in competitive environments, cooperation often emerges as the winning strategy.</p><h4>Lessons for Everyday Life</h4><p>So, what can game theory teach us about how to think strategically and make decisions in our everyday lives?</p><p><strong>First</strong>, anticipate possible incentives. Before reacting to others’ choices, ask: <em>What motivates them? What are they optimizing for?</em> Understanding the “game” from multiple perspectives is the first step toward better outcomes.</p><p><strong>Second</strong>, remember that long-term relationships change the rules. In one-time encounters, defection may pay off. But in ongoing relationships (such as those with colleagues, customers, or romantic partners) cooperation and integrity usually yield the best returns.</p><p><strong>Third</strong>, embrace both analysis and intuition. The science of game theory provides frameworks and models; the art lies in timing, empathy, and judgment. The best strategists are not those who simply try to manipulate others, but those who strive to truly understand them.</p><p><strong>Finally</strong>, recognize that trust and risk are inseparable. Every meaningful connection, whether personal or professional, involves a degree of uncertainty. Strategic thinking doesn’t eliminate that risk; it just helps you to manage it more wisely.</p><h4>Thinking Strategically, Living Wisely</h4><p>In the end, the art and science of strategic thinking converge into a simple truth: our success depends not only on how well we play our own game, but on how well we understand the games others are playing.</p><p>Game theory gives us elegant mathematical tools, but its deepest insight is profoundly human: cooperation and trust, though risky, are often the most rational paths forward when participating in interdependent relationships.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=9d16b91aa229" width="1" height="1" alt=""><hr><p><a href="https://blog.gopenai.com/the-art-and-science-of-strategic-thinking-9d16b91aa229">The Art and Science of Strategic Thinking</a> was originally published in <a href="https://blog.gopenai.com/">GoPenAI</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Mutual Information vs Correlation: Finding Nonlinear Alpha]]></title>
            <description><![CDATA[<div class="medium-feed-item"><p class="medium-feed-image"><a href="https://blog.gopenai.com/mutual-information-vs-correlation-finding-nonlinear-alpha-e21ac0d7c836?source=rss-b4aded07cd68------2"><img src="https://cdn-images-1.medium.com/max/1536/0*GoEFfhkNxa69yMEK" width="1536"></a></p><p class="medium-feed-snippet">Part 2 in Series: Alpha from Structure&#x200A;&#x2014;&#x200A;Information Theory in Quant Finance</p><p class="medium-feed-link"><a href="https://blog.gopenai.com/mutual-information-vs-correlation-finding-nonlinear-alpha-e21ac0d7c836?source=rss-b4aded07cd68------2">Continue reading on GoPenAI »</a></p></div>]]></description>
            <link>https://blog.gopenai.com/mutual-information-vs-correlation-finding-nonlinear-alpha-e21ac0d7c836?source=rss-b4aded07cd68------2</link>
            <guid isPermaLink="false">https://medium.com/p/e21ac0d7c836</guid>
            <category><![CDATA[data-science]]></category>
            <category><![CDATA[quantitative-finance]]></category>
            <category><![CDATA[information-theory]]></category>
            <category><![CDATA[statistics]]></category>
            <category><![CDATA[machine-learning]]></category>
            <dc:creator><![CDATA[Jhalyl Mason]]></dc:creator>
            <pubDate>Fri, 11 Jul 2025 01:01:31 GMT</pubDate>
            <atom:updated>2025-07-11T17:53:40.352Z</atom:updated>
        </item>
        <item>
            <title><![CDATA[Entropy, Markets, and the Hidden Cost of Noise]]></title>
            <description><![CDATA[<div class="medium-feed-item"><p class="medium-feed-image"><a href="https://blog.gopenai.com/entropy-markets-and-the-hidden-cost-of-noise-e0a3fd1d0500?source=rss-b4aded07cd68------2"><img src="https://cdn-images-1.medium.com/max/1536/1*z8jtlDzJ55ujqofYzCR6YQ.png" width="1536"></a></p><p class="medium-feed-snippet">Part 1 in Series: Alpha from Structure&#x200A;&#x2014;&#x200A;Information Theory in Quant Finance</p><p class="medium-feed-link"><a href="https://blog.gopenai.com/entropy-markets-and-the-hidden-cost-of-noise-e0a3fd1d0500?source=rss-b4aded07cd68------2">Continue reading on GoPenAI »</a></p></div>]]></description>
            <link>https://blog.gopenai.com/entropy-markets-and-the-hidden-cost-of-noise-e0a3fd1d0500?source=rss-b4aded07cd68------2</link>
            <guid isPermaLink="false">https://medium.com/p/e0a3fd1d0500</guid>
            <category><![CDATA[statistics]]></category>
            <category><![CDATA[finance]]></category>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[information-theory]]></category>
            <category><![CDATA[quantitative-finance]]></category>
            <dc:creator><![CDATA[Jhalyl Mason]]></dc:creator>
            <pubDate>Fri, 27 Jun 2025 00:49:57 GMT</pubDate>
            <atom:updated>2025-07-01T12:13:42.866Z</atom:updated>
        </item>
        <item>
            <title><![CDATA[Next Gen Quant: A Conversation with Jiri Pik]]></title>
            <description><![CDATA[<div class="medium-feed-item"><p class="medium-feed-image"><a href="https://medium.com/@JhalylM/next-gen-quant-a-conversation-with-jiri-pik-0a84f9ee891a?source=rss-b4aded07cd68------2"><img src="https://cdn-images-1.medium.com/max/1024/1*RMo-BO5h75tSBuyO4HfPqw.png" width="1024"></a></p><p class="medium-feed-snippet">Bridging Bank-Grade Rigor with Startup Speed</p><p class="medium-feed-link"><a href="https://medium.com/@JhalylM/next-gen-quant-a-conversation-with-jiri-pik-0a84f9ee891a?source=rss-b4aded07cd68------2">Continue reading on Medium »</a></p></div>]]></description>
            <link>https://medium.com/@JhalylM/next-gen-quant-a-conversation-with-jiri-pik-0a84f9ee891a?source=rss-b4aded07cd68------2</link>
            <guid isPermaLink="false">https://medium.com/p/0a84f9ee891a</guid>
            <category><![CDATA[data-science]]></category>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[quant]]></category>
            <category><![CDATA[software-engineering]]></category>
            <category><![CDATA[finance]]></category>
            <dc:creator><![CDATA[Jhalyl Mason]]></dc:creator>
            <pubDate>Thu, 22 May 2025 23:56:08 GMT</pubDate>
            <atom:updated>2025-05-23T00:04:43.538Z</atom:updated>
        </item>
        <item>
            <title><![CDATA[Next Gen Quant: An Interview with Jared Broad]]></title>
            <description><![CDATA[<div class="medium-feed-item"><p class="medium-feed-image"><a href="https://medium.com/@JhalylM/next-gen-quant-an-interview-with-jared-broad-on-democratizing-algorithmic-trading-4a863a3d99af?source=rss-b4aded07cd68------2"><img src="https://cdn-images-1.medium.com/max/1024/1*weaSjq5BrU7Dgabvt3peIg.png" width="1024"></a></p><p class="medium-feed-snippet">A conversation on democratizing algorithmic trading &#x2026;</p><p class="medium-feed-link"><a href="https://medium.com/@JhalylM/next-gen-quant-an-interview-with-jared-broad-on-democratizing-algorithmic-trading-4a863a3d99af?source=rss-b4aded07cd68------2">Continue reading on Medium »</a></p></div>]]></description>
            <link>https://medium.com/@JhalylM/next-gen-quant-an-interview-with-jared-broad-on-democratizing-algorithmic-trading-4a863a3d99af?source=rss-b4aded07cd68------2</link>
            <guid isPermaLink="false">https://medium.com/p/4a863a3d99af</guid>
            <category><![CDATA[artificial-intelligence]]></category>
            <category><![CDATA[quantitative-finance]]></category>
            <category><![CDATA[entrepreneurship]]></category>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[finance]]></category>
            <dc:creator><![CDATA[Jhalyl Mason]]></dc:creator>
            <pubDate>Mon, 12 May 2025 18:00:03 GMT</pubDate>
            <atom:updated>2025-05-13T00:04:59.392Z</atom:updated>
        </item>
        <item>
            <title><![CDATA[Demystifying Probability Theory]]></title>
            <description><![CDATA[<div class="medium-feed-item"><p class="medium-feed-image"><a href="https://medium.com/@JhalylM/demystifying-probability-theory-1ce977627700?source=rss-b4aded07cd68------2"><img src="https://cdn-images-1.medium.com/max/2600/0*pOYFYps8UcfOsdzJ" width="6000"></a></p><p class="medium-feed-snippet">From Foundational Concepts to Calculus-Based Applications in Modeling Uncertainty</p><p class="medium-feed-link"><a href="https://medium.com/@JhalylM/demystifying-probability-theory-1ce977627700?source=rss-b4aded07cd68------2">Continue reading on Medium »</a></p></div>]]></description>
            <link>https://medium.com/@JhalylM/demystifying-probability-theory-1ce977627700?source=rss-b4aded07cd68------2</link>
            <guid isPermaLink="false">https://medium.com/p/1ce977627700</guid>
            <dc:creator><![CDATA[Jhalyl Mason]]></dc:creator>
            <pubDate>Mon, 24 Mar 2025 02:32:52 GMT</pubDate>
            <atom:updated>2025-05-12T18:20:09.419Z</atom:updated>
        </item>
        <item>
            <title><![CDATA[Mastering Time Series Stationarity]]></title>
            <description><![CDATA[<div class="medium-feed-item"><p class="medium-feed-image"><a href="https://medium.com/@JhalylM/mastering-time-series-stationarity-38de9b86825d?source=rss-b4aded07cd68------2"><img src="https://cdn-images-1.medium.com/max/1424/1*T8gvWF4ndBJg2APvO6VbwA.png" width="1424"></a></p><p class="medium-feed-snippet">Understanding Stationarity for Improved Forecasting</p><p class="medium-feed-link"><a href="https://medium.com/@JhalylM/mastering-time-series-stationarity-38de9b86825d?source=rss-b4aded07cd68------2">Continue reading on Medium »</a></p></div>]]></description>
            <link>https://medium.com/@JhalylM/mastering-time-series-stationarity-38de9b86825d?source=rss-b4aded07cd68------2</link>
            <guid isPermaLink="false">https://medium.com/p/38de9b86825d</guid>
            <category><![CDATA[data-science]]></category>
            <category><![CDATA[time-series-analysis]]></category>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[predictive-analytics]]></category>
            <category><![CDATA[statistics]]></category>
            <dc:creator><![CDATA[Jhalyl Mason]]></dc:creator>
            <pubDate>Fri, 21 Feb 2025 02:58:16 GMT</pubDate>
            <atom:updated>2025-05-12T18:21:23.153Z</atom:updated>
        </item>
        <item>
            <title><![CDATA[Understanding Markov Models]]></title>
            <link>https://medium.com/@JhalylM/understanding-markov-models-6c631c4d8433?source=rss-b4aded07cd68------2</link>
            <guid isPermaLink="false">https://medium.com/p/6c631c4d8433</guid>
            <category><![CDATA[markov-chains]]></category>
            <category><![CDATA[stochastic-process]]></category>
            <category><![CDATA[data-science]]></category>
            <category><![CDATA[quant]]></category>
            <category><![CDATA[machine-learning]]></category>
            <dc:creator><![CDATA[Jhalyl Mason]]></dc:creator>
            <pubDate>Fri, 14 Feb 2025 08:08:59 GMT</pubDate>
            <atom:updated>2025-02-14T22:50:10.799Z</atom:updated>
            <content:encoded><![CDATA[<p><em>From Theory to Applications</em></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*8ubkAFxFvoPFZJAS0QaLvg.jpeg" /></figure><h4>Introduction</h4><p><strong>Markov Models<em> </em></strong>are a fundamental class of probabilistic models that are used to define a system that changes over time. Named after 20th century mathematician <strong><em>Andrey Markov</em></strong>, all of these models share what is known as the <strong>Markov Property</strong><em>.</em><strong><em> </em></strong>The Markov Property assumes that the future state of a system depends only on its current state, and not on the sequence of events that preceded it.. This is also known as being “memory-less”, as they need no prior memory to determine the probability distributions of future states. This property makes them particularly useful for modeling sequential data, where patterns and transitions play a crucial role.</p><p>These models have shown to have a wide range of real-world applications. For instance, in <strong>natural language processing (NLP)</strong>, they are used for speech recognition and text generation. In <strong>finance</strong>,<strong> </strong>they have been used to identify market regimes and predict asset price movements. In <strong>reinforcement learning (RL), </strong>they form the backbone<strong> </strong>of decision making algorithms.</p><p>This article will break down three key types of Markov models: <strong>Markov Chains</strong> (the simplest form, where transitions between states follow fixed probabilities), <strong>Hidden Markov Models (HMMs) </strong>(a more advanced model where the system’s actual states are hidden, but we observe outputs that help infer them), and <strong>Markov Decision Processes </strong>(a powerful extension of Markov chains with actions and rewards). By the end of this article, you’ll understand how these models work, when to use each, and some of their practical applications.</p><h4>Markov Chains: The Foundation</h4><p><strong><em>Overview</em></strong></p><p>A <strong>Markov Chain </strong>is a type of stochastic process that models a system transitioning between different <strong>states</strong> according to some fixed probabilities.</p><p><strong><em>Mathematical Representation</em></strong></p><p>If we denote the sequence of states possible as S₁, S₂, S₃,…, then a Markov chain satisfies:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/501/1*L2Ae7S0UjdImAbupjLa05g.png" /><figcaption>Figure 1.1 Markov Property</figcaption></figure><p>Figure 1.1 shows the Markov property, showing the probability of transitioning to the next state (Sₜ₊₁) is dependent only on the current state (Sₜ).</p><p><strong><em>States</em></strong></p><p><strong>States </strong>are the different possible conditions that the system can be in.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/260/0*PstmW93jp1AHXHMk.png" /><figcaption>Figure 1.2 Markov Chain (<a href="https://en.wikipedia.org/wiki/Markov_chain#/media/File:Markovkate_01.svg">https://en.wikipedia.org/wiki/Markov_chain#/media/File:Markovkate_01.svg</a>)</figcaption></figure><p>Above (Figure 1.2) is an example of a simple Markov chain with 2 states: A and E. If we are at state E, the probability of the next state being state A is 70%, with a 30% chance it will be remain in state E at the next step. Likewise, from state A there is a 40% chance of transitioning to state E on the next step, and a 60% chance we remain in state A. What is important is that these probabilities are fixed: no matter how you get to state A, it will always have the same probabilities of either staying the same or transitioning to state E, and vice versa.</p><p><strong><em>Transition Probabilities</em></strong></p><p>As described above, the probability of being in state A at the next step in our Markov chain, given that we are in state E currently, is 70%.</p><p>The probabilities of moving from one state to another are known as the <strong>transition probabilities</strong>. These transition probabilities are often put into a matrix of probabilities, known as the <strong>transition matrix</strong>. The transition matrix for the above Markov chain is shown below:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/671/1*bMXjjQrEZYzaEgFXprupUw.png" /><figcaption>Figure 1.3 Transition Matrix</figcaption></figure><p>Figure 1.3 shows a transition matrix, labeled P, for the previously described Markov chain. Each entry into the matrix represents the probability of transitioning from one state to another. Notice that each row of the matrix is a <strong>probability vector</strong>, it represents the total probability for each state (as an example, row 1 in Figure 1.3 shows all the possible transitions from state A), as such they sum up to 1.</p><p><strong><em>Applications</em></strong></p><p>Markov chains have multiple real world applications and uses. For instance, they are used for ranking webpages like in Google’s Page rank algorithm. Each page represents a state, and hyperlinks represent transitions between states. This approach helps determine the importance of web pages based on the likelihood of randomly navigating to them [1].</p><p>They also have been used in fields of healthcare and medicine. Markov chain models of HIV usually include things like states to model progression to AIDS or transmission. Comparing such models of different risk groups has helped guide public health organizations to develop strategies to reduce the risk for such diseases [1].</p><h4>Hidden Markov Models (HMMs)</h4><p><strong><em>Overview</em></strong></p><p><strong>Hidden Markov Models </strong>are like Markov chains, however their states are “hidden”. This just means we cannot directly observe them. Instead, HMMs include <strong>observations</strong>, which are generated from the hidden states. From these observations, we can infer the hidden states.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/300/0*dl4eOfkpP5iGC7PB.png" /><figcaption>Figure 2.1 Hidden Markov Model (<a href="https://vitalflux.com/hidden-markov-models-concepts-explained-with-examples/">https://vitalflux.com/hidden-markov-models-concepts-explained-with-examples/</a>)</figcaption></figure><p>Figure 2.1 shows a Hidden Markov Model with 2 hidden states (rainy or sunny) and 3 observations (walk, shop, or clean). This figure also includes the <strong>initial state distribution </strong>of the model. The initial state distribution describes the probability of starting in each state (60% chance the initial state of the model is rainy and 40% it is sunny in this case). These states are hidden, so we do not know them initially.</p><p><strong><em>Emission Probability</em></strong></p><p>The <strong>emission probability</strong> represents the likelihood of observing a specific output, given the model is in a particular hidden state. For example, Figure 2.1 is a model depicting whether someone will be walking, shopping, or cleaning given the day is sunny or rainy. The observations are whether the person is found walking, shopping, or cleaning, and the emission probabilities are the probabilities that they are observed doing one of the activities given the day (50% chance the observed output is the person cleaning given the day is rainy, 60% chance the observed output is the person walking given it is sunny, etc).</p><p>Similar to transition probabilities, emission probabilities are often represented in matrix form as well. Each entry in the matrix represents the probability of the model generating an observation given a state.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/805/1*vYZLKCugMxpPDLT3FU8CAg.png" /><figcaption>Figure 2.2 Emission Probability Matrix</figcaption></figure><p>Figure 2.2 shows the emission probability matrix for the previously given Hidden Markov Model. Each row of the emission matrix represents a probability vector for a state in the model, and contains the probability of generating each observation given the state.</p><p><strong><em>Decoding</em></strong></p><p><strong>Decoding </strong>in an HMM refers to the process of determining the most likely sequence of hidden states that results in a sequence of observed events.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/379/1*M2yaVgvgwNoML9DVpOYiwg.png" /><figcaption>Figure 2.3 Optimal Sequence of States</figcaption></figure><p>Figure 2.3 shows the decoding problem. S* represents the most likely sequence of hidden states given an HMM λ (consisting of transition probabilities, emission probabilities, and initial state probabilities) and a sequence of observations O. It is defined as the argmax of the joint probability of a state sequence given the observations and the HMM. In order to solve this equation efficiently, we can use the <strong><em>Viterbi Algorithm</em></strong>.</p><p>The <strong>Viterbi Algorithm</strong>, named after <strong><em>Andrew Viterbi</em></strong>,<strong> </strong>is a dynamic programming algorithm used to solve the most likely sequence of states problem. It operates by computing the highest probability path to each state at each given time step. It stores each of these probabilities, and then backtracks to determine the most probable sequence of the hidden states. This algorithm solves the problem in O(N²T) instead of the brute force solution which is O(Nᵀ) (with N being the number of hidden states and T being the number of observations).</p><p><strong><em>Applications</em></strong></p><p>Like Markov chains, HMMs have a wide variety of uses and applications. One example is their use in speech recognition. Phonemes (distinct units of sound in a specified language) are modeled as hidden states with certain audio features used as the observations. From this, they can use the model to decode spoken language [2].</p><p>They have also shown use in computational biology. In these cases, the hidden states might represent certain biological features with the observations being things such as nucleotide or amino acid chains. This allows the models to be used for tasks such as gene prediction, protein structure prediction, and sequence alignment [3].</p><h4>Markov Decision Process (MDP)</h4><p><strong><em>Overview</em></strong></p><p><strong>Markov Decision Processes (MDPs) </strong>are a framework for modeling decision making in stochastic environments. They extend Markov chains by including <strong>actions</strong> that influence state transitions and <strong>rewards</strong> that quantify the value of taking specific actions.</p><p><strong><em>Agents</em></strong></p><p>Often in MDPs you will see reference to something known as an <strong>agent</strong>. An agent is the system responsible for making decisions and performing actions in the MDP, such as algorithms in reinforcement learning.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/499/0*3FqhR5-mDSEB0CKQ.png" /><figcaption>Figure 3.1 Markov Decision Process (<a href="https://optimization.cbe.cornell.edu/index.php?title=File:Markov_Decision_Process_Example_2.png">https://optimization.cbe.cornell.edu/index.php?title=File:Markov_Decision_Process_Example_2.png</a>)</figcaption></figure><p>Figure 3.1 above shows an example of an MDP. The agent in this example is a college student, each state is represented by the circles/squares in the diagram, and the rewards for taking each action are shown in red.</p><p><strong><em>Policy</em></strong></p><p>The algorithm used to determine an agents actions is called it’s <strong>policy</strong>. The goal of Markov Decision Processes is to find the optimal policy that maximizes the total expected reward over time. A <strong>deterministic policy</strong> always selects the same action for a given state whereas a <strong>stochastic policy</strong> assigns probabilities to different actions.</p><p><strong><em>Value Functions</em></strong></p><p>Value functions are used to calculate the expected cumulative reward when following a certain policy. The <strong>state value function</strong> is the expected reward starting from state s, following policy π.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/528/1*PIIWQkxgvQ_LLWm5YQ4OYg.png" /><figcaption>Figure 3.2 State Value Function</figcaption></figure><p>Figure 3.2 shows the expression representing the state value function for state s, where:</p><ul><li><strong>R(s,a)</strong> = Reward function (defines the expected immediate reward received when taking action a in state s).</li><li><strong>γ</strong> = Discount factor (0≤ γ ≤1). (determines how much future rewards are valued compared to immediate rewards)</li></ul><p>The <strong>action value function </strong>is the expected reward for taking action a in state s, then following policy π.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/625/1*sF35b4mkhXEe47djv0DQnw.png" /><figcaption>Figure 3.3 Action Value Function</figcaption></figure><p><strong><em>Q-value iteration</em></strong></p><p><strong>Q-value iteration</strong> is an algorithm used to find the optimal state-action values, or Q values (quality values) of an MDP. It begins by initializing all of the current Q-value estimates to 0. Then, at each iteration, the Q-values are updated using the Bellman Optimality equation:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/814/1*yvNOARWpGfI2FhAXBC1APw.png" /><figcaption>Figure 3.4 Bellman Optimality Equation</figcaption></figure><p>Figure 3.4 shows the Q-value iteration algorithm where:</p><ul><li>Q(s,a): Current Q-value for the state-action pair (s,a).</li><li>α: <strong>Learning rate</strong> (controls how much the Q-values should be updated).</li><li>max⁡ a′ Q(s′, a′): The maximum Q-value for the next state s′, considering all possible actions a′ that could be taken from state s′.</li><li>s′: The next state after taking action a from state s.</li></ul><p>This algorithm repeats until convergence (the Q-values stop changing significantly between iterations) or after a given number of iterations. Once you have the optimal Q-values, the optimal policy can be defined bas choosing the action with the highest Q-value for each state.</p><p><strong><em>Applications</em></strong></p><p>As stated earlier, one of the applications for MDPs is reinforcement learning (RL) in Artificial Intelligence. In RL, an agent learns to make decisions through trial and error by interacting with an environment. The agent’s goal is to maximize its cumulative reward over time by selecting optimal actions based on its current state.</p><p>MDPs are also applied in financial decision-making to model the decision process of allocating assets in a portfolio over time. Each action (buy, sell, hold) depends on the current market state, and the reward comes from the returns on the portfolio.</p><h4><strong><em>Comparison: When to use each</em></strong></h4><p>Markov Models, though sharing the fundamental Markov Property, differ in their applications based on the complexity of the system being modeled. Here’s a comparison of when to use each of the three types of models discussed.</p><p><em>Markov Chains</em></p><p>Markov Chains are ideal when the system’s future state depends only on its current state, and the transitions between states are based on fixed probabilities. If you are modeling a simple system where the goal is to observe the probabilities of moving from one state to another over time, a Markov Chain is a good fit. Common applications include modeling random processes in finance, web page ranking, and queueing systems.</p><p><em>Hidden Markov Models</em></p><p>Hidden Markov Models are appropriate when the system’s true state is unobservable, but you have indirect observations that can help infer the hidden states. This is useful when you need to model systems where you can observe some output, but the underlying cause or state is not directly available. Applications include speech recognition, bioinformatics (e.g., gene prediction), and financial modeling where market conditions are not directly observable but can be inferred from observed data.</p><p><em>Markov Decision Processes</em></p><p>Markov Decision Processes are suited for decision-making problems where an agent interacts with an environment. If you have an environment where decisions influence state transitions and there is a reward or cost associated with each action, MDPs provide a framework for optimizing decision-making over time. Typical use cases include reinforcement learning, robotics, and financial decision-making (e.g., portfolio management and asset allocation).</p><h4>Conclusion</h4><p>In conclusion, Markov Models offer powerful tools for modeling and understanding systems that evolve over time, with each type offering distinct advantages depending on the complexity of the problem. Markov Chains are best suited for systems with observable, fixed transitions between states, making them ideal for applications like web page ranking and queueing systems. Hidden Markov Models, on the other hand, excel in scenarios where the true system state is hidden, but observable outputs provide valuable information for inference, such as in speech recognition and gene prediction. Finally, Markov Decision Processes provide a comprehensive framework for decision-making problems, especially in environments where actions influence future states and rewards are crucial for optimizing decisions, making them fundamental in reinforcement learning, robotics, and financial decision-making.</p><p>As you explore Markov Models further, understanding their various forms will allow you to select the right approach for your specific problem, be it modeling sequences, inferring hidden states, or making optimal decisions. These models not only offer insights into complex systems but also provide the foundation for numerous real-world applications across diverse fields such as AI, finance, healthcare, and beyond.</p><h4>References</h4><p>[1] <a href="https://math.libretexts.org/Bookshelves/Applied_Mathematics/Applied_Finite_Mathematics_%28Sekhon_and_Bloom%29/10%3A_Markov_Chains/10.02%3A_Applications_of_Markov_Chains?utm_source=chatgpt.com">https://math.libretexts.org/Bookshelves/Applied_Mathematics/Applied_Finite_Mathematics_%28Sekhon_and_Bloom%29/10%3A_Markov_Chains/10.02%3A_Applications_of_Markov_Chains?</a></p><p>[2] <a href="https://www.geeksforgeeks.org/hidden-markov-model-in-machine-learning/">https://www.investopedia.com/terms/m/markov-analysis.asp</a></p><p>[3] <a href="https://link.springer.com/article/10.1007/s11831-020-09422-4">https://link.springer.com/article/10.1007/s11831-020-09422-4</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=6c631c4d8433" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[From Data to Detection: Identifying Fraud in E-Commerce Transactions]]></title>
            <link>https://medium.com/@JhalylM/from-data-to-detection-identifying-fraud-in-e-commerce-transactions-0e10bb3ae22b?source=rss-b4aded07cd68------2</link>
            <guid isPermaLink="false">https://medium.com/p/0e10bb3ae22b</guid>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[risk-management]]></category>
            <category><![CDATA[data-science]]></category>
            <category><![CDATA[fraud]]></category>
            <dc:creator><![CDATA[Jhalyl Mason]]></dc:creator>
            <pubDate>Fri, 31 Jan 2025 23:32:20 GMT</pubDate>
            <atom:updated>2025-01-31T23:32:20.351Z</atom:updated>
            <content:encoded><![CDATA[<p><em>A deep dive into fraud detection using data analysis, feature engineering, and predictive modeling.</em></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*ygcCIfJJ-W8J1pUi" /><figcaption>Photo by <a href="https://unsplash.com/@blocks?utm_source=medium&amp;utm_medium=referral">blocks</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><h4>Overview</h4><p>As online shopping continues to dominate global commerce, e-commerce platforms are handling millions of transactions every day. While this rapid digital expansion offers convenience and accessibility, it also comes with a significant downside — fraud. Cybercriminals are constantly devising new ways to exploit online payment systems, leading to an increase in the amount of fraudulent transactions globally. According to a June 2023 study by Juniper Research, “<em>online payment fraud will exceed $362 billion globally between 2023 to 2028” </em>with an estimated $91 billion of that expected to come in 2028 alone [1].</p><p>Due to this increasingly growing issue, detecting fraud is a crucial challenge for businesses. Machine learning offers the possibility of an adaptive approach to this problem. With their ability to analyze patterns and identify anomalies, machine learning models stand to be used as a tool to improve fraud detection accuracy.</p><p>In this article, I review a project I completed where I built a fraud detection model in order to benefit between genuine and fraudulent transactions. I will walk through the key steps of the process — from data exploration and feature engineering to model selection and evaluation — offering insights into how data science can help combat financial fraud in the e-commerce industry.</p><p>The project in it’s entirety can be found on my portfolio <a href="https://jhalylm.github.io/myportfolio">here</a> and directly on my Github <a href="https://github.com/JhalylM/E-commerce-Fraud-Detection-Model/blob/main/README.md">here</a> [3].</p><h4><strong>Data Collection &amp; Exploration</strong></h4><p>The dataset being used for this task is the <a href="https://www.kaggle.com/datasets/shriyashjagtap/fraudulent-e-commerce-transactions/data">Fraudulent E-Commerce Transactions dataset by shriyashjagtap</a> on kaggle [2]. It consists of 1.4 million+ e-commerce transactions as well as labels such as transaction amount, transaction date, payment method, product category, etc.</p><pre>path = kagglehub.dataset_download(&quot;shriyashjagtap/fraudulent-e-commerce-transactions/versions/1&quot;)<br><br>csv_file_path = os.path.join(path, &#39;Fraudulent_E-Commerce_Transaction_Data.csv&#39;)<br><br>df = pd.read_csv(csv_file_path)<br><br>df.head()</pre><pre>Transaction ID      Customer ID      Transaction Amount      Transaction Date      Payment Method     Product Category      Quantity    Customer Age   Customer Location   Device Used   IP Address   Shipping Address   Billing Address   Is Fraudulent   Account  Age  Days  Transaction Hour<br>0   15d2e414-8735-46fc-9e02-80b472b2580f d1b87f62-51b2-493b-ad6a-77e0fe13e785 58.09 2024-02-20 05:58:41 bank transfer electronics 1 17 Amandaborough tablet 212.195.49.198 Unit 8934 Box 0058\nDPO AA 05437 Unit 8934 Box 0058\nDPO AA 05437 0 30 5<br>1   0bfee1a0-6d5e-40da-a446-d04e73b1b177 37de64d5-e901-4a56-9ea0-af0c24c069cf 389.96 2024-02-25 08:09:45 debit card electronics 2 40 East Timothy desktop 208.106.249.121 634 May Keys\nPort Cherylview, NV 75063 634 May Keys\nPort Cherylview, NV 75063 0 72 8<br>2   e588eef4-b754-468e-9d90-d0e0abfc1af0 1bac88d6-4b22-409a-a06b-425119c57225 134.19 2024-03-18 03:42:55 PayPal home &amp; garden 2 22 Davismouth tablet 76.63.88.212 16282 Dana Falls Suite 790\nRothhaven, IL 15564 16282 Dana Falls Suite 790\nRothhaven, IL 15564 0 63 3<br>3   4de46e52-60c3-49d9-be39-636681009789 2357c76e-9253-4ceb-b44e-ef4b71cb7d4d 226.17 2024-03-16 20:41:31 bank transfer clothing 5 31 Lynnberg desktop 207.208.171.73 828 Strong Loaf Apt. 646\nNew Joshua, UT 84798 828 Strong Loaf Apt. 646\nNew Joshua, UT 84798 0 124 20<br>4   074a76de-fe2d-443e-a00c-f044cdb68e21 45071bc5-9588-43ea-8093-023caec8ea1c 121.53 2024-01-15 05:08:17 bank transfer clothing 2 51 South Nicole tablet 190.172.14.169 29799 Jason Hills Apt. 439\nWest Richardtown, ... 29799 Jason Hills Apt. 439\nWest Richardtown, ... 0 158 5</pre><p>Now we can take a look at some of the statistics of our dataset.</p><pre>df.shape()</pre><pre>(1472952, 16)</pre><p>As we can see, the dataset consists of 1.4 million datapoints with 16 features for each. Below we can see each feature individually:</p><pre>df.info()</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/558/1*Bn8xNkGdja8gYG5UjnyhhQ.png" /></figure><p>And finally we can look at the distributions of our data:</p><pre>df.describe().T</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/932/1*e4Vg-2-WqvoFQTRLGh0Lvg.png" /></figure><h4>Data Cleaning &amp; Feature Engineering</h4><p>Now we can begin cleaning and preparing the data for use in our future model. This includes addressing some of the issues that are obvious through our look at the data previously. Afterword, we will create some new features out of our current ones.</p><p>The first and most obvious of these is the fact that the minimum value for out “Customer Age” feature is -16. That’s clearly an inconsistency and should be looked into further.</p><pre>plt.boxplot(df[&#39;Customer Age&#39;], vert=False)</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/718/1*gPwfXBQc_GLpFSasaiTCcA.png" /></figure><p>As we can see from the above boxplot of our customer age values, we have several outliers extending below 0. In order to handle these we can calculate the lower fence (Q1 — (1.5 * IQR)) of our age feature, this will be used to determine a reasonable cutoff range. In this case, our lower fence is 8.5, so we can take any values between -8 and 8 and replace them with the mean. Any values less than -8 will be replaced with their absolute values.</p><pre>mean_value = np.round(df[&#39;Customer Age&#39;].mean(),0)<br>df[&#39;Customer Age&#39;] = np.where(df[&#39;Customer Age&#39;] &lt;= -8,<br>                              np.abs(df[&#39;Customer Age&#39;]),<br>                              df[&#39;Customer Age&#39;])<br><br>df[&#39;Customer Age&#39;] = np.where(df[&#39;Customer Age&#39;] &lt; 8,<br>                              mean_value,<br>                              df[&#39;Customer Age&#39;])</pre><pre>plt.boxplot(df[&#39;Customer Age&#39;], vert=False)</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/675/1*poq2Y65cygGIfv8syw0aJA.png" /></figure><p>Now we have a more reasonable looking distribution of datapoints for age.</p><p>Next we can move on to encoding some of the categorical data. We will start with out “Transaction Date” feature. In order to turn the transaction date into categorical features we can use in our model, we will break it up into three columns : day of the week, month, and date.</p><pre>df[&quot;Transaction Date&quot;] = pd.to_datetime(df[&quot;Transaction Date&quot;])<br><br>df[&#39;Transaction Day&#39;] = df[&quot;Transaction Date&quot;].dt.day<br>df[&quot;Day of Week&quot;] = df[&quot;Transaction Date&quot;].dt.day_of_week<br>df[&quot;Transaction Month&quot;] = df[&quot;Transaction Date&quot;].dt.month</pre><p>Now to get rid of the unnecessary columns:</p><pre>df.drop(columns=[&quot;Transaction ID&quot;, &quot;Customer ID&quot;, &quot;Customer Location&quot;,<br>                     &quot;IP Address&quot;, &quot;Transaction Date&quot;,&quot;Shipping Address&quot;,&quot;Billing Address&quot;], inplace=True)<br><br>df.head()</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*v5zVrccxE6q8p1O1e1Qc6A.png" /></figure><h4>Exploratory Data Analysis (EDA)</h4><p>Now we proceed to the step of Exploratory Data Analysis. This step is important, as it gives us the ability to use visualizations and statistical analysis in order to explore the distribution of key features, examine correlations, and assess the balance between fraud and non-fraud classes.</p><p>First let’s look at our transactions:</p><pre>plt.hist(df[&#39;Transaction Amount&#39;], bins=100)<br>plt.show()</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/813/1*_I43HuCEITcogHxuzz5Lxw.png" /><figcaption>Distribution for Transaction Amount</figcaption></figure><p>As we can see, although our maximum transaction amount may be over $12,000, the distribution is right skewed with the majority of our transactions distributed around less than $1,000 (as seen by the transaction amount average of 226 previously).</p><p>Below we can look at the distribution of transaction amounts based on fraudulent status:</p><pre>categories = df[&#39;Is Fraudulent&#39;].unique()<br>categories.sort()<br>data = [df[df[&#39;Is Fraudulent&#39;] == cat][&#39;Transaction Amount&#39;] for cat in categories]<br><br><br>plt.figure(figsize=(10, 6))<br>plt.violinplot(<br>    data,<br>    showmeans=True,<br>    showextrema=True,<br>    showmedians=True<br>)<br><br><br>plt.xticks(ticks=np.arange(1, len(categories) + 1), labels=categories)<br>plt.xlabel(&quot;Is Fraudulent&quot;)<br>plt.ylabel(&quot;Transaction Amount&quot;)<br>plt.title(&quot;Violin Plot of Transaction Amount by Fraudulent Status&quot;)<br><br><br>plt.show()</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*DK3-f69yRF_FSloWVFDbyw.png" /></figure><p>As to be expected, the fraudulent cases have outlier/s extending far beyond that of the non-fraudulent transactions.</p><p>We can also check out the amount of fraudulent cases compared to non-fraudulent for certain categories.</p><pre>column = [&#39;Payment Method&#39;, &#39;Product Category&#39;,<br>       &#39;Quantity&#39;, &#39;Device Used&#39;,&#39;Day of Week&#39;,<br>       &#39;Transaction Month&#39;,&#39;Addresses Match&#39;]<br><br>plt.figure(figsize=(10,35))<br><br>plot_num = 1<br>for col in column:<br>    plt.subplot(10, 2, plot_num)  # Create subplots with 10 rows and 2 columns<br><br>    # Prepare the data for the bar plot<br>    data = df.groupby([col, &quot;Is Fraudulent&quot;]).size().unstack(fill_value=0)<br>    categories = data.index<br>    fraudulent_counts = data[1] if 1 in data.columns else [0] * len(categories)  # Fraudulent counts (if exists)<br>    non_fraudulent_counts = data[0] if 0 in data.columns else [0] * len(categories)  # Non-fraudulent counts (if exists)<br><br>    # Plot the bars<br>    bar_width = 0.4<br>    x = range(len(categories))<br>    plt.bar(x, non_fraudulent_counts, width=bar_width, label=&#39;Non-Fraudulent&#39;, color=&#39;blue&#39;, alpha=0.7)<br>    plt.bar(<br>        [i + bar_width for i in x], fraudulent_counts, width=bar_width, label=&#39;Fraudulent&#39;, color=&#39;orange&#39;, alpha=0.7<br>    )<br><br>    # Customizations<br>    plt.xticks([i + bar_width / 2 for i in x], categories, rotation=90)  # Rotate x-axis labels<br>    plt.title(col)<br>    plt.legend()<br><br>    plt.tight_layout()  # Adjust layout to prevent overlap<br>    plot_num += 1<br><br># Show the plots<br>plt.show()</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*M_fPzI-nH28eI4_QIPMr8Q.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*BhvBc2e6knm5eKodcT2OBw.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*AqzLCpGat9nz63AHdrwgcA.png" /></figure><p>As shown, our dataset is largely unbalanced. There are far more non-fraudulent cases than there are fraudulent ones. This is also to be expected, as assumedly there are way more legitimate transactions occurring than there are fraudulent ones. We will see how this affects our results.</p><h4>Model Selection &amp; Training</h4><p>In order to decide what model to use for our task, I decided to train several different models and assess their effectiveness using 3 measures: precision, recall, and overall accuracy. Precision will tell us how many of the positive predictions our model makes were correct (for instance, if a model says 10 transactions are fraudulent but only 8 of them were really fraudulent, it would have a precision of 80%). Recall will tell us how many of the positive transactions our model catches (for instance if a dataset has 10 total fraudulent transactions and the model catches 8 of them, it has a recall of 80%). Accuracy will be a measure of the proportion of correctly identified cases (both fraudulent and non-fraudulent) out of the total cases. The four models we will test will be a logistic regression model, decision tree, random forest, and XGBoost model.</p><p>First we will split the data into training and testing sets and encode/normalize our values.</p><pre>X = df.drop(&#39;Is Fraudulent&#39;, axis=1)<br>y = df[&#39;Is Fraudulent&#39;]<br><br>X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, random_state=42)<br><br>catCols = X_train.select_dtypes(include=&quot;object&quot;).columns<br>numCols = []<br>for col in X_train.columns:<br>    if col not in catCols  and col != &#39;Addresses Match&#39;:<br>        numCols.append(col)<br><br>transformer = ColumnTransformer(transformers=[<br>    (&#39;encoding&#39;,OneHotEncoder(),catCols),<br>    (&#39;scaling&#39;,StandardScaler(),numCols)<br>],remainder=&#39;passthrough&#39;)</pre><p>And now we begin our pipeline of training models:</p><pre>classifiers = {<br>    &quot;Logistic Regression&quot;: LogisticRegression(),<br>    &quot;Decision Tree&quot;: DecisionTreeClassifier(),<br>    &quot;Random Forest&quot;: RandomForestClassifier(),<br>    &quot;XGBoost&quot;: XGBClassifier()<br>}<br><br><br>classifierNames = []<br>accuracy = []<br>for name, classifier in classifiers.items():<br><br>    model = Pipeline(steps=[<br>        (&#39;transformer&#39;,transformer),<br>        (&#39;classifier&#39;,classifier)<br>    ])<br><br>    model.fit(X_train, y_train)<br><br>    y_pred = model.predict(X_test)<br><br>    acc_score = accuracy_score(y_test, y_pred)<br><br>    class_report = classification_report(y_test, y_pred)<br><br>    classifierNames.append(name)<br>    accuracy.append(acc_score)<br><br>    print(f&quot;Classifier name : {name}&quot;)<br>    print(f&quot;Accuracy score : {acc_score}&quot;)<br>    print(f&quot;Classification report :\n{class_report}&quot;)<br>    print(&quot;-&quot;*55)</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/740/1*dKAQuGe2KSKbFQ0aDsjaOA.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/737/1*XbppkedUsomfOhVCrbI0iA.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/706/1*5DlBynvVGaGyw1L4vhk2DQ.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/707/1*Bn7wJfV49oJIvl7fNx9mqA.png" /></figure><p>The XGBoost Classifier seems to outperform the other models in all 3 of our test metrics with the highest accuracy, recall, and precision. It has a high accuracy of ~96%, showing it was able to correctly identify the majority of the cases as either fraudulent or non-fraudulent. It also has a high precision and recall for non-fraudulent cases, 96% and 100% respectively. The biggest concern is the recall for fraudulent cases at 15%. This means that our model missed a lot of fraudulent cases, however the precision of 81% means when it did claim a transaction as fraudulent it was accurate. The low recall is most likely due to the large imbalance of non-fraudulent transactions in the dataset.</p><h4>Summary</h4><p>The goal of this project was to develop a machine learning model capable of detecting fraudulent transactions in an e-commerce dataset. After carefully selecting relevant features and applying appropriate preprocessing steps to our data, we trained several models to determine the best solution for identifying fraud. The final model selected for this task was an XGBoost Classifier which achieved an overall accuracy of 95.5%, suggesting that it correctly predicted the outcome of most transactions.</p><p>For non-fraudulent transactions, precision was 96%, meaning that when the model predicted a transaction as non-fraudulent, it was correct 96% of the time. For fraudulent transactions, precision was 81%, indicating that while the model was fairly good at identifying fraudulent transactions when it predicted them, there was still some room for improvement. The recall for non-fraudulent transactions was 1.00, meaning the model correctly identified all non-fraudulent transactions without missing any. However, the recall for fraudulent transactions was low at 0.15, indicating that the model was not very effective at identifying fraudulent transactions. The dataset was heavily imbalanced, with far more non-fraudulent transactions than fraudulent ones. The model showed a strong bias toward predicting non-fraudulent transactions, which led to its high accuracy. However, this resulted in poor recall for fraudulent transactions, a critical issue for fraud detection tasks.</p><h4>Conclusion</h4><p>Through this project, we explored how machine learning models can help distinguish between fraudulent and legitimate transactions. By leveraging <strong>data exploration, feature engineering, and model selection</strong>, we built a fraud detection system that can significantly reduce financial risks for e-commerce platforms. While our model performs well, there’s always room for improvement — whether through deep learning techniques, real-time deployment, or integrating external fraud intelligence data.</p><p>As fraud tactics evolve, so must our detection methods. This project is just a stepping stone toward more sophisticated fraud prevention strategies.</p><h4>References</h4><p>[1] <a href="https://www.juniperresearch.com/press/losses-online-payment-fraud-exceed-362-billion/">https://www.juniperresearch.com/press/losses-online-payment-fraud-exceed-362-billion/</a></p><p>[2] <a href="https://www.kaggle.com/datasets/shriyashjagtap/fraudulent-e-commerce-transactions/data">https://www.kaggle.com/datasets/shriyashjagtap/fraudulent-e-commerce-transactions/data</a></p><p>[3] <a href="https://github.com/JhalylM/E-commerce-Fraud-Detection-Model/blob/main/README.md">https://github.com/JhalylM/E-commerce-Fraud-Detection-Model/blob/main/README.md</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=0e10bb3ae22b" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Introduction to Deep Learning for Portfolio Optimization]]></title>
            <link>https://medium.com/@JhalylM/introduction-to-deep-learning-for-portfolio-optimization-103a48bdf094?source=rss-b4aded07cd68------2</link>
            <guid isPermaLink="false">https://medium.com/p/103a48bdf094</guid>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[quantitative-finance]]></category>
            <category><![CDATA[deep-learning]]></category>
            <category><![CDATA[portfolio-management]]></category>
            <category><![CDATA[finance]]></category>
            <dc:creator><![CDATA[Jhalyl Mason]]></dc:creator>
            <pubDate>Mon, 27 Jan 2025 02:44:12 GMT</pubDate>
            <atom:updated>2025-01-29T01:59:32.014Z</atom:updated>
            <content:encoded><![CDATA[<p><em>Deep Neural Networks &amp; Modern Portfolio Theory</em></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*ac4wXEA_qWwRmyta" /><figcaption>Photo by <a href="https://unsplash.com/@yorgosntrahas?utm_source=medium&amp;utm_medium=referral">Yorgos Ntrahas</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p><strong>Overview</strong></p><p><em>When investing, how do I pick stocks to maximize my returns? How much do I invest into each stock in my portfolio? How risky are my investments, and how does that relate to my overall returns?</em></p><p>These questions are all extremely important to the process of investing, and being able to effectively answer them is an important cornerstone of modern financial portfolio management. One of the most foundational and influential approaches to addressing these problems is known as Modern Portfolio Theory.</p><h4>Portfolio Optimization</h4><p><strong>Modern Portfolio Theory</strong></p><p><strong><em>Modern Portfolio Theory (MPT)</em></strong><em> </em>is defined as “a practical method for selecting investments in order to maximize their overall returns within an acceptable level of risk” [1]. The theory was pioneered by American economist Harry Markowitz in his 1952 paper “<strong><em>Portfolio Selection</em></strong>”. In the landmark paper, Markowitz takes a deep look into the way portfolios are built and analyzed and the criteria used to analyze them. Before this investors would simply “find a good stock and buy it at the best price”, and investing was no more than “laying bets on stocks that you thought were at their best price” [4]. Markowitz’ paper introduced the idea of looking into the risk of a given investment. He insisted that “<em>A good portfolio is more than a long list of good stocks and bonds. It is a balanced whole, providing the investor with protections and opportunities with respect to a wide range of contingencies</em>” [5]. These sentiments laid the foundation for a new way of looking at building portfolios with a focus on risk.</p><p>The key idea is that most assets are either <strong>high risk/ high return</strong> or <strong>low risk/ low return</strong>, and by finding the optimal mix of the two, a portfolio can achieve it’s best possible results [1]. Essentially, using MPT an investor would try to find the lowest risk necessary to achieve their desired returns for their portfolio. In that same vein, it can also be used to find the highest returns possible for the portfolio within a given risk tolerance. In order to do this however, there needs to be a way to quantitatively determine how much risk a portfolio is taking on and how this is related to it’s returns. This can be accomplished through Mean-Variance Analysis.</p><p><strong>Mean-Variance Analysis</strong></p><p><strong><em>Mean-Variance Analysis (MVA) </em>or<em> Mean-Variance Optimization (MVO) </em></strong>is a part of Modern Portfolio Theory that is used to help weigh investment decisions [2]. It first involves calculating the <strong>mean,</strong> or <strong>expected returns</strong> of the assets. This is simply the average returns an investor can expect to make on an interview. It also involves calculating the <strong>variance </strong>which measures the spread of the expected returns (also known as the <strong>risk</strong>). The variance/risk measures the uncertainty associated with the expected returns (higher variance means more risk, lower variance means more stable returns). Finally it also requires calculating the <strong>covariance </strong>and <strong>correlation </strong>between the assets in the portfolio. The covariance of two assets measures if they tend to move together (positive covariance) or in opposite directions (negative covariance). The correlation measures the strength of that relationship between assets (correlation of 1 means assets perfectly move together, -1 means they perfectly move in opposite directions, and 0 means there is no linear relationship between them). This is an overlooked but extremely important part of the process as well, as Markowitz states in his paper : “<em>To reduce risk it is necessary to avoid a portfolio whose securities are all highly correlated with each other. One hundred securities whose returns rise and fall in near unison afford little more protection than the uncertain return of a single security</em>” [5].</p><p><strong>Sharpe Ratio</strong></p><p>By knowing both the mean and variance of the assets in a portfolio, you can look to optimize the portfolio’s Sharpe Ratio<em>.</em> The <strong><em>Sharpe Ratio</em></strong> is an expression used to compare how well a portfolio is performing in comparison to the risk associated with it [3]. It divides a portfolio’s excess returns by it’s volatility to give a measure of the <strong>risk-adjusted returns </strong>of the portfolio. As such, it is one of the most widely used metrics for determining how well a portfolio is balanced, and is useful for comparing different assets and portfolios. A Sharpe Ratio of 1 or greater is usually defined as showing a good risk-adjusted performance, with 2 or higher being very good, and less than 1 being sub-optimal.</p><h4>Deep Learning</h4><p>Now that we’ve established some of the basics behind Modern Portfolio Theory and some of the metrics used to evaluate portfolios, where does Deep Learning come in?</p><p><strong>Enter Deep Learning</strong></p><p><strong><em>Deep Learning</em></strong> refers to the field of machine learning algorithms that “uses multilayered neural networks, called deep neural networks, to simulate the complex decision-making power of the human brain” [6]. These algorithms are becoming increasingly more popular amongst a variety of fields due to their ability to adapt to and excel at a multitude of different tasks. Deep neural nets have shown success in applications such as healthcare (<a href="https://arxiv.org/abs/1804.04591"><em>Ulloa et al., 2018;</em></a><em> </em><a href="https://academic.oup.com/sleep/article/43/12/zsaa120/5859167?login=false"><em>Li et al. (2020a)</em></a>; <a href="https://www.sciencedirect.com/science/article/pii/S1053811920307734?via%3Dihub"><em>Billot et al. (2020)</em></a><em>), </em>national defense (<a href="https://www.sciencedirect.com/science/article/abs/pii/S0957417424004810"><em>Gao et. al. (2023)</em></a>; <a href="https://www.sciencedirect.com/science/article/pii/S030324342100163X"><em>Osco et al., 2021</em></a><em>), </em>and of course finance (<a href="https://fbr.springeropen.com/articles/10.1186/s11782-020-00082-6"><em>Huang et al., 2020</em></a>; <a href="https://www.mdpi.com/2673-2688/5/4/101"><em>Mienye et al., 2024</em></a>; <a href="https://www.mdpi.com/2076-3417/13/3/1956"><em>Mokhade et al., 2023</em></a><em>).</em></p><p>Deep learning algorithms have been shown to have particular use in financial applications. This is due to their proven ability to handle and process large datasets and their ability to deal with complex, nonlinear relationships, which many financial tasks require. Neural networks such as <em>Recurrent Neural Networks</em> or <strong>RNNs</strong> are well suited for analyzing sequential data (like that of economic time series data) [7], <strong>Transformer</strong> architectures have been shown to handle processing large datasets and analyze sentiment data [8], and <strong>Deep Reinforcement</strong> models have been used for optimizing trading strategies and portfolios alike [9]. As with the plethora of other fields it has found use in thus far, deep learning has shown the ability to change the way financial tasks are approached and handled.</p><p><strong>Deep Learning in Portfolio Optimization</strong></p><p>For the task of portfolio optimization, there are multiple ways deep learning can help on top of Modern Portfolio Theory. One example would be when it comes to the process of calculating the expected returns of the assets in the portfolio for MVO. This process would usually involve finding the average of the asset’s historical returns or forecasts based on fundamental factors (such as earnings projections or industry trends). However, RNNs and their time series capability may show a possible new option. RNNs can be trained to learn the patterns of stock data and predict future returns based on the patterns it learns. These returns can be used for the MVO and can be more accurate than just going off of historical returns [10].</p><p>Another example is the use of Deep Reinforcement models for portfolio allocation [11]. The system is trained on historical financial data in order to learn optimal allocation strategies. The system is then given some type of reward to optimize (like Sharpe Ratio for example), and allocates weights to each asset to maximize the reward. The weights represent what percentage of your portfolio belongs to each stock (for instance a weight of .23 represents a certain asset being 23% of your total portfolio). This is useful as it provides a way to <em>dynamically</em> change the weight allocations for your assets, allowing it to update to market changes <strong>in real time</strong>.</p><p><strong>Conclusion</strong></p><p>In conclusion, portfolio optimization is an important part of any investment strategy. Modern Portfolio Theory gives us a way to address the problem of portfolio optimization by providing ways to quantify and assess the risk associated with the assets in our portfolio, along with an ability to weigh that risk along with the returns we get from our portfolio. Meanwhile, deep learning, a subfield of <em>Machine Learning</em> within the broader domain of <strong><em>Artificial Intelligence</em></strong>, has emerged as a powerful tool for tackling complex problems across various industries, including finance. In recent years, deep learning has demonstrated significant potential in financial applications, such as stock price prediction and trading strategy optimization [12]. There has also been research into using DL models and techniques in the area of portfolio optimization such as for predicting expected returns [10] or dynamically rebalancing portfolio allocations [11]. These advancements highlight the transformative role deep learning can play in refining financial strategies and reshaping how we approach investing.</p><p>As deep learning continues to evolve, its integration into portfolio management holds great promise for improving investment outcomes and driving innovation in the financial industry.</p><h4><strong><em>References</em></strong></h4><p>[1] <a href="https://www.investopedia.com/terms/m/modernportfoliotheory.asp">https://www.investopedia.com/terms/m/modernportfoliotheory.asp</a></p><p>[2] <a href="https://www.investopedia.com/terms/m/meanvariance-analysis.asp">https://www.investopedia.com/terms/m/meanvariance-analysis.asp</a></p><p>[3] <a href="https://www.investopedia.com/terms/s/sharperatio.asp">https://www.investopedia.com/terms/s/sharperatio.asp</a></p><p>[4] <a href="https://www.investopedia.com/articles/07/portfolio-history.asp">https://www.investopedia.com/articles/07/portfolio-history.asp</a></p><p>[5] Markowitz, Harry. “Portfolio Selection.” <em>The Journal of Finance</em>, vol. 7, no. 1, 1952, pp. 77–91. JSTOR, <a href="https://doi.org/10.2307/2975974.">https://doi.org/10.2307/2975974.</a></p><p>[6] <a href="https://www.ibm.com/think/topics/deep-learning">https://www.ibm.com/think/topics/deep-learning</a></p><p>[7] Fischer, T., &amp; Krauss, C. (2018). <em>Deep learning with long short-term memory networks for financial market predictions</em>. European Journal of Operational Research. DOI: 10.1016/j.ejor.2018.05.054</p><p>[8] Hu, Z., Liu, W., &amp; Bian, J. (2018). <em>Listening to Chaotic Whispers: A Deep Learning Framework for News-oriented Stock Trend Prediction</em>. Proceedings of the 11th ACM International Conference on Web Search and Data Mining (WSDM). DOI: 10.1145/3159652.3159659</p><p>[9] Deng, Y., et al. (2017). <em>Deep direct reinforcement learning for financial signal representation and trading</em>. IEEE Transactions on Neural Networks and Learning Systems. DOI: 10.1109/TNNLS.2016.2582790</p><p>[10] Chen, Yuzhe, and Hongming Zhang. “Optimal Portfolio Model Based on LSTM Neural Network and Markowitz Theory.” <em>Proceedings of the 2023 International Conference on Financial Innovation and Economic Development</em>, Association for Computing Machinery, 2023, pp. 45–50. <a href="https://doi.org/10.1145/3584816.3584820.">https://doi.org/10.1145/3584816.3584820.</a></p><p>[11] Jiang, Z., Xu, D., &amp; Liang, J. (2017).<strong> </strong><em>A deep reinforcement learning framework for the financial portfolio management problem. </em>Proceedings of the 25th ACM International Conference on Advances in Geographic Information Systems. DOI: 10.1145/3132847.3132886</p><p>[12] Mienye, Ebikella, et al. “Deep Learning in Finance: A Survey of Applications and Techniques.” <em>AI</em>, vol. 5, no. 4, 2024, p. 101. <a href="https://doi.org/10.3390/ai5040101.">https://doi.org/10.3390/ai5040101.</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=103a48bdf094" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>