To Compute Sectoral NSE Indices Returns

This program will compute the NSE Sectoral Indices returns (52 Weeks, YTD , MTD, Last month returns)

In [1]:
from datetime import datetime
from datetime import timedelta
import pandas as pd, seaborn as sns
from nsepy import get_history
from datetime import date
import calendar

List of Sector Indices

In [2]:
symbol=["NIFTY 50",'NIFTY NEXT 50','NIFTY 100','NIFTY 200','NIFTY 500','NIFTY MIDCAP 50','NIFTY MIDCAP 100','NIFTY SMALL 100']

To Compute and Plot 52 Week Sectoral Returns

In [3]:
s=datetime.today()-timedelta(days=365)
y=s.year
m=s.month
d=s.day

ret=[]
for sym in symbol:
    result = get_history(symbol=sym, start=date(y,m,d), end=date.today(), index=True)
    if result.empty:
        ret.append(0)
    else:
        
        r1=[]
        s2=result[[3]]
        v1=s2.values.T.tolist()
        value=(v1[0][0])
        r1.append(value)
        
        value=(v1[0][-1])
        r1.append(value)
        s=(r1[-1]-r1[0])*100/r1[0]
        ret.append(s)
        
/root/anaconda2/lib/python2.7/site-packages/bs4/__init__.py:166: UserWarning: No parser was explicitly specified, so I'm using the best available HTML parser for this system ("lxml"). This usually isn't a problem, but if you run this code on another system, or in a different virtual environment, it may use a different parser and behave differently.

To get rid of this warning, change this:

 BeautifulSoup([your markup])

to this:

 BeautifulSoup([your markup], "lxml")

  markup_type=markup_type))
In [4]:
import numpy as np
import seaborn as sns
import matplotlib.pyplot as plt
%pylab inline
import pandas as pd
fig, ax = plt.subplots()
# the size of A4 paper
fig.set_size_inches(13.7, 8.27)

ax = sns.barplot(x=symbol, y=ret, palette='RdBu_r')
ax.set_ylabel("PERCENTAGE")
ax.set_xlabel("52 WEEK RETURNS")
Populating the interactive namespace from numpy and matplotlib
WARNING: pylab import has clobbered these variables: ['datetime']
`%matplotlib` prevents importing * from pylab and numpy
Out[4]:
<matplotlib.text.Text at 0x6f4fbc5dc150>

To Compute and Plot Last Month Sectoral Returns

In [5]:
#finding the year and month of last two month
s=date.today()-timedelta(2*365/12)
y=s.year
m=s.month

s=calendar.monthrange(y,m)
last=s[-1]
#getting the last day of previous month
today = date.today()
first = today.replace(day=1)
lastMonth = first -timedelta(days=1)
s=lastMonth.strftime("%Y%m%d")
a=int(s[0:4])

b=int(s[4:6])

c=int(s[-2:])


r=[]
r1=[]
for sym in symbol:
    result = get_history(symbol=sym, start=date(y,m,1), end=date(y,m,last),index=True)
    if result.empty:
        ret.append(0)
    else:       
        s2=result[[3]]
        v1=s2.values.T.tolist()
        value=(v1[0][-1])
        r.append(value)
        
        
for sym in symbol:
    result = get_history(symbol=sym, start=date(y,m,last), end=date(a,b,c),index=True)
    if result.empty:
        ret.append(0)
    else:       
        s2=result[[3]]
        v1=s2.values.T.tolist()
        value=(v1[0][-1])
        r1.append(value)   
#FINDING THE RETURN        
        
j=0
ret=[]
for i in r:
    s=(r1[j]-r[j])*100/r[j]
    ret.append(s)
    j=j+1    
    
    
#PLOTTING THE BARCAHRT FOR LAST MONTH RETURN    
fig, ax = plt.subplots()
# the size of A4 paper
fig.set_size_inches(13.7, 8.27)

ax = sns.barplot(x=symbol, y=ret, palette='RdBu_r')
ax.set_ylabel("PERCENTAGE")
ax.set_xlabel("LAST MONTH RETURNS")
    
Out[5]:
<matplotlib.text.Text at 0x6f4faf8efc50>

To Compute and Plot Year to Date Sectoral Returns

In [6]:
#finding the last year
s=date.today().year -1

r=[]
r1=[]
for sym in symbol:
    result = get_history(symbol=sym, start=date(s,12,1), end=date(s,12,31),index=True)
    if result.empty:
        ret.append(0)
    else:       
        s2=result[[3]]
        v1=s2.values.T.tolist()
        value=(v1[0][-1])
        r.append(value)
        
        
for sym in symbol:
    result = get_history(symbol=sym, start=date(s,12,31), end=date.today(),index=True)
    if result.empty:
        ret.append(0)
    else:       
        s2=result[[3]]
        v1=s2.values.T.tolist()
        value=(v1[0][-1])
        r1.append(value)        
#CALCULATING THE RETUN        
j=0
ret=[]
for i in r:
    s=(r1[j]-r[j])*100/r[j]
    ret.append(s)
    j=j+1
         
#PLOTTING THE BARCHART FOR YEAR TO DATE RETURNS

fig, ax = plt.subplots()
# the size of A4 paper
fig.set_size_inches(13.7, 8.27)

ax = sns.barplot(x=symbol, y=ret, palette='RdBu_r')
ax.set_ylabel("PERCENTAGE")
ax.set_xlabel("YEAR TO DATE RETURNS")        
        
        
Out[6]:
<matplotlib.text.Text at 0x6f4fbc5d3850>

To Compute and Month to Date Sectoral Returns

In [7]:
#THE CODE FOR MONTH TO DATE RETURNS

#finding the last month from the currentmonth
y=date.today().year
m=date.today().month -1
s=calendar.monthrange(y,m)
last=s[-1]


r=[]
r1=[]
for sym in symbol:
    result = get_history(symbol=sym, start=date(y,m,1), end=date(y,m,last),index=True)
    if result.empty:
        ret.append(0)
    else:       
        s2=result[[3]]
        v1=s2.values.T.tolist()
        value=(v1[0][-1])
        r.append(value)
        
        
for sym in symbol:
    result = get_history(symbol=sym, start=date(y,m,last), end=date.today(),index=True)
    if result.empty:
        ret.append(0)
    else:       
        s2=result[[3]]
        v1=s2.values.T.tolist()
        value=(v1[0][-1])
        r1.append(value)      
        
# FINDING THE RETURNS

j=0
ret=[]
for i in r:
    s=(r1[j]-r[j])*100/r[j]
    ret.append(s)
    j=j+1
    
    
#PLOTTING THE BARCHART FOR MONTH TO DATE RETURNS
import numpy as np
import seaborn as sns
import matplotlib.pyplot as plt
%pylab inline
import pandas as pd
fig, ax = plt.subplots()
# the size of A4 paper
fig.set_size_inches(13.7, 8.27)

ax = sns.barplot(x=symbol, y=ret, palette='RdBu_r')
ax.set_ylabel("PERCENTAGE")
ax.set_xlabel("MONTH TO DATE RETURNS")
Populating the interactive namespace from numpy and matplotlib
Out[7]:
<matplotlib.text.Text at 0x6f4fafe6d910>
In [ ]: