# ---
# 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
# ---

# # Technology Stock Analysis - Apple, Google, Microsoft & Amazon (Yahoo finance)

# +
#1. Importing Data Analysis Modules

import pandas as pd

from pandas import Series, DataFrame

import numpy as np


#2. Importing time Modules

from datetime import datetime


#3. Importing Data reader to read stock data

from pandas_datareader.data import DataReader

# +
#4. Importing Data Visualization Modules

import matplotlib.pyplot as plt

import seaborn as sns

sns.set_style('white')

# %matplotlib inline

# +
#5. Reading Data from Yahoo Finance
# -

tech_list = ['AAPL', 'GOOG', 'MSFT', 'AMZN']

# +
end = datetime.now()

start = datetime(end.year - 1, end.month, end.day)
# -

for stock in tech_list:
    globals()[stock] = DataReader(stock, 'yahoo', start, end)

# Analysis:
# 1. What was the change in price of the stock over time? - Apple
# 2. What was the daily return of the stock on average? - Apple
# 3. What was the moving average of the various stocks? - All companies under consideration
# 4. What was the correlation between different stocks' closing prices? - Apple v/s Google
# 5. What was the correlation between different stocks' daily returns? - All companies under consideration 
# 6. How much value do we put at risk by investing in a particular stock? - All companies under consideration
# 7. How can we attempt to predict future stock behavior? - 

# # Analyzing Apple Stock

AAPL.describe()

AAPL.info()

AAPL['Adj Close'].plot(legend = True, figsize = (10,4))

AAPL['High'].plot()

AAPL['Volume'].plot(legend = True, figsize = (20,4))

# # 1. Moving Average - Apple

# +
ma_day = [10,20,50]

for ma in ma_day:
    column_name = "MA for %s days" %(str(ma))
    AAPL[column_name] = AAPL['Adj Close'].rolling(ma).mean()

AAPL[['Adj Close','MA for 10 days','MA for 20 days','MA for 50 days']].plot(figsize = (20,4))
# -

#    

# #   

# # 2. Daily return on the stocks - Apple

# +
AAPL['Daily Return'] = AAPL['Adj Close'].pct_change()

AAPL['Daily Return'].plot(legend = True, color = 'green', figsize = (20,4), linestyle = '--', marker = 'o')
# -

AAPL['Daily Return'].plot(figsize = (20,4))

AAPL['Daily Return'].hist(figsize = (10,4))

sns.distplot(AAPL['Daily Return'].dropna(),bins = 100, color = 'purple')

#    

#        

# # 3. What was the moving average of the various stocks

# +
returns_df = DataReader(tech_list, 'yahoo', start, end)['Adj Close']

returns_df

# +
tech_rets  = returns_df.pct_change()

tech_rets.head()

# +
# Verifying the above dataset - Drawing linear relationship between Google and Google

# (expexting: pearsons ratio of 1)
# -

sns.jointplot('GOOG', 'GOOG', data = tech_rets, kind = 'scatter', color = 'seagreen')

#     

#     

# # 4. What was the correlation between different stocks' closing prices? - Apple v/s Google

sns.jointplot('GOOG', 'AAPL', data = tech_rets, kind = 'scatter', color = 'red')

# # from the graph we can conclude the linear relationship between AAPL and GOOG stocks are positive 

#     

#     

# # 5. What was the correlation between different stocks' daily returns? 

sns.pairplot(data = tech_rets.dropna())

# +
pairgrid = sns.PairGrid(data = tech_rets.dropna())

pairgrid.map_upper(plt.scatter,color = 'purple')

pairgrid.map_lower(sns.kdeplot, color = 'green')

pairgrid.map_diag(plt.hist, color = 'red')
# -

# # All the 4 tech companies under consideration have a positive co - relationship on their daily returns

#     

#       

# +
closingprice_df = DataReader(tech_list, 'yahoo', start, end)['Close']

closingprice_df

# +
closing_price = sns.PairGrid(data = closingprice_df. dropna())

closing_price.map_upper(plt.scatter, color = 'purple')

closing_price.map_lower(sns.kdeplot, color = 'green')

closing_price.map_diag(plt.hist, color = 'blue')

# +
corr = closingprice_df.corr()

mask = np.zeros_like(corr)

mask[np.triu_indices_from(mask)] = True

sns.heatmap(corr, mask = mask, vmin = 0, vmax = 1, square = True)

# +
corr_tech_rets = tech_rets.corr()

mask = np.zeros_like(corr, dtype=np.bool)

mask[np.triu_indices_from(mask)] = True

sns.heatmap(corr, mask=mask, vmin=0, vmax=1,annot=True)
# -

# # All the 4 tech companies under consideration have a positive co - relationship on their closing prices

#     

#     

# # 6. How much value do we put at risk by investing in a particular stock?

# +
rets = tech_rets.dropna()

area = np.pi * 20

plt.scatter(x = rets.mean(), y = rets.std(), s = area)

plt.xlabel('Expected Return')
plt.ylabel('Risk')

for label,x,y in zip(rets.columns, rets.mean(),rets.std()):
    plt.annotate(
        label,xy = (x, y), xytext = (50, 70),
        textcoords = 'offset points', ha = 'right', va = 'baseline',
        arrowprops = dict(arrowstyle = '-', connectionstyle = ('arc3, rad = 1'), color = 'red'))
        
        
# -

# # AAPL having the highest return value 

sns.distplot(AAPL['Daily Return'], bins = 100, color = 'green')

rets.head()

# +
# Risk Analysis - Method 1 (Bootstrap method - Quantile)

rets['AAPL'].quantile(.05)
# -

# # with 95% confidence we will lose a max of 3.3% on AAPL Stocks

#     

#     

# # 7. How can we attempt to predict future stock behavior? 

# +
# Risk Analysis - Method 2 (Monte Carlo method)

days = 365

dt = 1/days

mu = rets['GOOG'].mean()

sigma = rets['GOOG'].std()

# -

def stock_monte_carlo(start_price, days, mu, sigma):
    
    price = np.zeros(days)
    price[0] = start_price
    
    shock = np.zeros(days)
    drift = np.zeros(days)
    
    for x in range(1,days):
        
        shock[x] = np.random.normal(loc = mu * dt, scale = sigma * np.sqrt(dt))
        
        drift[x] = mu * dt
        
        price[x] = price[x - 1] + (price[x - 1] * (drift[x] + shock[x]))
    
    return price
    


GOOG.head()

# +
start_price = 1050.630005

for run in range(100):
    plt.plot(stock_monte_carlo(start_price, days, mu, sigma))

# +
runs = 10000

simulations = np.zeros(runs)

for run in range(runs):
    simulations[run] = stock_monte_carlo(start_price, days, mu, sigma)[days-1]

# +
q = np.percentile(simulations, 1)

plt.hist(simulations, bins = 200)

# Starting price 
plt.figtext(0.6, 0.8, s = 'Start Price: $%.2f' %start_price)

# Mean ending price
plt.figtext(0.6, 0.7,'Mean Final Price: $%.2f' %simulations.mean())

# Variance of the price (within 99% of the confidence interval)
plt.figtext(0.6, 0.6,'VaR(0.99): $%.2f' %(start_price - q))

# Display 1% quantile
plt.figtext(0.15, 0.6,'q(0.99): $%.2f' %q)

# Plot a line at 1% quantile result
plt.axvline(x = q, linewidth = 4, color = 'red')

# Title

plt.title('Final price distribution for google stock after {} days'.format(days), weight = 'bold')

# -

# # with 99% confidence we will lose a max of $50.53 on GOOG Stocks



StarcoderdataJupyterScriptsDedupFiltered