<jupyter_start><jupyter_text>Stock Market Example Project In this example project we will be looking at data from the stock market, particularly some technology stocks.We will use pandas to get stock information, visualise different aspects of it, and finally we will look at a few ways of analysing the risk of a stock, based on its previous performance history. We will also be predicting future stock prices through a Monte Carlo method!We'll be answering the following questions along the way:1.) What was the change in price of the stock over time?2.) What was the daily return of the stock on average?3.) What was the moving average of the various stocks?4.) What was the correlation between different stocks' closing prices?4.) What was the correlation between different stocks' daily returns?5.) How much value do we put at risk by investing in a particular stock?6.) How can we attempt to predict future stock behavior?**Basic Analysis of Stock Information**In this section we'll go over how to handle requesting stock information with pandas, and how to analyze basic attributes of a stock.<jupyter_code>import pandas as pd
from pandas import Series,DataFrame
import numpy as np
import matplotlib.pyplot as plt
import seaborn as sns
sns.set_style('whitegrid')
%matplotlib inline
from pandas_datareader import data
import datetime
from __future__ import division
tech_list = ['AAPL','GOOG','MSFT','AMZN']
end = datetime.datetime(2021, 4, 14)

start = datetime.datetime(2020, 4, 14)
for stock in tech_list:
    globals()[stock] = data.DataReader(stock,'yahoo',start,end)
AAPL
GOOG.head()
AAPL.describe()
AAPL.info()
AAPL['Adj Close'].plot(legend=True,figsize=(10,4))
AAPL['Volume'].plot(legend=True,figsize=(10,4))<jupyter_output><empty_output><jupyter_text>For more information on the moving average check out the following links:1) https://www.investopedia.com/terms/m/movingaverage.asp 2) https://www.investopedia.com/articles/active-trading/052014/how-use-moving-average-buy-stocks.asp<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(subplots=False,figsize=(10,4))
AAPL['Daily Return'] = AAPL['Adj Close'].pct_change()

AAPL['Daily Return'].plot(figsize=(10,4),legend=True,linestyle='--',marker='o')
sns.displot(AAPL['Daily Return'].dropna(),bins=100,color='purple')
sns.histplot(AAPL['Daily Return'].dropna(),bins=100,color='purple')
AAPL['Daily Return'].hist(bins=100)
closing_df = data.DataReader(tech_list,'yahoo',start,end)['Adj Close']
closing_df.head()
tech_rets = closing_df.pct_change()
tech_rets.head()
sns.jointplot('GOOG','GOOG',tech_rets,kind='scatter',color='seagreen')
sns.jointplot('GOOG','MSFT',tech_rets,kind='scatter')
tech_rets.head()
sns.pairplot(tech_rets.dropna())
returns_fig = sns.PairGrid(tech_rets.dropna())

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

returns_fig.map_lower(sns.kdeplot,cmap='cool_d')

returns_fig.map_diag(plt.hist,bins=30)
returns_fig = sns.PairGrid(closing_df)

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

returns_fig.map_lower(sns.kdeplot,cmap='cool_d')

returns_fig.map_diag(plt.hist,bins=30)
sns.heatmap(data = tech_rets.corr(), annot=True)
sns.heatmap(data = closing_df.corr(), annot=True)<jupyter_output><empty_output><jupyter_text>**Risk Analysis**There are many ways we can quantify risk, one of the most basic ways using the information we've gathered on daily percentage returns is by comparing the expected return with the standard deviation of the daily returns.<jupyter_code>rets = tech_rets.dropna()
area = np.pi*20

plt.scatter(rets.mean(),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, 50),
        textcoords = 'offset points', ha = 'right', va = 'bottom',
        arrowprops = dict(arrowstyle = '-', connectionstyle = 'arc3,rad=-0.3'))
