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
|
{
"cells": [
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"import datetime\n",
"import pandas.tseries.offsets as off\n",
"import globeop_reports as go\n",
"import pandas as pd\n",
"import matplotlib.pyplot as plt\n",
"import numpy as np\n",
"\n",
"from db import dbengine\n",
"from yieldcurve import YC\n",
"from quantlib.termstructures.yield_term_structure import YieldTermStructure\n",
"\n",
"engine = dbengine('dawndb')\n",
"Sengine = dbengine('serenitasdb')"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"#Plot this month's PNL\n",
"pnl_alloc_last_month = pnl_alloc.xs(report_date)\n",
"ax = pnl_alloc_last_month['strat_return'].plot(kind='bar', figsize = (6,6), width = .35)\n",
"ax.set_xlabel('Strategy')\n",
"ax.set_ylabel('Return (%)')\n",
"x_ticks = ax.get_xticks()\n",
"y_ticks = ax.get_yticks()\n",
"ax.set_yticklabels(['{:.2f}%'.format(y*100) for y in y_ticks])\n",
"plt.tight_layout()"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"#Pnl through time\n",
"#pnl_alloc_sum = pnl_alloc['mtdtotalbookpl']/ pnl_alloc['mtdtotalbookpl'].groupby(['date']).sum()\n",
"#pnl_alloc_sum['strat_return'].unstack().plot(kind='bar')"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"#Capital Allocation - Find the strategies that are not defined: undefined needs to be mapped in strat_map\n",
"port = go.get_portfolio().reset_index()\n",
"cap_alloc = port.reset_index().merge(strats, on=['strat', 'custacctname'], how='left')\n",
"undefined = cap_alloc[cap_alloc.pnl.isna()].groupby(['strat', 'custacctname']).last()\n",
"alloc1 = cap_alloc[cap_alloc.periodenddate == report_date].groupby(['capital']).sum()"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"# create piechart and add a circle at the center\n",
"alloc1['percentage'] = alloc1['endbooknav']/alloc1['endbooknav'].sum()\n",
"ax = alloc1[alloc1>0]['percentage'].plot(kind='pie', figsize=(8,4), autopct='%1.1f%%', pctdistance=1.25, labeldistance=1.5)\n",
"ax.add_artist(plt.Circle((0,0), 0.7, color='white'))\n",
"ax.axis('equal')\n",
"plt.tight_layout()"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"#Number of bond positions by strategy by month\n",
"df = go.get_portfolio()\n",
"df = df[(df.custacctname == 'V0NSCLMAMB') &\n",
" ~(df.invid.isin(['USD', 'CAD', 'EUR'])) & (df.endqty > 0)]\n",
"df = df.groupby(pd.Grouper(freq='M'), group_keys=False).apply(lambda df: df.loc[df.index[-1]])\n",
"num_bond_pos = df.groupby(['periodenddate', 'port']).identifier.nunique().unstack()"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"#Number of bond trades by direction by month\n",
"sql_string = \"SELECT * FROM bonds\"\n",
"df = pd.read_sql_query(sql_string, dbengine('dawndb'), parse_dates=['trade_date'],\n",
" index_col=['trade_date'])\n",
"df = df.groupby([pd.Grouper(freq='M'), 'buysell'], group_keys=False).identifier.count().unstack()\n",
"idx = pd.date_range(df.index[0], df.index[-1], freq = 'M')\n",
"num_bond_trades = df.reindex(idx, fill_value = 0)"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"#capital allocation across time\n",
"cap_alloc_time = cap_alloc.groupby(['periodenddate','capital']).sum()\n",
"cap_alloc_time = cap_alloc_time.reset_index('capital').groupby(pd.Grouper(freq='M'), group_keys=False).apply(lambda df: df.loc[df.index[-1]])\n",
"cap_alloc_time['perc'] = cap_alloc_time['endbooknav'].groupby('periodenddate').apply(lambda x: x/x.sum())\n",
"cap_alloc_time = cap_alloc_time.set_index('capital', append=True)['perc'].unstack()"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"ax = cap_alloc_time.plot.bar(stacked=True, legend=False, figsize=(10,6))\n",
"\n",
"#Format Y Axis\n",
"vals = ax.get_yticks()\n",
"ax.set_yticklabels(['{:3.0f}%'.format(x*100) for x in vals])\n",
"\n",
"#Format X Axis\n",
"visible = ax.xaxis.get_ticklabels()[::6]\n",
"for label in ax.xaxis.get_ticklabels():\n",
" if label not in visible:\n",
" label.set_visible(False)\n",
"ax.xaxis.set_major_formatter(plt.FixedFormatter(df.index.to_series().dt.strftime(\"%b %Y\")))\n",
"ax.xaxis.set_label_text(\"\")\n",
"lgd = ax.legend(loc='lower center', bbox_to_anchor=(0.50, -0.6), ncol=4)\n",
"plt.tight_layout()\n",
"ax.figure.savefig(\"/home/serenitas/edwin/PythonGraphs/cap_alloc_1.png\", bbox_extra_artists=(lgd,), bbox_inches='tight')"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": []
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": []
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"#Calculate Interests allocation \n",
"sql_string = \"select periodenddate, strat, sum(endqty) as bal, counterparty \" \\\n",
" \"from valuation_reports where invid = 'USDLOAN' and \" \\\n",
" \"extract(month from periodenddate) = %s and \" \\\n",
" \"extract(year from periodenddate) = %s \" \\\n",
" \"group by periodenddate, strat, counterparty \" \\\n",
" \"order by periodenddate desc\"\n",
"df = pd.read_sql_query(sql_string, dbengine('dawndb'), \n",
" parse_dates=['periodenddate'],\n",
" index_col=['strat', 'counterparty'],\n",
" params=[report_date.month, report_date.year])\n",
"df['day_frac'] = -(df.groupby(level=['strat','counterparty'])['periodenddate'].transform(lambda s:\n",
" s.diff().astype('timedelta64[D]') / 360)).astype(float)\n",
"df = df.fillna(0)\n",
"r = {}\n",
"yc = YieldTermStructure()\n",
"for t in df['periodenddate'].unique():\n",
" yc.link_to(YC(evaluation_date=pd.Timestamp(t)))\n",
" r[pd.Timestamp(t)] = (float(yc.zero_rate(.083333)))\n",
"rates = pd.DataFrame.from_dict(r, orient='index')\n",
"df = df.reset_index().set_index('periodenddate', drop=False).join(rates)\n",
"df = df.rename(columns={0: 'rate'})\n",
"df = df.set_index(['strat','counterparty'], append=True)\n",
"df['interest'] = df['rate'] * df['day_frac'] * df['bal']\n",
"interests = df['interest'].groupby(level=['counterparty','strat']).sum()"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": []
}
],
"metadata": {
"kernelspec": {
"display_name": "Python 3",
"language": "python",
"name": "python3"
},
"language_info": {
"codemirror_mode": {
"name": "ipython",
"version": 3
},
"file_extension": ".py",
"mimetype": "text/x-python",
"name": "python",
"nbconvert_exporter": "python",
"pygments_lexer": "ipython3",
"version": "3.7.3"
}
},
"nbformat": 4,
"nbformat_minor": 4
}
|