<jupyter_start><jupyter_text>Technology Stock Analysis - Apple, Google, Microsoft & Amazon (Yahoo finance)<jupyter_code>#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)<jupyter_output><empty_output><jupyter_text>Analysis:1. What was the change in price of the stock over time? - Apple2. What was the daily return of the stock on average? - Apple3. What was the moving average of the various stocks? - All companies under consideration4. What was the correlation between different stocks' closing prices? - Apple v/s Google5. 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 consideration7. How can we attempt to predict future stock behavior? -   Analyzing Apple Stock<jupyter_code>AAPL.describe()
AAPL.info()
AAPL['Adj Close'].plot(legend = True, figsize = (10,4))
AAPL['High'].plot()
AAPL['Volume'].plot(legend = True, figsize = (20,4))<jupyter_output><empty_output><jupyter_text>1. Moving Average - Apple<jupyter_code>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))<jupyter_output><empty_output><jupyter_text>2. Daily return on the stocks - Apple<jupyter_code>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')<jupyter_output><empty_output><jupyter_text>3. What was the moving average of the various stocks<jupyter_code>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')<jupyter_output><empty_output><jupyter_text>4. What was the correlation between different stocks' closing prices? - Apple v/s Google<jupyter_code>sns.jointplot('GOOG', 'AAPL', data = tech_rets, kind = 'scatter', color = 'red')<jupyter_output><empty_output><jupyter_text>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?<jupyter_code>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')<jupyter_output><empty_output><jupyter_text>All the 4 tech companies under consideration have a positive co - relationship on their daily returns<jupyter_code>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)<jupyter_output><empty_output><jupyter_text>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?<jupyter_code>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'))<jupyter_output><empty_output><jupyter_text>AAPL having the highest return value<jupyter_code>sns.distplot(AAPL['Daily Return'], bins = 100, color = 'green')
rets.head()
# Risk Analysis - Method 1 (Bootstrap method - Quantile)

rets['AAPL'].quantile(.05)<jupyter_output><empty_output><jupyter_text>with 95% confidence we will lose a max of 3.3% on AAPL Stocks            7. How can we attempt to predict future stock behavior?<jupyter_code># 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')<jupyter_output><empty_output>
{'fraction_non_alphanumeric': 0.13335265980576896, 'fraction_numerical': 0.020582693143933902, 'mean_word_length': 4.8031959629941126, 'pattern_counts': {'":': 0, '<': 45, '<?xml version=': 0, '>': 45, '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': '11', 'dir': 'jupyter-structured-clean-dedup', 'id': '590921', 'license': 'MIT', 'n_tokens_mistral': 2541, 'n_tokens_neox': 2405, 'n_words': 664, 'path': 'Stock Market Analysis.ipynb', 'repo_name': 'Sanjansprasad/Data-Viz---Python', 'size': '6899'}