import numpy as np
import pandas as pd
"""
### Importing the data
"""
df = pd.read_csv('../input/nifty50-stocks-dataset/National_Stock_Exchange_of_India_Ltd.csv', header=0)
df
"""
###  Checking for null values
"""
df.isnull().sum()
"""
### Checking Data Types
"""
df.dtypes
"""
### Changing Object type of Open, High, Low,LTP to float 
"""
df['Open'] = df['Open'].str.replace(',','')
df['Open'] = df['Open'].astype(float)
df.head(5)
df['High'] = df['High'].str.replace(',','')
df['High'] = df['High'].astype(float)
df['Low'] = df['Low'].str.replace(',','')
df['Low'] = df['Low'].astype(float)
df.head()
df['LTP'] = df['LTP'].str.replace(',','')
df['LTP'] = df['LTP'].astype(float)
df.dtypes
df['Turnover (crs.)'] = df['Turnover (crs.)'].str.replace(',','')
df['Turnover (crs.)'] = df['Turnover (crs.)'].astype(float)
df['52w H'] = df['52w H'].str.replace(',','')
df['52w H'] = df['52w H'].astype(float)
df['52w L'] = df['52w L'].str.replace(',','')
df['52w L'] = df['52w L'].astype(float)
df.dtypes
"""
### Now we have every column in float. 
"""
df.describe()
df['Open'] = df['Open'].astype(int)
df['High'] = df['High'].astype(int)
df['Low'] = df['Low'].astype(int)
df['LTP'] = df['LTP'].astype(int)
df['Chng'] = df['Chng'].astype(int)
df['% Chng'] = df['% Chng'].astype(int)
df['Volume (lacs)'] = df['Volume (lacs)'].astype(int)
df['Turnover (crs.)'] = df['Turnover (crs.)'].astype(int)
df['52w H'] = df['52w H'].astype(int)
df['365 d % chng'] = df['365 d % chng'].astype(int)
df['30 d % chng	'] = df['30 d % chng'].astype(int)

df.head()
import matplotlib.pyplot as plt
import seaborn as sns

import warnings 
warnings.filterwarnings("ignore")

plt.figure(figsize=(15,7))
sns.boxplot(df['365 d % chng'],color = 'mediumorchid')
plt.show
"""
### Plotting Boxplot as well the below histogram, we can find that majority of the companies have shown atleast  10% returns if stayed invested for a year in it
"""
plt.figure(figsize=(15,7))

df['365 d % chng'].plot.hist(color = 'mediumorchid',alpha=0.7, rwidth=0.85) 
plt.show
#plt.barh(x=df['Symbol'],y=df['30 d % chng']) 

plt.figure(figsize=(15,7))
plt.xticks(rotation=90)


sns.barplot(data = df, x = 'Symbol', y = '30 d % chng')
sns.color_palette("flare", as_cmap=True)



plt.show
"""
### When we plot 30d %chg, hardly any stock has given positive returns. In such instances, it seems 30days is not enough holding period for Nifty50 stocks. Investors should hold it for relatively higher time frame.
"""
plt.figure(figsize=(15,7))
plt.xticks(rotation=90)


sns.barplot(data = df, x = 'Symbol', y = '365 d % chng')
sns.color_palette("flare", as_cmap=True)



plt.show
"""
###  We can prove same that staying invested for 365 days gives positive, higher returns for majority of the stocks.
"""
"""
### Creating group of Banking and Financial Companies in this dataset. 
"""
bank_df = df['Symbol'].isin(['AXISBANK','HDFCBANK','ICICIBANK','INDUSINDBK','KOTAKBANK','SBIN','HDFC','BAJAJFINSV','BAJFINANCE','HDFCLIFE'])
bank_table = df[bank_df].pivot_table(values =['Open','High','Low','LTP','Chng','Volume (lacs)','52w H','52w L','Turnover (crs.)','365 d % chng','30 d % chng'], index= ['Symbol'])
bank_table.reset_index(level=0, inplace=True)
bank_table

plt.figure(figsize=(15,7))
plt.xticks(rotation=45)


sns.barplot(data = bank_table, x = 'Symbol', y = '365 d % chng', palette='flare')


plt.xlabel("Symbol")  # add X-axis label
plt.ylabel('% Change in a Year')  # add Y-axis label
plt.title("Yearly Growth")  # add title


plt.show
"""
### As the above data, BajajFinserv and SBIN have shown extremely positive growth in comparison to its peers. HDFC LIFE has shown no growth against its peers. Same applies for majority of banks.
"""
plt.figure(figsize=(15,7))
plt.xticks(rotation=45)


