<?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 Karan Thakur on Medium]]></title>
        <description><![CDATA[Stories by Karan Thakur on Medium]]></description>
        <link>https://medium.com/@kt.26karanthakur?source=rss-4a6f6f4d0b06------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*4dD89vTYZB4bdLZWFSSzpQ.png</url>
            <title>Stories by Karan Thakur on Medium</title>
            <link>https://medium.com/@kt.26karanthakur?source=rss-4a6f6f4d0b06------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Sat, 28 Nov 2026 07:47:00 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@kt.26karanthakur/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[Stock Market Signal Analysis Using Fast Fourier Transform]]></title>
            <link>https://medium.com/@kt.26karanthakur/stock-market-signal-analysis-using-fast-fourier-transform-e3bdde7bcee6?source=rss-4a6f6f4d0b06------2</link>
            <guid isPermaLink="false">https://medium.com/p/e3bdde7bcee6</guid>
            <category><![CDATA[python]]></category>
            <category><![CDATA[quantitative-finance]]></category>
            <category><![CDATA[finance]]></category>
            <category><![CDATA[mathematics]]></category>
            <category><![CDATA[signal-processing]]></category>
            <dc:creator><![CDATA[Karan Thakur]]></dc:creator>
            <pubDate>Tue, 25 Jun 2024 17:03:20 GMT</pubDate>
            <atom:updated>2024-06-26T11:58:49.121Z</atom:updated>
            <content:encoded><![CDATA[<h3>Introduction</h3><p>Financial markets are inherently noisy and unpredictable, posing significant challenges for traders and investors seeking to identify and exploit profitable opportunities.</p><p>To navigate this complexity, modern day traders use a variety of mathematical and statistical techniques to filter out the noise and gain a clearer understanding of underlying cycles/trends in the data. One such powerful tool is the Fast Fourier Transform (FFT) Algorithm, an algorithm designed for the representing any signal/wave as a sum of its sine components with varying frequency. Therefore converting a signal from its time domain to frequency domain.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/900/1*e-_z80BnbHWyFTfRLblJ_w.gif" /></figure><p>The FFT algorithm discussed here in this article uses signal processing to detect the most significant frequencies and therefore removing noise from data.</p><h3><strong>Why make use of FFT?</strong></h3><h4><strong>Detecting Cycles and Patterns</strong></h4><p>Financial time series, such as stock prices or trading volumes, often exhibit periodic patterns due to various economic cycles, seasonality, or investor behaviour. The Fourier Transform helps to identify these cycles and their corresponding frequencies.</p><h4><strong>Filtering Noise</strong></h4><p>Financial data is often noisy due to random fluctuations. By transforming the data into the frequency domain, analysts can filter out high-frequency noise to focus on significant lower-frequency trends.</p><h4><strong>Predictive Modelling</strong></h4><p>By identifying dominant frequencies, analysts can make predictions about future price movements or trends based on historical patterns.</p><h4><strong>Feature Extraction for Machine Learning</strong></h4><p>The frequency components obtained from the Fourier Transform can be used as features in machine learning models to improve the accuracy of predictions.</p><h3><strong>Code And Step By Step Analysis</strong></h3><h4>Setting up the notebook and collection of stock data</h4><p>The first step would involve importing of libraries required for elementary stock data collection and data frame manipulation.</p><p>We will also be setting the period of our analysis to 1 year and the stock under study would be Tata Consultancy Services (TCS). OLHCAV data for the required stock is stored in dataframe named ‘df’.</p><pre>#importing libraries<br>import pandas as pd<br>from pandas_datareader import data as pdr<br>import numpy as np<br>import math<br>import datetime<br>import scipy.stats as stats<br>import matplotlib.pyplot as plt<br>import yfinance as yfin<br>yfin.pdr_override()<br><br># setting the period of analysis<br>end_date = datetime.datetime.now()<br>start_date = end_date - datetime.timedelta(365)<br>ticker = &#39;TCS&#39;<br><br>df = pdr.get_data_yahoo(ticker + &#39;.NS&#39;, start = start_date, end = end_date)</pre><h4>Application of FFT</h4><p>We will be using np.fft.fft() to perform the fit transformations, we also get the frequencies using np.fft.fftfreq(). We can plot the magnitude vs periods to indicate when the most important frequencies occur.</p><pre>fft_result = np.fft.fft(df[&#39;Close&#39;])<br>frequencies = np.fft.fftfreq(len(fft_result), d=1)  # assuming daily data, d=1<br>magnitude = np.abs(fft_result)<br>periods = 1 / frequencies</pre><h4>Visualisation of Price and Frequency Domain Representation</h4><p>The frequency plot below highlights the dominant frequencies within the time series. These frequencies can be used to perform an inverse FFT, allowing us to recreate the original time series or produce a version with reduced noise.</p><pre># simple visualisation of price<br>plt.figure(figsize=(10, 8))<br>plt.subplot(2, 1, 1)<br>plt.plot(df.index, df[&#39;Close&#39;])<br>plt.title(&#39;TCS Time Series&#39;)<br>plt.xlabel(&#39;Date&#39;)<br>plt.ylabel(&#39;Price&#39;)<br><br># frequency domain representation<br>plt.subplot(2, 1, 2)<br>plt.plot(periods, magnitude)<br>plt.title(&#39;FFT of TCS&#39;)<br>plt.xlabel(&#39;Period (Days)&#39;)<br>plt.ylabel(&#39;Magnitude&#39;)<br>plt.xlim(0, max(periods[1:]))  # limiting x-axis to view significant periods (ignore large periods)<br>plt.ylim(0, max(magnitude[1:]) * 1.1)  # ignore the zero frequency component<br><br>plt.tight_layout()<br>plt.show()</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/986/1*wMc8bEoieU-CfhgADaZwYA.png" /></figure><p>However, the significance of these dominant frequencies extends beyond simply reconstructing the time series. They may be associated with events such as key economic reports or macroeconomic occurrences that impact the time series structure.</p><h4>Recovering the original stock market data</h4><p>We can recover the original time series with the np.fft.ifft() function, which inverts the fft_results. We can see from the graph below that it is perfectly reconstructed.</p><pre>recovered = np.fft.ifft(fft_result)<br>plt.figure(figsize=(14, 6))<br>plt.plot(df.index, df[&#39;Close&#39;], label=&#39;Original&#39;)<br>plt.plot(df.index, recovered, label=&#39;Recovered&#39;)<br>plt.title(&#39;TCS Time Series: FFT Inverse&#39;)<br>plt.xlabel(&#39;Date&#39;)<br>plt.ylabel(&#39;Price&#39;)<br>plt.legend()<br>plt.show()</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*mviJZRuDVkxSNfrewQ3nJQ.png" /></figure><h4>Reconstruction of wave with dominant frequencies</h4><p>This produces the reconstructed signal with only the top 25 FFT frequencies. This is essentially a denoising of the data.</p><pre>dominant_periods = pd.Series(periods, index = magnitude).nlargest(25)<br>dominant_periods.to_frame(&#39;Period (Days)&#39;)<br>top_periods = dominant_periods.index<br>top_fft_result = fft_result.copy()<br>top_fft_result[np.abs(frequencies) &gt; 1 / top_periods.min()] = 0<br>top_recovered = np.fft.ifft(top_fft_result)<br><br><br>plt.figure(figsize = (14, 6))<br>plt.plot(df.index, df[&#39;Close&#39;], label = &#39;Original&#39;)<br>plt.plot(df.index, top_recovered, label = &#39;Recovered&#39;)<br>plt.title(&#39;TCS Time Series: FFT Inverse&#39;)<br>plt.xlabel(&#39;Date&#39;)<br>plt.ylabel(&#39;Price&#39;)<br>plt.legend()<br>plt.show()</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*rPGuhyH6vbk0ZUf_jENeQw.png" /></figure><h3>Conclusion</h3><p>The algorithm I have explained in this article represents a gross oversimplification of the analysis used by industry experts. Model tweaks are generally made on a daily basis to improve performance.</p><p>I hope this helped, you can find the github file here: <a href="https://github.com/karantha-kur/Signal-Analysis-Using-FFT/tree/main">https://github.com/karantha-kur/Signal-Analysis-Using-FFT/tree/main</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=e3bdde7bcee6" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Why is Euclidean Distance Not Always The Best?]]></title>
            <link>https://medium.com/@kt.26karanthakur/why-is-euclidean-distance-not-always-the-best-51bf57d66fdf?source=rss-4a6f6f4d0b06------2</link>
            <guid isPermaLink="false">https://medium.com/p/51bf57d66fdf</guid>
            <category><![CDATA[data-analysis]]></category>
            <category><![CDATA[data-science]]></category>
            <category><![CDATA[multivariate-analysis]]></category>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[python]]></category>
            <dc:creator><![CDATA[Karan Thakur]]></dc:creator>
            <pubDate>Sun, 31 Mar 2024 18:11:40 GMT</pubDate>
            <atom:updated>2024-03-31T18:11:40.176Z</atom:updated>
            <content:encoded><![CDATA[<h3>Why is Euclidean Distance Not Always The Best? | Exploring Multivariate Analysis with Mahalanobis Distance</h3><p>One of the underlying assumptions for the Euclidean Distance is that the axes (features) are independent.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*m98jiFIdt4S4I1eKeQndjg.png" /></figure><p>For any type of correlation not realising the mistake will produce misleading results.</p><p>Consider the scatter plot of the dummy dataset below:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Szm6HELszrb9P_6m1h0z4w.png" /></figure><p>In this dataset there is an obvious positive correlation between the 2 features, now let us also consider 3 data points P1, P2 and P3.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Ph6vGF66sdXE3XtbMQ_7hw.png" /></figure><p>Considering the data distribution we can intuitive say that P2 is closer to P1 than P3 just because it lies more within the data set, i.e. in other words the distance between point P2 and the distribution is lesser than that of P3 and the distribution.</p><p>But, when we calculate the Euclidean Distance of the points P2 and P3 from P1 we can see that they are the same.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/446/1*Yv1DUqJoGW6j5KO_9kbWYA.png" /><figcaption>Euclidean Distance between the points P2, P3 and P1</figcaption></figure><p>The Mahalanobis Distance measures this limitation as it is a measure of the distance between a point and a distribution, considering correlations and variances of features rendering it important for tasks like outlier detection, clustering, and classification across diverse domains. We get the Mahalanobis Distance from the formula:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/782/1*3fdzlU09PhX8h2E1h_vHEA.png" /><figcaption>Formula for calculating the Mahalanobis Distance, where x = Input Array, S = Covariance Matrix, <em>μ = Mean</em></figcaption></figure><p>The significance of the above given formula is:</p><p>Step 1: Transform the columns into uncorrelated variables.</p><p>Step 2: Scale the new variables to make their variance equal to 1.</p><p>Step 3: Find the Euclidean Distance in this new coordinate system.</p><p>Taking the previous example again and the calculating the Mahalanobis Distance for the points again we get:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Ph6vGF66sdXE3XtbMQ_7hw.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/626/1*Q0I7xzLEW8Pe6AoLbbC53w.png" /><figcaption>Mahalanobis Distance between points P2, P3 and P1</figcaption></figure><p>This metric paints a better picture regarding the data points. This method becomes even more useful in a high-dimensional setting where visualisation is not possible.</p><h3><strong>Use Cases</strong></h3><ol><li>Outlier Detection: Identifying unusual data points in a dataset by measuring their distance from the distribution centre.</li><li>Clustering: Grouping data points based on similarity, where Mahalanobis Distance helps determine cluster membership by considering the shape and orientation of the data distribution.</li><li>Classification: Utilised in classification algorithms to calculate distances between data points and class centroids, aiding in assigning class labels to new instances.</li><li>Anomaly Detection: Detecting abnormalities or deviations from expected patterns in data, such as fraud detection in finance or equipment failure prediction in manufacturing.</li><li>Quality Control: Assessing the quality of manufactured products by comparing their characteristics with a reference distribution, enabling early detection of defects.</li><li>Biometrics: Verifying or identifying individuals based on their physiological or behavioural characteristics, where Mahalanobis Distance helps quantify the dissimilarity between feature vectors.</li></ol><h3>Implementation in Python</h3><pre>#importing the libraries<br><br>import numpy as np <br>import pandas as pd <br>import scipy as stats <br>  <br># calculate_mahalanobis function to calculate the Mahalanobis distance <br>def calculate_mahalanobis(y = None, data = None, cov = None): <br>    y_mu = y - np.mean(data) <br>    if not cov: <br>        cov = np.cov(data.values.T) <br>    inv_covmat = np.linalg.inv(cov) <br>    left = np.dot(y_mu, inv_covmat) <br>    mahal = np.dot(left, y_mu.T) <br>    return mahal.diagonal() <br>  <br># data <br>data = { &#39;Price&#39;: [100000, 800000, 650000, 700000,  <br>                   860000, 730000, 400000, 870000, <br>                   780000, 400000], <br>         &#39;Distance&#39;: [16000, 60000, 300000, 10000,  <br>                      252000, 350000, 260000, 510000,  <br>                      2000, 5000], <br>         &#39;Emission&#39;: [300, 400, 1230, 300, 400, 104, <br>                      632, 221, 142, 267], <br>         &#39;Performance&#39;: [60, 88, 90, 87, 83, 81, 72,  <br>                         91, 90, 93], <br>         &#39;Mileage&#39;: [76, 89, 89, 57, 79, 84, 78, 99,  <br>                     97, 99] <br>           } <br>  <br># Creating dataset <br>df = pd.DataFrame(data, columns = [&#39;Price&#39;, &#39;Distance&#39;, <br>                                   &#39;Emission&#39;,&#39;Performance&#39;, &#39;Mileage&#39;]) <br>  <br><br>df[&#39;calculateMahalanobis&#39;] = calculate_mahalanobis(y=df, data=df[[ <br>  &#39;Price&#39;, &#39;Distance&#39;, &#39;Emission&#39;,&#39;Performance&#39;, &#39;Mileage&#39;]]) <br><br>df.head()<br></pre><p>You can also view the official scipy manual here:</p><p><a href="https://docs.scipy.org/doc/scipy/reference/generated/scipy.spatial.distance.mahalanobis.html">scipy.spatial.distance.mahalanobis - SciPy v1.12.0 Manual</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=51bf57d66fdf" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Importing and Visualising financial data in Python]]></title>
            <link>https://medium.com/@kt.26karanthakur/importing-and-visualising-financial-data-in-python-0bc560ea0259?source=rss-4a6f6f4d0b06------2</link>
            <guid isPermaLink="false">https://medium.com/p/0bc560ea0259</guid>
            <category><![CDATA[financial-analysis]]></category>
            <category><![CDATA[data]]></category>
            <category><![CDATA[finance]]></category>
            <category><![CDATA[technical-indicator]]></category>
            <category><![CDATA[python]]></category>
            <dc:creator><![CDATA[Karan Thakur]]></dc:creator>
            <pubDate>Sun, 24 Dec 2023 14:33:07 GMT</pubDate>
            <atom:updated>2023-12-24T14:33:07.022Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*SsQ3Ms3vvhDMuG8s" /><figcaption>Photo by <a href="https://unsplash.com/@lukechesser?utm_source=medium&amp;utm_medium=referral">Luke Chesser</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p>Initiating the analysis of data in Python involves the first step of importing and visualising the data,(we will be using Yahoo Finance for this blog) maybe even drawing some initial insights from the price chart. This blog is dedicated to guiding you through the complete process of importing historical financial data for any company on the American (AMEX) as well as the Indian market (NSE).</p><p>This method works for best with python notebooks such as JuPyter or Google Colab.</p><ul><li><strong>Importing the required libraries</strong></li></ul><ol><li>For importing financial data</li></ol><pre>import datetime <br>from pandas_datareader import data as pdr</pre><p><strong>Datetime: </strong>This library allows us to set the amount of days of historical data we require, the default in this blog is 365 days.</p><p><strong>Pandas_datareader: </strong>This<strong> </strong>is a Python library that provides functions to access financial data from various online sources directly into a Pandas DataFrame. It serves as a convenient tool for fetching data for analysis and manipulation in Python.</p><p>2. <strong>For visualisation</strong></p><p>We will be using simple line charts and for this matplotlib is a sufficient library.</p><pre>import matplotlib.pyplot as plt</pre><ul><li><strong>Creating the function</strong></li></ul><ol><li><strong>For setting the time frame</strong></li></ol><p>This is necessary to set the number of days you want your data to go. In this case I have set it as 1 year from the current date (although I am aware a year has only 242 trading days).</p><pre>end_date = datetime.datetime.now()<br>start_date = end_date - datetime.timedelta(365)</pre><p>2. <strong>For storing financial data</strong></p><pre>def get_data(ticker):<br>  asset = pdr.get_data_yahoo(ticker, start = start_date, end = end_date)<br>  asset.reset_index(inplace = True)<br>  return asset</pre><p>If we want to use data from the Indian Stock Market (NSE) on yahoo finance we will have to add the country code for India which is ‘.NS’, a small modification to the above code can be simply performed.</p><pre>def get_data(ticker):<br>  asset = pdr.get_data_yahoo(ticker + &#39;.NS&#39;, start = start_date, end = end_date)<br>  asset.reset_index(inplace = True)<br>  return asset</pre><p>The above method is the best and simple way as it returns 6 columns namely; Date, Open, High, Low, Close, Adj Close, and Volume.</p><p>3.<strong> For visualising financial data</strong></p><p>To plot simple price chart we can use the given below function.</p><pre>def visualise(ticker):<br>  plt.plot(ticker[&#39;Date&#39;], ticker[&#39;Adj Close&#39;])<br>  plt.xlabel(&#39;Date&#39;)<br>  plt.ylabel(&#39;Price&#39;)<br>  plt.show()</pre><p>Combining all of the simple above functions we can store and visualise financial data for many companies, the advantage of using this is that we make repeated use of the functions while just changing the ticker.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=0bc560ea0259" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>