<?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 Alwan Alkautsar on Medium]]></title>
        <description><![CDATA[Stories by Alwan Alkautsar on Medium]]></description>
        <link>https://medium.com/@kautsr?source=rss-b190c0874170------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*MPuSmPbgbPF0tloXL5u6VQ@2x.jpeg</url>
            <title>Stories by Alwan Alkautsar on Medium</title>
            <link>https://medium.com/@kautsr?source=rss-b190c0874170------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Sun, 06 Dec 2026 10:51:10 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@kautsr/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[Can You Quantify the Quality of a 10-K Without an LLM?]]></title>
            <description><![CDATA[<div class="medium-feed-item"><p class="medium-feed-image"><a href="https://medium.com/algocraft/can-you-quantify-the-quality-of-a-10-k-without-an-llm-4d230daac71c?source=rss-b190c0874170------2"><img src="https://cdn-images-1.medium.com/max/2160/1*el7lAVDTn0kXNtgIY_RlYw.png" width="2160"></a></p><p class="medium-feed-snippet">A reproducible, deterministic approach to SEC filing analysis validated on 478 S&amp;P 500 firms against independent academic benchmarks</p><p class="medium-feed-link"><a href="https://medium.com/algocraft/can-you-quantify-the-quality-of-a-10-k-without-an-llm-4d230daac71c?source=rss-b190c0874170------2">Continue reading on AlgoCraft »</a></p></div>]]></description>
            <link>https://medium.com/algocraft/can-you-quantify-the-quality-of-a-10-k-without-an-llm-4d230daac71c?source=rss-b190c0874170------2</link>
            <guid isPermaLink="false">https://medium.com/p/4d230daac71c</guid>
            <category><![CDATA[investment]]></category>
            <category><![CDATA[data-science]]></category>
            <category><![CDATA[open-source]]></category>
            <category><![CDATA[artificial-intelligence]]></category>
            <category><![CDATA[machine-learning]]></category>
            <dc:creator><![CDATA[Alwan Alkautsar]]></dc:creator>
            <pubDate>Tue, 30 Jun 2026 15:58:49 GMT</pubDate>
            <atom:updated>2026-06-30T15:58:49.501Z</atom:updated>
        </item>
        <item>
            <title><![CDATA[Implementation of AI Starts with Good Data Quality: A Compelete Guide to Training Data Development]]></title>
            <link>https://medium.datadriveninvestor.com/implementation-of-ai-starts-with-good-data-quality-a-compelete-guide-to-training-data-development-18cd96250710?source=rss-b190c0874170------2</link>
            <guid isPermaLink="false">https://medium.com/p/18cd96250710</guid>
            <category><![CDATA[data-engineering]]></category>
            <category><![CDATA[data-science]]></category>
            <category><![CDATA[artificial-intelligence]]></category>
            <category><![CDATA[machine-learning]]></category>
            <dc:creator><![CDATA[Alwan Alkautsar]]></dc:creator>
            <pubDate>Mon, 15 Jun 2026 03:05:39 GMT</pubDate>
            <atom:updated>2026-06-15T03:05:39.307Z</atom:updated>
            <content:encoded><![CDATA[<h3>Implementation of AI Starts with Good Data Quality: A Guide to Training Data Development</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/700/1*wXGfQv3tf9oWJFnX39mtLg.gif" /></figure><p>For the past few years, we have seen AI revolutionizing industries at an unprecedented rate. It drives automation, insight, and innovation. Various sectors are racing to integrate AI in their operations. In banking, for example, has been one of the forefronts in AI implementation, where it is used in various processes such as fraud detection, onboarding process improvement, enhancement of knowledge management systems, and streamlining customer support.</p><p>One crucial aspect often overlooked in AI implementation is the quality of the data fueling it. Bad data leads to bad results, which can lead to poor decision-making. Some scholars have dubbed data awareness as the ‘last mile’ gap between AI implementation and operations. The traditional model-centric approach focuses solely on iterating the model by developing state-of-the-art algorithms with minimal effort to improve and maintain the data quality it relies on during the development cycle. In model-centric AI development, data engineering is usually a one-time task, with the majority of emphasis going toward the iteration and enhancement of the model algorithms<strong>.</strong> This raises the question: Are performance gains due to actual model improvements or simply the model that overfits the training data?</p><p>Data-centric AI shifts the focus toward ensuring data quality, labeling, and maintenance are prioritized throughout AI development. This approach emphasizes that better data will have a more significant impact on the model’s performance than just refining the algorithms. A good data-centric AI strategy will not only improve the performance of AI models but also increase the amount of high-value data available to the model, ultimately making AI more scalable and dependable.</p><h3>Deeper Dive to Training Data Development</h3><p>Training data development is a critical aspect of building effective AI models. The quality and preparation of the data will directly influence the model’s performance and dependability. The training data development process can be broken down into several key stages. Each stage plays a specific role in transforming raw data into a refined dataset that can maximize the performance of AI models. This process can be segmented into five stages: 1) data collection, 2) data labeling, 3) data preparation, 4) data reduction, and 5) data augmentation <em>(Zha et al., 2023). </em>Let’s breakdown each of the stages one by one.</p><h4>Data Collection</h4><p>Data collection is the process of gathering datasets. Data can be collected through primary and secondary means:</p><p>(1) <strong>Primary data collection </strong>is when you directly gather the data from its sources; for example, to understand user preference of your product, you provide feedback forms for them to fill in and give feedback of their experience.</p><p>(2) <strong>Secondary data collection</strong> means you collect the data from a readily available database, like using an open-source dataset (like Kaggle or Google Dataset Search) or even using APIs to directly feed it into your system, especially if you need your datasets to be regularly updated. This might apply when you’re collecting weather data, social media updates, or even stock prices.</p><h4>Data Labelling</h4><p>Data labelling is the process of assigning the metadata to the collected datasets. Metadata describes the properties, structure, and significance of your data, giving the user crucial context of what the data stored is about; this is why metadata is also often referred to as “data about data.” Generally, there are two approaches when it comes to data labeling:</p><p>(1) <strong>Manual data labeling</strong>, which involves human annotators, is commonly used for complex tasks like object recognition in images, like what you’re doing with Captcha.</p><p>(2) <strong>Automated data labeling</strong>, such as programmatic labeling, will make use of rules, heuristics, or models to automatically label huge datasets. This serves to keep things consistent and avoid potential errors that come with human labeling.</p><h4>Data Preparation</h4><p>After the data is labelled, it’s crucial to ensure that the data is accurate and well-organized. Data preparation is the process of transforming raw data into something more structured and clean, making it ready to be trained into your model. Data preparation involves two main processes:</p><p>(1) <strong>Data cleaning</strong> has the objective to remove noises and errors in your data; this is done by removing duplicates, handling missing values, and ensuring consistency across the dataset.</p><p>(2) <strong>Data preprocessing</strong> transforms your data into a format suitable for model training; methods to preprocess data may include standardization and normalization for numerical data or tokenization for text-based data.</p><h4>Data Reduction</h4><p>Data reduction is the process of simplifying and reducing the size of the dataset while preserving its information. The objective is to simplify and make the data more understandable, which potentially could lead to better performance. Among the many methods of data reduction, some of the popular methods are:</p><p>(1) <strong>dimensionality reduction, </strong>which is done by reducing the dimension of the model and</p><p>(2) <strong>feature selection, </strong>where you reduce the data by only using the subset of the most relevant features from the dataset.</p><p>Both methods aim to improve model performance with the objective to avoid overfitting, which might result from an increased number of variables or features, as this could lead to an increase in the complexity of the model.</p><h4>Data Augmentation</h4><p>Data augmentation is a technique used to artificially increase the size and diversity of a dataset without collecting new data. Data augmentation works to generate variants that enhance the performance of the model as well as its robustness by implementing different modifications to the current data.</p><p>Methods to augment data vary depending on the type of data you’re working with. For example, in the case of image data, basic manipulations can be done by flipping, rotating, or cropping the images. Such transformations help in creating new variations of your existing data, thereby increasing the robustness of a model by considering different conditions.</p><p>All in all, implementation of an effective AI model starts with good data quality, with data-centric approaches emphasizing the importance of developing and maintaining well-prepared, high-quality data throughout the AI development lifecycle. While traditional model-centric approaches focus primarily on model optimization, a data-centric approach recognizes that better data can significantly enhance AI performance. The stages of training data development, from collection to augmentation, ensure that raw data is transformed into a refined dataset that will drive robust and scalable AI models, making it more adaptable and reliable in real-world applications.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=18cd96250710" width="1" height="1" alt=""><hr><p><a href="https://medium.datadriveninvestor.com/implementation-of-ai-starts-with-good-data-quality-a-compelete-guide-to-training-data-development-18cd96250710">Implementation of AI Starts with Good Data Quality: A Compelete Guide to Training Data Development</a> was originally published in <a href="https://medium.datadriveninvestor.com/">DataDrivenInvestor</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[How Tracking Options Hedging Pressure can Reveal Short-Term Price Momentum]]></title>
            <description><![CDATA[<div class="medium-feed-item"><p class="medium-feed-image"><a href="https://medium.com/algocraft/how-tracking-options-hedging-pressure-can-reveal-short-term-price-momentum-9fd8141d23cc?source=rss-b190c0874170------2"><img src="https://cdn-images-1.medium.com/max/2240/1*DLbiV6g7FRDeIkdp3vwReQ.png" width="2240"></a></p><p class="medium-feed-snippet">Can Options Hedging Pressure Predict Short-Term Stock Returns?</p><p class="medium-feed-link"><a href="https://medium.com/algocraft/how-tracking-options-hedging-pressure-can-reveal-short-term-price-momentum-9fd8141d23cc?source=rss-b190c0874170------2">Continue reading on AlgoCraft »</a></p></div>]]></description>
            <link>https://medium.com/algocraft/how-tracking-options-hedging-pressure-can-reveal-short-term-price-momentum-9fd8141d23cc?source=rss-b190c0874170------2</link>
            <guid isPermaLink="false">https://medium.com/p/9fd8141d23cc</guid>
            <category><![CDATA[quantitative-finance]]></category>
            <category><![CDATA[options-trading]]></category>
            <category><![CDATA[data-science]]></category>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[algorithmic-trading]]></category>
            <dc:creator><![CDATA[Alwan Alkautsar]]></dc:creator>
            <pubDate>Wed, 10 Jun 2026 07:47:56 GMT</pubDate>
            <atom:updated>2026-06-11T03:24:35.621Z</atom:updated>
        </item>
        <item>
            <title><![CDATA[Why I Built a Terminal-Based Bloomberg Alternative for ETF Research and Portfolio Analytics]]></title>
            <link>https://medium.com/algocraft/why-i-built-a-terminal-based-bloomberg-alternative-for-etf-research-and-portfolio-analytics-c7c54b12fafb?source=rss-b190c0874170------2</link>
            <guid isPermaLink="false">https://medium.com/p/c7c54b12fafb</guid>
            <category><![CDATA[etf]]></category>
            <category><![CDATA[data-science]]></category>
            <category><![CDATA[investing]]></category>
            <category><![CDATA[open-source]]></category>
            <category><![CDATA[quantitative-finance]]></category>
            <dc:creator><![CDATA[Alwan Alkautsar]]></dc:creator>
            <pubDate>Mon, 01 Jun 2026 15:16:01 GMT</pubDate>
            <atom:updated>2026-06-01T15:16:54.025Z</atom:updated>
            <content:encoded><![CDATA[<p>If you have ever tried to build a custom portfolio analyzer or an ETF research pipeline, you’ve inevitably hit the same brick wall: the financial data tax.</p><p>To answer basic questions like:</p><p><em>“What is my true, aggregate exposure to Nvidia across all the ETFs I own?”</em></p><p>or</p><p><em>“How much overlap is there between these three funds?”,</em></p><p>You are forced to make a compromise. You either pay hundreds of dollars a month for institutional data APIs (Morningstar, Bloomberg, or FactSet), or you upload your private portfolio positions to a third-party SaaS dashboard that sells your data, tracks your habits, and locks advanced analytics behind a subscription paywall.</p><p>To tackle this, I built <a href="https://github.com/alwank/etfray"><strong>ETFray</strong></a>: an open-source, terminal-based ETF research and portfolio analytics suite written in Python and powered by the modern TUI framework Textual.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*tQNoJBp-XDSW3qufW0S8Cw.png" /></figure><p>Here is the story of how it works under the hood, how I bypassed paid data providers using the SEC’s database, and how you can use it to audit your own investments.</p><h3><strong>Bypassing Paid APIs with SEC EDGAR N-PORT Filings</strong></h3><p>The core challenge of any ETF analysis tool is acquiring holdings data. An ETF is a basket of underlying stocks, and those baskets change. If you don’t know the exact daily or monthly holdings of an ETF, you can’t calculate your actual sector exposure, geographic risk, or stock concentration.</p><p>Instead of paying an expensive financial data aggregator, I solved this by implementing a combining data from three different Source</p><h4>Source 1: SEC EDGAR N-PORT Filings</h4><p>Under SEC rules, registered management investment companies (which include mutual funds and ETFs) are legally mandated to file Form N-PORT on a quarterly basis. Form N-PORT contains a complete portfolio holdings disclosure, structured in XML format, and it is made publicly available on the SEC’s EDGAR database.</p><p>By writing an automated, rate-limited parser that queries EDGAR, <strong>ETFray</strong> pulls the official, institutional-grade holdings XML filings directly to your machine.</p><h4>Source 2: Real-Time Web Scraping</h4><p>Because SEC filings are published with a slight regulatory lag, relying <em>only</em> on N-PORT filings would mean your holdings calculations might occasionally be a few weeks behind real-time rebalancing.</p><p>To bridge this gap, I implement a <strong>web scraping engine</strong>. When you need instant visibility, you can switch the data source on the holding view for the app to scrapes live holdings directly from public web directories.</p><h4>Source 3: yfinance Integration</h4><p>Holding lists are useless without live market evaluations. To bring raw share quantities and historical allocations to life, I incorporate yfinance to fetch real-time market quotes, key fund statistics, and deep historical price metrics.</p><h3>Deep-Dive Features: What ETFray Can Do</h3><h4>Instant ETF Search &amp; Holdings Inspection</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*k2tvkbWMf2-HG4-3Q1Iv6Q.png" /></figure><p>At the heart of the research tab is the <strong>Interactive ETF Explorer</strong>. When you search for any ticker, ETFray orchestrates its dual-source approach asynchronously:</p><ol><li><strong>Local SQLite Cache:</strong> It first checks your local database.</li><li><strong>Scraper Fallback:</strong> If the ticker is missing, it runs a web scraper to fetch live holdings immediately, populating your UI instantly.</li><li><strong>EDGAR Sync:</strong> Simultaneously, it queues a rate-limited fetch for the official N-PORT XML record to cache authoritative disclosures on your machine.</li></ol><p>When you have selected a ticker, you can navigate to Holdings Page where the TUI will show:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*pWlm9NRWkn8X4S97rULGZQ.png" /></figure><ul><li><strong>Asset Name &amp; Ticker:</strong> Decoded identifiers mapping institutional holdings to recognizable retail tickers.</li><li><strong>Weight Percentages :</strong> Representing the relative size of each holdingin the fund.</li><li><strong>Total Value &amp; Quantity:</strong> Deep regulatory values showing the absolute scale of the fund’s commitment.</li></ul><h4>The True Portfolio “Lookthrough”</h4><p>When you look at your broker dashboard, it tells you that you own 10 shares of VOO and 15 shares of QQQM. But what do you actually own? Both of those funds hold massive stakes in Apple, Microsoft, and Nvidia.</p><p>ETFray performs a recursive <strong>portfolio lookthrough</strong>. It pulls your live IBKR positions, fetches the underlying holdings for every ETF in your portfolio, and flattens them. Accessing the ETF Lookhrough menu on ETFray instantly rolls this up to show you your true stock concentration:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Sy1HVZ-umsVY2ag_6qwWTQ.png" /></figure><h4>Rich Terminal Seasonality Charts</h4><p>To analyze historical trends without leaving the terminal, ETFray implements <strong>Seasonals</strong>. It pulls historical price data from Yahoo Finance and computes year-over-year cumulative returns.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*FreEcEwhpiJS0wC8tW4zyQ.png" /><figcaption>Seasonals — Chart</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*puQamA8-8fCKk-_V8zrCEQ.png" /><figcaption>Seasonals — Table</figcaption></figure><p>If your terminal supports modern graphics protocols (like <strong>S</strong>ixel, Kitty, or VS Code’s integrated terminal), I used Matplotlib to render a crisp, high-resolution vector chart directly inside your terminal pane. If you are on a legacy terminal, it gracefully falls back to an optimized Unicode/ASCII layout using Plotext.</p><h3>Getting Started</h3><p>Because etfray is packaged cleanly in Python, you can spin it up on your machine in under a minute.</p><h4>1. Quick Installation</h4><p>Install the core application via pip:</p><pre>pip install etfray</pre><p>If you want the high-resolution vector charts in your terminal, install the optional chart dependencies:</p><pre>pip install &quot;etfray[charts]&quot;</pre><p><em>Note: For crisp, high-resolution terminal images, ensure your terminal supports image rendering (Cursor/VS Code terminal, iTerm2, Kitty, WezTerm, or Windows Terminal 1.22+).</em></p><h4>2. Run It</h4><p>Simply run:</p><pre>etfray</pre><h4>3. Add Your SEC Identity</h4><p>The SEC requires all programmatic users to declare a user-agent header containing an email address for fair-use tracking. Navigate to <strong>Workspace → Settings</strong> in the sidebar and input your email. This identity is only used to query the official EDGAR endpoints directly from your machine — no third-party ever sees it.</p><h3>Wrap-up</h3><p>ETFray is a love letter to open-source software, local-first architectures, and the terminal. It proves that you don&#39;t need to surrender your privacy or pay thousands of dollars in subscriptions to run institutional-grade financial analytics.</p><p>By combining Python&#39;s scientific ecosystem, the regulatory transparency of SEC disclosures, and the modern UI capabilities of Textual, we can build tools that rival expensive proprietary dashboards right in our command line.</p><p><strong>ETFray</strong> <strong>has also recently been featured on the </strong><a href="https://github.com/wilsonfreitas/awesome-quant"><strong>Awesome Quant</strong></a><strong> list, </strong>the definitive curated directory of the world&#39;s best open-source quantitative finance projects! It&#39;s a huge milestone that validates our mission of making institutional-grade financial research accessible, private, and completely free.</p><ul><li>Visit the <a href="https://etfray.xyz/"><strong>ETFray Official Website</strong></a><strong>.</strong></li><li>Check out the <a href="https://github.com/alwank/etfray"><strong>ETFray GitHub Repository</strong></a> (give it a star if you like it!).</li><li>See our listing on the <a href="https://github.com/wilsonfreitas/awesome-quant"><strong>Awesome Quant List</strong></a>.</li><li>Read the <a href="https://etfray.readthedocs.io/"><strong>Full Documentation on ReadTheDocs</strong></a>.</li></ul><p>Pull requests, feature requests, and feedback are highly appreciated as I plan to build out more advanced stress scenarios and brokerage integrations!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=c7c54b12fafb" width="1" height="1" alt=""><hr><p><a href="https://medium.com/algocraft/why-i-built-a-terminal-based-bloomberg-alternative-for-etf-research-and-portfolio-analytics-c7c54b12fafb">Why I Built a Terminal-Based Bloomberg Alternative for ETF Research and Portfolio Analytics</a> was originally published in <a href="https://medium.com/algocraft">AlgoCraft</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Getting Started with Statistical Arbitrage: A Comprehensive Guide to Pairs Trading in Python]]></title>
            <link>https://medium.com/algocraft/getting-started-with-statistical-arbitrage-a-comprehensive-guide-to-pairs-trading-in-python-d303b0f8415d?source=rss-b190c0874170------2</link>
            <guid isPermaLink="false">https://medium.com/p/d303b0f8415d</guid>
            <category><![CDATA[quantitative-finance]]></category>
            <category><![CDATA[trading-strategy]]></category>
            <category><![CDATA[algorithmic-trading]]></category>
            <category><![CDATA[trading-ideas]]></category>
            <category><![CDATA[data-science]]></category>
            <dc:creator><![CDATA[Alwan Alkautsar]]></dc:creator>
            <pubDate>Sun, 12 Jan 2025 17:31:08 GMT</pubDate>
            <atom:updated>2025-01-12T17:31:08.639Z</atom:updated>
            <content:encoded><![CDATA[<p>There are tons of algorithmic trading strategies out there. Statistical arbitrage is one of the most popular, which is done by utilizing statistical methods to identify significant relationships of the assets.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*V8S6_MR8TsCAORTaloLWOQ.gif" /><figcaption>A robot trading the stock market, generated by OpenAI Sora.</figcaption></figure><p>At its core, a statistical arbitrage trading strategy relies on a mean reversion principle, which assumes that when there are two highly correlated assets, and one of the assets is moving disproportionately compared to the other, a position would be opened by the trader to exploit the short-term fluctuations under the assumption that the prices of both stocks would revert to their historical correlation.</p><p>Although perfect correlation is <em>extremely rare </em>in the market, there are statistical methods that we can employ to find highly correlated stocks. Traders are doing this by examining stocks that exhibit a high degree of comovement (which can be done by correlation analysis or cointegration testing) and would exploit its short-term price fluctuations, which usually are driven by market sentiment or sudden news announcements.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*TNSrztvErPCrwzi1yE6Mfw.png" /><figcaption><strong>Figure 1. </strong>Illustration of temporary mispricing in statistical arbitrage</figcaption></figure><p><strong>Figure 1</strong> illustrates the historical price movements of <strong>Stock A</strong> (blue line) and <strong>Stock B</strong> (red line). Notice how the two stocks have moved closely together over time, demonstrating a strong positive correlation. However, in the most recent period, <strong>Stock B</strong>’s price spikes upward, deviating significantly from its usual relationship with <strong>Stock A</strong>. Traders would address this as a temporary mispricing and would take advantage by executing the following trades:</p><p><strong>Option 1. </strong>Going Long on <strong>Stock A</strong> → Assuming Stock A will rise.</p><p><strong>Option 2. </strong>Going Short on <strong>Stock B</strong> → Assuming Stock B will fall back.</p><p>Both actions are taken under the assumption that either stock will revert toward its historical relationship with each other. Traders can either only take Option 1, only take Option 2, or take both options. When they both take both options, it’s what we refer to as pairs trading.</p><h3><strong>Understanding Pairs Trading</strong></h3><p>Pairs trading is a form of statistical arbitrage. Pairs trading is done by simultaneously taking two positions on a short-term mispricing of highly correlated assets. If we take on previous examples, it means going long on stock A and going short on stock B.</p><p>In pairs trading, trading signals are generated by the price difference (spread) of the two assets that we are pairing. Traders would find assets with high correlation, identify unusually large spreads in comparison to their historical trend, and open simultaneous positions on both assets with the anticipation that this divergence will correct itself.</p><h3>Step-by-Step Guide to Pairs Trading with Python</h3><h4>Importing the Packages</h4><pre>import yfinance as yf<br>import pandas as pd<br>import numpy as np<br>import statsmodels.api as sm<br>import matplotlib.pyplot as plt<br>from itertools import combinations<br>from statsmodels.tsa.stattools import coint</pre><p>The first step to any Python project is to import all the necessary packages that we will use on this strategy. Here’s a breakdown of the packages:</p><ul><li><strong>yfinance: </strong>Fetches historical stock or forex data directly from Yahoo Finance.</li><li><strong>pandas: </strong>Handles data manipulation and cleaning.</li><li><strong>numpy: </strong>Provides mathematical operations and support for arrays.</li><li><strong>statsmodels.api:</strong> Performs statistical analysis for regression analysis and cointegration testing.</li><li><strong>matplotlib.pyplot:</strong> Creates visualizations for data and analysis.</li><li><strong>itertools.combinations:</strong> Finds all possible pairs from a list of stocks or forex pairs.</li><li><strong>statsmodels.tsa.stattools.coint: </strong>Tests for cointegration between two time series, essential for pairs trading.</li></ul><h4>Stock Selection and Identifying Cointegrated Pairs</h4><p>After we import all the libraries, we need to find highly correlated stock pairs to perform our trading strategy on. Let’s list the stocks to analyze. For this example,we will focus on the media and entertainment industry.</p><pre>stocks = [<br>    &quot;DIS&quot;,   # The Walt Disney Company<br>    &quot;NFLX&quot;,  # Netflix, Inc.<br>    &quot;PARA&quot;,  # Paramount Global<br>    &quot;CMCSA&quot;, # Comcast Corporation<br>    &quot;FOX&quot;,   # Fox Corporation (Class B)<br>    &quot;FOXA&quot;,  # Fox Corporation (Class A)<br>    &quot;WBD&quot;,   # Warner Bros. Discovery, Inc.<br>    &quot;ROKU&quot;,  # Roku, Inc.<br>    &quot;SPOT&quot;,  # Spotify Technology S.A.<br>    &quot;LYV&quot;    # Live Nation Entertainment, Inc.<br>]</pre><p>After storing the list of stocks to observe under <strong>stocks, </strong>we will utilize yfinance to fetch the historical data of each stock under the list.</p><pre># Create a dictionary to hold data for each pair<br>data_dict = {}<br><br># Loop over each FX symbol in the list<br>for ticker in stocks:<br>    print(f&quot;Downloading data for: {ticker}&quot;)<br>    data = yf.download(<br>        tickers=ticker,<br>        period=&quot;1y&quot;,        <br>        interval=&quot;1d&quot;<br>    )<br>    <br>    # Store the DataFrame in our dictionary<br>    data_dict[ticker] = data</pre><p>We start by creating an empty dictionary named <strong>data_dict </strong>to hold the data for each stock ticker. Then, we create a <strong>for </strong>loop to iterate over a list of stocks we previously created. For each ticker in the stocks list, we use the <strong>yf.download </strong>function<strong> </strong>from the yfinance library to fetch one year&#39;s worth of daily historical data. Once downloaded, we then store the resulting data in <strong>data_dict</strong>.</p><p><strong>Finding All Unique Stock Pairs Combination</strong></p><p>The first step in identifying cointegrated pairs of stocks in our search space is to generate a list of unique pairs of stocks from the <strong>stocks</strong> list, this can be done by performing the <strong>combinations()</strong> function from the <strong>itertools </strong>package we imported earlier.</p><pre>stock_pairs = list(combinations(stocks, 2))<br>stock_pairs</pre><p>When run, it will generate the following listings:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*KuR0XItN_zC5o5Awga-aag.png" /><figcaption><strong>Figure 2. </strong>Output from the combination() function.</figcaption></figure><p>By printing <strong>stock_pairs,</strong> we found that there are 45 unique pairs of stocks, which we will test for cointegration to see their eligibility to be pair traded.</p><p><strong>Identifying Cointegrated Pairs of Stocks</strong></p><p>To identify cointegrated pairs of stocks, we will perform the Engle-Granger tests from our unique stock list. The Engle-Granger test is a statistical method used to determine if a pair of time series data share a long-term relationship despite being non-stationary individually. It does this by testing if the residuals from a linear regression between the series are stationary.</p><p>To run the Engle-Granger test, we run the following code:</p><pre>results = []  <br><br>for pair in stock_pairs:<br>    sym1, sym2 = pair<br><br>    # Ensure both DataFrames exist in our dictionary<br>    if sym1 not in data_dict or sym2 not in data_dict:<br>        print(f&quot;Data not found for one of these symbols: {sym1}, {sym2}&quot;)<br>        continue<br><br>    # Extract &#39;Adj Close&#39; price series for each symbol<br>    df1 = data_dict[sym1][&quot;Adj Close&quot;]<br>    df2 = data_dict[sym2][&quot;Adj Close&quot;]<br><br>    # Combine into one DataFrame on the same dates (inner join), drop missing values<br>    combined = pd.concat([df1, df2], axis=1, join=&quot;inner&quot;).dropna()<br>    combined.columns = [&quot;Price1&quot;, &quot;Price2&quot;]<br><br>    # If there&#39;s not enough data after alignment, skip<br>    if len(combined) &lt; 10:<br>        continue<br><br>    # Run Engle-Granger cointegration test<br>    coint_t, p_value, critical_values = coint(combined[&quot;Price1&quot;], combined[&quot;Price2&quot;])<br><br>    # Check if p-value &lt; 0.05 for significance<br>    is_significant = (p_value &lt; 0.05)<br><br>    # Store results<br>    results.append({<br>        &quot;Symbol1&quot;: sym1,<br>        &quot;Symbol2&quot;: sym2,<br>        &quot;Test Statistic&quot;: coint_t,<br>        &quot;p-value&quot;: p_value,<br>        &quot;5% Critical Value&quot;: critical_values[0],  # 1%, 5%, 10% in array<br>        &quot;Is_Cointegrated_5pct&quot;: is_significant<br>    })<br>    <br>for res in results:<br>    status = &quot;Cointegrated&quot; if res[&quot;Is_Cointegrated_5pct&quot;] else &quot;Not Cointegrated&quot;<br>    print(<br>        f&quot;{res[&#39;Symbol1&#39;]} &amp; {res[&#39;Symbol2&#39;]} | &quot;<br>        f&quot;Test Statistic: {res[&#39;Test Statistic&#39;]:.3f} | &quot;<br>        f&quot;p-value: {res[&#39;p-value&#39;]:.3f} | &quot;<br>        f&quot;5% Crit. Value: {res[&#39;5% Critical Value&#39;]:.3f} | &quot;<br>        f&quot;Result: {status}&quot;<br>    )</pre><p>Breakdown of above code:</p><ol><li><strong>Initialize Results Storage</strong><br>The <strong>results</strong> list is prepared to store test outcomes for each pair.</li><li><strong>Loop Through Pairs</strong><br>For each pair in <strong>stock_pairs</strong>, we unpack the pair into <strong>sym1 </strong>and <strong>sym2</strong>.<br>It checks whether both symbols have corresponding data in <strong>data_dict</strong>. If not, it logs a message and skips to the next pair.</li><li><strong>Data Alignment</strong><br>The adjusted close prices (<strong>Adj Close</strong>) for <strong>sym1 </strong>and <strong>sym2 </strong>are extracted from the <strong>data_dict</strong>. The two time series are merged into a single DataFrame using an <strong>inner join </strong>to ensure both have data for the same dates, we also use <strong>.dropna() </strong>to drop any missing values.</li><li><strong>Engle-Granger Test</strong><br>Using the <strong>coint()</strong> function from the <strong>statsmodels.tsa.stattools, we </strong>test for cointegration for each pair in our <strong>stock_list</strong>. It returns:<br>The test statistic (<strong>coint_t</strong>).<br>The p-value (<strong>p_value</strong>), indicating the likelihood that the two series are not cointegrated.<br>Critical values at different confidence levels, which we store as <strong>critical_values</strong>.</li><li><strong>Significance Check</strong><br>A p-value below 0.05 indicates significant cointegration at the 5% level. We use 5% as it is a widely used threshold, you are welcome to adjust this parameter as you see fit, like increasing the threshold to 10% if you can’t find any cointegrated. The result for the significance check is stored as <strong>Is_Cointegrated_5pct</strong>.</li><li><strong>Results Storage</strong><br>A dictionary containing the test outcomes for each pair is appended to the results list.</li><li><strong>Return Value</strong><br>The results are printed for each pair, showing the test statistic, p-value, critical value, and whether the pair is cointegrated.</li></ol><p>If there are no errors found upon running the code, the following output will be generated:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*axlg3qN1UOF_UxkYfOhhkg.png" /><figcaption><strong>Figure 3. </strong>Finding Cointegrated Stock Pairs</figcaption></figure><p>If you prefer to see the output in a dataframe, you can run the following code to convert the test result into a dataframe:</p><pre>#Convert Cointegration Test Result to Dataframe<br>results_df = pd.DataFrame(results)<br>results_df</pre><p>Next, let’s shortlist to just show stock pairs that are cointegrated and store it in <strong>cointegrated_pairs</strong>:</p><pre># Filter for rows where Is_Cointegrated_5pct is True<br>filtered_df = results_df[results_df[&#39;Is_Cointegrated_5pct&#39;] == True]<br><br># Create a new list of only the cointegrated pairs<br>cointegrated_pairs = [<br>    (row[&#39;Symbol1&#39;], row[&#39;Symbol2&#39;]) <br>    for _, row in filtered_df.iterrows()<br>]<br><br>print(&quot;Cointegrated Pairs (5% level):&quot;)<br>for cp in cointegrated_pairs:<br>    print(cp)</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*o-MlNJAeUYtt_kyhm6-Uww.png" /><figcaption><strong>Figure 4. </strong>Shortlisted cointegrated stock pairs</figcaption></figure><p>We found that there are 5 stock pairs that For easier analysis, let’s just focus on one pair to analyze. For this example, let’s go with <strong>PARA </strong>and <strong>SPOT.</strong></p><h4>Finding The Spread</h4><p>As I have previously mentioned, signals in pairs trading are generated by the spread of our pair of assets. Therefore, after we found a highly correlated pair, the next step to find its spread and convert it to Z Score.</p><p>We will create a new function, which we’re going to call <strong>analyze_pair.</strong> In this function, we will use the OLS regression model to examine how the price of <strong>PARA </strong>predicts the price of <strong>SPOT</strong>, calculate the spread between the actual and predicted prices, and visualize the results.</p><pre>def analyze_pair(data_dict, sym1, sym2):<br><br>    # Extract &amp; align data<br>    priceX = data_dict[sym1][&quot;Adj Close&quot;].rename(&quot;X&quot;)<br>    priceY = data_dict[sym2][&quot;Adj Close&quot;].rename(&quot;Y&quot;)<br>    df = pd.concat([priceX, priceY], axis=1, join=&quot;inner&quot;).dropna()<br><br>    # If insufficient data remains, exit<br>    if len(df) &lt; 10:<br>        print(f&quot;Not enough overlapping data for {sym1} &amp; {sym2}. Exiting.&quot;)<br>        return None<br><br>    # Prepare &amp; fit OLS model<br>    X = sm.add_constant(df[&quot;X&quot;])  <br>    Y = df[&quot;Y&quot;]<br>    model = sm.OLS(Y, X).fit()<br><br>    # Compute predictions &amp; spread<br>    df[&quot;Y_pred&quot;] = model.predict(X)<br>    df[&quot;Spread&quot;] = df[&quot;Y&quot;] - df[&quot;Y_pred&quot;]<br><br>    # Plot results<br>    plt.figure(figsize=(10, 5))<br>    plt.plot(df.index, df[&quot;Y&quot;], label=f&quot;{sym2} (Actual)&quot;)<br>    plt.plot(df.index, df[&quot;Y_pred&quot;], label=f&quot;{sym2} (Predicted from {sym1})&quot;)<br>    plt.title(f&quot;Pair: {sym1} (X) → {sym2} (Y)&quot;)<br>    plt.legend()<br>    plt.show()<br><br>    plt.figure(figsize=(10, 4))<br>    plt.plot(df.index, df[&quot;Spread&quot;], label=&quot;Spread (Y - Y_pred)&quot;)<br>    plt.axhline(df[&quot;Spread&quot;].mean(), color=&#39;red&#39;, linestyle=&#39;--&#39;, label=&quot;Spread Mean&quot;)<br>    plt.title(f&quot;Spread for {sym1} &amp; {sym2}&quot;)<br>    plt.legend()<br>    plt.show()<br><br>    results_dict = {<br>        &quot;model_params&quot;: model.params,  # alpha (const) and beta<br>        &quot;df&quot;: df,                      # the aligned dataframe with Spread<br>        &quot;summary&quot;: model.summary()     # statsmodels summary object<br>    }<br>    return results_dict</pre><p>Breakdown of above code:</p><ol><li><strong>Function Inputs</strong><br>The function will take a dictionary of historical price data, where each key is a financial asset’s symbol and its value is a DataFrame containing price information.</li><li><strong>Data Extraction and Alignment</strong><br>Extracts the adjusted closing prices for the two specified symbols.<br>And then we will combine price series into a single DataFrame with matching dates and remove any missing data.</li><li><strong>Regression Model Fitting</strong><br>Fits a linear regression model using <strong>sym1 </strong>as the independent variable and <strong>sym2</strong> as the dependent variable.<br>This determines the relationship (slope and intercept) between the two assets’ prices.</li><li><strong>Prediction and Spread Calculation<br></strong>We then will use a regression model to predict the prices of <strong>sym2</strong> based on <strong>sym1 </strong>and calculate the spread between the two input variables.</li><li><strong>Visualization<br></strong>We’re going to visualize two plots with this function:<br>a. A comparison of the actual prices of sym2 against the predicted prices based on the relationship with sym1.<br>b. A plot of the spread over time, highlighting its mean for reference.</li><li><strong>Return Value</strong><br>The function will return a dictionary with the following:<br>a. Regression parameters<br>b. The aligned DataFrame containing the actual prices, predicted prices, and spread.<br>c. A statistical summary of the regression model, including metrics like R-squared and standard errors.</li></ol><p>We can run the <strong>analyze_pair </strong>function by executing the following lines of code:</p><pre>sym1 = &quot;PARA&quot;<br>sym2 = &quot;SPOT&quot;<br>pair_results = analyze_pair(data_dict, sym1, sym2)</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*DdD-d7Lb3yVY1Ee6fCxasQ.png" /><figcaption><strong>Figure 5: </strong>Displaying the spread as the linear regression model&#39;s residuals</figcaption></figure><p>As we can see on the second chart shown in Figure 5, we have successfully visualized the spread as the residuals of the linear regression model. Since spreads may vary among asset classes, it would be ideal to standardize them into a single scalar to facilitate comparison and strategy formulation. We can do this by converting the spread into Z-scores.</p><p><strong>Converting to Z-score</strong></p><p>We use Z-score to measure how many standard deviations the daily spread deviates from its mean. The magnitude of the Z-score indicates the distance from the mean, positive for above the mean and negative for below.</p><p>For stock prices, which are inherently volatile, we use a moving average approach to calculate the running mean and standard deviation. Where each daily spread would have corresponding running mean and standard deviation based on the collection of the spreads in the rolling window.</p><p>In order to convert the spread to z-score, we will create a new function called <strong>convert_zscore:</strong></p><pre>def convert_zscore(df, sym1, sym2, window_size=10):<br>    #Compute rolling mean, rolling std, and Z-score<br>    df[&quot;Spread_MA&quot;] = df[&quot;Spread&quot;].rolling(window_size).mean()<br>    df[&quot;Spread_STD&quot;] = df[&quot;Spread&quot;].rolling(window_size).std()<br>    df[&quot;Zscore&quot;] = (df[&quot;Spread&quot;] - df[&quot;Spread_MA&quot;]) / df[&quot;Spread_STD&quot;]<br><br>    # Visualize the Z-score<br>    plt.figure(figsize=(10, 4))<br>    plt.plot(df.index, df[&quot;Zscore&quot;], label=&quot;Z-Score of Spread&quot;)<br>    plt.axhline(0, color=&quot;black&quot;, linestyle=&quot;--&quot;, lw=1)<br>    plt.axhline(2.0, color=&quot;green&quot;, linestyle=&quot;--&quot;, lw=1, label=&quot;+2 Z&quot;)<br>    plt.axhline(1.0, color=&quot;green&quot;, linestyle=&quot;--&quot;, lw=1, label=&quot;+1 Z&quot;)<br>    plt.axhline(-1.0, color=&quot;red&quot;, linestyle=&quot;--&quot;, lw=1, label=&quot;-1 Z&quot;)<br>    plt.axhline(-2.0, color=&quot;red&quot;, linestyle=&quot;--&quot;, lw=1, label=&quot;-2 Z&quot;)<br>    plt.title(f&quot;Z-Score of Spread (Window={window_size}): {sym1}, {sym2}&quot;)<br>    plt.legend()<br>    plt.show()<br><br>    return df</pre><p>Breakdown of above code:</p><ol><li><strong>Inputs<br></strong>The input takes a dataFrame containing at least a column named<strong> “Spread”</strong>, which represents the difference between the actual and predicted values of two assets of our input variable which will be represented by <strong>sym1 </strong>and <strong>sym2. </strong>Additionally, the last input variable will be <strong>window_size</strong>, which will be the size of the rolling window used to compute the mean and standard deviation.</li><li><strong>Rolling Calculations</strong><br><strong>Rolling Mean (Spread_MA):</strong> Computes the moving average of the “Spread” column over the specified rolling window size.<br><strong>Rolling Standard Deviation (Spread_STD): </strong>Computes the moving standard deviation of the “Spread” column over the rolling window size.<br><strong>Z-Score (Zscore):</strong> Calculates the Z-score for each point in the “Spread” column. The Z-score measures how many standard deviations the current spread deviates from the rolling mean.</li><li><strong>Z-Score Calculation Formula</strong><br>For each row in the DataFrame, we will apply the following formula:<br>(<em>spread -spread mean) / spread standard deviation</em></li><li><strong>Visualization</strong><br>We further will plot the Z-score over time. Additionally, for easy viewing, we also add horizontal reference lines at key Z-score levels to easily identify the the deviation from its means.</li><li><strong>Return Value</strong><br>The function returns the updated <strong>df</strong>, which now contains three new columns:<br><strong>Spread_MA:</strong> Rolling mean of the spread.<br><strong>Spread_STD:</strong> Rolling standard deviation of the spread.<br><strong>Zscore:</strong> Z-score of the spread.</li></ol><p>We can run the <strong>analyze_pair </strong>function by executing the following lines of code:</p><pre>df_zscore = convert_zscore(pair_results_df, sym1, sym2, window_size=10)</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*dk2kTagBsTMsDUAz2QXe0w.png" /><figcaption><strong>Figure 6. </strong>Visualizing the z-scores after standardizing the spreads using the running mean and standard deviation</figcaption></figure><h4>Trading Strategy Formulation and Backtesting</h4><p>After successfully converting the spread into Z-scores, we can use them to generate trading signals:</p><ul><li><strong>Long Entry</strong>: Enter a long position in the first stock when the Z-score falls below a preset negative threshold (e.g., -2).</li><li><strong>Long Exit</strong>: Exit the long position in the first stock when the Z-score crosses above a less extreme negative threshold (e.g., -1).</li><li><strong>Short Entry</strong>: Enter a short position in the second stock when the Z-score exceeds a preset positive threshold (e.g., 2).</li><li><strong>Short Exit</strong>: Exit the short position in the second stock when the Z-score crosses below a less extreme positive threshold (e.g., 1).</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*_t7p1ru_ncZYbxrehlvGlg.png" /><figcaption><strong>Figure 7. </strong>Formulation of trading signals based on the threshold of z-scores</figcaption></figure><p>Now let’s get into coding the strategy by creating a new function called <strong>run_pair_trading</strong>:</p><pre>def run_pair_trading(sym1, sym2, data_dict, df_zscore, window_size=10, initial_equity=100_000.0):<br>    # 1) Align close prices<br>    df1 = data_dict[sym1][&quot;Adj Close&quot;].rename(&quot;X&quot;)<br>    df2 = data_dict[sym2][&quot;Adj Close&quot;].rename(&quot;Y&quot;)<br>    df = pd.concat([df1, df2], axis=1, join=&quot;inner&quot;).dropna().sort_index()<br><br>    if len(df) &lt; window_size:<br>        return {<br>            &quot;df&quot;: None,<br>            &quot;metrics&quot;: f&quot;Not enough data for {sym1}-{sym2}&quot;,<br>            &quot;trades_df&quot;: pd.DataFrame()<br>        }<br>   <br>    df = df.join(df_zscore, how=&quot;inner&quot;, rsuffix=&quot;_zscore&quot;)<br><br>    if &quot;Zscore&quot; not in df or df[&quot;Zscore&quot;].isna().all():<br>        return {<br>            &quot;df&quot;: None,<br>            &quot;metrics&quot;: f&quot;Missing or invalid Zscore data for {sym1}-{sym2}&quot;,<br>            &quot;trades_df&quot;: pd.DataFrame()<br>        }<br><br>    # 2) Determine positions on each pair<br>    df[&quot;x_position&quot;] = np.nan<br>    df[&quot;y_position&quot;] = np.nan<br><br>    # zscore &gt; 2 =&gt; Short X, Long Y<br>    df.loc[df[&quot;Zscore&quot;] &gt; 2, [&quot;x_position&quot;, &quot;y_position&quot;]] = [-1, 1]<br><br>    # -1 &lt; zscore &lt; 1 =&gt; Exit<br>    df.loc[(df[&quot;Zscore&quot;] &gt; -1) &amp; (df[&quot;Zscore&quot;] &lt; 1), [&quot;x_position&quot;, &quot;y_position&quot;]] = [0, 0]<br><br>    # zscore &lt; -2 =&gt; Long X, Short Y<br>    df.loc[df[&quot;Zscore&quot;] &lt; -2, [&quot;x_position&quot;, &quot;y_position&quot;]] = [1, -1]<br><br>    # Forward-fill positions in between signals<br>    df[&quot;x_position&quot;] = df[&quot;x_position&quot;].ffill().fillna(0)<br>    df[&quot;y_position&quot;] = df[&quot;y_position&quot;].ffill().fillna(0)<br><br>    # 3) Calculate daily returns from each pair<br>    df[&quot;x_return&quot;] = df[&quot;X&quot;].pct_change().fillna(0.0)<br>    df[&quot;y_return&quot;] = df[&quot;Y&quot;].pct_change().fillna(0.0)<br><br>    # Equity Allocation<br>    df[&quot;x_notional&quot;] = 0.02 * initial_equity<br>    df[&quot;y_notional&quot;] = 0.02 * initial_equity<br><br>    # Daily PnL for each pair<br>    df[&quot;daily_pnl_x&quot;] = df[&quot;x_position&quot;].shift(1) * df[&quot;x_notional&quot;] * df[&quot;x_return&quot;]<br>    df[&quot;daily_pnl_y&quot;] = df[&quot;y_position&quot;].shift(1) * df[&quot;y_notional&quot;] * df[&quot;y_return&quot;]<br>    df[[&quot;daily_pnl_x&quot;, &quot;daily_pnl_y&quot;]] = df[[&quot;daily_pnl_x&quot;, &quot;daily_pnl_y&quot;]].fillna(0.0)<br><br>    df[&quot;daily_pnl&quot;] = df[&quot;daily_pnl_x&quot;] + df[&quot;daily_pnl_y&quot;]<br>    df[&quot;equity&quot;] = initial_equity + df[&quot;daily_pnl&quot;].cumsum()<br><br>    # 4) Performance metrics<br>    final_equity = df[&quot;equity&quot;].iloc[-1]<br>    total_return_pct = (final_equity - initial_equity) / initial_equity<br><br>    df[&quot;equity_return&quot;] = df[&quot;equity&quot;].pct_change().fillna(0.0)<br>    ann_factor = 252<br>    mean_daily_ret = df[&quot;equity_return&quot;].mean()<br>    std_daily_ret = df[&quot;equity_return&quot;].std()<br><br>    if std_daily_ret != 0:<br>        sharpe_ratio = (mean_daily_ret / std_daily_ret) * np.sqrt(ann_factor)<br>    else:<br>        sharpe_ratio = np.nan<br><br>    neg_returns = df.loc[df[&quot;equity_return&quot;] &lt; 0, &quot;equity_return&quot;]<br>    std_downside = neg_returns.std() if not neg_returns.empty else np.nan<br>    if std_downside and std_downside != 0:<br>        sortino_ratio = (mean_daily_ret / std_downside) * np.sqrt(ann_factor)<br>    else:<br>        sortino_ratio = np.nan<br><br>    df[&quot;running_max&quot;] = df[&quot;equity&quot;].cummax()<br>    df[&quot;drawdown&quot;] = (df[&quot;equity&quot;] / df[&quot;running_max&quot;]) - 1<br>    max_drawdown = df[&quot;drawdown&quot;].min()<br><br>    # 5) Trade-by-trade details<br>    df[&quot;trade_signal&quot;] = (df[&quot;x_position&quot;].diff().abs() &gt; 0) | (df[&quot;y_position&quot;].diff().abs() &gt; 0)<br>    trades = df[df[&quot;trade_signal&quot;]].copy()<br>    trades[&quot;entry_date&quot;] = trades.index<br>    trades[&quot;exit_date&quot;] = trades[&quot;entry_date&quot;].shift(-1)<br>    trades[&quot;pnl&quot;] = trades[&quot;daily_pnl&quot;]<br>    trades[&quot;x_position&quot;] = trades[&quot;x_position&quot;]<br>    trades[&quot;y_position&quot;] = trades[&quot;y_position&quot;]<br><br>    trades_df = trades[[&quot;entry_date&quot;, &quot;exit_date&quot;, &quot;x_position&quot;, &quot;y_position&quot;, &quot;pnl&quot;]]<br>    num_trades = len(trades_df)<br>    win_rate = (trades_df[trades_df[&quot;pnl&quot;] &gt; 0].shape[0] / num_trades) if num_trades &gt; 0 else np.nan<br><br>    metrics = {<br>        &quot;sym1&quot;: sym1,<br>        &quot;sym2&quot;: sym2,<br>        &quot;final_equity&quot;: final_equity,<br>        &quot;total_return_pct&quot;: total_return_pct,<br>        &quot;sharpe_ratio&quot;: sharpe_ratio,<br>        &quot;sortino_ratio&quot;: sortino_ratio,<br>        &quot;max_drawdown_pct&quot;: max_drawdown,<br>        &quot;num_trades&quot;: num_trades,<br>        &quot;win_rate_pct&quot;: 100.0 * win_rate if not np.isnan(win_rate) else np.nan<br>    }<br><br>    return {<br>        &quot;df&quot;: df,<br>        &quot;metrics&quot;: metrics,<br>        &quot;trades_df&quot;: trades_df<br>    }</pre><ol><li><strong>Align Data</strong><br>First we need to align the adjusted close prices of the two assets and ensure data consistency. First is to check if there’s enough overlapping data to run the analysis, and then join the aligned price data with the Z-score data <strong>(df_zscore) </strong>to include the spread’s standardized values.</li><li><strong>Generate Trading Signals</strong><br>Long/Short Signals:<br><strong>Z-score &gt; 2:</strong> Go short on the first asset <strong>(sym1) </strong>and long on the second <strong>(sym2)</strong>.<br><strong>Z-score &lt; -2:</strong> Go long on the first asset <strong>(sym1)</strong> and short on the second <strong>(sym2)</strong>.<br><strong>-1 &lt; Z-score &lt; 1:</strong> Exit all positions.<br>Positions are forward-filled to maintain positions until a new signal is triggered.</li><li><strong>Calculate Daily Returns and Equity Changes</strong><br><strong>Daily Returns:</strong> Computes percentage changes in prices for both assets.<br><strong>Equity Allocation: </strong>Allocates<strong> 2%</strong> of the initial equity to each asset for trading.<br><strong>Daily PnL:</strong><br> — Multiplies positions by notional value and daily returns to compute profit/loss for each asset.<br> — Sums the PnL of both assets to get the total daily PnL.<br><strong>Equity Update: </strong>Tracks the cumulative equity over time by adding daily PnL to the initial equity.</li><li><strong>Performance Metrics</strong><br><strong>Final Equity: </strong>The total value of the portfolio at the end of the simulation.<br><strong>Total Return: </strong>Percentage return from initial equity to final equity.<br><strong>Sharpe Ratio:</strong> Measures risk-adjusted returns based on mean and standard deviation of daily returns.<br><strong>Sortino Ratio:</strong> Similar to the Sharpe Ratio but only considers downside volatility (negative returns).<br><strong>Max Drawdown: </strong>The largest peak-to-trough decline in equity measured as a percentage.<br><strong>Running Max: </strong>Tracks the highest equity value over time to compute drawdowns.</li><li><strong>Trade Details</strong><br><strong>Identify trade signals: </strong>When either <strong>x_position </strong>(position of Asset 1) or <strong>y_position </strong>(position of Asset 2)<strong> </strong>changes, a new trade is initiated/closed.<br><strong>Record each trade in trades_df with:</strong><br> — <strong>entry_date:</strong> The date on which the position changes.<br> — <strong>exit_date: </strong>The next signal date (shifted by -1).<br> — <strong>pnl: </strong>The daily_pnl on that date (though for a more detailed trade PnL, you’d sum over the holding period).<br><strong>Positions:</strong> The actual positions in Asset 1 and Asset 2 at entry.<br><strong>Number of trades</strong>: Count of trading signal generated.<br><strong>Win -rate: </strong>Percentage of trades with pnl &gt; 0.</li><li><strong>Output</strong><br><strong>Returns a dictionary containing:</strong><br><strong> — df: </strong>The DataFrame with detailed results, including prices, positions, returns, PnL, and equity over time.<br><strong> — metrics:</strong> A dictionary of key performance metrics for the trading strategy.<br> <strong>— trades_df:</strong> A DataFrame summarizing individual trade details.</li></ol><p>Now we have formulated our trading strategy, it’s time for us to run it. We can do this by:</p><pre>pair_trading = run_pair_trading(sym1,sym2,data_dict,df_zscore)<br>pair_trading[&#39;metrics&#39;] </pre><p>We run the <strong>pair_trading[‘metrics’] </strong>so that we can focus on the performance of our strategy, you can also run <strong>pair_trading[‘df’] </strong>if you want to see the full and detailed dataframe, or <strong>pair_trading[‘trades_df’] </strong>to only see the trades made during our backtesting period.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*3fclR4DYgAd2NAtxr3gW6Q.png" /><figcaption><strong>Figure 8</strong>. Performance result of our trading pair trading strategy</figcaption></figure><p>The relatively high Sharpe ratio of about <strong>2.0 </strong>and the low max drawdown of <strong>0.22% </strong>suggest that despite the small total return, the strategy maintained a favorable balance between returns and risk.</p><p><strong>Let’s plot the cummulative returns</strong></p><pre>def plot_return(df):<br>    # Calculate cumulative return in percentage<br>    initial_equity = df[&quot;equity&quot;].iloc[0]<br>    df[&quot;cumulative_return_pct&quot;] = ((df[&quot;equity&quot;] - initial_equity) / initial_equity) * 100<br><br>    plt.figure(figsize=(14, 7))<br>    plt.plot(df.index, df[&quot;cumulative_return_pct&quot;], label=&quot;Cumulative Return (%)&quot;, color=&quot;green&quot;, alpha=0.8)<br>    plt.title(&quot;Cumulative Return in Percentage&quot;)<br>    plt.xlabel(&quot;Date&quot;)<br>    plt.ylabel(&quot;Cumulative Return (%)&quot;)<br>    plt.legend()<br>    plt.grid()<br>    plt.show()</pre><p>Now we can run the followingfunction to generate the</p><pre>plot_return(pair_trading[&#39;df&#39;])</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*WifLSzAjRz2jWxbS5_1lbA.png" /><figcaption><strong>Figure 9</strong>. Cumulative return graph of our pair trading strategy</figcaption></figure><h3><strong>Summary</strong></h3><p>This strategy provides a solid foundation for a pairs trading, but there is definitely a lot of room for refinement. Potential improvements include adjusting position sizing based on volatility, adjust trading signals parameters (you can try the bayesian optimization technique), and taking into accounts transaction costs and slippage to ensure more realistic backtesting. However, this example serves as a great starting point for further development and experimentation in pair trading.</p><p><strong>If you wish to download the Jupyter Notebook file for this stretegy, you can find it here:</strong></p><blockquote><a href="https://algocraft.gumroad.com/l/pairtrading01">https://algocraft.gumroad.com/l/pairtrading01</a></blockquote><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=d303b0f8415d" width="1" height="1" alt=""><hr><p><a href="https://medium.com/algocraft/getting-started-with-statistical-arbitrage-a-comprehensive-guide-to-pairs-trading-in-python-d303b0f8415d">Getting Started with Statistical Arbitrage: A Comprehensive Guide to Pairs Trading in Python</a> was originally published in <a href="https://medium.com/algocraft">AlgoCraft</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Mastering Forex Forecasting: A Comprehensive Guide to Harnessing XGBoost for Predictive Analytics]]></title>
            <link>https://medium.com/algocraft/mastering-forex-forecasting-a-comprehensive-guide-to-harnessing-xgboost-for-predictive-analytics-54f9ce85ce01?source=rss-b190c0874170------2</link>
            <guid isPermaLink="false">https://medium.com/p/54f9ce85ce01</guid>
            <category><![CDATA[forecasting]]></category>
            <category><![CDATA[forex-trading]]></category>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[artificial-intelligence]]></category>
            <category><![CDATA[data-analytics]]></category>
            <dc:creator><![CDATA[Alwan Alkautsar]]></dc:creator>
            <pubDate>Thu, 12 Oct 2023 16:03:24 GMT</pubDate>
            <atom:updated>2023-10-12T16:03:24.702Z</atom:updated>
            <content:encoded><![CDATA[<p>In the fast-paced world of finance, Forex trading stands as a towering figure. It’s a massive market, where currencies whirl around in exchange, their values ebbing and flowing like the tide. For us retail traders, its very important to have the right tool in our belt to navigate through the forex market so that we can generate consistent profit.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*pmWr0lqkvPvk9MT2" /></figure><p>After previously we learned how to forecast the forex market with LSTM, now we’ll try to forecast the same pair with another machine learning algorithm called XGBoost.</p><p><em>If you haven’t read my article on LSTM, I’ll save you the trouble from trying to finding it:</em></p><p><a href="https://algocraft.xyz/eur-usd-forecasting-simplified-an-lstm-users-guide-337ccdda6158">EUR/USD Forecasting Simplified: an LSTM User’s Guide</a></p><h3>XGBoost: The Game-Changer</h3><p>XGBoost, standing for eXtreme Gradient Boosting, represents one of the pinnacles of modern machine learning methodologies. Born from the idea of optimizing the Gradient Boosting framework, XGBoost deploys decision trees to break down intricate predictive challenges into manageable bits. Noted for its unparalleled efficiency and formidable accuracy, this algorithm is a master at sifting through diverse data forms, be they structured or unstructured. What sets XGBoost apart is its ability to adapt swiftly and refine its models, making iterative enhancements to bolster the accuracy of its predictions. In essence, when faced with convoluted prediction scenarios, XGBoost emerges as a dependable and potent ally.</p><h4>Why XBoost is Well Suited for Forex Forecasting?</h4><p>Forex trading is all about predicting currency exchange rates quickly and accurately. XGBoost is particularly helpful for this task. Its method for improving predictions is great for making precise forecasts in the fast-paced world of Forex.</p><p>In Forex, where prices change rapidly, XGBoost’s ability to process large amounts of data and make accurate predictions is incredibly valuable. It simplifies the complex Forex landscape, giving traders the confidence they need to make decisions.</p><h3>XGBoost for Forex Forecasting</h3><p>To start using XGBoost for Forex forecasting, let’s first start import all the necessary libraries:</p><pre>import yfinance as yf<br>import numpy as np<br>import pandas as pd<br>import xgboost as xgb<br>import matplotlib.pyplot as plt<br>from sklearn.model_selection import train_test_split<br>from sklearn.metrics import mean_squared_error<br>from sklearn.metrics import mean_absolute_error<br>from sklearn.preprocessing import StandardScaler<br>from ta.momentum import RSIIndicator, StochasticOscillator<br>from ta.trend import MACD, PSARIndicator<br>from ta.volatility import BollingerBands<br>from ta.utils import dropna</pre><p>Looking at the libraries above, you will notice that we will be fetch the forex data using yfinance, a popular library to extract financial data. numpy and pandas are included for data processing purposes, while xgboost is imported for the predictive modeling. Finally, all data visualization in this forecast will be facilitated by matplotlib.</p><p><strong>Next, let’s import our data:</strong></p><pre># Define the ticker symbol and fetch data<br>ticker_symbol = &quot;EURUSD=X&quot;<br>df = yf.download(ticker_symbol, start=&quot;2000-01-01&quot;, end=&quot;2023-01-01&quot;)<br>df</pre><p>The above code utilize the yfinance library where we import the necessary data for our forecast. In thismodel, we will try to forecast EUR/USD daily databy utlizing the data from 2020–01–01 to 2023-01-01 which we store into dataset df .</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*sWlPCaqOZJfR9f6IiEoC4g.png" /><figcaption>Raw Data Output for EUR/USD Pair retrieved with yfinance library</figcaption></figure><h4>Feature Engineering for Forex Forecasting</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Xz_oZ3cLbdEAnlsprxRs-g.png" /><figcaption>DALL-E Generated Illustration for Forecast Forecasting just because I thought it would be fun</figcaption></figure><p>In predictive modeling, especially in financial forecasting, the quality and relevance of input features play a pivotal role in the accuracy and reliability of predictions. While raw data provides a foundational perspective, it often lacks the nuanced context that can capture the complexity of market dynamics. This is where feature engineering becomes invaluable. By transforming and synthesizing the raw data using established technical indicators, we can provide the model with enriched insights that could explain underlying market patterns and trends. Such enriched data can significantly improve the model’s ability to anticipate future price movements.</p><p>For this forecast, we will utilize a couple of technical indicators for our feature engineering like RSI, MACD, Bollinger Bands, Parabolic SAR, and Stochastic Oscillator. Additionally, we introduce lag features to capture temporal dependencies, ensuring our model benefits from both current and historical contexts.</p><p><strong>Let’s calculate the features we will utilize in this forecast</strong></p><pre># Compute RSI<br>df[&#39;momentum_rsi&#39;] = RSIIndicator(close=df[&#39;Close&#39;]).rsi()<br><br># Compute MACD<br>macd = MACD(close=df[&#39;Close&#39;])<br>df[&#39;trend_macd&#39;] = macd.macd()<br>df[&#39;trend_macd_signal&#39;] = macd.macd_signal()<br>df[&#39;trend_macd_diff&#39;] = macd.macd_diff()<br><br># Compute Bollinger Bands<br>bollinger = BollingerBands(close=df[&#39;Close&#39;])<br>df[&#39;volatility_bbm&#39;] = bollinger.bollinger_mavg()<br>df[&#39;volatility_bbl&#39;] = bollinger.bollinger_lband()<br>df[&#39;volatility_bbh&#39;] = bollinger.bollinger_hband()<br><br># Compute Parabolic SAR<br>psar = PSARIndicator(high=df[&#39;High&#39;], low=df[&#39;Low&#39;], close=df[&#39;Close&#39;])  # Assuming you have &#39;High&#39; and &#39;Low&#39; columns in your df<br>df[&#39;trend_psar&#39;] = psar.psar()<br><br><br># Compute Stochastic Oscillator<br>stochastic = StochasticOscillator(high=df[&#39;High&#39;], low=df[&#39;Low&#39;], close=df[&#39;Close&#39;])  # Assuming you have &#39;High&#39; and &#39;Low&#39; columns<br>df[&#39;momentum_stoch&#39;] = stochastic.stoch()<br>df[&#39;momentum_stoch_signal&#39;] = stochastic.stoch_signal()<br><br># Create Lag Features<br>df[&#39;Close_Lag1&#39;] = df[&#39;Close&#39;].shift(1)<br><br># Drop NaN values introduced due to lag features and indicators<br>df = df.dropna()<br><br># Define features and target<br>X = df[[&#39;momentum_rsi&#39;, &#39;trend_macd&#39;, &#39;trend_macd_signal&#39;, &#39;trend_macd_diff&#39;, &#39;volatility_bbm&#39;, &#39;volatility_bbl&#39;, &#39;volatility_bbh&#39;, &#39;trend_psar&#39;, &#39;momentum_stoch&#39;, &#39;momentum_stoch_signal&#39;, &#39;Close_Lag1&#39;]]<br>y = df[&#39;Close&#39;]</pre><p>The above code is organizing the dataset df into input features and a target variable for our model. The input features, captured under X, consist of various the features we calculated on and previously defined. The target variable, denoted by y, is the Close column, representing the daily closing price of EUR/USD, which our model aims to predict based on the provided features.</p><p><strong>Model Initialization and Training</strong></p><pre># Initialize the model<br>model = xgb.XGBRegressor(<br>    learning_rate=0.75,<br>    n_estimators=200,<br>    max_depth=5,<br>    subsample=0.9,<br>    colsample_bytree=0.8,<br>    colsample_bylevel=0.8,<br>    gamma=0,<br>    min_child_weight=1<br>)<br><br># Train the model<br>model.fit(X_train, y_train)</pre><p>Continuing from the previously discussed data preparation, this section of code dives into the model initialization and training phases using XGBoost. The xgb.XGBRegressor() initializes a regression model with specified hyperparameters to optimize the forecast. Key parameters include a learning rate of 0.75, which determines the step size at each iteration while optimizing, 200 estimators or trees, and a maximum depth of 5 for each tree, among others. These hyperparameters play a role in controlling the model’s complexity and fit to the data.</p><p>After initializing, the model is trained on the X_train and y_train datasets using the fit method. This step allows the model to learn the underlying patterns from the training data, preparing it to make future predictions on unseen data.</p><p><strong>Performance Evaluation and Testing</strong></p><pre># Predict on the test set<br>y_pred = model.predict(X_test)<br><br># Calculate performance metrics<br>mae = mean_absolute_error(y_test, y_pred)<br>mse = mean_squared_error(y_test, y_pred)<br>rmse = np.sqrt(mse)<br><br>print(f&quot;Mean Absolute Error: {mae}&quot;)<br>print(f&quot;Mean Squared Error: {mse}&quot;)<br>print(f&quot;Root Mean Squared Error: {rmse}&quot;)<br><br>y_train_pred = model.predict(X_train)</pre><p>After training the model on the historical data we evaluate its performance on unseen or test data. Using the predict method of the trained model, predictions (y_pred) are generated for the test dataset X_test. Subsequently, to assess the accuracy and reliability of these predictions, various performance metrics are computed:</p><ul><li><strong>The Mean Absolute Error (MAE)</strong> provides an average magnitude of errors between predicted and actual values.</li><li><strong>The Mean Squared Error (MSE) </strong>squares these errors to emphasize larger discrepancies.</li><li><strong>Root Mean Squared Error (RMSE) </strong>is the square root of MSE, providing error in the same units as the original data.</li></ul><p>These metrics are then printed for clear visibility. We concludes by also predicting on the training set (X_train) with y_train_pred, to further analyze and compare the model’s performance on both training and test datasets.</p><p>The following output displays the performance metricswhich assess the accuracy of our model’s predictions:</p><pre>Mean Absolute Error: 0.009141215039947168<br>Mean Squared Error: 0.000303615460154008<br>Root Mean Squared Error: 0.017424564848340058</pre><ul><li><strong>Mean Absolute Error (MAE): </strong>At 0.0091, it shows the model’s average absolute deviation from the actual values.</li><li><strong>Mean Squared Error (MSE):</strong> With a value of 0.0003036, it indicates the average squared error, emphasizing larger mistakes.</li><li><strong>Root Mean Squared Error (RMSE):</strong> At 0.0174, it provides the average error in the original unit, illustrating the typical magnitude of error.</li></ul><p>The relatively low values across these metrics suggest that the model has a good degree of accuracy in its predictions. The model appears to be reliably forecasting the target variable, depicted with minimal deviations in the forecasted data when compared to the actual data.</p><p><strong>Data Visualization</strong></p><pre># Create a new DataFrame for visualization<br>viz_df = pd.DataFrame({&#39;True&#39;: y_test, &#39;Predicted&#39;: y_pred})<br><br># Concatenate the training data for a complete view<br>viz_df_train = pd.DataFrame({&#39;True&#39;: y_train, &#39;Predicted&#39;: y_train_pred})<br>viz_df = pd.concat([viz_df_train, viz_df])<br><br># Plot the results<br>plt.figure(figsize=(14, 7))<br>plt.plot(viz_df[&#39;True&#39;], label=&#39;True&#39;, color=&#39;blue&#39;)<br>plt.plot(viz_df[&#39;Predicted&#39;], label=&#39;Predicted&#39;, color=&#39;red&#39;, alpha=0.7)<br>plt.title(&#39;EUR/USD Forecast: True vs Predicted&#39;)<br>plt.legend()<br>plt.grid(True)<br>plt.show()</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/818/1*cLlTTCFRMZqUBQIUBeya0g.png" /></figure><p>The visual representation of the EUR/USD currency pair’s forecasted versus actual values offers an insightful glimpse into the model’s capabilities. The close alignment between the blue True line and the red Predicted line for most of the chart affirms the model’s strong predictive proficiency, especially given the low Mean Absolute Error (MAE) of 0.0091. The few areas where deviations occur resonate with the Root Mean Squared Error (RMSE) of 0.0174, indicating the average magnitude of error.</p><p>Notably, the small segment towards the right end, where predictions seem to diverge slightly, underscores the challenges of exact currency forecasting. Nevertheless, the model, as depicted in the graph and corroborated by the performance metrics, has shown remarkable accuracy in capturing the nuances of the EUR/USD exchange rate’s movements.</p><h3>Conclusion</h3><p>In conclusion, this exploration into Forex forecasting has underscored the critical interplay between data preprocessing, feature engineering, and model selection. Through this model we found that XGBoost in predicting the EUR/USD currency pair stands out, demonstrating the algorithm’s robustness and adaptability. Finally, the precision showcased by our model reinforces XGBoost’s reputation as an efficient tool to forecast financial data.</p><p>Read more of my stories here:</p><ul><li><a href="https://algocraft.xyz/eur-usd-forecasting-simplified-an-lstm-users-guide-337ccdda6158">EUR/USD Forecasting Simplified: an LSTM User’s Guide</a></li><li><a href="https://algocraft.xyz/how-to-get-131-return-with-mean-reversion-trading-strategy-from-stock-selection-to-backtesting-c623870adf31">How to Get a 131% Return with Mean Reversion Trading Strategy: From Stock Selection to Backtesting</a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=54f9ce85ce01" width="1" height="1" alt=""><hr><p><a href="https://medium.com/algocraft/mastering-forex-forecasting-a-comprehensive-guide-to-harnessing-xgboost-for-predictive-analytics-54f9ce85ce01">Mastering Forex Forecasting: A Comprehensive Guide to Harnessing XGBoost for Predictive Analytics</a> was originally published in <a href="https://medium.com/algocraft">AlgoCraft</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[How to Get a 131% Return with Mean Reversion Trading Strategy: From Stock Selection to Backtesting]]></title>
            <link>https://medium.com/algocraft/how-to-get-131-return-with-mean-reversion-trading-strategy-from-stock-selection-to-backtesting-c623870adf31?source=rss-b190c0874170------2</link>
            <guid isPermaLink="false">https://medium.com/p/c623870adf31</guid>
            <category><![CDATA[trading-ideas]]></category>
            <category><![CDATA[stock-market]]></category>
            <category><![CDATA[mean-reversion]]></category>
            <category><![CDATA[algorithmic-trading]]></category>
            <category><![CDATA[quantitative-finance]]></category>
            <dc:creator><![CDATA[Alwan Alkautsar]]></dc:creator>
            <pubDate>Sun, 03 Sep 2023 15:54:05 GMT</pubDate>
            <atom:updated>2023-10-12T16:06:02.095Z</atom:updated>
            <content:encoded><![CDATA[<p>In this comprehensive guide, we’ll dive into mean-reversion trading strategy using Python. We’ll start by selecting stocks based on specific criteria and then explore the core principles of the strategy. Ultimately, we’ll conduct a backtest to evaluate the performance of our selected stocks when the mean-reversion strategy is applied.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*o95y-D4ETf1Geqx3" /></figure><h3>Mean Reversion Trading</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*hTHz4H1jyx5x-9uR.jpg" /><figcaption>Image Courtesy of HFT Research</figcaption></figure><p>In general, trading strategies can be broadly categorized into two types: trend-following and mean-reversion. While trend-following strategies aim to exploit the persistence of a price movement, mean-reversion strategies, on the other hand, bet on the price returning to an average or mean level after a deviation.</p><p>Mean reversion is a trading strategy grounded in the belief that asset prices and historical returns eventually revert to their long-term mean or average level.<strong> </strong>Essentially, if a stock or asset temporarily deviates significantly from its historical average — whether by underperforming or overperforming — the mean reversion trader anticipates that it will soon return to its “normal” state.</p><p>In essence, mean reversion capitalizes on price fluctuations and assumes that a stock’s high and low prices are temporary and that its price will, over time, revert to its average.</p><h3>The Code: Step-by-Step Guide</h3><p>This guide will be divided into two primary sections: The first section focuses on stock selection, while the second section will be strategy validation through backtesting the chosen stocks using a mean-reversion strategy.</p><h4>Stock Selection</h4><p>Choosing the right stocks is crucial. One of the most effective technique to identify mean-reverting stocks is the Augmented Dickey-Fuller (ADF) test, which checks for the stationarity of a time series.</p><p>By assessing the stationarity of a time series data, the ADF test aids in determining whether a stock’s price movements tend to revert to its historical mean over time. A statistically significant result from the ADF test suggests that the stock’s price is likely to return to its average value after deviating, indicating a potential mean reversion pattern.</p><p><strong>Let’s start with the code. First, let’s import all the necessary libraries</strong>.</p><pre># Import necessary libraries<br>import yfinance as yf<br>import pandas as pd<br>import numpy as np<br>import matplotlib.pyplot as plt<br>from backtesting import Backtest, Strategy<br>from backtesting.lib import crossover<br>from statsmodels.tsa.stattools import adfuller</pre><p>We will be using yfinance to retrieve the data from Yahoo! Finance and from statsmodels.tsa.stattools import adfuller to calculate the Augmented Dickey-Fuller (ADF) test for our universe of stocks.</p><pre># Create a list of US stocks <br>stock_symbols = [<br>    &#39;AAPL&#39;, &#39;MSFT&#39;, &#39;GOOGL&#39;, &#39;AMZN&#39;, &#39;TSLA&#39;, &#39;BRK-A&#39;, &#39;NVDA&#39;,<br>    &#39;JPM&#39;, &#39;JNJ&#39;, &#39;V&#39;, &#39;PG&#39;, &#39;UNH&#39;, &#39;MA&#39;, &#39;DIS&#39;, &#39;HD&#39;, &#39;BAC&#39;, &#39;VZ&#39;,<br>    &#39;INTC&#39;, &#39;KO&#39;, &#39;PFE&#39;, &#39;WMT&#39;, &#39;MRK&#39;, &#39;PEP&#39;, &#39;T&#39;, &#39;BA&#39;, &#39;XOM&#39;, &#39;ABBV&#39;,<br>    &#39;NKE&#39;, &#39;MCD&#39;, &#39;CSCO&#39;, &#39;DOW&#39;, &#39;ADBE&#39;, &#39;IBM&#39;, &#39;CVX&#39;, &#39;CRM&#39;, &#39;ABT&#39;, &#39;MDT&#39;,<br>    &#39;PYPL&#39;, &#39;NEE&#39;, &#39;COST&#39;, &#39;AMGN&#39;, &#39;CMCSA&#39;, &#39;NFLX&#39;, &#39;ORCL&#39;, &#39;PM&#39;, &#39;HON&#39;, &#39;ACN&#39;,<br>    &#39;TMO&#39;, &#39;AVGO&#39;<br>]<br><br># Fetch the data from Yahoo Finance<br>df = {}<br>for symbol in stock_symbols:<br>    data = yf.download(symbol, start=&#39;2015-01-01&#39;, end=&#39;2023-01-01&#39;)<br>    df[symbol] = data[&#39;Close&#39;]</pre><p>After importing all of the necessary libraries, we need to create a list of stocks that we would like to scan and store it to list stock_symbols. You are free to include as many stocks as you wish, but for this case study, I will only include around <strong>47 stocks</strong> to ensure faster data retrieval and processing.</p><p>Next, we are going to use the yfinance library to retrieve the historcial price of our selected stocks. For this case, I will retrieve the historical data from 2015–01–01 to 2023–01–01.</p><p>If you would like to inspect the historical data, you can use print(df) . Meanwhile, to print the closing stock prices individually for a specific stock (e.g., ‘AAPL’): print(df[‘AAPL’].Close).</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*HmBTbvhKl5VwA8AmsJ5L0g.png" /><figcaption>Inspecting individual stock closing price in Jupyter Notebook.</figcaption></figure><p><strong>Moving on, let’s code the ADF calculation:</strong></p><pre>stationary_stocks = []<br>p_values = []  <br><br>for symbol, data in df.items():<br>    result = adfuller(data[&#39;Close&#39;])<br>    # A p-value less than 0.05 indicates that the data is stationary<br>    p_value = result[1]<br>    if p_value &lt;= 0.05:<br>        stationary_stocks.append(symbol)<br>        p_values.append(p_value)<br><br>print(&quot;Stocks suitable for mean reversion strategy:&quot;)<br>for stock, p_value in zip(stationary_stocks, p_values):  # Use zip to iterate over both lists simultaneously<br>    print(f&quot;Stock: {stock}, p-value: {p_value:.4f}&quot;)</pre><p>The provided code evaluates stocks for potential mean reversion strategies using the Augmented Dickey-Fuller (ADF) test. Like previously mentioned, the ADF test assesses whether a stock’s historical closing prices exhibit stationarity, a key characteristic for mean reversion strategies.</p><p>For this case, the ADF test’s p-value (probability) is checked against the <strong>significance level of 0.05</strong>. A p-value below this threshold suggests that the data is stationary, indicating that the stock prices tend to revert to their mean over time.</p><p>The code compiles a list of stocks with p-values less than or equal to 0.05 in list stationary_stocks, identifying those that are potentially suitable candidates for mean reversion strategies due to their demonstrated tendency to revert to their historical averages.</p><p>Running above code will result in the following output:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*2OroG9WcZ5gjuaLlX1Kc_A.png" /></figure><p>As it turns out, from our universe of stocks. <strong>IBM </strong>is the only stock which its daily closing price exhibit mean-reverting properties with a p-value of <em>0.0120.</em></p><p><strong>We can also visualize the stock to assess its mean-reverting tendencies using </strong>matplotlib.pylot<strong> with the following code:</strong></p><pre>def plot_stationary_stocks(df, stationary_stocks):<br>    for stock in stationary_stocks:<br>        data = df[stock].Close<br>        <br>        # Calculate rolling statistics<br>        rolling_mean = data.rolling(window=30).mean()  # 30-day rolling mean<br>        rolling_std = data.rolling(window=30).std()   # 30-day rolling standard deviation<br>        <br>        # Plot the statistics<br>        plt.figure(figsize=(12, 6))<br>        plt.plot(data, label=f&#39;{stock} Prices&#39;, color=&#39;blue&#39;)<br>        plt.plot(rolling_mean, label=&#39;Rolling Mean&#39;, color=&#39;red&#39;)<br>        plt.plot(rolling_std, label=&#39;Rolling Std. Dev.&#39;, color=&#39;black&#39;)<br>        plt.title(f&#39;Stationarity Check for {stock}&#39;)<br>        plt.xlabel(&#39;Date&#39;)<br>        plt.ylabel(&#39;Prices&#39;)<br>        plt.legend()<br>        plt.grid(True)<br>        plt.show()<br><br><br># Calling the function<br>plot_stationary_stocks(df, stationary_stocks)</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/724/1*sgY5VEPMiWqbXpTsoldFGg.png" /><figcaption>Stationarity check for IBM with a 30-day rolling mean and 30-day rolling standard deviation.</figcaption></figure><h4>Strategy Formulation and Backtesting</h4><p>Let’s move on to trying out a mean-reversion strategy on our selected stock (IBM).</p><p>To accomplish this, we’ll be harnessing the capabilities of the <strong>backtesting.py </strong>library — a user-friendly and powerful toolkit for assessing trading strategies within the Python ecosystem. This library shines particularly brightly when it comes to validating straightforward strategies, making it an ideal choice for such scenarios. For more information about <strong>backtesting.py</strong>, you can visit its official page: <a href="https://kernc.github.io/backtesting.py/">Backtesting.py — Backtest trading strategies in Python (kernc.github.io)</a>.</p><p><strong>Strategy Formulation</strong></p><pre>class MeanReversion(Strategy):<br>    n1 = 30  # Period for the moving average<br>    <br>    def init(self):<br>        # Compute moving average<br>        self.offset = 0.01  # Buy/sell when price is 1% below/above the moving average<br>        prices = self.data[&#39;Close&#39;]<br>        self.ma = self.I(self.compute_rolling_mean, prices, self.n1)<br><br>    def compute_rolling_mean(self, prices, window):<br>        return [(sum(prices[max(0, i - window):i]) / min(i, window)) if i &gt; 0 else np.nan for i in range(len(prices))]<br><br>    def next(self):<br>        size = 0.1<br>        # If price drops to more than offset% below n1-day moving average, buy<br>        if self.data[&#39;Close&#39;] &lt; self.ma[-1] * (1 - self.offset):<br>            if self.position.size &lt; 0:  # Check for existing short position<br>                self.buy()  # Close short position<br>            self.buy(size=size)<br><br>        # If price rises to more than offset% above n1-day moving average, sell<br>        elif self.data[&#39;Close&#39;] &gt; self.ma[-1] * (1 + self.offset):<br>            if self.position.size &gt; 0:  # Check for existing long position<br>                self.sell()  # Close long position<br>            self.sell(size=size)</pre><p>Now this might be a little too technical, I’ll try my best to explain it thoroughly.</p><p>The strategy’s objective is to capitalize on price movements that deviate significantly from a specified moving average.</p><p><strong>Here’s an explanation of the key components:</strong></p><ul><li>The MeanReversion class is derived from the Strategy class, inheriting its functionality. This class serves as the foundation for implementing the mean-reversion strategy.</li><li>Within the init method, the moving average period n1 is set to <strong>30 days</strong>. The strategy uses a simple moving average to assess price trends.</li><li>The offset parameter is defined as <strong>1%</strong>, indicating that buying or selling actions will be executed when the price deviates by <strong>1%</strong> below or above the moving average.</li><li>The compute_rolling_mean method calculates the rolling mean of the closing prices over the specified window. The calculated values are then used to determine the moving average.</li><li>The next method is the core of the strategy, executed for each new trading data point. The variable size is set to <strong>0.1</strong>, means that for every trade executed by this strategy, a position will be opened or closed with an amount equal to <strong>10%</strong> of the total available capital in the portfolio.</li></ul><p>The strategy employs conditional statements to trigger buy and sell actions based on price deviations from the moving average. If the price falls below the moving average by more than the offset percentage, a buy action is triggered. Conversely, if the price rises above the moving average by more than the offset percentage, a sell action is triggered.</p><p>The strategy includes additional checks to close existing positions before initiating new ones, ensuring proper handling of long and short positions.</p><p>In essence, this mean-reversion strategy leverages the relationship between price and moving average to identify buying and selling opportunities when significant deviations occur.</p><p><strong>Running the backtest</strong></p><pre>stock_to_backtest = stationary_stocks[0]<br>df = df[stock_to_backtest]<br>bt = Backtest(df, MeanReversion, cash=100000, commission=.002)<br>stats = bt.run()<br>bt.plot()</pre><p>In the code above, the Backtest class is employed to set up the backtesting environment. This is done by creating an instance named bt, where historical price data from the DataFrame df is combined with the MeanReversion strategy we formulated earlier. Additional parameters such as initial cash of <strong>$100,000 </strong>and a commision fee of 0.<strong>2% per trade </strong>are also specified for the backtesting simulation.</p><p><strong>Backtest Result and Intepretation</strong></p><p>Let’s observe how the strategy perform through the generated plot using bt.plot().</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*uNfx0wpw-qQz-I3NpuBUhQ.png" /><figcaption>Plot generated from <strong>bt.plot()</strong></figcaption></figure><p>We can also print the stats with the following code</p><pre>print(stats)</pre><p>Here’s what the output of what our trading statistic will look like</p><pre>Start                     2014-12-31 00:00:00<br>End                       2022-12-30 00:00:00<br>Duration                   2921 days 00:00:00<br>Exposure Time [%]                   99.851117<br>Equity Final [$]                231170.852727<br>Equity Peak [$]                 235442.515106<br>Return [%]                         131.170853<br>Buy &amp; Hold Return [%]               -8.145763<br>Return (Ann.) [%]                   11.048887<br>Volatility (Ann.) [%]               23.417591<br>Sharpe Ratio                          0.47182<br>Sortino Ratio                        0.798583<br>Calmar Ratio                         0.339264<br>Max. Drawdown [%]                  -32.567221<br>Avg. Drawdown [%]                   -3.396693<br>Max. Drawdown Duration      645 days 00:00:00<br>Avg. Drawdown Duration       42 days 00:00:00<br><br># Trades                                 1613<br>Win Rate [%]                        73.961562<br>Best Trade [%]                      25.858214<br>Worst Trade [%]                    -15.540084<br>Avg. Trade [%]                       1.976996<br>Max. Trade Duration         189 days 00:00:00<br>Avg. Trade Duration          42 days 00:00:00<br>Profit Factor                        3.146867<br>Expectancy [%]                       2.089253<br>SQN                                  7.474048<br>_strategy                       MeanReversion<br>_equity_curve                             ...<br>_trades                         Size  Entr...<br>dtype: object</pre><p>The strategy produced a positive return of <strong>131.17%</strong>, which translates to an annualized return of <strong>11.05%</strong>. For comparison, a Buy &amp; Hold strategy over the same period would have resulted in a <strong>loss </strong>of <strong>8.15%</strong>.</p><p>Key risk metrics reveal a maximum drawdown of <strong>32.57%</strong>, meaning the strategy at its worst point had a drop of <strong>32.57%</strong> from its peak value.</p><p>The Sharpe Ratio, a measure of risk-adjusted returns, stands at <strong>0.47182. </strong>A Sharpe Ratio above 1 is generally considered excellent, so this strategy’s return per unit of risk is moderate. The Calmar Ratio, which compares the annualized return to the maximum drawdown, is <strong>0.339</strong>, indicating that the strategy’s return is about a third of its maximum drawdown, suggesting that there might be potential improvements in risk management.</p><p>Regarding individual trades, the strategy made a total of <strong>1,613 trades </strong>with a high win rate of <strong>73.96%</strong>. The Profit Factor, which is the ratio of gross profit to gross loss, is at a favorable level of <strong>3.147</strong>, implying that the strategy’s <strong>profitable trades were over three times larger than its losing trades</strong>.</p><h3>Conclusion</h3><p>Throughout this case study, we’ve successfully identified a mean-reverting stock using the ADF test and validated it by applying the strategy through backtesting with backtesting.py library, resulting in an impressive <strong>131.17% return</strong>.</p><p>While this approach delivered substantial returns, it’s important to acknowledge that this framework is a basic implementation of mean-reversion trading strategy and would serves as an excellent foundation for developing a more sophisticated and resilient algorithmic trading strategy.</p><p>Feel free to share your ideas on enhancing the strategy in the comments section below!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=c623870adf31" width="1" height="1" alt=""><hr><p><a href="https://medium.com/algocraft/how-to-get-131-return-with-mean-reversion-trading-strategy-from-stock-selection-to-backtesting-c623870adf31">How to Get a 131% Return with Mean Reversion Trading Strategy: From Stock Selection to Backtesting</a> was originally published in <a href="https://medium.com/algocraft">AlgoCraft</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[EUR/USD Forecasting Simplified: an LSTM User’s Guide]]></title>
            <link>https://medium.com/algocraft/eur-usd-forecasting-simplified-an-lstm-users-guide-337ccdda6158?source=rss-b190c0874170------2</link>
            <guid isPermaLink="false">https://medium.com/p/337ccdda6158</guid>
            <category><![CDATA[forecasting]]></category>
            <category><![CDATA[forex]]></category>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[quantitative-finance]]></category>
            <category><![CDATA[algorithmic-trading]]></category>
            <dc:creator><![CDATA[Alwan Alkautsar]]></dc:creator>
            <pubDate>Sun, 27 Aug 2023 08:12:19 GMT</pubDate>
            <atom:updated>2023-08-28T10:24:30.363Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*EUIE-cUkt3x2AqBX5nUotA.jpeg" /></figure><p>LSTM, or Long Short-Term Memory, is a specialized type of Recurrent Neural Network (RNN) designed to recognize patterns in sequences of data. Unlike traditional RNNs, LSTM is adept at learning long-term dependencies thanks to its unique architecture, which includes memory cells governed by mechanisms called gates. These gates regulate the flow of information, ensuring that the network retains crucial data from earlier in the sequence, making LSTMs particularly resistant to the vanishing gradient problem that plagues vanilla RNNs.</p><p>Forecasting financial time series data, like stock, options, bond, and forex rates is challenging due to the inherent noise, non-stationarity, and the influence of numerous unpredictable external factors. However, LSTM tend to perform better for this kind of data than others due to the following reasons:</p><h4>The Pros</h4><ul><li><strong>Temporal Dependencies: </strong>LSTMs are explicitly designed to handle sequences, making them well-suited for time series data.</li><li><strong>Complex Patterns: </strong>Financial data can have non-linear patterns that are challenging for traditional models. LSTMs can capture these patterns.</li><li><strong>Flexibility: </strong>LSTMs can be designed in various architectures, such as stacked, bidirectional, or even in combination with other neural network types (like CNN-LSTM).</li></ul><p>Despite many of its benefits, LSTM also has some caveats that you should also consider:</p><h4>The Cons</h4><ul><li><strong>Data Volume: </strong>LSTMs benefit from large amounts of data. If your dataset is limited, you might not be able to fully leverage the power of LSTMs.</li><li><strong>Computational Cost: </strong>Training LSTMs, especially deep architectures, can be computationally intensive. It’s beneficial to have access to powerful hardware.</li><li><strong>Overfitting: </strong>LSTMs can overfit to the training data, especially when the data is noisy (as financial data often is). It’s essential to use techniques like dropout, early stopping, or regularization to counteract this.</li></ul><h3>Data Collection and Preparation</h3><p>Let’s move on to the juicy part where we’ll be using LSTM to forecast EUR/USD data. Here are some key details about the data that you should be aware of:</p><ul><li><strong>Data Source:</strong> Investing.com ( <a href="https://www.investing.com/currencies/eur-usd-historical-data">EUR USD Historical Data — Investing.com</a>)</li><li><strong>Data Granularity:</strong> Daily</li><li><strong>Data Period :</strong> January 1, 2010–December 31, 2022</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*2K0a_STGx2dn3eHp" /></figure><pre>      Date   Price    Open    High     Low     Vol.   Change %<br>0  12/30/2022  1.0702  1.0663  1.0714  1.0639   NaN    0.38%<br>1  12/29/2022  1.0661  1.0609  1.0691  1.0609   NaN    0.50%<br>2  12/28/2022  1.0608  1.0642  1.0675  1.0606   NaN   -0.28%<br>3  12/27/2022  1.0638  1.0638  1.0670  1.0611   NaN    0.03%<br>4  12/26/2022  1.0635  1.0611  1.0638  1.0604   NaN    0.20%</pre><p>The dataset contains historical data for EUR/USD, with the following columns:</p><ol><li><strong>Date:</strong> The date of the data entry.</li><li><strong>Price:</strong> The closing price for the EUR/USD pair on that date.</li><li><strong>Open:</strong> The opening price for the EUR/USD pair on that date.</li><li><strong>High:</strong> The highest price reached for the EUR/USD pair on that date.</li><li><strong>Low:</strong> The lowest price reached for the EUR/USD pair on that date.</li><li><strong>Vol.: </strong>Trading volume for the day (seems to have missing values).</li><li><strong>Change %: </strong>The percentage change in price from the previous day.</li></ol><p>Looking at the first few collumn above, you’ll observe the presence of some missing <strong>Volume </strong>data. However, there’s no need for concern as we will exclusively utilize the <strong>Price </strong>column for our forecasting purposes.</p><h3>The Code</h3><h4>Import Necessary Libraries</h4><p>First, we’ll import all the essential libraries for our model. Our coding will be done in Python, and while I’ll be using Jupyter Notebook as our integrated development environment (IDE), feel free to use your preferred IDE.</p><pre>import pandas as pd<br>import numpy as np<br>import matplotlib.pyplot as plt<br>from sklearn.preprocessing import MinMaxScaler<br>from sklearn.model_selection import train_test_split<br>from sklearn.metrics import mean_squared_error<br>from keras.models import Sequential<br>from keras.layers import LSTM, Dense, Dropout<br>from keras.callbacks import EarlyStopping</pre><h4>Data Preparation</h4><p>Let’s import the CSV data for EUR/USD that you’ve downloaded from investing.com</p><pre>data = pd.read_csv(&quot;EUR_USD Historical Data.csv&quot;)</pre><p>Since the default order of historical data from investing.com is from the latest to the earliest, we need to extract the Price column and then reverse it to arrange it chronologically.</p><pre># Reverse the entire DataFrame to ensure it&#39;s in chronological order<br>data = data.iloc[::-1].reset_index(drop=True)<br><br># Extract the &#39;Price&#39; column without reversing<br>prices = data[&#39;Price&#39;].values<br>prices = prices.reshape(-1, 1)</pre><p>Next we need to normalize the data as normalization is crucial for LSTMs because they are sensitive to input data scale. Scaling data to a range, typically between 0 and 1, ensures consistent representation, prevents any particular feature from disproportionately influencing the model, and facilitates smoother and faster convergence during training.</p><pre># Normalize the data<br>scaler = MinMaxScaler(feature_range=(0, 1))<br>normalized_prices = scaler.fit_transform(prices)</pre><p>Next, let’s create sequences of a given length to be fed into the LSTM, in the case we wil use sequence_length=60 .</p><pre># Create sequences of a given length (60 days) to feed into the LSTM<br>sequence_length = 60<br>X, y = [], []<br>for i in range(sequence_length, len(normalized_prices)):<br>    X.append(normalized_prices[i-sequence_length:i, 0])<br>    y.append(normalized_prices[i, 0])</pre><h4>Data Training and Model Creation</h4><p>To start training our data, we first need to split our data into training and validation sets. This allows us to evaluate the model’s performance on unseen data.</p><pre>X, y = np.array(X), np.array(y)<br>X = np.reshape(X, (X.shape[0], X.shape[1], 1))<br>X_train, X_val, y_train, y_val = train_test_split(X, y, test_size=0.2, shuffle=False)</pre><p>Now let’s define our LSTM model, this part might be a little bit difficult to follow so I’ll try my best to thoroughly explain it:</p><pre>model = Sequential()<br><br>#This is the first LSTM layer with 50 units (or cells).<br>model.add(LSTM(units=50, return_sequences=True, input_shape=(X_train.shape[1], 1)))<br>#First Dropout Layer with a rate of 20% to prevent overfitting<br>model.add(Dropout(0.2))<br><br>#This is the second LSTM layer, also with 50 units.<br>model.add(LSTM(units=50, return_sequences=True))<br>#Second Dropout Layer with a rate of 20% to prevent overfitting<br>model.add(Dropout(0.2))<br><br>#The third LSTM layer, also with 50 units.<br>model.add(LSTM(units=50))<br>#Third Dropout Layer with a rate of 20% to prevent overfitting<br>model.add(Dropout(0.2))<br><br>#This is a fully connected layer that outputs aggregates of features learned by the LSTM layers and produces a single output value<br>model.add(Dense(units=1))<br>#The model is compiled using the Adam optimization algorithm that combines the advantages of two other extensions of stochastic gradient descent: AdaGrad and RMSProp.<br>model.compile(optimizer=&#39;adam&#39;, loss=&#39;mean_squared_error&#39;)</pre><p>So, the model we’re using is is defined using the Sequential class from Keras, which allows us to build a model layer by layer in a linear stack. The model uses <strong>three LSTM layer </strong>as well as <strong>Dropout layers </strong>to mitigate overfitting, which can be a concern with deep networks and limited data.</p><p>For the<strong> first </strong>and <strong>second </strong>layer of LSTM :</p><ul><li>The return_sequences=True argument means these LSTM layers will return the full sequence to the next layer. This is necessary when stacking LSTM layers so that the next LSTM layer receives sequences as input.</li><li>input_shape specifies the shape of the input data. In this case, it takes sequences of length X_train.shape[1] and each sequence has 1 feature.</li></ul><p>For the third LSTM layer, return_sequences is set to False, so this layer will only return the output of the last time step, we set this to False because after processing the entire input sequence, we’re going to use the model to make a single prediction (<strong>Price</strong>). Hence, only the final output of the sequence is passed to the Dense layer.</p><p>For all dropout layer:</p><ul><li>Dropout is a regularization technique where randomly selected neurons are ignored during training, helping to prevent overfitting. The rate 0.2 means approximately 20% of the input units will be dropped out at each training step.</li></ul><p>Now, that we’re done defining our model, let’s start training our model</p><pre>early_stop = EarlyStopping(monitor=&#39;val_loss&#39;, patience=10, restore_best_weights=True)<br>history = model.fit(X_train, y_train, epochs=100, batch_size=32, validation_data=(X_val, y_val), callbacks=[early_stop], shuffle=False)</pre><p>Next, let’s visualize the training and validation loss to understand how well the model is learning.</p><pre>plt.figure(figsize=(10, 6))<br>plt.plot(history.history[&#39;loss&#39;], label=&#39;Training Loss&#39;)<br>plt.plot(history.history[&#39;val_loss&#39;], label=&#39;Validation Loss&#39;)<br>plt.title(&#39;Training and Validation Loss&#39;)<br>plt.xlabel(&#39;Epoch&#39;)<br>plt.ylabel(&#39;Mean Squared Error&#39;)<br>plt.legend()<br>plt.show()</pre><p><strong>The Output will be the following plot:</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/863/1*OycIt4cSNkjSNjTul11QVA.png" /></figure><p><strong>MSE ( Mean Squared Error)<br></strong>MSE measures the average squared difference between predicted and actual values, with lower values indicating that the LSTM model is more accurately predicting the time series data.</p><p><strong>Epoch<br></strong>An epoch represents one full pass of the training data through the LSTM, refining its predictions with each iteration, while monitoring metrics like RMSE to gauge learning progress.</p><p><strong>Let’s see what this plot tells us.</strong></p><p>As the training progresses across epochs, we observe a decreasing trend in both training and validation losses. Each epoch signifies a full pass of the training data through the LSTM network.</p><p>The consistent downtrend in Training Loss and Validation Loss is a positive indicator, suggesting the LSTM model is not only assimilating patterns from the training data effectively but also showcasing a promising ability to generalize to new data.</p><h4>Forecast Performance: Predicted vs Actual</h4><p>Let’s use matplotlib to see how the <strong>Predicted Price </strong>perform vs the <strong>Actual Price:</strong></p><pre># Use the trained model to generate predictions on the validation dataset.<br># `X_val` contains the input features for the validation set.<br># The resulting predictions are stored in `y_val_pred` for further evaluation against actual values.<br>y_val_pred = model.predict(X_val)<br><br># Assuming val_dates is the list/array of dates corresponding to your validation set<br>val_dates = data[&#39;Date&#39;][-len(y_val):].values<br>val_dates = pd.to_datetime(val_dates)  # Convert to datetime format<br><br>plt.figure(figsize=(14,5))<br>plt.plot(val_dates, y_val, color=&#39;blue&#39;, label=&#39;Actual EUR/USD Price&#39;)<br>plt.plot(val_dates, y_val_pred, color=&#39;red&#39;, linestyle=&#39;dashed&#39;, label=&#39;Predicted EUR/USD Price&#39;)<br>plt.title(&#39;EUR/USD Price Prediction&#39;)<br>plt.xlabel(&#39;Date&#39;)<br>plt.ylabel(&#39;EUR/USD Price&#39;)<br>plt.legend()<br>plt.grid(True)<br>plt.show()</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*fozV9cETUqzjxNE4sbdaOQ.png" /></figure><p>Looking at this plot we can understand:</p><ul><li>The LSTM model seems to follow the overall trend of the actual prices quite closely.</li><li>There are certain periods where the model’s predictions deviate from the actual prices. However, the model generally captures the upward and downward movements.</li><li>The LSTM appears to be slightly lagging in capturing rapid changes or peaks in some areas. This is a common characteristic of LSTM models in time series forecasting, especially when rapid or abrupt changes occur in the data.</li></ul><p>We can also generate the Histogram of Prediction errors to see the the distribution of prediction errors (residuals) for the LSTM model:</p><pre># Calculate prediction errors<br>errors = y_val - y_val_pred.flatten()<br><br><br># Plot histogram of errors<br>plt.figure(figsize=(10, 6))<br>plt.hist(errors, bins=50, color=&#39;blue&#39;, alpha=0.7)<br>plt.title(&#39;Histogram of Prediction Errors&#39;)<br>plt.xlabel(&#39;Error Value&#39;)<br>plt.ylabel(&#39;Frequency&#39;)<br>plt.show()</pre><p>The code will generate the following chart:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/841/1*bwYh374viabhbsqgpt8v-g.png" /></figure><p>Looking at the histogram above, we can understand that:</p><ol><li><strong>Centered Around Zero:</strong> Most of the errors are centered around zero, indicating that the model’s predictions are generally close to the actual values.</li><li><strong>Bell-Shaped Curve: </strong>The error distribution somewhat resembles a bell-shaped curve (though not perfectly normal). This suggests that large errors (both positive and negative) are less frequent.</li><li><strong>Skewness: </strong>The histogram seems to have a slight right skew, indicating that there are a few instances where the model underpredicts (predicts a value lower than the actual value) by a larger margin.</li></ol><h3>Conclusion</h3><p>In our forecast the EUR/USD exchange rates using LSTM, the results have been promising. The model’s predictions closely align with actual observed rates. This is proved by the <strong>Root Mean Squared Error (RMSE) for our LSTM model’s predictions on the EUR/USD data being 0.02860742615917037. </strong>This means that, on average, the model’s predictions deviate from the actual values by about 2.860%.</p><p>Such results indicate the reliability of LSTM for time series forecasting, especially in financial contexts. While the model isn’t flawless, its performance in this analysis suggests it’s a valuable tool for forecasting tasks.</p><p>Feel free to share your thoughts on utilizing LSTM for forecasting Forex data in the comments section below!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=337ccdda6158" width="1" height="1" alt=""><hr><p><a href="https://medium.com/algocraft/eur-usd-forecasting-simplified-an-lstm-users-guide-337ccdda6158">EUR/USD Forecasting Simplified: an LSTM User’s Guide</a> was originally published in <a href="https://medium.com/algocraft">AlgoCraft</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[How Behavioral Factor Affect Indonesian Stock Market?]]></title>
            <link>https://kautsr.medium.com/how-behavioral-factor-affect-indonesian-stock-market-9ca27327b573?source=rss-b190c0874170------2</link>
            <guid isPermaLink="false">https://medium.com/p/9ca27327b573</guid>
            <category><![CDATA[indonesian-stock-market]]></category>
            <category><![CDATA[behavioral-finance]]></category>
            <category><![CDATA[economic-analysis]]></category>
            <category><![CDATA[political-risk]]></category>
            <category><![CDATA[stock-market]]></category>
            <dc:creator><![CDATA[Alwan Alkautsar]]></dc:creator>
            <pubDate>Mon, 28 Dec 2020 08:59:29 GMT</pubDate>
            <atom:updated>2020-12-28T14:18:10.252Z</atom:updated>
            <content:encoded><![CDATA[<p>There are times when the price movement in the stock market can’t be explained by their fundamental factors, sometimes also referred as market anomalies as the stock price moves away from their intrinsic value. This is where behavioral finance comes in, the theory proposes that the behaviors of investors and financial professionals are affected by psychological influences and biases.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*1U1dbKWWPU0XHbjG9_ooJQ.jpeg" /></figure><p>Behavioral factors are used to explain noise traders whose investment decisions are affected by emotions, these traders plays a huge role when stock prices move away from their intrinsic value. A study by Baker and Wurgler in 2006 found that there are more sentiment-sensitive stock found in developing countries (such as Indonesia) compared to developed countries. These sentiment-sensitive stocks are vulnerable and subjects to the behavioral capital asset pricing theory which introduced by Shefrin and Statman in 1994. The theory suggested that when bullish sentiment dominates the stock market, investors and traders buys more stock and prices will move above their intrinsic value; however when a bearish sentiment dominates, investors and traders will sell more stocks and prices will dragged below their real value.</p><p>Political risk is one of the factors which associated with behavioral finance. Studies found that political shocks can cause the stock market to either overreact or underreact which may lead to the fluctuation of the stock price. On the other hand, a stable political environment plays a huge role in a good performing stock market.</p><h3><strong>Political Risk in Indonesia</strong></h3><p>Thampayana and Wu in early 2020 suggested that Indonesia, compared to the other four countries in the ASEAN-5, has the biggest political risk. Unstable political landscape and policies issued by the government are some of the factors that might affect the political risk in a country.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*hi2BBApUZFl9HWDZws2WGw.jpeg" /><figcaption><strong>Indonesian Parliament Building.</strong> Courtesy of The Conversation</figcaption></figure><h4><strong>Public Distrust to How the Government Respond to COVID-19</strong></h4><p>When the news about the coronavirus pandemic spread, Indonesian political leadership was relatively slow to respond. Even after the first case was reported in early march, there were distrust towards political leaders as many believed the government were not able to get the pandemic under control. The absence of strict social distancing measures and inefficient health resource mobilization strategies were to name a few of the factors why the country still struggling to control the spread of the virus.</p><h4><strong>The Controversial Omnibus Law on Job Creation</strong></h4><p>Despite public protest and rejection, surprisingly, the Indonesian House of Representatives was speeding up the discussion on the decision-making of the Job Creation Bill. Some of the most commonly addressed issues were potential environmental fallout, endangerment of worker’s right, and procedural flaws. Not to mention that many academics were worried about the bill since there were a limited time allocated for deliberation and poor participation of stakeholders.</p><h3><strong>How Indonesian Political Risk Affect The Stock Market</strong></h3><p>In countries with high political risk, political dynamics and policy issued by the government are affecting on how investors make their investment decisions. Negative sentiment, for example, are causing foreign investors to release their shares and invest in other countries. In addition, the Indonesian capital market is relatively a weak capital market, therefore investors are very sensitive to changes that occur in the country, especially those related to political factors.</p><p>A study by Thampayana and Wu also suggested that behavioral factors plays a bigger role than fundamental factors in affecting market volatility in Indonesia as a result from measures taken by investors due to unstable political environment.</p><p>To sum up, behavioral factors comes into play when the price move away from their intrinsic value. In Indonesia, due to its high political risk, investors decision is sensitively affected to changes that occur in the political condition of the country, which ultimately lead to the increase of market volatility.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=9ca27327b573" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Why Now is a Great Time to Buy Stocks]]></title>
            <link>https://kautsr.medium.com/why-now-is-a-great-time-to-buy-stocks-1bae813e7101?source=rss-b190c0874170------2</link>
            <guid isPermaLink="false">https://medium.com/p/1bae813e7101</guid>
            <category><![CDATA[stock-market]]></category>
            <category><![CDATA[economy]]></category>
            <category><![CDATA[macroeconomics]]></category>
            <category><![CDATA[indonesia-economy]]></category>
            <category><![CDATA[economic-recovery]]></category>
            <dc:creator><![CDATA[Alwan Alkautsar]]></dc:creator>
            <pubDate>Sat, 21 Nov 2020 08:15:48 GMT</pubDate>
            <atom:updated>2020-11-22T14:26:00.765Z</atom:updated>
            <content:encoded><![CDATA[<p>The coronavirus pandemic has brought a negative effect not only to the global economy but also to the stock market. Yet, according to a survey held by <a href="https://medium.com/r?url=https%3A%2F%2Fwww.mckinsey.com%2Fbusiness-functions%2Fstrategy-and-corporate-finance%2Four-insights%2Fthe-coronavirus-effect-on-global-economic-sentiment">McKinsey</a>, economic and corporate outlooks have remained more optimistic than negative as the result shows that the majority of respondents anticipate a rise in the global growth rate over the next six months.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*tp40Fs3hTeHmYaoTfaNSiA.jpeg" /><figcaption>Meaningless Illustration hehe</figcaption></figure><h4>The Big Picture — Indonesia Economy is Recovering</h4><p>In analyzing economy for investing, we use an approach known as the top-down analysis. The top-down approach focuses on the big picture, or how the overall economy, down to each industrial sectors and, ultimately, the stock price of each companies.</p><p>Commonly, investors will try to identify which economic cycle a country is going through as it would give them an edge in managing their portfolio in order to obtain the highest chance of profit. This can be done by measuring the GDP growth rate of a country. There are four stages in the economic cycle: expansion/boom, peak, contraction/recession, and trough.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1000/1*uf8FC7znRiLexk59mJLsBA.png" /><figcaption><strong>Figure 1. The Economic Cycle. </strong><em>(Courtesy of Intelligent Economist)</em></figcaption></figure><p>If you’re unfamiliar with the concept, you can read in details the economic cycle <a href="https://www.investopedia.com/terms/e/economic-cycle.asp">here</a>. For this article, I’m just going to focus on discussing the recovery stage of the economic cycle.</p><p>As shown in the graph on Figure 1, the economic cycle recovery stage marks the beginning of the economy’s improvement. Economic activity is beginning to pick up. Investment, employment, confidence, spending, and prices are starting to increase. This occurs as low prices help to fuel higher levels of demand, and production and employment levels are beginning to rise at the same time. At this moment, lending is also increasing, further contributing to economic revitalization.</p><p><em>“Recovery story is equity friendly”, </em>is a famous saying among investors. As I mentioned before, the increase in spending and prices means that businesses will secure higher earning. Not to mention that it means that credit risk will relatively be lower as the economy begins to recover. All this being said, investors tends to shift their investment portfolio to stocks, hence the saying <em>“Recovery story is equity friendly”.</em></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*nCnp4rPfxhwT3MvmzmeTkw.jpeg" /><figcaption><strong>Figure 2. Indonesian GDP Growth Rate (%). </strong><em>(Courtesy of CEIC)</em></figcaption></figure><p>Figure 2 shows Indonesia’s GDP growth in the last few quarter. Real GDP declined by 5.32% in Q2 2020 after growing by 2.97% in Q1 2020 as the effects of the coronavirus pandemic undermined both domestic and external demands indicator. During Q3 2020, as consumptions starting to picked up, though it’s still recorded as a 3.49% decline, it’s still an improvement compared to the previous quarter and a good sign that the economy begin to recover.</p><h4>The Index</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Becff2wdcuawA0f6FCj6hA.png" /><figcaption><strong>Figure 3. IDX Price Movement Chart</strong></figcaption></figure><p>After a massive dip in the stock market in Q1 2020, the index price slowly begins to pick up. A notable increase in transaction volume from Q3 2020, which also leads to the increase of index price, also shows that confidence among investors that the economy is recovering.</p><p>All in all, as Indonesia’s economy is recovering from the coronavirus pandemic, I believe that it’s the right time to shift our portfolio from a safer, low return investment to a relatively riskier, but more profitable stocks. Moreover, if we can identify which industries/sectors and companies that have a good prospects for the periods to come, I’m convinced that we will secure our desirable return on our investments in the stock market.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=1bae813e7101" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>