Skip to content

Commit 425e1ca

Browse files
committed
Added data and first two projects
Renamed the projects so they're easier to distinguish. Will add further projects as we finalize them.
1 parent 3ffb185 commit 425e1ca

File tree

1,014 files changed

+3015534
-0
lines changed

Some content is hidden

Large Commits have some content hidden by default. Use the searchbox below for content that may be hidden.

1,014 files changed

+3015534
-0
lines changed

assess_portfolio_mc1p1/analysis.py

Lines changed: 73 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,73 @@
1+
"""MC1-P1: Analyze a portfolio."""
2+
3+
import pandas as pd
4+
import matplotlib.pyplot as plt
5+
import numpy as np
6+
import datetime as dt
7+
from util import get_data, plot_data
8+
9+
# This is the function that will be tested by the autograder
10+
# The student must update this code to properly implement the functionality
11+
def assess_portfolio(sd = dt.datetime(2008,1,1), ed = dt.datetime(2009,1,1), \
12+
syms = ['GOOG','AAPL','GLD','XOM'], \
13+
allocs=[0.1,0.2,0.3,0.4], \
14+
sv=1000000, rfr=0.0, sf=252.0, \
15+
gen_plot=False):
16+
17+
# Read in adjusted closing prices for given symbols, date range
18+
dates = pd.date_range(sd, ed)
19+
prices_all = get_data(syms, dates) # automatically adds SPY
20+
prices = prices_all[syms] # only portfolio symbols
21+
prices_SPY = prices_all['SPY'] # only SPY, for comparison later
22+
23+
# Get daily portfolio value
24+
port_val = prices_SPY # add code here to compute daily portfolio values
25+
26+
# Get portfolio statistics (note: std_daily_ret = volatility)
27+
cr, adr, sddr, sr = [0.25, 0.001, 0.0005, 2.1] # add code here to compute stats
28+
29+
# Compare daily portfolio value with SPY using a normalized plot
30+
if gen_plot:
31+
# add code to plot here
32+
df_temp = pd.concat([port_val, prices_SPY], keys=['Portfolio', 'SPY'], axis=1)
33+
pass
34+
35+
# Add code here to properly compute end value
36+
ev = sv
37+
38+
return cr, adr, sddr, sr, ev
39+
40+
def test_code():
41+
# This code WILL NOT be tested by the auto grader
42+
# It is only here to help you set up and test your code
43+
44+
# Define input parameters
45+
# Note that ALL of these values will be set to different values by
46+
# the autograder!
47+
start_date = dt.datetime(2009,1,1)
48+
end_date = dt.datetime(2010,1,1)
49+
symbols = ['GOOG', 'AAPL', 'GLD', 'XOM']
50+
allocations = [0.2, 0.3, 0.4, 0.1]
51+
start_val = 1000000
52+
risk_free_rate = 0.0
53+
sample_freq = 252
54+
55+
# Assess the portfolio
56+
cr, adr, sddr, sr, ev = assess_portfolio(sd = start_date, ed = end_date,\
57+
syms = symbols, \
58+
allocs = allocations,\
59+
sv = start_val, \
60+
gen_plot = False)
61+
62+
# Print statistics
63+
print "Start Date:", start_date
64+
print "End Date:", end_date
65+
print "Symbols:", symbols
66+
print "Allocations:", allocations
67+
print "Sharpe Ratio:", sr
68+
print "Volatility (stdev of daily returns):", sddr
69+
print "Average Daily Return:", adr
70+
print "Cumulative Return:", cr
71+
72+
if __name__ == "__main__":
73+
test_code()
Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,4 @@
1+
# Ignore everything in this directory
2+
*
3+
# Except this file
4+
!.gitignore

assess_portfolio_mc1p1/util.py

Lines changed: 32 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,32 @@
1+
"""MLT: Utility code."""
2+
3+
import os
4+
import pandas as pd
5+
import matplotlib.pyplot as plt
6+
7+
def symbol_to_path(symbol, base_dir=os.path.join("..", "data")):
8+
"""Return CSV file path given ticker symbol."""
9+
return os.path.join(base_dir, "{}.csv".format(str(symbol)))
10+
11+
def get_data(symbols, dates, addSPY=True, colname = 'Adj Close'):
12+
"""Read stock data (adjusted close) for given symbols from CSV files."""
13+
df = pd.DataFrame(index=dates)
14+
if addSPY and 'SPY' not in symbols: # add SPY for reference, if absent
15+
symbols = ['SPY'] + symbols
16+
17+
for symbol in symbols:
18+
df_temp = pd.read_csv(symbol_to_path(symbol), index_col='Date',
19+
parse_dates=True, usecols=['Date', colname], na_values=['nan'])
20+
df_temp = df_temp.rename(columns={colname: symbol})
21+
df = df.join(df_temp)
22+
if symbol == 'SPY': # drop dates SPY did not trade
23+
df = df.dropna(subset=["SPY"])
24+
25+
return df
26+
27+
def plot_data(df, title="Stock prices", xlabel="Date", ylabel="Price"):
28+
"""Plot stock prices with a custom title and meaningful axis labels."""
29+
ax = df.plot(title=title, fontsize=12)
30+
ax.set_xlabel(xlabel)
31+
ax.set_ylabel(ylabel)
32+
plt.show()

data/$DJI.csv

Lines changed: 1932 additions & 0 deletions
Large diffs are not rendered by default.

data/$SPX.csv

Lines changed: 1932 additions & 0 deletions
Large diffs are not rendered by default.

0 commit comments

Comments
 (0)