-
Notifications
You must be signed in to change notification settings - Fork 1
/
charts.py
222 lines (162 loc) · 6.67 KB
/
charts.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
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
"""
Z-Spread Charting
Code for charts used in the 'Z-Spread' project.
Author: Will Carpenter
"""
import numpy as np
import pandas as pd
import os
import matplotlib.pyplot as plt
from scipy import interpolate
from scipy.interpolate import CubicSpline
from matplotlib.ticker import AutoMinorLocator, MultipleLocator, MaxNLocator
# Additional imports for charting
from matplotlib.colors import LightSource
from datetime import datetime
from mpl_toolkits.mplot3d import Axes3D
from matplotlib.dates import DateFormatter
#%%
# Read in par-yield data
tsy = pd.read_csv("https://raw.githubusercontent.com/wrcarpenter/Z-Spread/main/Data/daily-treasury-rates.csv", header=0)
head = pd.read_csv("https://raw.githubusercontent.com/wrcarpenter/Z-Spread/main/Data/daily-treasury-spot-header.csv")
spots = pd.read_csv("https://raw.githubusercontent.com/wrcarpenter/Z-Spread/main/Data/spots-semi-annual.csv", header=0)
ylds = pd.read_csv("https://raw.githubusercontent.com/wrcarpenter/Z-Spread/main/Data/ylds-semi-annual.csv", header=0)
# Define columns
tsy_cols = list(tsy.columns.values)
cols = list(head.columns.values)
from matplotlib.colors import LightSource
from datetime import datetime
from mpl_toolkits.mplot3d import Axes3D
from matplotlib.dates import DateFormatter
import mortgage_cash_flow as mbs # custom module cash flow engine
def cash_flow_plot(cf, w, l, name):
x1 = np.array(cf['Period'])
y1 = np.array(cf['Cash Flow'])
y2 = np.array(cf['Interest'])
fig,ax = plt.subplots(figsize=(w, l))
ax.set_xticks(np.arange(0, len(x1)+30, 30))
ax.set_yticks(np.arange(0, cf["Cash Flow"].max()+200, round(cf["Cash Flow"].max()/10, -3)))
ax.set_ylabel('Dollars ($)', fontsize="large")
ax.set_xlabel('Months', fontsize="large")
ax.set_title(name)
plt.xticks(fontsize=8)
plt.yticks(fontsize=8)
fig.patch.set_facecolor('gainsboro')
plt.plot(x1,y1, label="Total Cash Flow", color='blue')
plt.plot(x1, y2, label="Interest", color='green')
plt.legend(loc='upper right', fontsize='medium')
def tsy_rate_plot():
# Define data
x1 = np.array(tsy_cols[5:])
x1 = x1.astype(float)
y1 = np.array(tsy.loc[1])
y1 = y1[5:]
# Define figure
fig, ax = plt.subplots(figsize=(11, 5))
# Set ticks for x-axis
ax.set_xticks(x1)
ax.set_yticks(np.arange(4.0, 6.0, 0.25))
# Titling
ax.set_ylabel('Yield (%)', fontsize="large")
ax.set_xlabel('Months', fontsize="large")
ax.set_title('Treasury Par Rates 3/8/24')
# set text size
plt.xticks(fontsize=8)
plt.yticks(fontsize=8)
# Generate plot
plt.scatter(x1,y1, color="green", marker="s", label='Treasury Par Yields')
plt.legend(loc='upper right', fontsize='large')
# Plot interpolated treasury yields
def interp_tsy_yld_plot(ylds, tsy_cols, w, l):
# Define data
x1 = np.array(tsy_cols[5:])
x1 = x1.astype(float)
x2 = np.array(list(ylds.columns.values[2:])).astype(float)
y2 = np.array(ylds.loc[1])
y2 = y2[2:]
# Define data
x3 = np.array(tsy_cols[5:])
x3 = x3.astype(float)
y3 = np.array(tsy.loc[1])
y3 = y3[5:]
# Create plot/axis with sizing
fig, ax = plt.subplots(figsize=(w, l))
fig.patch.set_facecolor('gainsboro')
# Define axis markers and sizes
ax.set_xticks(x1)
ax.set_yticks(np.arange(4.0, 6.0, 0.25))
plt.xticks(fontsize=8)
plt.yticks(fontsize=8)
# Axis labels
ax.set_xlabel('Months', fontsize="large")
ax.set_ylabel('Yield (%)', fontsize="large")
ax.set_title('Interpolated Treasury Par Rates 3/8/24')
# Scatter points
plt.scatter(x2,y2, label="Spline Interpolated Par Yields")
plt.scatter(x3,y3, color="darkgreen", marker="s", label='Treasury Par Yields')
plt.plot(x2, y2)
# Add legend
plt.legend(loc='upper right', fontsize='large')
def spot_rate_curve(ylds, tsy_cols, spots, w, l):
x1 = np.array(tsy_cols[5:])
x1 = x1.astype(float)
x2 = np.array(list(ylds.columns.values))
x2 = x2[2:].astype(float)
y2 = np.array(ylds.loc[1])
y2 = y2[2:]
y3 = np.array(spots.loc[1])
y3 = y3[2:]
fig, ax = plt.subplots(figsize=(w, l))
# Background plot color
fig.patch.set_facecolor('gainsboro')
ax.set_xticks(x1)
ax.set_yticks(np.arange(4.0, 6.0, 0.5))
plt.xticks(fontsize=8)
plt.yticks(fontsize=8)
# Axis labels
ax.set_xlabel('Months', fontsize="large")
ax.set_ylabel('Yield (%)', fontsize="large")
ax.set_title('Spot and Yield Rates 3/8/24')
# Scatter plots
plt.scatter(x2,y2, label="Spline Interpolated Par Yields")
plt.scatter(x2,y3, color="darkblue", label='Spot Rates')
# Line plots
plt.plot(x2, y2)
plt.plot(x2, y3, color="darkblue")
# Adding legend
plt.legend(loc='upper right', fontsize='large')
#def z_spread_visual():
# use the arrow function in matplotlib
def tsy_rate_surface(tsy, elevation, azimuthal, w, l):
tsy['Date'] = pd.to_datetime(tsy['Date'], format='%m/%d/%Y')
z = tsy.iloc[: , 1:].to_numpy() # numpy list
x = tsy['Date'].to_numpy().astype('datetime64[D]')
x = x.astype(float)
#x = np.array(x, dtype='datetime64')
y = np.array(list(tsy.columns.values[1:])).astype(float) # tenors
#t1 = pd.DataFrame(Z)
#t1.to_clipboard()
X, Y = np.meshgrid(x, y)
Z = z.T
fig = plt.figure(figsize=(w, l)) # old fig size was 12/15
ax = fig.add_subplot(111, projection='3d')
start_date = min(x)
end_date = max(x)
ax.xaxis.set_major_formatter(DateFormatter('%Y-%d')) # Define date format
# ax.set_box_aspect([2, 1, 1])
rts = np.arange(2.0, 6.0, 0.5)
tenors = np.arange(0, 400, 60)
ax.set_yticks(tenors)
ax.set_zticks(rts)
plt.xticks(fontsize=8)
plt.yticks(fontsize=8)
ax.view_init(elev=elevation, azim=azimuthal) #40,50 40,110 to flip around
ax.set_xlabel('Date', labelpad=20)
ax.set_ylabel('Tenor (months)', labelpad=20)
ax.set_zlabel('Rate (%)', labelpad=3)
ax.set_title('Treasury Par Yields Overtime', fontsize='large')
surf = ax.plot_surface(X,Y,Z, cmap='plasma',
linewidth=0, antialiased=False)
if __name__ == "__main__":
cf_7cpr = mbs.cash_flow('03/29/2024', 6.50, 360, 360, 360, 0, 54, 7, 'CPR', 1000000)
cash_flow_plot(cf_7cpr, 10, 5, "6.5% Mortgage Bond Cash Flow at 7 CPR")