# Refer to matplotlib annotations guide
# https://matplotlib.org/1.5.3/users/annotations_guide.html<jupyter_output><empty_output><jupyter_text>**Value at Risk**Let's go ahead and define a value at risk parameter for our stocks.We can treat value at risk as the amount of money we could expect to lose (aka putting at risk) for a given confidence interval.There are several methods we can use for estimating a value at risk.Let's go ahead and see some of them in action.**Value at risk using the "bootstrap" method**For this method we will calculate the empirical quantiles from a histogram of daily returns. For more information on quantiles, check out this link: https://en.wikipedia.org/wiki/QuantileLet's go ahead and repeat the daily returns histogram for Apple stock.<jupyter_code>sns.displot(AAPL['Daily Return'].dropna(),bins=100,color='purple')
rets.head()
rets['AAPL'].quantile(0.05)<jupyter_output><empty_output><jupyter_text>**Value at Risk using the Monte Carlo method**Using the Monte Carlo to run many trials with random market conditions, then we'll calculate portfolio losses for each trial. After this, we'll use the aggregation of all these simulations to establish how risky the stock is.Let's start with a brief explanation of what we're going to do:We will use the geometric Brownian motion (GBM), which is technically known as a Markov process. This means that the stock price follows a random walk and is consistent with (at the very least) the weak form of the efficient market hypothesis (EMH): past price information is already incorporated and the next price movement is "conditionally independent" of past price movements.This means that the past information on the price of a stock is independent of where the stock price will be in the future, basically meaning, you can't perfectly predict the future solely based on the previous price of a stock.The equation for geometric Browninan motion is given by the following equation:ΔSS=μΔt+σϵΔt−−−√Where S is the stock price, mu is the expected return (which we calculated earlier),sigma is the standard deviation of the returns, t is time, and epsilon is the random variable.We can mulitply both sides by the stock price (S) to rearrange the formula and solve for the stock price.ΔS=S(μΔt+σϵΔt−−−√)Now we see that the change in the stock price is the current stock price multiplied by two terms. The first term is known as "drift", which is the average daily return multiplied by the change of time. The second term is known as "shock", for each tiem period the stock will "drift" and then experience a "shock" which will randomly push the stock price up or down. By simulating this series of steps of drift and shock thousands of times, we can begin to do a simulation of where we might expect the stock price to be.For more info on the Monte Carlo method for stocks, check out the following link: https://www.investopedia.com/articles/07/montecarlo.aspTo demonstrate a basic Monte Carlo method, we will start with just a few simulations. First we'll define the variables we'll be using the Google DataFrame GOOG<jupyter_code>days = 365

dt = 1/days

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

sigma = rets.std()['GOOG']
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 = 1220.51

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

plt.xlabel('Days')
plt.ylabel('Price')
plt.title('Monte Carlo Analysis for Google')
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)

plt.figtext(0.6,0.8,s="Start price: $%.2f" %start_price)

plt.figtext(0.6,0.7,"Mean final price: $%.2f" % simulations.mean())

plt.figtext(0.6,0.6,"VaR(0.99): $%.2f" % (start_price - q,))

plt.figtext(0.15,0.6,"q(0.99): $%.2f" % q)

plt.axvline(x=q, linewidth=4, color='r')

plt.title(u"Final price distribution for Google Stock after %s days" % days, weight='bold');<jupyter_output><empty_output>
{'fraction_non_alphanumeric': 0.10993283845881938, 'fraction_numerical': 0.01661364439731354, 'mean_word_length': 5.245768947755702, 'pattern_counts': {'":': 0, '<': 21, '<?xml version=': 0, '>': 21, 'https://': 5, 'lorem ipsum': 0, 'www.': 3, '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': '5', 'dir': 'jupyter-structured-clean-dedup', 'id': '154142', 'license': 'MIT', 'n_tokens_mistral': 2789, 'n_tokens_neox': 2629, 'n_words': 931, 'path': 'stocks/Stock Market Example Project.ipynb', 'repo_name': 'locspoc/data_analysis_and_visualisation', 'size': '8487'}