# Read stock price time series from .csv files # Estimate yield mean and covariance # Use mean/variance analysis to calculate the efficient frontier # For the class # https://www.math.nyu.edu/faculty/goodman/teaching/MathFin2019/MathFinance.html # For use with Assignment 7, posted there # The "tickers" for assets you want to invest in. # There must be a .csv file for each of at least the required length tickerList = c( "T", # ATT (phone company) "F", # Ford (cars) "IBM", # IBM (computers, mostly software) "MSFT", # Microsoft (software) "BA", # Boeing (planes, aerospace) "GM", # General Motors (cars) "AAPL", # Apple (computers, phones, software) "GE", # General Electric (jet engines, other things) "AMD", # AMD (chips) "JPM", # J P Morgan Chase (bank) "NVDA", # Nvidia (chips) "SPY") # S & P index ETF # Read historical time series from .csv files in this directory T = 250 # number of days of historical data to use n = length(tickerList) # number of assets # prices[t,k] = closing price on day t (counting back from today) of asset k prices = matrix( nrow = T, ncol = n) # allocate memory for the matrix for ( k in 1:n){ # iterate over k, not the ticker name ticker = tickerList[k] # get the corresponding ticker name fileName = paste( c( "StockPriceTimeSeries_", # Every series starts like this ticker, # ".csv"), # a .csv file collapse = "") # no blanks between the parts CSVfile = read.csv( fileName ) closingPriceSeries = CSVfile[["close"]] # The column under "close"... # ... holds the closing prices for ( t in 1:T){ # Copy from the "data frame"... prices[ t, k] = closingPriceSeries[t] # ... to the matrix } } # Calculate the daily returns, the mean return, and the empirical covariance returns = matrix( nrow = (T-1), ncol = n) for ( t in 1:(T-1)){ for ( k in 1:n){ returns[ t, k] = ( prices[ t+1, k] - prices[ t,k ])/prices[ t, k] } } mu = matrix( 0, ncol = 1, nrow = n) # Column vector of expected returns # initialized to zero so this works: for ( k in 1:n){ # For asset k ... for ( t in 1:(T-1)){ # ... add the returns over time mu[k] = mu[k] + returns[t,k] } mu[k] = mu[k]/(T-1) # Divide by the number of samples ... } # ... to get the empirical mean C = matrix( 0, ncol = n, nrow = n)