Documenti di Didattica
Documenti di Professioni
Documenti di Cultura
Setup
In [1]:
import numpy as np
import pandas as pd
import yfinance as yf
import warnings
import riskfolio as rp
In [2]:
warnings.filterwarnings("ignore")
start = '2008-01-01'
end = '2022-01-28'
In [3]:
df = pd.read_excel('ticker.xlsx')
df.sort_values(by=['Ticker'], inplace=True)
df
Azionario
27 BR50.MI Azioni Azionario EM iShares BRIC 50 UCITS ETF
globale
Azionario
15 CHIP.PA Azioni Azionario tematico Lyxor MSCI Semiconductors ESG
tematico
Azionario
8 EUN.MI Azioni Azionario europeo iShares STOXX Europe 50 UCITS ETF
globale
Azionario
7 EXSA.MI Azioni Azionario europeo iShares STOXX Europe 600
globale
Azionario
26 IAPD.MI Azioni Azionario asia iShares Asia Pacific Dividend
globale
Obbligazioni mid-
24 IEF Obbligazioni ObbligazioniUS iShares 7-10 Year Treasury Bond ETF
term
Azionario
10 IEUX.MI Azioni Azionario europeo iShares MSCI Europe ex-UK UCITS
globale
Azionario
12 IFFF.MI Azioni Azionario EM iShares MSCI AC Far East ex-Japan
globale
localhost:8888/lab/tree/Desktop/Lazy/Untitled.ipynb 1/16
30/01/22, 13:15 Untitled
Azionario
16 IH2O.MI Azioni Azionario tematico iShares Global Water UCITS
tematico
Azionario Azionario
3 INAA.MI Azioni iShares MSCI North America
americano americano
Azionario
17 INRG.MI Azioni Azionario tematico iShares Global Clean Energy
tematico
Azionario Azionario
5 IUSA.MI Azioni iShares S&P 500 UCITS ETF
americano americano
Obbligazioni
19 LQDE.MI Obbligazioni ObbligazioniEUR iShares $ Corp Bond UCITS ETF
corporate
Azionario
29 NRJ.PA Azioni Azionario tematico Lyxor New Energy
tematico
Azionario
30 PRF Azioni Azionario globale Invesco FTSE RAFI US 1000
americano
Obbligazioni long
23 TLT Obbligazioni ObbligazioniUS iShares 20+ Year Treasury Bond ETF
term
Azionario Azionario
6 UST.PA Azioni Lyxor Nasdaq-100
americano americano
Obbligazioni long
22 X15E.MI Obbligazioni ObbligazioniEUR Eurozone Government Bond 15-30
term
Obbligazioni Obbligazioni
21 XGIN.MI Obbligazioni Global Inflation-Linked Bond
inflation globali
Azionario
14 XLPE.MI Azioni Azionario tematico Private Equity Swap
tematico
Azionario Azionario
4 XMUS.MI Azioni MSCI USA Swap UCITS ETF
americano americano
Azionario
11 XNIF.MI Azioni Azionario indiano Nifty 50 Swap
globale
In [4]:
ticker=df['Ticker'].values.tolist()
ticker
classe1=df['Classe1'].values.tolist()
classe2=df['Classe2'].tolist()
nome=df['Nome'].tolist()
In [5]:
data = yf.download(ticker, start=start, end=end,period='5d')
data.columns=nome
[*********************100%***********************] 33 of 33 completed
In [6]:
Y = data[nome].pct_change().dropna()
localhost:8888/lab/tree/Desktop/Lazy/Untitled.ipynb 2/16
30/01/22, 13:15 Untitled
Date
2008-
-0.004975 0.044888 0.009128 0.010551 -0.013663 0.037471 0.008057 0.000000
11-28
2008-
-0.004167 0.016706 -0.018278 0.004795 -0.004617 0.017813 0.010813 -0.012089
12-01
2008-
-0.063598 0.018779 -0.000314 -0.038637 -0.009278 -0.053108 -0.064186 0.000000
12-02
2008-
0.020554 -0.050691 0.003919 0.006001 -0.006689 0.014659 0.022366 0.000000
12-03
2008-
0.007005 -0.014563 -0.004874 -0.000906 0.034343 0.005025 0.004861 0.000000
12-04
2022-
-0.033874 -0.028179 -0.017778 -0.020798 -0.018892 -0.020506 -0.014586 -0.019271
01-21
2022-
0.000000 -0.049452 -0.023529 0.000000 0.000000 0.000000 0.000000 0.000000
01-24
2022-
0.000000 0.005975 0.005746 0.000000 0.000000 0.000000 0.000000 0.000000
01-25
2022-
0.000000 0.024259 0.016587 0.000000 0.000000 0.000000 0.000000 0.000000
01-26
2022-
0.000000 -0.019101 -0.003444 0.000000 0.000000 0.000000 0.000000 0.000000
01-27
method_mu='hist'
method_cov='hist'
In [8]:
ax = rp.plot_pie(w=w_sharpe1, title='Sharpe Mean Variance', others=0.05, nrow=25, cm
height=6, width=10, ax=None)
localhost:8888/lab/tree/Desktop/Lazy/Untitled.ipynb 3/16
30/01/22, 13:15 Untitled
In [9]:
points = 50
hist = True # Use historical scenarios for risk measures that depend on scenarios
l = 0
localhost:8888/lab/tree/Desktop/Lazy/Untitled.ipynb 4/16
30/01/22, 13:15 Untitled
cVar
In [10]:
port = rp.Portfolio(returns=Y)
method_mu='hist'
method_cov='hist'
In [11]:
ax = rp.plot_pie(w=w_cvar1, title='Sharpe CVaR', others=0.03, nrow=25, cmap = "tab20
height=6, width=10, ax=None)
Constraints
In [12]:
df1 = pd.read_excel('ticker.xlsx')
df1 = df1.sort_values(by=['Ticker'])
constraints= pd.read_excel('const.xlsx',na_filter=False)
In [13]:
df1= df1[ [ col for col in df1.columns if col != 'Ticker' ] + ['Ticker']]
In [14]:
constraints
Lyxor Nasdaq-
0 False Assets <= 0.00
100
localhost:8888/lab/tree/Desktop/Lazy/Untitled.ipynb 5/16
30/01/22, 13:15 Untitled
Type Relative
Disabled Type Set Position Sign Weight Relative Factor
Relative Set
Azionario
3 False Classes Classe2 >= 0.05
globale
Azionario
4 False Classes Classe2 >= 0.05
tematico
In [15]:
A, B = rp.assets_constraints(constraints, df1)
In [16]:
df1
9 iShares EURO STOXX Small UCITS ETF Azioni Azionario europeo Azionario globale
8 iShares STOXX Europe 50 UCITS ETF Azioni Azionario europeo Azionario globale
20 iShares Euro Inflation Linked Govt Bond Obbligazioni Obbligazioni inflation ObbligazioniEUR
Obbligazioni
18 iShares Euro Corp Bond Large Cap UCITS Obbligazioni ObbligazioniEUR
corporate
Obbligazioni mid-
24 iShares 7-10 Year Treasury Bond ETF Obbligazioni ObbligazioniUS
term
10 iShares MSCI Europe ex-UK UCITS Azioni Azionario europeo Azionario globale
Azionario
3 iShares MSCI North America Azioni Azionario americano
americano
Azionario
32 iShares MSCI North America UCITS ETF Azioni Azionario americano
americano
Azionario
5 iShares S&P 500 UCITS ETF Azioni Azionario americano
americano
Obbligazioni
19 iShares $ Corp Bond UCITS ETF Obbligazioni ObbligazioniEUR
corporate
localhost:8888/lab/tree/Desktop/Lazy/Untitled.ipynb 6/16
30/01/22, 13:15 Untitled
Azionario
30 Invesco FTSE RAFI US 1000 Azioni Azionario globale
americano
Obbligazioni long
23 iShares 20+ Year Treasury Bond ETF Obbligazioni ObbligazioniUS
term
Azionario
6 Lyxor Nasdaq-100 Azioni Azionario americano
americano
Obbligazioni long
22 Eurozone Government Bond 15-30 Obbligazioni ObbligazioniEUR
term
Obbligazioni
21 Global Inflation-Linked Bond Obbligazioni Obbligazioni inflation
globali
Azionario
4 MSCI USA Swap UCITS ETF Azioni Azionario americano
americano
In [19]:
port.ainequality = A
port.binequality = B
model = 'Classic'
rm = 'CVaR'
obj = 'Sharpe'
rf = 0
In [20]:
ax = rp.plot_pie(w=w_personale, title='Constrained CVaR', others=0.05, nrow=25, cmap
height=6, width=10, ax=None)
In [22]:
constraints= pd.read_excel('prudente.xlsx',na_filter=False)
localhost:8888/lab/tree/Desktop/Lazy/Untitled.ipynb 7/16
30/01/22, 13:15 Untitled
port = rp.Portfolio(returns=Y)
method_mu='hist'
method_cov='hist'
A, B = rp.assets_constraints(constraints, df1)
port.ainequality = A
port.binequality = B
model = 'Classic'
rm = 'CVaR'
obj = 'Utility'
rf = 0
In [57]:
constraints= pd.read_excel('moderato.xlsx',na_filter=False)
port = rp.Portfolio(returns=Y)
method_mu='hist'
method_cov='hist'
A, B = rp.assets_constraints(constraints, df1)
port.ainequality = A
port.binequality = B
model = 'Classic'
rm = 'CVaR'
obj = 'Sharpe'
rf = 0
localhost:8888/lab/tree/Desktop/Lazy/Untitled.ipynb 8/16
30/01/22, 13:15 Untitled
In [58]:
constraints= pd.read_excel('aggressivo.xlsx',na_filter=False)
port = rp.Portfolio(returns=Y)
method_mu='hist'
method_cov='hist'
A, B = rp.assets_constraints(constraints, df1)
port.ainequality = A
port.binequality = B
model = 'Classic'
rm = 'CVaR'
obj = 'Sharpe'
rf = 0
Backtesting
localhost:8888/lab/tree/Desktop/Lazy/Untitled.ipynb 9/16
30/01/22, 13:15 Untitled
In [59]: import bt
In [60]:
def varname(variable):
expression = f'id({name})'
if id(variable) == eval(expression):
return name
In [61]:
rebalance = bt.algos.RunIfOutOfBounds(0.1)
rebalAlgo = bt.algos.Rebalance()
In [62]:
z = pd.read_csv('rayd.csv', sep=';')
z=z.dropna()
rayd=z.T
In [63]:
w_tot= [w_cvar1,w_sharpe1, w_const1,rayd, w_prudente, w_moderato, w_aggressivo]
In [64]:
i=0
a={}
for x in w_tot:
weight= bt.algos.WeighSpecified(**x.T)
var = bt.Strategy('static',[rebalance,weight,rebalAlgo])
backtest = bt.Backtest(
var,
data.dropna(),
integer_positions=False
r= bt.run(backtest)
i=i+1
if i==1:
s=r.stats
s=s.rename(columns={'static':varname(x)})
w_tot=pd.DataFrame(x)
else:
stats=r.stats
s[varname(x)]=stats['static']
a[varname(x)]=r.backtest_list[0].strategy.values
In [65]:
s
localhost:8888/lab/tree/Desktop/Lazy/Untitled.ipynb 10/16
30/01/22, 13:15 Untitled
localhost:8888/lab/tree/Desktop/Lazy/Untitled.ipynb 11/16
30/01/22, 13:15 Untitled
In [66]:
wealth=pd.DataFrame.from_dict(a)
In [67]:
wealth
2008-
1.000000e+06 1.000000e+06 1.000000e+06 1.000000e+06 1.000000e+06 1.000000e+06 1.0000
11-30
2008-
1.000000e+06 1.000000e+06 1.000000e+06 1.000000e+06 1.000000e+06 1.000000e+06 1.0000
12-01
2008-
9.964175e+05 9.949578e+05 1.003242e+06 9.797872e+05 1.000663e+06 9.978744e+05 9.8386
12-02
2008-
1.007656e+06 1.007094e+06 1.010001e+06 9.850978e+05 1.009595e+06 1.008028e+06 9.9947
12-03
2008-
1.014509e+06 1.013938e+06 1.014442e+06 1.000277e+06 1.015306e+06 1.014837e+06 1.0102
12-04
2022-
3.179693e+06 3.554511e+06 2.757186e+06 2.675647e+06 2.725522e+06 2.701050e+06 4.2593
01-14
2022-
3.160042e+06 3.532198e+06 2.741207e+06 2.661191e+06 2.711661e+06 2.684599e+06 4.2303
01-18
2022-
3.153983e+06 3.526102e+06 2.733788e+06 2.669247e+06 2.708908e+06 2.679852e+06 4.2263
01-19
2022-
3.160083e+06 3.534126e+06 2.737264e+06 2.684444e+06 2.713226e+06 2.682720e+06 4.2397
01-20
2022-
3.144624e+06 3.513417e+06 2.726687e+06 2.677839e+06 2.702342e+06 2.672219e+06 4.2039
01-21
In [68]:
wealth.plot(figsize=(25,15))
Out[68]: <AxesSubplot:>
localhost:8888/lab/tree/Desktop/Lazy/Untitled.ipynb 12/16
30/01/22, 13:15 Untitled
df['Cumulative'] = df.Profit.cumsum().round(2)
df['HighValue'] = df['Cumulative'].cummax()
In [69]:
#w_name= [w_cvar1,w_sharpe1, w_const1, w_const2,w_worst,rayd
In [70]:
w_tot= [w_cvar1,w_sharpe1, w_const1,rayd, w_prudente, w_moderato, w_aggressivo]
cs=pd.concat(w_tot, axis=1)
In [71]:
cs.to_csv('output1.csv',sep=";")
In [72]:
wealth
2008-
1.000000e+06 1.000000e+06 1.000000e+06 1.000000e+06 1.000000e+06 1.000000e+06 1.0000
11-30
2008-
1.000000e+06 1.000000e+06 1.000000e+06 1.000000e+06 1.000000e+06 1.000000e+06 1.0000
12-01
2008-
9.964175e+05 9.949578e+05 1.003242e+06 9.797872e+05 1.000663e+06 9.978744e+05 9.8386
12-02
2008-
1.007656e+06 1.007094e+06 1.010001e+06 9.850978e+05 1.009595e+06 1.008028e+06 9.9947
12-03
2008-
1.014509e+06 1.013938e+06 1.014442e+06 1.000277e+06 1.015306e+06 1.014837e+06 1.0102
12-04
2022-
3.179693e+06 3.554511e+06 2.757186e+06 2.675647e+06 2.725522e+06 2.701050e+06 4.2593
01-14
2022-
3.160042e+06 3.532198e+06 2.741207e+06 2.661191e+06 2.711661e+06 2.684599e+06 4.2303
01-18
localhost:8888/lab/tree/Desktop/Lazy/Untitled.ipynb 13/16
30/01/22, 13:15 Untitled
2022-
3.153983e+06 3.526102e+06 2.733788e+06 2.669247e+06 2.708908e+06 2.679852e+06 4.2263
01-19
2022-
3.160083e+06 3.534126e+06 2.737264e+06 2.684444e+06 2.713226e+06 2.682720e+06 4.2397
01-20
2022-
3.144624e+06 3.513417e+06 2.726687e+06 2.677839e+06 2.702342e+06 2.672219e+06 4.2039
01-21
In [73]:
wealth_max=wealth.cummax()
In [74]:
dd= wealth - wealth_max
In [75]:
dd.plot(figsize=(20,10))
Out[75]: <AxesSubplot:>
In [76]:
dd['2020':'06/2020'].plot(figsize=(20,10), title='Max Drawdown during Covid19 Outbre
localhost:8888/lab/tree/Desktop/Lazy/Untitled.ipynb 14/16
30/01/22, 13:15 Untitled
In [77]:
dd['2013':'2015'].plot(figsize=(20,10), title='Max Drawdown during Euro Crisis')
In [78]:
dd['2008':'2009'].plot(figsize=(20,10), title='Max Drawdown during Subrime Crisis')
localhost:8888/lab/tree/Desktop/Lazy/Untitled.ipynb 15/16
30/01/22, 13:15 Untitled
In [79]:
s.to_csv('Stats1.csv',sep=";")
In [80]:
dd.to_csv('drawdown.csv',sep=";")
In [81]:
wealth.to_csv('wealth.csv',sep=";")
In [ ]:
In [ ]:
localhost:8888/lab/tree/Desktop/Lazy/Untitled.ipynb 16/16