-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathfedor_levin_toolkit.py
255 lines (195 loc) · 7.8 KB
/
fedor_levin_toolkit.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
223
224
225
226
227
228
229
import yfinance as yf
import pandas as pd
import numpy as np
import robin_stocks as rs
def get_oneasset_hist_returns(tick):
"""
Input: 'ticker'
Returns Data Frame of daily returns history (max period) for provided ticker using yfinance module
"""
df = yf.Ticker(tick).history(period='max')
df = pd.DataFrame(df['Close'])
df.rename(columns={"Close": tick}, inplace=True)
df[tick] = df[tick].pct_change()
df.dropna(inplace=True)
return df
def hist_returns(lis):
"""
Input: list of tickers
Returns Data Frame of daily returns history (max period) for provided list of tickers using yfinance module
"""
l=[]
for i in lis:
l.append(get_oneasset_hist_returns(i))
final = pd.concat(l, axis=1)
return final
def robin_login(usrnm, psw):
"""
Function connects to Robinhood API
Returns confirmation message
"""
a = rs.login(username=usrnm,
password=psw,
expiresIn=86400,
by_sms=True)
return a
def robin_sector_marketcap_ticker(tick):
"""
Input: 'ticker'
Returns Data Frame of Sector for that ticker as index, Market Cap as value and Ticker as column name
"""
sector = rs.stocks.get_fundamentals(tick, info='sector')
market_cap = rs.stocks.get_fundamentals(tick, info='market_cap')
df = pd.DataFrame([market_cap], index=[sector], columns=[tick])
return df
def sector_mktcap(lis):
"""
Input: list of tickers
Returns Data Frame of Sectors for these tickers as indexes, Market Caps as values and Tickers as column names
"""
l=[]
for i in lis:
l.append(robin_sector_marketcap_ticker(i))
final = pd.concat(l, axis=1)
return final.astype(float)
def robin_crypto_get_oneasset_hist_returns(tick):
"""
Input: 'crypto ticker'
Returns Data Frame of daily returns history (5 years) for provided ticker using robin_stocks module
"""
df = pd.DataFrame(rs.crypto.get_crypto_historicals(tick, interval="day", span="5year"))
df = df[['begins_at', 'close_price']]
df.rename(columns={"close_price": tick, 'begins_at': 'Date'}, inplace=True)
df[tick] = pd.to_numeric(df[tick])
df[tick] = df[tick].pct_change()
df.dropna(inplace=True)
df['Date'] = pd.to_datetime(df['Date'], format='%Y/%m/%d')
df = df.set_index('Date')
return df
def reindex(df):
df = df.reset_index()
df['Date'] = pd.to_datetime(df['Date']).dt.date
df['Date'] = pd.to_datetime(df['Date'])
df = df.set_index('Date')
return df
def crypto_hist_returns_robin(lis):
"""
Input: list of crypto tickers
Returns Data Frame of daily returns history (5 years) for provided list of crypto tickers using robin_stocks module
"""
l=[]
for i in lis:
l.append(robin_crypto_get_oneasset_hist_returns(i))
final = pd.concat(l, axis=1)
return reindex(final)
def cap_weighted(mktcap):
"""
Input: Data Frame of Market Caps (Sector as index, Ticker as column)
Returns Series of cap weights with Tickers as index
"""
l=[]
w=[]
for i in mktcap.columns.to_list():
l.append(mktcap[i].dropna().values)
sum_cap = sum(l)
for i in mktcap.columns.to_list():
w.append(mktcap[i].dropna().values/sum_cap)
res = pd.DataFrame(w, index=mktcap.columns.to_list())
res.rename(columns={0: "Mkt Cap"}, inplace=True)
return res['Mkt Cap']
def wealth(x, start, weight):
"""
Input: x - Data Frame of returns from fltk.hist_returns();
start - total starting amount of a portfolio;
weight - weight of the asset relative to total portfolio;
Returns Data Frame of asset return alongside with wealth generated by the returns
"""
x[f'Wealth_{x.columns.to_list()[0]}'] = 'N/A'
x.iloc[0,1] = start*weight*(1 + x.iloc[0,0])
for i in range(x.shape[0]-1):
x.iloc[i+1, 1] = x.iloc[i,1]*(1+x.iloc[i+1,0])
return x
def input_for_reweight(tick1, tick2, w1, start_sum, start_year, end_year=None):
"""
Input: tick1 - '1st asset'
tick2 - '2nd asset'
w1 - weight of the 1st asset
start_sum - starting amount invested
start_year - starting year, to ensure the starting point of investing is the same for both assets
end_year - None is default
"""
w2 = 1 - w1
s1 = wealth(hist_returns([tick1])[start_year:end_year], start_sum, w1)
s2 = wealth(hist_returns([tick2])[start_year:end_year], start_sum, w2)
fin = pd.concat([s1, s2], axis=1)
fin.dropna(inplace=True)
return fin
def equal_reweight(final, stocks, w1, period):
"""
Input: final - Data Frame of wealth of 2 assets
stocks - list of 2 assets
w1 - weight of the 1st asset
period - e.g. 5 = every 5 days
Returns resulting wealth achieved by reweighting to constant weight
"""
w2 = 1 - w1
l=[]
s = final.index.to_list()[0]
wealth_w1 = final.loc[s, f'Wealth_{stocks[0]}']
wealth_w2 = final.loc[s, f'Wealth_{stocks[1]}']
l.append([wealth_w1, wealth_w2])
weight_w1 = wealth_w1/(wealth_w1 + wealth_w2)
extra_weight_w1 = max((weight_w1 - w1), 0)
weight_w2 = wealth_w2/(wealth_w1 + wealth_w2)
extra_weight_w2 = max((weight_w2 - w2), 0)
new_wealth_w1 = (wealth_w1 - extra_weight_w1*wealth_w1 + extra_weight_w2*wealth_w2)*(1 + final.iloc[1,0])
new_wealth_w2 = (wealth_w2 + extra_weight_w1*wealth_w1 - extra_weight_w2*wealth_w2)*(1 + final.iloc[1,2])
l.append([new_wealth_w1, new_wealth_w2])
for ii, i in enumerate(final.index.to_list()[1:-1]):
if (ii + 2) % period != 0:
#adding wealth calculation (no rebalancing)
new2_wealth_w1 = new_wealth_w1*(1 + final.iloc[(ii+2),0])
new2_wealth_w2 = new_wealth_w2*(1 + final.iloc[(ii+2),2])
new_wealth_w1 = new2_wealth_w1
new_wealth_w2 = new2_wealth_w2
#done with wealth calculation (no rebalancing)
else:
weight_w1 = new_wealth_w1/(new_wealth_w1 + new_wealth_w2)
weight_w2 = new_wealth_w2/(new_wealth_w1 + new_wealth_w2)
extra_weight_w1 = max((weight_w1 - w1), 0)
extra_weight_w2 = max((weight_w2 - w2), 0)
new2_wealth_w1 = (new_wealth_w1 - extra_weight_w1*new_wealth_w1 + extra_weight_w2*new_wealth_w2)*(1 + final.iloc[(ii+2),0])
new2_wealth_w2 = (new_wealth_w2 + extra_weight_w1*new_wealth_w1 - extra_weight_w2*new_wealth_w2)*(1 + final.iloc[(ii+2),2])
new_wealth_w1 = new2_wealth_w1
new_wealth_w2 = new2_wealth_w2
l.append([new_wealth_w1, new_wealth_w2])
return pd.DataFrame(l, columns=[f'Wealth_{stocks[0]}', f'Wealth_{stocks[1]}'],
index=final.index.to_list()[0:])
def plot_cum_returns(stocks, period=None):
"""
Input: list of stocks
Returns: plot of cumulated return for a given period
"""
data = hist_returns(stocks)
data.dropna(inplace=True)
data = data[period:]
return (1 + data).cumprod().plot(figsize=(10,5))
def index_ret(rets, weights, name, start_value=1):
"""
Input: list of returns, weights, name of the index
Returns: combined returned of assets given weightes - no reweighting
"""
em_risky = rets
em_risky.dropna(inplace=True)
col = em_risky.columns.to_list()
ind = em_risky.index.to_list()
for i in col:
#starting wealth for stocks in future index
em_risky.loc[ind[0], f'Wealth_{i}'] = start_value*weights[col.index(i)]*(1+em_risky.loc[ind[0], i])
for i in col:
for n, y in enumerate(ind[:-1]):
em_risky.loc[ind[n+1], f'Wealth_{i}'] = em_risky.loc[ind[n], f'Wealth_{i}']*(1+em_risky.loc[ind[n+1], i])
em_risky = em_risky.drop(columns=col)
em_risky[name] = em_risky.sum(axis=1)
em_risky[name] = em_risky[name].pct_change()
return em_risky[name]