sns.barplot(data = bank_table, x = 'Symbol', y = '30 d % chng',palette='mako')

"""
### **AxisBank and IndusInd Bank have been the worst performers with more than 20% wealth loss of the investors in a single month.**
"""

sns.pairplot(bank_table,hue = 'Symbol',x_vars = ('Volume (lacs)',"Turnover (crs.)","30 d % chng",'365 d % chng'),
             y_vars=('52w H','52w L'),height=3,palette='icefire')
"""
###  The above pairplot showcases that Axis Bank with highest turnover doesnot seem to have any correlation with its peers while rest of stock seems to be following a range bound pattern
"""
"""
### Creating Group of Oil and Energy
"""
one_df = df['Symbol'].isin(['BPCL','COALINDIA','IOC','NTPC','ONGC','POWERGRID','RELIANCE'])
one_table = df[one_df].pivot_table(values =['Open','High','Low','LTP','Chng','Volume (lacs)','52w H','52w L','Turnover (crs.)','365 d % chng','30 d % chng'], index= ['Symbol'])
one_table.reset_index(level=0, inplace=True)
one_table


plt.figure(figsize=(15,7))
plt.xticks(rotation=90)


sns.barplot(data = one_table, x = 'Symbol', y = '365 d % chng',palette='flare')


plt.xlabel("Symbol")  # add X-axis label
plt.ylabel('% Change in a Year')  # add Y-axis label
plt.title("Yearly Growth")  # add title


plt.show
plt.figure(figsize=(15,7))
plt.xticks(rotation=45)


sns.barplot(data = one_table, x = 'Symbol', y = '30 d % chng',palette='mako')

"""
### Without doubt investor should be aggressive in ONGC as it has outperformed its peers by approx 50% more returns with investment period of atleast a month.

### While PowerGrid being the only stock that has increased investor's wealth by 5% in 1month, rest of the peers have on an average have made investors lose atleast 5% -7% in a single month
"""

sns.pairplot(one_table,hue = 'Symbol',x_vars = ('Volume (lacs)',"Turnover (crs.)","30 d % chng",'365 d % chng'),
             y_vars=('52w H','52w L'),height=3,palette='icefire')
"""
### Reliance is the alone leader in this category. Rest of the stocks are following a range bound pattern
"""
"""
### Creating a group of Pharma sector 
"""
pharma_df = df['Symbol'].isin(['CIPLA','DIVISLAB','DRREDDY','SUNPHARMA'])
pharma_table = df[pharma_df].pivot_table(values =['Open','High','Low','LTP','Chng','Volume (lacs)','52w H','52w L','Turnover (crs.)','365 d % chng','30 d % chng'], index= ['Symbol'])
pharma_table.reset_index(level=0,inplace=True)
pharma_table


plt.figure(figsize=(15,7))
plt.xticks(rotation=90)


sns.barplot(data = pharma_table, x = 'Symbol', y = '365 d % chng',palette='flare')

plt.xlabel("Symbol")  # add X-axis label
plt.ylabel('% Change in a Year')  # add Y-axis label
plt.title("Yearly Growth")  # add title


plt.show
"""
### Investors should avoid investing in DRREDDY. 0% wealth creation for investors in a year. Fixed Deposit returns are comparatively better investment choice if investing in DRREDDY.
"""
plt.figure(figsize=(15,7))
plt.xticks(rotation=45)


sns.barplot(data = pharma_table, x = 'Symbol', y = '30 d % chng',palette='mako')

"""
### No pattern as such seen in 30 days. All the stock are followig different momentum it seems.
"""

sns.pairplot(pharma_table,hue = 'Symbol',x_vars = ('Volume (lacs)',"Turnover (crs.)","30 d % chng",'365 d % chng'),
             y_vars=('52w H','52w L'),height=3,palette='icefire')
"""
### None of the stocks have any correlation with one another.Turnover is different for all while even 30 day change and 365 days change has not correlation within the category to be considered as any investing sector.
"""
"""
### Creating a group of IT sector
"""
IT_df = df['Symbol'].isin(['INFY','TCS','WIPRO','HCLTECH','TECHM'])
IT_table = df[IT_df].pivot_table(values =['Open','High','Low','LTP','Chng','Volume (lacs)','52w H','52w L','Turnover (crs.)','365 d % chng','30 d % chng'], index= ['Symbol'])
IT_table.reset_index(level=0,inplace=True)
IT_table
plt.figure(figsize=(15,7))
plt.xticks(rotation=90)


