<jupyter_start><jupyter_text>Introduction to timeseries plots in Python<jupyter_code>%matplotlib inline
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
import math

from datetime import date
from nsepy import get_history
import altair as alt
# NIFTY 50 index
nifty_50 = get_history(symbol="NIFTY 50",
                            start=date(2001,1,1),
                            end=date(2020,5,3),
                            index=True)

# NIFTY Next 50 index
nifty_next50 = get_history(symbol="NIFTY NEXT 50",
                            start=date(2001,1,1),
                            end=date(2020,5,3),
                            index=True)

# # India VIX index
# india_vix = get_history(symbol="INDIAVIX",
#                             start=date(2001,1,1),
#                             end=date(2020,5,3),
#                             index=True)
nifty_50.shape, nifty_next50.shape
MKT = nifty_next50.join(nifty_50['Close'], how='outer', rsuffix='_N50').dropna()
data = MKT.rename(columns={'Close':'NN50','Close_N50':'N50'})\
            .assign(NN50_returns=lambda x: np.log(x['NN50']/x['NN50'].shift(1)))\
            .assign(N50_returns=lambda x: np.log(x['N50']/x['N50'].shift(1)))
data = data[['NN50', 'N50', 'NN50_returns', 'N50_returns']].dropna()
data.index = pd.DatetimeIndex(data.index)
# Let's plot SPX and VIX cumulative returns with recession overlay
plot_cols = ['NN50', 'N50']

# 2 axes for 2 subplots

fig, axes = plt.subplots(2,1, figsize=(10,7), sharex=True)
data[plot_cols].plot(subplots=True, ax=axes)
# Let's plot SPX and VIX cumulative returns with recession overlay
plot_cols = ['NN50_returns', 'N50_returns']

# 2 axes for 2 subplots

fig, axes = plt.subplots(2,1, figsize=(10,7), sharex=True)
data[plot_cols].plot(subplots=True, ax=axes)
# ================================================================== #
# resample log returns weekly starting monday
lrets_resampled = data[['NN50_returns', 'N50_returns']].resample('W-MON').sum()

# ================================================================== #
# rolling mean returns
n = 52
roll_mean = lrets_resampled.rolling(window=n, min_periods=n ).mean().dropna(axis=0,how='all')

# ================================================================== #
# rolling sigmas
roll_sigs = lrets_resampled.rolling(window=n, min_periods=n ).std().dropna(axis=0,how='all') * math.sqrt(n)

# ================================================================== #
# rolling risk adjusted returns 
roll_risk_rets = roll_mean/roll_sigs
# Let's plot SPX and VIX cumulative returns with recession overlay
plot_cols = ['NN50_returns', 'N50_returns']

# 2 axes for 2 subplots

fig, axes = plt.subplots(2,1, figsize=(10,7), sharex=True)
roll_mean[plot_cols].plot(subplots=True, ax=axes)
NN50 = alt.Chart(data.reset_index()).transform_fold(
    ['NN50'],
    as_=['symbol', 'price']
).mark_line().encode(
    x='Date:T',
    y='price:Q'
).properties(width=600, height=200)

N50 = alt.Chart(data.reset_index()).transform_fold(
    ['N50'],
    as_=['symbol', 'price']
).mark_line().encode(
    x='Date:T',
    y='price:Q'
).properties(width=600, height=200)

alt.vconcat(NN50, N50)
%load_ext watermark
%watermark<jupyter_output>The watermark extension is already loaded. To reload it, use:
  %reload_ext watermark
2020-05-17T23:00:15+05:30

CPython 3.7.4
IPython 7.9.0

compiler   : Clang 4.0.1 (tags/RELEASE_401/final)
system     : Darwin
release    : 19.4.0
machine    : x86_64
processor  : i386
CPU cores  : 4
interpreter: 64bit
{'fraction_non_alphanumeric': 0.21079545454545454, 'fraction_numerical': 0.05539772727272727, 'mean_word_length': 3.98019801980198, 'pattern_counts': {'":': 0, '<': 4, '<?xml version=': 0, '>': 4, 'https://': 0, 'lorem ipsum': 0, 'www.': 0, 'xml': 0}, 'pii_count': 0, 'substrings_counts': 0, 'word_list_counts': {'cursed_substrings.json': 0, 'profanity_word_list.json': 0, 'sexual_word_list.json': 0, 'zh_pornsignals.json': 0}}
{'chain_length': '1', 'dir': 'jupyter-structured-clean-dedup', 'id': '519469', 'license': 'MIT', 'n_tokens_mistral': 1341, 'n_tokens_neox': 1191, 'n_words': 246, 'path': 'Nifty_Next_50_Returns.ipynb', 'repo_name': 'suresh/notebooks', 'size': '3520'}