Finance: Stock Price Time Series
1. Preparing the environment and data
pip install yfinance
pip install scipy
pip install scikit-learnimport datetime, warnings
import yfinance as yf
import pandas as pd
import numpy as np
from scipy.stats import zscore
from scipy.signal import detrend
def download(symbols, start, days):
end = start + datetime.timedelta(days=days)
startstr = start.strftime('%Y-%m-%d')
endstr = end.strftime('%Y-%m-%d')
print(f'Obtaining {symbols} data from {startstr} to {endstr}...')
close = yf.download(symbols, start=startstr, end=endstr, progress=True)['Close']
# Match data up with weekdays
weekdays = pd.date_range(start=startstr, end=endstr, freq='B')
close = close.reindex(weekdays)
# For any NaN's, propogate last valid value forward (and remove first value)
z = close.fillna(method='ffill').values.T[:,2:]
# Make sure to always detrend and normalise your data, otherwise most statistics will give spurious results.
return detrend(zscore(z,ddof=1,nan_policy='omit',axis=1))
# The FAANG tickers (Facebook/Meta, Amazon, Apple, Netflix, Google)
stocks = ['META','AMZN','AAPL','NFLX','GOOGL']
# We'll download 140 days of data (corresponding to ~100 observations from business days)
ndays = 140
# Set a recent(ish) starting date for the period
start_datetime = datetime.datetime.strptime('2014-01-01', '%Y-%m-%d') # Earliest date we will sample
print('Begin data download.')
z = download(stocks,start_datetime,ndays)
print(f'Done. Obtained MTS of size {z.shape}')2. Inspecting the MTS

3. Applying pyspi
4. Classifying MTS using SPIs

Last updated