<jupyter_start><jupyter_text>Mahalanobis Distance  Mahalanobis distance is the distance between two points in a multivariate space. It’s  used in statistical analyses to find outliers that involve serval variables.  Formula: d(p,q) = √(p1-q1)^2 + (p2-q2)^2<jupyter_code>import numpy as np
import scipy as stats
from scipy.stats import chi2

import warnings
warnings.filterwarnings("ignore") 

# yfinance is used to fetch data 
import yfinance as yf
yf.pdr_override()
symbol = 'AMD'

start = '2018-01-01'
end = '2019-01-01'

# Read data 
dataset = yf.download(symbol,start,end)

# View Columns
dataset.head()
dataset.tail()
dataset = dataset.drop(['Adj Close', 'Volume'], axis=1)
dataset.head()
def mahalanobis_distance(x=None, data=None, cov=None):

    x_mu = x - np.mean(data)
    if not cov:
        cov = np.cov(data.values.T)
    inv_covmat = np.linalg.inv(cov)
    left = np.dot(x_mu, inv_covmat)
    mahal = np.dot(left, x_mu.T)
    return mahal.diagonal()
df = mahalanobis_distance(x=dataset, data=dataset)
df
dataset = dataset.reset_index(drop=True)
dataset.head()
dataset['mahalanobis'] = mahalanobis_distance(x=dataset, data=dataset[['Open', 'High', 'Low', 'Close']])
dataset.head()
dataset['p'] = 1 - chi2.cdf(dataset['mahalanobis'], 4)
dataset.head()<jupyter_output><empty_output>
{'fraction_non_alphanumeric': 0.13843774168600154, 'fraction_numerical': 0.02088167053364269, 'mean_word_length': 5.046728971962617, 'pattern_counts': {'":': 0, '<': 5, '<?xml version=': 0, '>': 5, 'https://': 0, 'lorem ipsum': 0, 'www.': 0, 'xml': 0}, 'pii_count': 0, 'substrings_counts': 0, 'word_list_counts': {'cursed_substrings.json': 1, 'profanity_word_list.json': 0, 'sexual_word_list.json': 0, 'zh_pornsignals.json': 0}}
{'chain_length': '1', 'dir': 'jupyter-structured-clean-dedup', 'id': '612257', 'license': 'MIT', 'n_tokens_mistral': 512, 'n_tokens_neox': 478, 'n_words': 116, 'path': 'Python_Stock/Apply_Mathematics_Trading_Investment/Mahalanobis_Distance_Stock.ipynb', 'repo_name': 'chunsj/Stock_Analysis_For_Quant', 'size': '1293'}