<jupyter_start><jupyter_text><jupyter_code>#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. 
from datetime import datetime
import time
import numpy as np
import pandas as pd
import pandas_datareader as web
import matplotlib.pyplot as plt
plt.style.use('fivethirtyeight')
#Get stock symbols for FAANG
stockSymbols = ["FB","AMZN","AAPL","NFLX","GOOG"]
#Get stock starting date
stockStartDate = '2013-01-01'
#Get today's date and format it in the form YYY-mm-dd
today = time.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.DataReader(stocks, data_source='yahoo', start=start, end=end)[col]     
  return data
# Get the stock portfolio Adj. Close price 
my_stocks = getMyPortfolio(stockSymbols)
# Show my stocks
my_stocks
# Create a function to visualize the stock/portfolio
def showGraph(stocks= stockSymbols,start=stockStartDate, end=today, col='Adj Close'):
  
  # Create the title 
  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)) 
  # 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.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                              
showGraph(stockSymbols)
# try another style https://www.dunderdata.com/blog/view-all-available-matplotlib-styles
available = ['default'] + plt.style.available
for i, style in enumerate(available):
    plt.style.use(style)
    showGraph(stockSymbols)
# Calculate Simple Returns
daily_simple_returns = my_stocks.pct_change(1)
daily_simple_returns
# Show the stock correlation
daily_simple_returns.corr()
# Show the co-variance matrix for simple returns (diagonal is the daily variance)
daily_simple_returns.cov()
# Show the variance
daily_simple_returns.var()
import math
math.sqrt(0.000471)
# Print the standard deviation
print("The Stock Volatility:")
daily_simple_returns.std()
plt.style.use('seaborn-poster')
plt.style.use('fivethirtyeight')
# Visualize the stocks daily simple returns / volatility 
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)
# 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 weights
# 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) 
# Print the daily expected portfolio return
print("The daily expected portfolio return: "+str(portfolioSimpleReturn))
# Print the expected annual portfolio simple return
# The number 253 was calculated 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("Expected annualised portfolio simple return : "+ str(portfolioSimpleReturn * 253))
# Calculate the growth of our investment
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)
# 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()<jupyter_output><empty_output>
{'fraction_non_alphanumeric': 0.10202360876897133, 'fraction_numerical': 0.01918212478920742, 'mean_word_length': 5.268163804491413, 'pattern_counts': {'":': 0, '<': 5, '<?xml version=': 0, '>': 5, 'https://': 1, 'lorem ipsum': 0, 'www.': 1, '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': '1', 'dir': 'jupyter-structured-clean-dedup', 'id': '481591', 'license': 'MIT', 'n_tokens_mistral': 1586, 'n_tokens_neox': 1466, 'n_words': 487, 'path': 'python-for-finance/Python_For_Finance.ipynb', 'repo_name': 'nheske/python-finance', 'size': '4744'}