Search
 
SCRIPT & CODE EXAMPLE
 

PYTHON

python cointegration

import matplotlib.pyplot as plt
import yfinance as yf
import pandas as pd
import datetime as dt
import statsmodels.tsa.stattools as ts
from scipy.stats import linregress


def download_data(stock, start, end):
    stock_data = {}
    ticker = yf.download(stock, start, end)
    stock_data['Price'] = ticker['Adj Close']
    return pd.DataFrame(stock_data)


def plot_pairs(data1, data2):
    fig, (ax1, ax2) = plt.subplots(2)
    fig.suptitle('Pair Of Stocks')
    ax1.plot(data1)
    ax2.plot(data2)
    plt.show()


def scatter_plot(data1, data2):
    plt.scatter(data1.values, data2.values)
    plt.suptitle('Cointegration')
    plt.xlabel('XOM')
    plt.ylabel('CVX')
    plt.show()


if __name__ == '__main__':
    start_date = dt.datetime(2011, 4, 1)
    end_date = dt.datetime(2020, 1, 1)

    pair1 = download_data('XOM', start_date, end_date)
    pair2 = download_data('CVX', start_date, end_date)

    plot_pairs(pair1, pair2)
    scatter_plot(pair1, pair2)

    # Linear Regression
    result = linregress(pair1.values[:, 0], pair2.values[:, 0])
    print(result)

    # Create the residual series
    residuals = pair1 - result.slope * pair2

    adf = ts.adfuller(residuals)
    print(adf)
Comment

PREVIOUS NEXT
Code Example
Python :: convert string ranges list python 
Python :: check if a string is palindrome or not using two pointer function in python 
Python :: argparse parse path 
Python :: django admin text box 
Python :: python identify image mode 
Python :: rename last layer of keras model 
Python :: if any number python 
Python :: how to add items to a set in python 
Python :: get all subarrays of an array python 
Python :: NumPy resize Syntax 
Python :: check pd.NaT python 
Python :: dbscan python 
Python :: convert to string in python 
Python :: start ipython with any version 
Python :: python unpack list 
Python :: how to make a new key in a dictionary python 
Python :: python hello world jenkins 
Python :: speech to text 
Python :: Python NumPy stack Function Example with 1d array 
Python :: case python 
Python :: accumulator programming python 
Python :: histogram python 
Python :: ocaml returns the last element of a list 
Python :: python inspect 
Python :: boder color in tkinter 
Python :: PySimpleGUI all elements 
Python :: python get element by index 
Python :: python divide and round away operator 
Python :: Common Python String Methods 
Python :: pip install pandas invalid syntax 
ADD CONTENT
Topic
Content
Source link
Name
1+5 =