# ---
# jupyter:
#   jupytext:
#     text_representation:
#       extension: .py
#       format_name: light
#       format_version: '1.5'
#       jupytext_version: 1.14.4
#   kernelspec:
#     display_name: Python 3
#     language: python
#     name: python3
# ---

# # Module - 2:  Data visualization and Technical Analysis

# ###### Loading required libraries

import pandas as pd    # data loading tool
import matplotlib.pyplot as plt   #ploting tool
import seaborn as sns
import numpy as np

# ## 2.1 Loading dataset and changing the Date format

mod2_data = pd.read_csv('week2.csv')
del mod2_data['Unnamed: 0']  #deleting Unnammed column
mod2_data.Date = pd.to_datetime(mod2_data['Date'])
mod2_data= mod2_data.set_index('Date')
print(mod2_data.index.dtype == "datetime64[ns]")
mod2_data.head()

fig, ax = plt.subplots(figsize=(10, 6))
sns.lineplot(data=mod2_data, x=mod2_data.index, y='Close Price', ax=ax)
plt.tight_layout()
plt.show()

# ###### News:
# 1. Between 2017-10 and 2018-02. 
# ***Tata Power Company (TPCL) has posted an improved performance in 1QFY18 with its consolidated net profit rising by 126% YoY to Rs1.64bn (vs. Rs0.72bn in 1QFY17) due to strong performance by the coal subsidiaries, renewable business and better operational performance. Notably, renewable business generated Rs1.09bn PAT in 1QFY18 compared to Rs0.26bn in 1QFY17. Consolidated revenue rose by 2% YoY to Rs67.2bn mainly due to improved revenue from Welspun Renewable Energy (WREPL).***
# Source:https://www.moneycontrol.com/news/business/stocks/buy-tata-power-target-of-rs-88-reliance-securities-2370965.html
# 2. Between 2018-02 and 2018-11.
# ***Tata Power Company's third quarter consolidated profit is expected to fall 22 percent to Rs 466 crore compared to Rs 599 crore in year-ago quarter.Revenue from operations may grow 11 percent to Rs 7,445 crore compared to Rs 6,684 crore in same quarter last fiscal, according to average of estimates of analysts polled by CNBC-TV18. Operating profit is likely to increase 15 percent year-on-year to Rs 1,611 crore and margin may expand 70 basis points to 21.6 percent in Q3.Year-on-year profit comparison may not be valid due to (1) higher interest cost in Q3FY18 to fund renewable asset acquisition and (2) tax reversal in Q3FY17, despite stable operations in the core distribution business.Analysts expect generation volumes to remain sluggish and realisations to remain flattish. They further expect coal business and renewable business to maintain strong momentum.More than numbers, the Street will watch out for restructuring news. Tata Power had guided for simplification of group structure in FY18 at the beginning of the year.***
# Source:https://www.moneycontrol.com/news/business/earnings/tata-power-q3-profit-seen-down-22-generation-volumes-may-remain-sluggish-2507829.html
# 3. Between 2018-10 and 2019-01.
# ***Tata Power, HPCL join hands to set up EV charging stations***
# source:https://www.moneycontrol.com/news/india/tata-power-hpcl-join-hands-to-set-up-ev-charging-stations-2991981.html
# 4. Between 2019-01 and 2019-03.
# ***Fuel cost of the company rose to Rs 3,189.87 crore from Rs 2,491.24 crore in the year-ago period. Similarly, the finance cost rose to Rs 1,013.96 crore from Rs 855.28 crore a year ago.***
# Source:https://www.moneycontrol.com/news/business/tata-power-q3-profit-plunges-67-to-rs-205-cr-in-q3-3445841.html
# 5. After 2019-04.
# ***Tata Power Q4 net drops 92% to Rs 107.32 cr; declares dividend of Rs 1.30/share***
# Source:https://www.moneycontrol.com/news/business/tata-power-q4-net-drops-92-to-rs-107-32-cr-declares-dividend-of-rs-1-30share-3924591.html

