forked from adi0509/Python
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathsimple_returns.py
201 lines (162 loc) · 10.6 KB
/
simple_returns.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
# -*- coding: utf-8 -*-
"""Simple_Returns.ipynb
Automatically generated by Colaboratory.
Original file is located at
https://colab.research.google.com/drive/1boqmTDSjvGNyxahoW4FmIBy0YQsIqE4I
"""
#Description: This is a python program for finance.
# This program will show you how to compute portfolio simple returns,
# get daily returns and volatility etc.
#Resources:
# Efficient Frontier => https://towardsdatascience.com/efficient-frontier-portfolio-optimisation-in-python-e7844051e7f
# How To Be A Successful Investor => https://towardsdatascience.com/how-to-be-a-successful-investor-simple-portfolio-analysis-with-python-7b66fc90fa68
# Financial Python => https://www.quantconnect.com/tutorials/introduction-to-financial-python/rate-of-return,-mean-and-variance
# How To Calculate stock returns in Python => https://www.codingfinance.com/post/2018-04-03-calc-returns-py/
# Log Returns VS Simple Returns => https://fintechprofessor.com/tag/log-returns-vs-simple-returns/
# A Tale Of Two Returns => https://www.portfolioprobe.com/2010/10/04/a-tale-of-two-returns/
# Stack Overflow => https://stackoverflow.com/questions/20000726/calculate-daily-returns-with-pandas-dataframe
# Get business days: https://stackoverflow.com/questions/2224742/most-recent-previous-business-day-in-python
# Log Returns for beginners => https://www.coursera.org/lecture/risk-governance-engage-the-board/video-3-2c-log-returns-for-beginners-Jsnqa
# Why we use log returns in finance => https://www.youtube.com/watch?v=PtoUlt3V0CI
# Market Lessons: Why we use log returns => http://mktlssns.blogspot.com/2010/04/why-we-use-log-returns.html
# Magic of log returns => https://investmentcache.com/magic-of-log-returns-concept-part-1/
# An easy mistake with returns => https://www.r-bloggers.com/an-easy-mistake-with-returns/
# Sharp Ratio => https://www.investopedia.com/terms/s/sharperatio.asp
# Simple Calculations to Determine Return on Investments => https://www.thebalance.com/determine-return-on-investment-3140687
# How Covariance used portfolio theory => https://www.investopedia.com/ask/answers/041315/how-covariance-used-portfolio-theory.asp
# Import the libraries
from datetime import datetime
import numpy as np
import pandas as pd
import pandas_datareader as web
import matplotlib.pyplot as plt
plt.style.use('fivethirtyeight')
# Get the stock symbols in your portfolio,
# I am using FAANG for the portfolio stock
# FAANG is an acronym for the market's five most popular and best-performing tech stocks
# (Facebook, Amazon, Apple, Netflix, & Google)
stockSymbols = ["FB", "AMZN", "AAPL", "NFLX", "GOOG"]
#Get the stock starting date
stockStartDate = '2013-01-01'
# Get todays date and format it in the form YYYY-MM-DD
today = datetime.today().strftime('%Y-%m-%d')
print(today)
# Get the number of assests in the portfolio
numAssets = len(stockSymbols)
# Print the number of assests in your portfolio
print('You have '+ str(numAssets)+ ' assets in your portfolio')
# Create a function to get the stock price(s) of the portfolio
def getMyPortfolio(stocks= stockSymbols, start = stockStartDate, end = today, col='Adj Close'):
#data = web.get_data_yahoo(stocks, start = start, end = end)[col]
data = web.DataReader(stocks, data_source='yahoo', start=start, end=end)[col]
return data
# Get the stock portfolio Adj. Close price and store it into my_stocks variable
my_stocks = getMyPortfolio(stockSymbols)
# Show my stocks
my_stocks
# Create a function to visualize the portfolio
def showGraph(stocks= stockSymbols,start=stockStartDate, end=today, col='Adj Close'):
# Create the title 'Portfolio (High, Low, Open, Close, Volume, Adj Close) Price History
title = 'Portfolio ' + col + ' Price History'
#Get the stocks
my_stocks = getMyPortfolio(stocks= stocks, start=start, end=end, col = col)
# Visualize the price history
plt.figure(figsize=(12.2,4.5)) #width = 12.2in, height = 4.5
# Loop through each stock and plot the Adj Close for each day
for c in my_stocks.columns.values:
plt.plot( my_stocks[c], label=c)#plt.plot( X-Axis , Y-Axis, line_width, alpha_for_blending, label)
plt.title(title)
plt.xlabel('Date',fontsize=18)
plt.ylabel(col +' Price USD ($)',fontsize=18)
plt.legend(my_stocks.columns.values, loc='upper left')
plt.show()
# Show the adjusted close price of FAANG and see how the stocks compare with each other
showGraph(stockSymbols)
# Calculate Simple Returns
daily_simple_returns = my_stocks.pct_change(1) # 1 for ONE DAY lookback for each individual return NOTE:simple return = new/old - 1
# monthly_simple_returns = my_stocks.pct_change(21) # 21 for ONE MONTH lookback for each individual return
# annual_simple_returns = my_stocks.pct_change(253) # 253 for ONE YEAR lookback for each individual return
# Show the daily simple returns
daily_simple_returns
# Show the stock correlation
# Covariance and correlation are two mathematical concepts which are commonly used in statistics.
# When comparing data samples from different populations,
# covariance is used to determine how much two random variables vary together
# (the directional relationship between two asset prices),
# whereas correlation is used to determine when a change in one variable can result in a change in another.
# A correlation value of 1 means two stocks have a perfect positive correlation. If one stock moves up while the other goes down,
# they would have a perfect negative correlation, noted by a value of -1
# The correlation will always have a measurement value between -1 and 1, and it adds a strength value on how the stocks move together. ... In short, covariance tells you that two variables change
# the same way while correlation reveals how a change in one variable affects a change in the other.
daily_simple_returns.corr()
# Show the covariance matrix for simple returns
# Covariance is an important measurement used in modern portfolio theory.
# Modern Portfolio Theory attempts to determine an efficient frontier
# (The efficient frontier is the set of optimal portfolios that offer the highest expected return for a defined level of risk or the lowest risk for a given level of expected return.) for a mix of assets in a portfolio.
# The efficient frontier seeks to optimize the maximum return versus the degree of risk for the overall combined assets
# in the portfolio.
# Covariance can tell how the stocks move together
# The diagonal entries of the covariance matrix are the variances and the other entries are the covariances
# The covariance of two stocks tells you how likely they are to increase or decrease simultaneously.
# Variance (σ^2) in statistics is a measurement of the spread between numbers in a data set.
# It measures how far each number in the set is from the mean and therefore from every other number in the set.
# In finance variance is a measure of dispersion and, most of the time variance is a synonym for risk.
# The higher the variance of an asset price, the higher risk the asset bears along with a higher return and a higher volatility
# The lower the variance of an asset price, the lower risk the asset bears along with a lower return and a lower volatility
# Variance measures the stocks volatility if you take the square root, e.g. sqrt(variance) = σ = volatility = standard deviation
# NOTE: Volatility is the degree of variation of a trading price series over time as measured by the standard deviation of logarithmic returns.
# Show the covariance matrix for simple returns
daily_simple_returns.cov()
# Show the variance
daily_simple_returns.var()
# Print the standard deviation σ (or volatility or sqrt(variance)) for daily simple returns
print("The Stock Volatility:")
daily_simple_returns.std()
# Visualize the stocks daily simple returns / volatility and see how the stocks compare to each other
plt.figure(figsize=(12,4.5)) #Set the figure size (width, height)
# Loop through each stock and plot the simple returns for each day
for c in daily_simple_returns.columns.values:
plt.plot(daily_simple_returns.index, daily_simple_returns[c], lw=2, label=c)#plt.plot( X-Axis , Y-Axis, line_width, alpha_for_blending, label)
# Place the legend in the upper left corner with font size of 10
plt.legend(loc='upper right', fontsize=10)
plt.title('Volatility')
plt.ylabel('Daily Simple Returns') #Label the Y-axis simple returns
plt.xlabel('Date')
plt.show()
# Show the mean / average of the daily simple return
dailyMeanSimpleReturns = daily_simple_returns.mean()
# Print the daily mean simple return
print("The daily mean simple return: ")
print(dailyMeanSimpleReturns)
# Calculate the expected portfolio daily performance with random weights
# [0.4, 0.1, 0.3,0.1,0.1] => 40% FB, 10% AMZN, 30% AAPL, 10% NFLX, 10% GOOG
randomWeights = np.array([0.4, 0.1, 0.3,0.1,0.1])
portfolioSimpleReturn = np.sum(dailyMeanSimpleReturns*randomWeights) #NOTE: Be sure to account for rounding of decimal
# Print the daily expected portfolio return
print("The daily expected portfolio return: " +str(portfolioSimpleReturn))
# Get the yearly simple return, we multiply by 253 instead of 365 because their are approximately 253 trading days in a year
# The NYSE and NASDAQ average about 252 or 253 trading days a year. In 2018 there were 252 trading days in 2020 there will be 253.
# This is from 365.25 (days on average per year) * 5/7 (proportion work days per week) - 6 (weekday holidays) - 3*5/7 (fixed date holidays) = 252.75 ≈ 253.
# Print the expected annual portfolio simple return
print("Expected annualised portfolio simple return : "+ str(portfolioSimpleReturn * 253))
# Calculate the growth of our investment or in other words,
# calculate the total returns from our investment,to do this we need to calculate the cumulative returns
# from that investment.
# The Daily cumulative simple return for n-periods:
# The simple return from period_1 + 1 times the simple return from period_2 + 1 times ... the simple return from period_n
# (1+simple_return_1) * (1+simple_return_2) * ... *(1+simple_return_n)
# Example: (daily_simple_returns["GOOG"][1] + 1) * (daily_simple_returns["GOOG"][2] + 1) = 1.020353
# 0.000581 * 0.019760 = 1.020353
dailyCumulSimplReturn = (daily_simple_returns+1).cumprod()
# Show the cumulative simple return
dailyCumulSimplReturn
# Visualize the daily cumulative simple returns
fig = plt.figure(figsize=(12.2,4.5))
for c in dailyCumulSimplReturn.columns.values:
plt.plot(dailyCumulSimplReturn.index, dailyCumulSimplReturn[c], lw=2, label=c)#plt.plot( X-Axis , Y-Axis, line_width, alpha_for_blending, label)
# Place the legend in the upper left corner with font size of 10
plt.legend(loc='upper left', fontsize=10)
plt.xlabel("Date")
plt.ylabel("Growth of $1 investment")
plt.title("Daily Cumulative Simple Returns")
plt.show()