# ---
# jupyter:
#   jupytext:
#     text_representation:
#       extension: .py
#       format_name: light
#       format_version: '1.5'
#       jupytext_version: 1.14.4
#   kernelspec:
#     display_name: Python 3.8.5 64-bit (conda)
#     metadata:
#       interpreter:
#         hash: a8f61be024eba58adef938c9aa1e29e02cb3dece83a5348b1a2dafd16a070453
#     name: python3
# ---

# # Chapter 1 Financial Time Series and Their Characteristics

import numpy as np 
import pandas as pd 
import statsmodels.api as sm
import statsmodels.formula.api as smf
import matplotlib.pyplot as plt 
from scipy import stats 

# da = pd.read_table(r'data\d-ibm3dx7008.txt', sep=r"\s+", header=0)
da = pd.read_csv(r'data\d-ibm3dx7008.txt', sep=r"[\f\n\r\t\v]", header=0, engine='python')

da.head()

da = pd.read_table(r'data\d-ibm3dx7008.txt', sep=r"\s+", header=0)

da.head()

da.size

da.iloc[:, 0:1]

ibm = da.iloc[:, 1:2]
ibm

ibm = ibm * 100
ibm.describe()

ibm_rtn = np.array(ibm)
fig, axes = plt.subplots(2, 1, figsize=(10,8))
axes[0].plot(ibm_rtn, alpha=0.6)
axes[0].set(title='Time Series of ibm_rtn.')
axes[1].hist(ibm_rtn, alpha=0.6, bins=200)
axes[1].set(title='Histogram of ibm_rtn.')
plt.show()


# +
def normtest(data):
    skew = data.skew()[0]
    t_skew = skew / np.sqrt(6/len(data))
    p_skew = stats.norm.sf(abs(t_skew)) * 2

    kurt = data.kurt()[0]
    t_kurt = kurt / np.sqrt(24/len(data))
    p_kurt = stats.norm.sf(abs(t_kurt)) * 2

    JBtest = (skew**2 / 6 + kurt**2 /24) * len(data)
    p_JBtest = stats.chi2.sf(JBtest, 2)

    result = pd.DataFrame({'Skewness': skew, 'P-Skew': p_skew, 'Kurtosis': kurt, 'P-Kurt': p_kurt, 'JBtest': JBtest, 'P-JBtest': p_JBtest}, index=['value'])

    return result

result = normtest(ibm)
result
# -

libm = np.log(da["rtn"] + 1) * 100
libm

libm.describe()

# student't-Test
tstatics, pval = stats.ttest_1samp(libm, 0)
print(f"tStatics = {tstatics:.10f}\nP-Value = {pval:.10f}")
if pval > 0.05:
    print("Cann't reject the NULL hypothesis at the 5% significance level.")
else:
    print("Reject the NULL hypothesis at the 5% significance level.")

chiStatics, pval, *_ = sm.stats.stattools.jarque_bera(libm)
print(f"chiStatics = {chiStatics:.10f}\nP-Value = {pval:.10f}")
if pval > 0.05:
    print("Cann't reject the NULL hypothesis at the 5% significance level.")
else:
    print("Reject the NULL hypothesis at the 5% significance level.")

# ## Exercise 1.2

da = pd.read_csv(r'data\m-gm3dx7508.txt', sep=r"\s+", header=0)
da.head()

gm = da.iloc[:, 1:2]
dates = pd.date_range('19980101', periods=len(gm))
# dates = np.array(dates)
gm_ts = pd.DataFrame(np.array(gm), index=dates)
gm_ts.head()

fig, axes = plt.subplots(2, 1, figsize=(12,8))
axes[0].plot(gm)
axes[1].plot(gm_ts)
plt.show()

# fig, axes = plt.subplots(2, 1, figsize=(12,8))
sm.graphics.tsa.plot_acf(gm, lags=40)
sm.graphics.tsa.plot_acf(gm_ts, lags=40)
plt.show()



StarcoderdataJupyterScriptsDedupFiltered