How to compare between nifty50 and S&P 500 in python?
How to get Financianl data from yahoo finance in Python?
First to analyse nifty 50 data
python code get data;
nsei = yf.download('^NSEI',
start='2020-01-01',
end='2021-08-22',
progress=False)
What is alternative sources to get financial data?
There are number of alternative sources like Quandal,intrinio,google others.
NSEI DATA
How to convert Stock prices into log and simple returns in python?
import matplotlib.pyplot as plt
import pandas as pd
import numpy as np
import yfinance as yf
pythone plot code nsei close
nsei['Close'].plot(figsize=(12,8))
<matplotlib.axes._subplots.AxesSubplot at 0x7ff8f1e4bc90>
nsei['Volume'].plot(figsize=(12,8))
<matplotlib.axes._subplots.AxesSubplot at 0x7ff8f1892b90>
nsei[['Close', 'Volume']].plot(subplots=True, style='b',
figsize=(12, 8))
array([<matplotlib.axes._subplots.AxesSubplot object at 0x7ff8f1855910>,
<matplotlib.axes._subplots.AxesSubplot object at 0x7ff8f07cc710>],
dtype=object)
nsei mean standard deviation
How to change stocks frequency in python?
We can change monthly weekly erc.
How to visualize time series financial data in python?
nsei['simple_rtn'] = nsei.Close.pct_change()
nsei['log_rtn'] = np.log(nsei.Close/nsei.Close.shift(1))
nsei['log_rtn'].plot(subplots=True, style='b',
figsize=(12, 8))
array([<matplotlib.axes._subplots.AxesSubplot object at 0x7ff8f065ef50>],
dtype=object)
Nsei log return
Date
2021-08-04 0.007907
2021-08-05 0.002199
2021-08-06 -0.003467
2021-08-09 0.001234
2021-08-10 0.001343
2021-08-11 0.000132
2021-08-12 0.005033
2021-08-13 0.010014
2021-08-16 0.002052
2021-08-17 0.003107
2021-08-18 -0.002757
2021-08-20 -0.007169
Name: log_rtn, dtype: float64
How to get identifying stocks outliers in python?
import cufflinks as cf
from plotly.offline import iplot, init_notebook_mode
import seaborn as sns
How to find simple and log return?
df_rolling = nsei[['simple_rtn']].rolling(window=21) \
.agg(['mean', 'std'])
df_rolling.columns = df_rolling.columns.droplevel()
df_outliers = nsei.join(df_rolling)
import pandas as pd
import numpy as np
import yfinance as yf
import seaborn as sns
import scipy.stats as scs
import statsmodels.api as sm
import statsmodels.tsa.api as smt
df = yf.download(['^NSEI', '^VIX'],
start='1985-01-01',
end='2021-08-22',
progress=False)
df = df[['Adj Close']]
df.columns = df.columns.droplevel(0)
df = df.rename(columns={'^NSEI': 'nsei', '^VIX': 'vix'})
df['log_rtn'] = np.log(df.nsei / df.nsei.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)
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'NSEI vs. VIX ($\\rho$ = {corr_coeff:.2f})',
ylabel='VIX log returns',
xlabel='NSEI log returns')
[Text(0, 0.5, 'VIX log returns'),
Text(0.5, 0, 'NSEI log returns'),
Text(0.5, 1.0, 'NSEI vs. VIX ($\\rho$ = -0.21)')]

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(1, 2, figsize=(16, 8))
# histogram
sns.distplot(df.log_rtn, kde=False, norm_hist=True, ax=ax[0])
ax[0].set_title('Distribution of NSEI 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');
# Q-Q plot
qq = sm.qqplot(df.log_rtn.values, line='s', ax=ax[1])
ax[1].set_title('Q-Q plot', fontsize = 16)
Text(0.5, 1.0, 'Q-Q plot')
How to analyse nsei distribution and QQplot?

df.log_rtn.plot(title='Daily nsei returns')
<matplotlib.axes._subplots.AxesSubplot at 0x7ff8ce380310>

N_LAGS = 50
SIGNIFICANCE_LEVEL = 0.05
acf = smt.graphics.plot_acf(df.log_rtn,
lags=N_LAGS,
alpha=SIGNIFICANCE_LEVEL
)

fig, ax = plt.subplots(2, 1, figsize=(12, 10))
smt.graphics.plot_acf(df.log_rtn ** 2, lags=N_LAGS,
alpha=SIGNIFICANCE_LEVEL, ax = ax[0])
ax[0].set(title='Autocorrelation Plots',
ylabel='Squared Returns')
smt.graphics.plot_acf(np.abs(df.log_rtn), lags=N_LAGS,
alpha=SIGNIFICANCE_LEVEL, ax = ax[1])
ax[1].set(ylabel='Absolute Returns',
xlabel='Lag')
[Text(0, 0.5, 'Absolute Returns'), Text(0.5, 0, 'Lag')]
df['moving_std_252'] = df[['log_rtn']].rolling(window=252).std()
df['moving_std_21'] = df[['log_rtn']].rolling(window=21).std()
fig, ax = plt.subplots(3, 1, figsize=(18, 15),
sharex=True)
df.plot(ax=ax[0])
ax[0].set(title='NSEI time series',
ylabel='Stock price ($)')
df.log_rtn.plot(ax=ax[1])
ax[1].set(ylabel='Log returns (%)')
df.moving_std_252.plot(ax=ax[2], color='r',
label='Moving Volatility 252d')
df.moving_std_21.plot(ax=ax[2], color='g',
label='Moving Volatility 21d')
ax[2].set(ylabel='Moving Volatility',
xlabel='Date')
ax[2].legend()
What is technical analysis?
The technical analysis is way to read stock price open,high,lowe and close with volume.
How to plot nsei time series modeling in stocks?What is volatility?
<matplotlib.legend.Legend at 0x7ff8c5d4e550>
Click ANALYSIS NIFTY50
Price S&P500 Analysis with Python
Need to analyse
How to explain stock returns volatility with ARCH models in python?
How to implement the CAPM model to get stock price in python?
How to implement the Fama- French three factor model on a portfolio analys in python?
How to implement four and five factor models in python?
How to use model volatility with GARCH model in python?
How to explain stock returns volatility with ARCH models in python?
0 Comments