sns.barplot(data = IT_table, x = 'Symbol', y = '365 d % chng',palette='flare')


plt.xlabel("Symbol")  # add X-axis label
plt.ylabel('% Change in a Year')  # add Y-axis label
plt.title("Yearly Growth")  # add title


plt.show
"""
### TECHM and WIPRO are generated higher returns in comparison to peers however almost all the companies have added the value of ~30% in investor's porfolio for a year's holding period
"""
plt.figure(figsize=(15,7))
plt.xticks(rotation=45)


sns.barplot(data = IT_table, x = 'Symbol', y = '30 d % chng',palette='mako')


sns.pairplot(IT_table,hue = 'Symbol',x_vars = ('Volume (lacs)',"Turnover (crs.)","30 d % chng",'365 d % chng'),
             y_vars=('52w H','52w L'),height=3,palette='icefire')
"""
### TCS and INFY has least change in 30days and least increment in a years time span. While rest of the stocks have highest decline in 30 days but highest returns in 365 days.INFY and TCS are safe bets in IT sector.
"""
"""
### Creating a group of Automotors sector 
"""
Motor_df = df['Symbol'].isin(['BAJAJ-AUTO','EICHERMOT','TATAMOTORS','HEROMOTOCO','M&M','MARUTI'])
Motor_table = df[Motor_df].pivot_table(values =['Open','High','Low','LTP','Chng','Volume (lacs)','52w H','52w L','Turnover (crs.)','365 d % chng','30 d % chng'], index= ['Symbol'])
Motor_table.reset_index(level=0,inplace=True)
Motor_table
plt.figure(figsize=(15,7))
plt.xticks(rotation=45)

sns.barplot(data = Motor_table, x = 'Symbol', y = '365 d % chng',palette='flare')

plt.xlabel("Symbol")  # add X-axis label
plt.ylabel('% Change in a Year')  # add Y-axis label
plt.title("Yearly Growth")  # add title


plt.show
"""
### Year has been most value-adding for TATA MOTORS are its has outperformed its peers with extermely high returns
"""
plt.figure(figsize=(15,7))
plt.xticks(rotation=45)


sns.barplot(data = Motor_table, x = 'Symbol', y = '30 d % chng',palette='mako')

"""
### None of the stock has shown upward trend in 30 days. Should stay invested for higher time frame
"""
sns.pairplot(Motor_table,hue = 'Symbol',x_vars = ('Volume (lacs)',"Turnover (crs.)","30 d % chng",'365 d % chng'),
             y_vars=('52w H','52w L'),height=3,palette='icefire')
"""
### Except Maruti, rest of the stocks have same range volume, turnover. 
"""
"""
### Creating a new category as other for remaining stocks.|
"""
other_df = df['Symbol'].isin(['ADANIPORTS','ASIANPAINT','BHARTIAIRTL','BRITANNIA','GRASIM','HINDALCO','HINDULILVR','JSWSTEEL','NESTLEIND','SHREECEM','TATACONSUM','TATASTEEL','TITAN','ULTRACEMCO','UPL'])
other_table = df[other_df].pivot_table(values =['Open','High','Low','LTP','Chng','Volume (lacs)','52w H','52w L','Turnover (crs.)','365 d % chng','30 d % chng'], index= ['Symbol'])
other_table.reset_index(level=0,inplace=True)
other_table
plt.figure(figsize=(15,7))
plt.xticks(rotation=45)

sns.barplot(data = other_table, x = 'Symbol', y = '365 d % chng',palette='flare')

plt.xlabel("Symbol")  # add X-axis label
plt.ylabel('% Change in a Year')  # add Y-axis label
plt.title("Yearly Growth")  # add title


plt.show
plt.figure(figsize=(15,7))
plt.xticks(rotation=45)


sns.barplot(data = other_table, x = 'Symbol', y = '30 d % chng',palette='mako')

"""
### TATASTEEL and GRASIM has been worst hit in the month of September. While the same including JSWSTEEL, HINDALCO has highest returns in a years timeframe
"""
sns.pairplot(other_table,hue = 'Symbol',x_vars = ('Volume (lacs)',"Turnover (crs.)","30 d % chng",'365 d % chng'),
             y_vars=('52w H','52w L'),height=3,palette='icefire')
"""
### Except JSWSTEEL and NESTLEIND, all the other stocks have followed same range
"""