{"id":19570,"date":"2019-09-27T12:53:32","date_gmt":"2019-09-27T16:53:32","guid":{"rendered":"https:\/\/ibkrcampus.com\/?p=19570"},"modified":"2022-11-21T09:44:18","modified_gmt":"2022-11-21T14:44:18","slug":"k-means-clustering-algo-part-ii","status":"publish","type":"post","link":"https:\/\/www.interactivebrokers.com\/campus\/ibkr-quant-news\/k-means-clustering-algo-part-ii\/","title":{"rendered":"K-Means Clustering Algorithm For Pair Selection In Python \u2013 Part II"},"content":{"rendered":"\n<p class=\"wp-block-paragraph\"><em>In the first installment, Lamarcus explained  <\/em><a href=\"\/campus\/ibkr-quant-news\/k-means-clustering-algo-part-i\/\"><em>K-Means Clustering<\/em><\/a><em>. In today&#8217;s article, the author will try to implement statistical arbitrage without using K-Means first. <\/em><\/p>\n\n\n\n<p class=\"wp-block-paragraph\"><strong>Life Without K-Means<\/strong><\/p>\n\n\n\n<p class=\"wp-block-paragraph\">To gain an understanding of why we may want to use K-Means to solve the problem of pair selection we will attempt to implement a Statistical Arbitrage as if there was no K-Means. This means that we will attempt to develop a brute force solution to our pair selection problem and then apply that solution within our Statistical Arbitrage strategy.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\">Let&#8217;s take a moment to think about why K-Means could be used for trading. What&#8217;s the benefit of using K-Means to form subgroups of possible pairs? I mean couldn&#8217;t we just come up with the pairs ourselves?<\/p>\n\n\n\n<p class=\"wp-block-paragraph\">This is a great question and one undoubtedly you may have wondered about. To better understand the strength of using a technique like K-Means for Statistical Arbitrage, we&#8217;ll do a walk-through of trading a Statistical Arbitrage strategy if there was no K-Means. I&#8217;ll be your ghost of trading past so to speak.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\">First, let&#8217;s identify the key components of any Statistical Arbitrage trading strategy.<\/p>\n\n\n\n<ol class=\"wp-block-list\"><li>We must identify assets that have a tradable relationship<\/li><li>We must calculate the Z-Score of the spread of these assets, as well as the hedge ratio for position sizing<\/li><li>We generate buy and sell decisions when the Z-Score exceeds some upper or lower bound<\/li><\/ol>\n\n\n\n<p class=\"wp-block-paragraph\">To begin we need some pairs to trade. But we can&#8217;t trade Statistical Arbitrage without knowing whether or not the pairs we select are cointegrated. Cointegration simply means that the statistical properties between our two assets are stable. Even if the two assets move randomly, we can count on the relationship between them to be constant, or at least most of the time.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\">Traditionally, when solving the problem of pair selection, in a world with no K-Means, we must find pairs by brute force, or trial and error. This was usually done by grouping stocks together that were merely in the same sector or industry. The idea was that if these stocks were of companies in similar industries, thus having similarities in their operations, their stocks should move similarly as well. But, as we shall see, this is not necessarily the case.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\">The first step is to think of some pairs of stocks that should yield a trading relationship. We&#8217;ll use stocks in the S&amp;P 500 but this process could be applied to any stocks within any index. Hmm, how about Walmart and Target. They both are retailers and direct competitors. Surely they should be cointegrated and thus would allow us to trade them in a Statistical Arbitrage Strategy.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\">Let&#8217;s begin by importing the necessary libraries as well as the data that we will need. We will use 2014-2016 as our analysis period.<\/p>\n\n\n\n<p style=\"background-color:#fcfcdb;font-size:11px\" class=\"has-background wp-block-paragraph\">#importing necessary libraries<br>\n#data analysis\/manipulation<br>\nimport numpy as np<br>\nimport pandas as pd<br>\n#importing pandas datareader to get our data<br>\nimport pandas_datareader as pdr<br>\n#importing the Augmented Dickey Fuller Test to check for cointegration<br>\nfrom statsmodels.tsa.api import adfuller<\/p>\n\n\n\n<p class=\"wp-block-paragraph\"><br><\/p>\n\n\n\n<p class=\"wp-block-paragraph\"><em>In the next article, Lamarcus will work with the data and provide the sample code.<\/em><\/p>\n","protected":false},"excerpt":{"rendered":"<p>Let&#8217;s take a moment to think about why K-Means could be used for trading. What&#8217;s the benefit of using K-Means to form subgroups of possible pairs?<\/p>\n","protected":false},"author":261,"featured_media":0,"comment_status":"closed","ping_status":"open","sticky":false,"template":"","format":"standard","meta":{"_acf_changed":false,"footnotes":"","jetpack_post_was_ever_published":false},"categories":[339,343,349,338,341,352,344],"tags":[851,806,4124,852,595,4271,4270],"contributors-categories":[13654],"class_list":["post-19570","post","type-post","status-publish","format-standard","category-data-science","category-programing-languages","category-python-development","category-ibkr-quant-news","category-quant-development","category-quant-north-america","category-quant-regions","tag-algo-trading","tag-data-science","tag-k-means-clustering","tag-machine-learning","tag-python","tag-statistical-arbitrage","tag-z-score","contributors-categories-quantinsti"],"pp_statuses_selecting_workflow":false,"pp_workflow_action":"current","pp_status_selection":"publish","acf":[],"yoast_head":"<!-- This site is optimized with the Yoast SEO Premium plugin v26.9 (Yoast SEO v28.3) - https:\/\/yoast.com\/product\/yoast-seo-premium-wordpress\/ -->\n<title>K-Means Clustering Algorithm For Pair Selection In Python \u2013 Part II<\/title>\n<meta name=\"description\" content=\"Lamarcus from QuantInsti discusses the benefit of using K-Means for trading, and how to form subgroups of possible pairs\" \/>\n<meta name=\"robots\" content=\"index, follow, max-snippet:-1, max-image-preview:large, max-video-preview:-1\" \/>\n<link rel=\"canonical\" href=\"https:\/\/www.interactivebrokers.com\/campus\/wp-json\/wp\/v2\/posts\/19570\/\" \/>\n<meta property=\"og:locale\" content=\"en_US\" \/>\n<meta property=\"og:type\" content=\"article\" \/>\n<meta property=\"og:title\" content=\"K-Means Clustering Algorithm For Pair Selection In Python \u2013 Part II\" \/>\n<meta property=\"og:description\" content=\"Lamarcus from QuantInsti discusses the benefit of using K-Means for trading, and how to form subgroups of possible pairs\" \/>\n<meta property=\"og:url\" content=\"https:\/\/www.interactivebrokers.com\/campus\/ibkr-quant-news\/k-means-clustering-algo-part-ii\/\" \/>\n<meta property=\"og:site_name\" content=\"IBKR Campus US\" \/>\n<meta property=\"article:published_time\" content=\"2019-09-27T16:53:32+00:00\" \/>\n<meta property=\"article:modified_time\" content=\"2022-11-21T14:44:18+00:00\" \/>\n<meta name=\"author\" content=\"Lamarcus Coleman\" \/>\n<meta name=\"twitter:card\" content=\"summary_large_image\" \/>\n<meta name=\"twitter:label1\" content=\"Written by\" \/>\n\t<meta name=\"twitter:data1\" content=\"Lamarcus Coleman\" \/>\n\t<meta name=\"twitter:label2\" content=\"Est. reading time\" \/>\n\t<meta name=\"twitter:data2\" content=\"3 minutes\" \/>\n<script type=\"application\/ld+json\" class=\"yoast-schema-graph\">{\n\t    \"@context\": \"https:\\\/\\\/schema.org\",\n\t    \"@graph\": [\n\t        {\n\t            \"@type\": \"NewsArticle\",\n\t            \"@id\": \"https:\\\/\\\/www.interactivebrokers.com\\\/campus\\\/ibkr-quant-news\\\/k-means-clustering-algo-part-ii\\\/#article\",\n\t            \"isPartOf\": {\n\t                \"@id\": \"https:\\\/\\\/www.interactivebrokers.com\\\/campus\\\/ibkr-quant-news\\\/k-means-clustering-algo-part-ii\\\/\"\n\t            },\n\t            \"author\": {\n\t                \"name\": \"Lamarcus Coleman\",\n\t                \"@id\": \"https:\\\/\\\/ibkrcampus.com\\\/campus\\\/#\\\/schema\\\/person\\\/d25f2d2d80f2efd41c14efd1767f840d\"\n\t            },\n\t            \"headline\": \"K-Means Clustering Algorithm For Pair Selection In Python \u2013 Part II\",\n\t            \"datePublished\": \"2019-09-27T16:53:32+00:00\",\n\t            \"dateModified\": \"2022-11-21T14:44:18+00:00\",\n\t            \"mainEntityOfPage\": {\n\t                \"@id\": \"https:\\\/\\\/www.interactivebrokers.com\\\/campus\\\/ibkr-quant-news\\\/k-means-clustering-algo-part-ii\\\/\"\n\t            },\n\t            \"wordCount\": 542,\n\t            \"publisher\": {\n\t                \"@id\": \"https:\\\/\\\/ibkrcampus.com\\\/campus\\\/#organization\"\n\t            },\n\t            \"keywords\": [\n\t                \"Algo Trading\",\n\t                \"Data Science\",\n\t                \"K-Means Clustering\",\n\t                \"Machine Learning\",\n\t                \"Python\",\n\t                \"Statistical Arbitrage\",\n\t                \"Z-Score\"\n\t            ],\n\t            \"articleSection\": [\n\t                \"Data Science\",\n\t                \"Programming Languages\",\n\t                \"Python Development\",\n\t                \"Quant\",\n\t                \"Quant Development\",\n\t                \"Quant North America\",\n\t                \"Quant Regions\"\n\t            ],\n\t            \"inLanguage\": \"en-US\"\n\t        },\n\t        {\n\t            \"@type\": \"WebPage\",\n\t            \"@id\": \"https:\\\/\\\/www.interactivebrokers.com\\\/campus\\\/ibkr-quant-news\\\/k-means-clustering-algo-part-ii\\\/\",\n\t            \"url\": \"https:\\\/\\\/www.interactivebrokers.com\\\/campus\\\/ibkr-quant-news\\\/k-means-clustering-algo-part-ii\\\/\",\n\t            \"name\": \"K-Means Clustering Algorithm For Pair Selection In Python \u2013 Part II\",\n\t            \"isPartOf\": {\n\t                \"@id\": \"https:\\\/\\\/ibkrcampus.com\\\/campus\\\/#website\"\n\t            },\n\t            \"datePublished\": \"2019-09-27T16:53:32+00:00\",\n\t            \"dateModified\": \"2022-11-21T14:44:18+00:00\",\n\t            \"description\": \"Lamarcus from QuantInsti discusses the benefit of using K-Means for trading, and how to form subgroups of possible pairs\",\n\t            \"inLanguage\": \"en-US\",\n\t            \"potentialAction\": [\n\t                {\n\t                    \"@type\": \"ReadAction\",\n\t                    \"target\": [\n\t                        \"https:\\\/\\\/www.interactivebrokers.com\\\/campus\\\/ibkr-quant-news\\\/k-means-clustering-algo-part-ii\\\/\"\n\t                    ]\n\t                }\n\t            ]\n\t        },\n\t        {\n\t            \"@type\": \"WebSite\",\n\t            \"@id\": \"https:\\\/\\\/ibkrcampus.com\\\/campus\\\/#website\",\n\t            \"url\": \"https:\\\/\\\/ibkrcampus.com\\\/campus\\\/\",\n\t            \"name\": \"IBKR Campus US\",\n\t            \"description\": \"Financial Education from Interactive Brokers\",\n\t            \"publisher\": {\n\t                \"@id\": \"https:\\\/\\\/ibkrcampus.com\\\/campus\\\/#organization\"\n\t            },\n\t            \"potentialAction\": [\n\t                {\n\t                    \"@type\": \"SearchAction\",\n\t                    \"target\": {\n\t                        \"@type\": \"EntryPoint\",\n\t                        \"urlTemplate\": \"https:\\\/\\\/ibkrcampus.com\\\/campus\\\/?s={search_term_string}\"\n\t                    },\n\t                    \"query-input\": {\n\t                        \"@type\": \"PropertyValueSpecification\",\n\t                        \"valueRequired\": true,\n\t                        \"valueName\": \"search_term_string\"\n\t                    }\n\t                }\n\t            ],\n\t            \"inLanguage\": \"en-US\"\n\t        },\n\t        {\n\t            \"@type\": \"Organization\",\n\t            \"@id\": \"https:\\\/\\\/ibkrcampus.com\\\/campus\\\/#organization\",\n\t            \"name\": \"Interactive Brokers\",\n\t            \"alternateName\": \"IBKR\",\n\t            \"url\": \"https:\\\/\\\/ibkrcampus.com\\\/campus\\\/\",\n\t            \"logo\": {\n\t                \"@type\": \"ImageObject\",\n\t                \"inLanguage\": \"en-US\",\n\t                \"@id\": \"https:\\\/\\\/ibkrcampus.com\\\/campus\\\/#\\\/schema\\\/logo\\\/image\\\/\",\n\t                \"url\": \"https:\\\/\\\/www.interactivebrokers.com\\\/campus\\\/wp-content\\\/uploads\\\/sites\\\/2\\\/2024\\\/05\\\/ibkr-campus-logo.jpg\",\n\t                \"contentUrl\": \"https:\\\/\\\/www.interactivebrokers.com\\\/campus\\\/wp-content\\\/uploads\\\/sites\\\/2\\\/2024\\\/05\\\/ibkr-campus-logo.jpg\",\n\t                \"width\": 669,\n\t                \"height\": 669,\n\t                \"caption\": \"Interactive Brokers\"\n\t            },\n\t            \"image\": {\n\t                \"@id\": \"https:\\\/\\\/ibkrcampus.com\\\/campus\\\/#\\\/schema\\\/logo\\\/image\\\/\"\n\t            },\n\t            \"publishingPrinciples\": \"https:\\\/\\\/www.interactivebrokers.com\\\/campus\\\/about-ibkr-campus\\\/\",\n\t            \"ethicsPolicy\": \"https:\\\/\\\/www.interactivebrokers.com\\\/campus\\\/cyber-security-notice\\\/\"\n\t        },\n\t        {\n\t            \"@type\": \"Person\",\n\t            \"@id\": \"https:\\\/\\\/ibkrcampus.com\\\/campus\\\/#\\\/schema\\\/person\\\/d25f2d2d80f2efd41c14efd1767f840d\",\n\t            \"name\": \"Lamarcus Coleman\",\n\t            \"url\": \"https:\\\/\\\/www.interactivebrokers.com\\\/campus\\\/author\\\/lamarcuscoleman\\\/\"\n\t        }\n\t    ]\n\t}<\/script>\n<!-- \/ Yoast SEO Premium plugin. -->","yoast_head_json":{"title":"K-Means Clustering Algorithm For Pair Selection In Python \u2013 Part II","description":"Lamarcus from QuantInsti discusses the benefit of using K-Means for trading, and how to form subgroups of possible pairs","robots":{"index":"index","follow":"follow","max-snippet":"max-snippet:-1","max-image-preview":"max-image-preview:large","max-video-preview":"max-video-preview:-1"},"canonical":"https:\/\/www.interactivebrokers.com\/campus\/wp-json\/wp\/v2\/posts\/19570\/","og_locale":"en_US","og_type":"article","og_title":"K-Means Clustering Algorithm For Pair Selection In Python \u2013 Part II","og_description":"Lamarcus from QuantInsti discusses the benefit of using K-Means for trading, and how to form subgroups of possible pairs","og_url":"https:\/\/www.interactivebrokers.com\/campus\/ibkr-quant-news\/k-means-clustering-algo-part-ii\/","og_site_name":"IBKR Campus US","article_published_time":"2019-09-27T16:53:32+00:00","article_modified_time":"2022-11-21T14:44:18+00:00","author":"Lamarcus Coleman","twitter_card":"summary_large_image","twitter_misc":{"Written by":"Lamarcus Coleman","Est. reading time":"3 minutes"},"schema":{"@context":"https:\/\/schema.org","@graph":[{"@type":"NewsArticle","@id":"https:\/\/www.interactivebrokers.com\/campus\/ibkr-quant-news\/k-means-clustering-algo-part-ii\/#article","isPartOf":{"@id":"https:\/\/www.interactivebrokers.com\/campus\/ibkr-quant-news\/k-means-clustering-algo-part-ii\/"},"author":{"name":"Lamarcus Coleman","@id":"https:\/\/ibkrcampus.com\/campus\/#\/schema\/person\/d25f2d2d80f2efd41c14efd1767f840d"},"headline":"K-Means Clustering Algorithm For Pair Selection In Python \u2013 Part II","datePublished":"2019-09-27T16:53:32+00:00","dateModified":"2022-11-21T14:44:18+00:00","mainEntityOfPage":{"@id":"https:\/\/www.interactivebrokers.com\/campus\/ibkr-quant-news\/k-means-clustering-algo-part-ii\/"},"wordCount":542,"publisher":{"@id":"https:\/\/ibkrcampus.com\/campus\/#organization"},"keywords":["Algo Trading","Data Science","K-Means Clustering","Machine Learning","Python","Statistical Arbitrage","Z-Score"],"articleSection":["Data Science","Programming Languages","Python Development","Quant","Quant Development","Quant North America","Quant Regions"],"inLanguage":"en-US"},{"@type":"WebPage","@id":"https:\/\/www.interactivebrokers.com\/campus\/ibkr-quant-news\/k-means-clustering-algo-part-ii\/","url":"https:\/\/www.interactivebrokers.com\/campus\/ibkr-quant-news\/k-means-clustering-algo-part-ii\/","name":"K-Means Clustering Algorithm For Pair Selection In Python \u2013 Part II","isPartOf":{"@id":"https:\/\/ibkrcampus.com\/campus\/#website"},"datePublished":"2019-09-27T16:53:32+00:00","dateModified":"2022-11-21T14:44:18+00:00","description":"Lamarcus from QuantInsti discusses the benefit of using K-Means for trading, and how to form subgroups of possible pairs","inLanguage":"en-US","potentialAction":[{"@type":"ReadAction","target":["https:\/\/www.interactivebrokers.com\/campus\/ibkr-quant-news\/k-means-clustering-algo-part-ii\/"]}]},{"@type":"WebSite","@id":"https:\/\/ibkrcampus.com\/campus\/#website","url":"https:\/\/ibkrcampus.com\/campus\/","name":"IBKR Campus US","description":"Financial Education from Interactive Brokers","publisher":{"@id":"https:\/\/ibkrcampus.com\/campus\/#organization"},"potentialAction":[{"@type":"SearchAction","target":{"@type":"EntryPoint","urlTemplate":"https:\/\/ibkrcampus.com\/campus\/?s={search_term_string}"},"query-input":{"@type":"PropertyValueSpecification","valueRequired":true,"valueName":"search_term_string"}}],"inLanguage":"en-US"},{"@type":"Organization","@id":"https:\/\/ibkrcampus.com\/campus\/#organization","name":"Interactive Brokers","alternateName":"IBKR","url":"https:\/\/ibkrcampus.com\/campus\/","logo":{"@type":"ImageObject","inLanguage":"en-US","@id":"https:\/\/ibkrcampus.com\/campus\/#\/schema\/logo\/image\/","url":"https:\/\/www.interactivebrokers.com\/campus\/wp-content\/uploads\/sites\/2\/2024\/05\/ibkr-campus-logo.jpg","contentUrl":"https:\/\/www.interactivebrokers.com\/campus\/wp-content\/uploads\/sites\/2\/2024\/05\/ibkr-campus-logo.jpg","width":669,"height":669,"caption":"Interactive Brokers"},"image":{"@id":"https:\/\/ibkrcampus.com\/campus\/#\/schema\/logo\/image\/"},"publishingPrinciples":"https:\/\/www.interactivebrokers.com\/campus\/about-ibkr-campus\/","ethicsPolicy":"https:\/\/www.interactivebrokers.com\/campus\/cyber-security-notice\/"},{"@type":"Person","@id":"https:\/\/ibkrcampus.com\/campus\/#\/schema\/person\/d25f2d2d80f2efd41c14efd1767f840d","name":"Lamarcus Coleman","url":"https:\/\/www.interactivebrokers.com\/campus\/author\/lamarcuscoleman\/"}]}},"jetpack_featured_media_url":"","_links":{"self":[{"href":"https:\/\/ibkrcampus.com\/campus\/wp-json\/wp\/v2\/posts\/19570","targetHints":{"allow":["GET"]}}],"collection":[{"href":"https:\/\/ibkrcampus.com\/campus\/wp-json\/wp\/v2\/posts"}],"about":[{"href":"https:\/\/ibkrcampus.com\/campus\/wp-json\/wp\/v2\/types\/post"}],"author":[{"embeddable":true,"href":"https:\/\/ibkrcampus.com\/campus\/wp-json\/wp\/v2\/users\/261"}],"replies":[{"embeddable":true,"href":"https:\/\/ibkrcampus.com\/campus\/wp-json\/wp\/v2\/comments?post=19570"}],"version-history":[{"count":0,"href":"https:\/\/ibkrcampus.com\/campus\/wp-json\/wp\/v2\/posts\/19570\/revisions"}],"wp:attachment":[{"href":"https:\/\/ibkrcampus.com\/campus\/wp-json\/wp\/v2\/media?parent=19570"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/ibkrcampus.com\/campus\/wp-json\/wp\/v2\/categories?post=19570"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/ibkrcampus.com\/campus\/wp-json\/wp\/v2\/tags?post=19570"},{"taxonomy":"contributors-categories","embeddable":true,"href":"https:\/\/ibkrcampus.com\/campus\/wp-json\/wp\/v2\/contributors-categories?post=19570"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}