# ## 2.2 Stem plot

fig, ax = plt.subplots(figsize=(10, 6))
ax.stem(mod2_data.index, mod2_data.Day_Perc_Change, 'g', label='Percente Change')
plt.tight_layout()
plt.legend()
plt.show()


# ## 2.3 Daily volume and comparison with %stem plot

# +
volume_scaled = mod2_data['No. of Trades'] - mod2_data['No. of Trades'].min()
volume_scaled = volume_scaled/volume_scaled.max()*mod2_data.Day_Perc_Change.max()
fig, ax = plt.subplots(figsize=(10, 6))
ax.plot(mod2_data.index, volume_scaled, label='Volume')
ax.set_xlabel('Date')
plt.legend(loc=2)

plt.tight_layout()
plt.show()

# +
fig, ax = plt.subplots(figsize=(10, 6))

ax.stem(mod2_data.index, mod2_data.Day_Perc_Change , 'g', label='Percente Change')
ax.plot(mod2_data.index, volume_scaled, 'k', label='Volume')

ax.set_xlabel('Date')
plt.legend(loc=2)

plt.tight_layout()
plt.show()
# -

# ###### Relationship between volume and daily percentage change
# As the volume increases the percentage change becomes positive and vice versa.

# ## 2.4  Pie chart and Bar plot 

# +
gridsize = (2, 6)
fig = plt.figure(figsize=(14, 10))
ax1 = plt.subplot2grid(gridsize, (0, 0), colspan=2, rowspan=1)
ax2 = plt.subplot2grid(gridsize, (0, 3), colspan=3)
ax3 = plt.subplot2grid(gridsize, (1, 0), colspan=6)

mod2_data['ones'] = np.ones((mod2_data.shape[0]))
sums = mod2_data.ones.groupby(mod2_data.Trend).sum()
explod = [0.2, 0.2, 0.5, 0, 0, 0, 0 ,0,0]
ax1.pie(sums, labels=sums.index, autopct='%1.1f%%', explode=explod)
ax2.title.set_text('Trend')
mod2_data = mod2_data.drop(['ones'], axis=1)

bard1 = mod2_data[['Trend', 'Total Traded Quantity']].groupby(['Trend'], as_index=False).mean()
bar1 = sns.barplot("Trend", 'Total Traded Quantity', data=bard1, ci=None, ax=ax2)
for item in bar1.get_xticklabels():
    item.set_rotation(45)
ax2.set_ylabel('') 
ax2.title.set_text('Trend to mean of Total Traded Quantity')

bard2 = mod2_data[['Trend', 'Total Traded Quantity']].groupby(['Trend'], as_index=False).median()
bar2 = sns.barplot("Trend", 'Total Traded Quantity', data=bard2, ci=None, ax=ax3)
for item in bar2.get_xticklabels():
    item.set_rotation(45)
ax3.set_ylabel('') 
ax3.title.set_text('Trend to meadian of Total Traded Quantity')

plt.tight_layout()
plt.show()
# -

# ## 2.5 Daily returns

fig, ax = plt.subplots(figsize=(10, 6))
ax.hist(mod2_data.Day_Perc_Change, bins=50)
ax.set_ylabel('Percent Change')
plt.show()

# ## 2.6  Correlation

# +
five_stocks = ['AMARAJABAT.csv', 'CUMMINSIND.csv', 'JINDALSTEL.csv', 'MRPL.csv', 'VOLTAS.csv']
dfs = {}
for i in five_stocks:
    stock = i.split('.')[0]
    temp_df = pd.read_csv(i)
    temp_df = temp_df[temp_df["Series"] == "EQ"]
    temp_df['Day_Perc_Change'] = temp_df['Close Price'].pct_change()*100
    temp_df = temp_df['Day_Perc_Change']
    temp_df = temp_df.drop(temp_df.index[0])
    dfs[stock] = temp_df

