Japan Stock Price Nikkei 225 Analysis in Python

What is Nikkei 225?

Nikkei 225 is  a stock market index  for the Tokyo stock exchange.
How to get  Nikkei 225 stock price?
We can get data from yahoo finance,quandai,wiki etc.
You can get data through python code.
we need to downloaded some python package.
import yfinance as yf
import numpy as np
import pandas as pd
import seaborn as sns
import scipy.stats as scs
import statsmodels.api as sm
import statsmodels.tsa.api as smt
import matplotlib.pyplot as plt
Code in python
df = yf.download('^N225',
start='1985-01-01',
end='2021-08-04',
progress=False)

How to convert Adj Close price?

df = df.loc[:, ['Adj Close']]
df.rename(columns={'Adj Close':'adj_close'}, inplace=True)

Getting simple and log return

df['simple_rtn'] = df.adj_close.pct_change()
df['log_rtn'] = np.log(df.adj_close/df.adj_close.shift(1))
df[['simple_rtn','log_rtn']].tail(20)
simple_rtnlog_rtn
Date
2021-07-060.0015740.001573
2021-07-07-0.009645-0.009692
2021-07-08-0.008775-0.008814
2021-07-09-0.006317-0.006337
2021-07-120.0224980.022249
2021-07-130.0052230.005210
2021-07-14-0.003822-0.003829
2021-07-15-0.011514-0.011581
2021-07-16-0.009760-0.009808
2021-07-19-0.012511-0.012590
2021-07-20-0.009568-0.009614
2021-07-210.0058360.005819
2021-07-260.0103560.010303
2021-07-270.0049200.004908
2021-07-28-0.013892-0.013989
2021-07-290.0072790.007252
2021-07-30-0.017955-0.018118
2021-08-020.0182320.018068
2021-08-03-0.005010-0.005023
2021-08-04-0.002089-0.002091

How to get realised volatility in python?

def realized_volatility(x):
 return np.sqrt(np.sum(x**2))
df_rv = df.groupby(pd.Grouper(freq='M')).apply(realized_volatility)
df_rv.rename(columns={'log_rtn''rv'}, inplace=True)
df_rv.rv = df_rv.rv * np.sqrt(12)
fig, ax = plt.subplots(21, sharex=True)
ax[0].plot(df)
ax[1].plot(df_rv)
[<matplotlib.lines.Line2D at 0x7f7559778410>,
 <matplotlib.lines.Line2D at 0x7f753b5b9dd0>,
 <matplotlib.lines.Line2D at 0x7f753b5b9fd0>]
nekkei225 log return 2021
fig, ax = plt.subplots(31, figsize=(2420), sharex=True)
df.adj_close.plot(ax=ax[0])
ax[0].set(title = 'Nikkei225 time series',
ylabel = 'Stock price ($)')
df.simple_rtn.plot(ax=ax[1])
ax[1].set(ylabel = 'Simple returns (%)')
df.log_rtn.plot(ax=ax[2])
ax[2].set(xlabel = 'Date',
ylabel = 'Log returns (%)')
df_rolling = df[['simple_rtn']].rolling(window=21) \
.agg(['mean''std'])
df_rolling.columns = df_rolling.columns.droplevel()
df_outliers = df.join(df_rolling)
def indentify_outliers(rown_sigmas=3):
   x = row['simple_rtn']
   mu = row['mean']
   sigma = row['std']
   if (x > mu + 3 * sigma) | (x < mu - 3 * sigma):
    return 1
   else:
    return 0

How to plot outlier in python?

df_outliers['outlier'] = df_outliers.apply(indentify_outliers,
axis=1)
outliers = df_outliers.loc[df_outliers['outlier'] == 1,
['simple_rtn']]
fig, ax = plt.subplots()
ax.plot(df_outliers.index, df_outliers.simple_rtn,
color='blue', label='Normal')
ax.scatter(outliers.index, outliers.simple_rtn,
color='red', label='Anomaly')
ax.set_title("Nikkei225 returns")
ax.legend(loc='lower right')
<matplotlib.legend.Legend at 0x7f75364b5e50>
nikkei225 outlier return 2021
r_range = np.linspace(min(df.log_rtn), max(df.log_rtn), num=1000)
mu = df.log_rtn.mean()
sigma = df.log_rtn.std()
norm_pdf = scs.norm.pdf(r_range, loc=mu, scale=sigma)
fig, ax = plt.subplots(12, figsize=(168))
# histogram
sns.distplot(df.log_rtn, kde=False, norm_hist=True, ax=ax[0])
ax[0].set_title('Distribution of Nikkei225 returns', fontsize=16)
ax[0].plot(r_range, norm_pdf, 'g', lw=2,
label=f'N({mu:.2f}{sigma**2:.4f})')
ax[0].legend(loc='upper left');

How to plot Nikkei225 and vix in python?

df = yf.download(['^N225''^VIX'],
start='1985-01-01',
end='2021-07-28',
progress=False)
df = df[['Adj Close']]
df.columns = df.columns.droplevel(0)
df = df.rename(columns={'^N225''Nikkei225''^VIX''vix'})
df['log_rtn'] = np.log(df.Nikkei225 / df.Nikkei225.shift(1))
df['vol_rtn'] = np.log(df.vix / df.vix.shift(1))
df.dropna(how='any', axis=0, inplace=True)
corr_coeff = df.log_rtn.corr(df.vol_rtn)
ax = sns.regplot(x='log_rtn', y='vol_rtn', data=df,
line_kws={'color''red'})
ax.set(title=f'N225 vs. VIX ($\\rho$ = {corr_coeff:.2f})',
ylabel='VIX log returns',
xlabel='Nikkei225 log returns')
[Text(0, 0.5, 'VIX log returns'),
 Text(0.5, 0, 'Nikkei225 log returns'),
 Text(0.5, 1.0, 'N225 vs. VIX ($\\rho$ = -0.11)')]

Post a Comment

0 Comments