Stock Market Analysis for Tech Stocks
In this project, we'll analyse data from the stock market for some technology stocks.
Again, we'll use Pandas to extract and analyse the information, visualise it, and look at different ways to analyse the risk of a stock, based on its performance history.
Here are the questions we'll try to answer:
- What was the change in a stock's price over time?
- What was the daily return average of a stock?
- What was the moving average of various stocks?
- What was the correlation between daily returns of different stocks?
- How much value do we put at risk by investing in a particular stock?
- How can we attempt to predict future stock behaviour?
1#Python Data Analysis imports2import pandas as pd3from pandas import Series,DataFrame4import numpy as np56#Visualisation imports7import matplotlib.pyplot as plt8import seaborn as sns9sns.set_style('whitegrid')10%matplotlib inline1112#To grab stock data13from pandas.io.data import DataReader14from datetime import datetime1516#To handle floats in Python 217from __future__ import division
We're going to analyse some tech stocks, and it seems like a good idea to look at their performance over the last year. We can create a list with the stock names, for future looping.
1#We're going to analyse stock info for Apple, Google, Microsoft, and Amazon2tech_list = ['AAPL','GOOG','MSFT','AMZN','YHOO']34#Setting the end date to today5end = datetime.now()67#Start date set to 1 year back8start = datetime(end.year-1,end.month,end.day)910#Using Yahoo Finance to grab the stock data11for stock in tech_list:12 globals()[stock] = DataReader(stock,'yahoo',start,end) #The globals method sets the stock name to a global variable
Thanks to the globals method, Apple's stock data will be stored in the AAPL global variable dataframe. Let's see if that worked.
1#Basic stats for Apple's Stock2AAPL.describe()
And that easily, we can make out what the stock's minimum, maximum, and average price was for the last year.
1#Some basic info about the dataframe2AAPL.info()
<class 'pandas.core.frame.DataFrame'>DatetimeIndex: 253 entries, 2015-09-23 to 2016-09-22Data columns (total 6 columns):Open 253 non-null float64High 253 non-null float64Low 253 non-null float64Close 253 non-null float64Volume 253 non-null int64Adj Close 253 non-null float64dtypes: float64(5), int64(1)memory usage: 13.8 KB
No missing info in the dataframe above, so we can go about our business.
What's the change in stock's price over time?
1#Plotting the stock's adjusted closing price using pandas2AAPL['Adj Close'].plot(legend=True,figsize=(12,5))
Similarily, we can plot change in a stock's volume being traded, over time.
1#Plotting the total volume being traded over time2AAPL['Volume'].plot(legend=True,figsize=(12,5))
What was the moving average of various stocks?
Let's check out the moving average for stocks over a 10, 20 and 50 day period of time. We'll add that information to the stock's dataframe.
1ma_day = [10,20,50]23for ma in ma_day:4 column_name = "MA for %s days" %(str(ma))56 AAPL[column_name] = AAPL['Adj Close'].rolling(window=ma,center=False).mean()78AAPL.tail()
|Open||High||Low||Close||Volume||Adj Close||MA for 10 days||MA for 20 days||MA for 50 days|
1AAPL[['Adj Close','MA for 10 days','MA for 20 days','MA for 50 days']].plot(subplots=False,figsize=(12,5))
1<matplotlib.axes._subplots.AxesSubplot at 0x114a9c390>
Moving averages for more days have a smoother plot, as they're less reliable on daily fluctuations. So even though, Apple's stock has a slight dip near the start of September, it's generally been on an upward trend since mid-July.
What was the daily return average of a stock?
1#The daily return column can be created by using the percentage change over the adjusted closing price2AAPL['Daily Return'] = AAPL['Adj Close'].pct_change()34AAPL['Daily Return'].tail()
Date2016-09-16 -0.0056242016-09-19 -0.0116602016-09-20 -0.0000882016-09-21 -0.0001762016-09-22 0.009423Name: Daily Return, dtype: float64
1#Plotting the daily return2AAPL['Daily Return'].plot(figsize=(14,5),legend=True,linestyle='--',marker='o')
Positive daily returns seem to be slightly more frequent than negative returns for Apple.
What was the correlation between daily returns of different stocks?
1#Reading just the 'Adj Close' column this time2close_df = DataReader(tech_list,'yahoo',start,end)['Adj Close']34close_df.tail()
Everything works as expected.
Just as we did earlier, we can use Pandas' pct_change method to get the daily returns of our stocks.
1rets_df = close_df.pct_change()23rets_df.tail()
Let's try creating a scatterplot to visualise any correlations between different stocks. First we'll visualise a scatterplot for the relationship between the daily return of a stock to itself.
As expected, the relationship is perfectly linear because we're trying to correlate something with itself. Now, let's check out the relationship between Google and Apple's daily returns.
There seems to be a minor correlation between the two stocks, looking at the figure above. The Pearson R Correlation Coefficient value of 0.45 echoes that sentiment.
But what about other combinations of stocks?
Quick and dirty overarching visualisation of the scatterplots and histograms of daily returns of our stocks. To see the actual numbers for the correlation coefficients, we can use seaborn's corrplot method.
Google and Microsoft seem to have the highest correlation. But another interesting thing to note is that all tech companies that we explored are positively correlated.
How much value do we put at risk by investing in a particular stock?
A basic way to quantify risk is to compare the expected return (which can be the mean of the stock's daily returns) with the standard deviation of the daily returns.
1rets = rets_df.dropna()23plt.figure(figsize=(8,5))45plt.scatter(rets.mean(),rets.std(),s=25)67plt.xlabel('Expected Return')8plt.ylabel('Risk')91011#For adding annotatios in the scatterplot12for label,x,y in zip(rets.columns,rets.mean(),rets.std()):13 plt.annotate(14 label,15 xy=(x,y),xytext=(-120,20),16 textcoords = 'offset points', ha = 'right', va = 'bottom',17 arrowprops = dict(arrowstyle='->',connectionstyle = 'arc3,rad=-0.5'))
We'd want a stock to have a high expected return and a low risk; Google and Microsoft seem to be the safe options for that. Meanwhile, Yahoo and Amazon stocks have higher expected returns, but also have a higher risk
Value at Risk
We can treat Value at risk as the amount of money we could expect to lose for a given confidence interval. We'll use the 'Bootstrap' method and the 'Monte Carlo Method' to extract this value.
Using this method, we calculate the empirical quantiles from a histogram of daily returns. The quantiles help us define our confidence interval.
To recap, our histogram for Apple's stock looked like the above. And our daily returns dataframe looked like:
1#Using Pandas built in qualtile method2rets['AAPL'].quantile(0.05)
The 0.05 empirical quantile of daily returns is at -0.019. This means that with 95% confidence, the worst daily loss will not exceed 2.57% (of the investment).
How can we attempt to predict future stock behaviour?
Monte Carlo Method
Check out this link for more info on the Monte Carlo method. In short: in this method, we run simulations to predict the future many times, and aggregate the results in the end for some quantifiable value.
1days = 36523#delta t4dt = 1/36556mu = rets.mean()['GOOG']78sigma = rets.std()['GOOG']910#Function takes in stock price, number of days to run, mean and standard deviation values11def stock_monte_carlo(start_price,days,mu,sigma):1213 price = np.zeros(days)14 price = start_price1516 shock = np.zeros(days)17 drift = np.zeros(days)1819 for x in xrange(1,days):2021 #Shock and drift formulas taken from the Monte Carlo formula22 shock[x] = np.random.normal(loc=mu*dt,scale=sigma*np.sqrt(dt))2324 drift[x] = mu * dt2526 #New price = Old price + Old price*(shock+drift)27 price[x] = price[x-1] + (price[x-1] * (drift[x]+shock[x]))2829 return price
We're going to run the simulation of Google stocks. Let's check out the opening value of the stock.
Let's do a simulation of 100 runs, and plot them.
1start_price = 622.049 #Taken from above23for run in xrange(100):4 plt.plot(stock_monte_carlo(start_price,days,mu,sigma))56plt.xlabel('Days')7plt.ylabel('Price')8plt.title('Monte Carlo Analysis for Google')
1runs = 1000023simulations = np.zeros(runs)45for run in xrange(runs):6 simulations[run] = stock_monte_carlo(start_price,days,mu,sigma)[days-1]
1q = np.percentile(simulations,1)23plt.hist(simulations,bins=200)45plt.figtext(0.6,0.8,s="Start price: $%.2f" %start_price)67plt.figtext(0.6,0.7,"Mean final price: $%.2f" % simulations.mean())89plt.figtext(0.6,0.6,"VaR(0.99): $%.2f" % (start_price -q,))1011plt.figtext(0.15,0.6, "q(0.99): $%.2f" % q)1213plt.axvline(x=q, linewidth=4, color='r')1415plt.title(u"Final price distribution for Google Stock after %s days" %days, weight='bold')
We can infer from this that, Google's stock is pretty stable. The starting price that we had was USD622.05, and the average final price over 10,000 runs was USD623.36.
The red line indicates the value of stock at risk at the desired confidence interval. For every stock, we'd be risking USD18.38, 99% of the time.