-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathdaily_returns.py
More file actions
71 lines (54 loc) · 2.17 KB
/
daily_returns.py
File metadata and controls
71 lines (54 loc) · 2.17 KB
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
"""Compute daily returns."""
import os
import pandas as pd
import matplotlib.pyplot as plt
def symbol_to_path(symbol, base_dir="data"):
"""Return CSV file path given ticker symbol."""
return os.path.join(base_dir, "{}.csv".format(str(symbol)))
def get_data(symbols, dates):
"""Read stock data (adjusted close) for given symbols from CSV files."""
df = pd.DataFrame(index=dates)
if 'SPY' not in symbols: # add SPY for reference, if absent
symbols.insert(0, 'SPY')
for symbol in symbols:
df_temp = pd.read_csv(symbol_to_path(symbol), index_col='Date',
parse_dates=True, usecols=['Date', 'Adj Close'], na_values=['nan'])
df_temp = df_temp.rename(columns={'Adj Close': symbol})
df = df.join(df_temp)
if symbol == 'SPY': # drop dates SPY did not trade
df = df.dropna(subset=["SPY"])
return df
def plot_data(df, title="Stock prices", xlabel="Date", ylabel="Price"):
"""Plot stock prices with a custom title and meaningful axis labels."""
ax = df.plot(title=title, fontsize=12)
ax.set_xlabel(xlabel)
ax.set_ylabel(ylabel)
plt.show()
def compute_daily_returns(df):
"""Compute and return the daily return values."""
# TODO: Your code here
# Note: Returned DataFrame must have the same number of rows
# One way of doing it:
# daily_returns = df.copy()
# daily_returns[1:] = (df[1:] / df[:-1].values) - 1
# daily_returns.ix[0, :] = 0
# Simpler way of doing it:
daily_returns = (df / df.shift(1)) - 1
daily_returns.ix[0] = 0
return daily_returns
def compute_cummulative_returns(df):
cum_returns = (df / df.ix[0]) - 1
return cum_returns
def test_run():
# Read data
dates = pd.date_range('2012-07-01', '2012-07-31') # one month only
symbols = ['SPY','XOM']
df = get_data(symbols, dates)
plot_data(df)
# Compute daily returns
daily_returns = compute_daily_returns(df)
cum_returns = compute_cummulative_returns(df)
plot_data(daily_returns, title="Daily returns", ylabel="Daily returns")
plot_data(cum_returns, title="Commulative returns", ylabel="Commulative returns")
if __name__ == "__main__":
test_run()