dfs = pd.DataFrame(dfs)
sns.pairplot(dfs)
plt.show()
# -

# There is no correlation among almost all the stocks, which is good thing. To get the profit from the stock market, the company's stocks trend should be independent from the other stock's trend

# ## 2.7 Volatility

rolling1 = dfs.rolling(7).std()
rolling1.dropna()
fig, ax = plt.subplots(figsize=(15, 5))
ax.plot(np.arange(len(rolling1.VOLTAS)), rolling1.VOLTAS, 'k')
plt.title('VOLTAS Volatility')
plt.show()

# ## 2.8 Comparing with Nifty50

nifty  = pd.read_csv('Nifty50.csv')
nifty['Day_Perc_Change'] = nifty['Close'].pct_change()*100
rolling2 = nifty['Day_Perc_Change'].rolling(7).std()
rolling2 = rolling2.dropna()

fig, ax = plt.subplots(figsize=(15, 5))
ax.plot(np.arange(len(rolling1.VOLTAS)), rolling1.VOLTAS, label = 'VOLTAS')
ax.plot(np.arange(len(rolling2)), rolling2, 'k', label = 'Nifty')
plt.legend()
plt.tight_layout()
plt.show()

# ## 2.9 Trade calls

nifty['roll21'] = nifty['Close'].rolling(21).mean()
nifty['roll34'] = nifty['Close'].rolling(34).mean()
nifty = nifty.dropna()

# +
nifty.Date = pd.to_datetime(nifty['Date'])
fig, ax = plt.subplots(figsize=(15, 7))

def cross(values):
    l=[]
    were = values[0]
    flag = True
    for i, ele in enumerate(values):
        if were==ele:
            l.append(0)
        else:
            l.append(1)
            were = ele
    return l

nifty['buy'] = nifty['roll21'] > nifty['roll34']
nifty['sell'] = nifty['roll21'] < nifty['roll34']

nifty['buy_change'] = np.array(cross(nifty.buy.values.reshape(1, len(nifty.buy)).flatten()))    #reshaping from (461, )
nifty['sell_change'] = np.array(cross(nifty.sell.values.reshape(1, len(nifty.sell)).flatten()))  #reshaping from(461, )

nifty['buy'] = nifty['buy_change'].where(nifty['buy']==True)
nifty['buy'] = nifty['roll21'].where(nifty['buy']==1)

nifty['sell'] = nifty['sell_change'].where(nifty['sell']==True)
nifty['sell'] = nifty['roll21'].where(nifty['sell']==1)

ax.plot(nifty.Date, nifty.Close, 'r')
ax.plot(nifty.Date, nifty.roll34, 'b', label='34_SMA')
ax.plot(nifty.Date, nifty.roll21, 'g', label='21_SMA')
ax.plot(nifty.Date, nifty.buy, "g^")
ax.plot(nifty.Date, nifty.sell, "kv")

ax.set_xlabel('Date')
plt.legend(loc=2)
plt.tight_layout()
plt.show()
    
# -

# ## 2.10  Trade call - using Bollinger band

# +
nifty['roll14'] = nifty['Close'].rolling(14).mean()
std = nifty['Close'].rolling(14).std()
nifty['upper_band'] = nifty['roll14']+2*std
nifty['lower_band'] = nifty['roll14']-2*std

fig, ax = plt.subplots(figsize=(15, 7))
ax.plot(nifty.Date, nifty['Close'],'k' ,label = 'avg price')
ax.plot(nifty.Date, nifty.roll14, label= 'roll14')
ax.plot(nifty.Date, nifty.upper_band, 'r', label = 'upper_band')
ax.plot(nifty.Date, nifty.lower_band,'g', label = 'lower_band')

ax.set_xlabel('Date')
plt.legend(loc=2)
plt.tight_layout()
plt.show()
# -





StarcoderdataJupyterScriptsDedupFiltered