-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmodel.py
1723 lines (1095 loc) · 57.5 KB
/
model.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
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
import pandas as pd
from pandas import to_datetime
from pandas.plotting import register_matplotlib_converters
import numpy as np
from pathlib import Path
import base64
import io
from datetime import date, datetime
import yfinance as yf
from PIL import Image # display an image
from io import StringIO # upload file
from io import BytesIO
from pyxlsb import open_workbook as open_xlsb
import altair as alt
from PIL import Image
from vega_datasets import data
import pandas_datareader as pdr
import streamlit as st
from htbuilder import HtmlElement, div, hr, a, p, img, styles
from htbuilder.units import percent, px
import seaborn as sns
import matplotlib.pyplot as plt
register_matplotlib_converters()
from statsmodels.tsa.seasonal import seasonal_decompose
from statsmodels.tsa.stattools import adfuller
import statsmodels.api as sm
import pmdarima as pm
from fpdf import FPDF
sns.set(style="whitegrid")
pd.set_option('display.max_rows', 15)
pd.set_option('display.max_columns', 500)
pd.set_option('display.width', 1000)
st.set_option('deprecation.showPyplotGlobalUse', False)
# Configuration de l'app (html, java script like venv\)
# Deploy the app localy in terminal: streamlit run model.py
st.set_page_config(
page_title="Finance", layout="wide", page_icon="./images/flask.png"
)
def img_to_bytes(img_path):
img_bytes = Path(img_path).read_bytes()
encoded = base64.b64encode(img_bytes).decode()
return encoded
def main():
def _max_width_():
max_width_str = f"max-width: 1000px;"
st.markdown(
f"""
<style>
.reportview-container .main .block-container{{
{max_width_str}
}}
</style>
""",
unsafe_allow_html=True,
)
# Hide the Streamlit header and footer
def hide_header_footer():
hide_streamlit_style = """
<style>
footer {visibility: hidden;}
</style>
"""
st.markdown(hide_streamlit_style, unsafe_allow_html=True)
# increases the width of the text and tables/figures
_max_width_()
# hide the footer
hide_header_footer()
image_hec = Image.open('images/hec.png')
st.image(image_hec, width=300)
########### DASHBOARD PART ###############
st.sidebar.header("Dashboard") # .sidebar => add widget to sidebar
st.sidebar.markdown("---")
#st.sidebar.number_input("**🪪 Input your groups student numbers:**",67609)
# Add multiple student numbers
import numpy as np
list_teachers = ["François Derien","Irina Zviadadze","Mian Liu","Teodor Duevski","Quirin Fleckenstein"]
select_teacher = st.sidebar.selectbox('Select your teacher ➡️', list_teachers)
list_section_code = [1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16]
select_code = st.sidebar.selectbox('Select your section code ➡️', list_section_code)
student_ids = np.arange(1000,2000,50)
select_student = st.sidebar.multiselect(
'Student id of each group member',
student_ids,
max_selections=3
)
lab_numbers = st.sidebar.selectbox('Select the exercise ➡️', [
'01 - One risky and one risk-free asset',
'02 - Two risky assets',
'03 - Diversification',
'04 - Test of the CAPM',
])
#st.sidebar.header("Select Stock Symbol")
# list_risky_assets = ['AAPL', 'AMZN', 'IBM','MSFT','TSLA','NVDA',
# 'PG','JPM','WMT','CVX','BAC','PFE','GOOG',
# 'ADBE','AXP','BBY','BA','CSCO','C','DIS','EBAY','ETSY','GE','INTC','JPM']
list_risky_assets = ['AAPL', 'AMZN', 'IBM','MSFT','TSLA','NVDA',
'PG','JPM','WMT','CVX','BAC','PFE','GOOG',
'ADBE','AXP','BBY','BA','ETSY','GE','INTC','JPM']
# Example of riskfree assets
list_riskfree_assets = ['CSCO','C','DIS','EBAY']
## Teaching information
dictionary_symbols = {
'AAPL':'Apple',
'AMZN':'Amazon',
'IBM':'IBM',
'MSFT':'Microsoft',
'TSLA':'Tesla',
'NVDA':'Nvidia',
'PG':'Procter & Gamble',
'JPM':'J&P Morgan',
'WMT':'Wallmart',
'CVX':'Chevron Corporation',
'BAC':'Bank of America',
'PFE':'Pfizer',
'GOOG':'Alphabet',
'ADBE':'Adobe',
'AXP':'American Express',
'BBY':'Best Buy',
'BA':'Bpeing',
'CSCO': 'Cisco',
'C': 'Citigroup',
'DIS': 'Disney',
'EBAY': 'eBay',
'ETSY': 'Etsy',
'GE': 'General Electric',
'INTC': 'Intel',
'JPM': 'JP Morgan Chase',
}
@st.cache_data # compression data
def get_data():
source = data.stocks()
source = source[source.date.gt("2004-01-01")]
return source
@st.cache_data
def get_chart(data):
hover = alt.selection_single(
fields=["Date_2"],
nearest=True,
on="mouseover",
empty="none",
)
lines = (
alt.Chart(data, title="Evolution of stock prices")
.mark_line()
.encode(
x="Date_2",
y=kpi,
#color="symbol",
# strokeDash="symbol",
)
)
# Draw points on the line, and highlight based on selection
points = lines.transform_filter(hover).mark_circle(size=65)
# Draw a rule at the location of the selection
tooltips = (
alt.Chart(data)
.mark_rule()
.encode(
x="yearmonthdate(date)",
y=kpi,
opacity=alt.condition(hover, alt.value(0.3), alt.value(0)),
tooltip=[
alt.Tooltip("date", title="Date"),
alt.Tooltip(kpi, title="Price (USD)"),
],
)
.add_selection(hover)
)
return (lines + points + tooltips).interactive()
@st.cache_data
def convert_df(df):
# IMPORTANT: Cache the conversion to prevent computation on every rerun
return df.to_csv().encode('utf-8')
########### TITLE #############
st.title("HEC Paris - Finance Labs🧪")
st.subheader("Portfolio theory 📈")
st.markdown("Course provided by: **François Derrien**, **Irina Zviadadze**, **Mian Liu**, **Teodor Duevski**, **Quirin Fleckenstein**")
st.markdown(" ")
# with open("Lecture_notes_2021.pdf", "rb") as file:
# st.download_button("Download Course PDF 💡", file.read(), file_name="Lecture_notes_2021.pdf")
st.markdown("---")
default_text = """Write the answer in this box"""
#####################################################################################
# EXERCICE 1 - One risky asset, one risk-free asset
#####################################################################################
if lab_numbers == "01 - One risky and one risk-free asset": # premiere page
#################################### SIDEBAR ##################################
risky_asset = st.sidebar.selectbox("Select a risky asset", list_risky_assets, key="select_risky")
risk_free_asset = "^FVX"
st.sidebar.markdown(" ")
################################### DATAFRAMES ###############################
# Risky asset dataframe (df_risky)
data_risky = yf.Ticker(risky_asset)
df_risky = data_risky.history(period="16mo").reset_index()[["Date","Close","Dividends"]]
df_risky = df_risky.loc[(df_risky["Date"]<="2023-07-26") & (df_risky["Date"]>"2022-03-08")] # filter dates
df_risky["Date"] = pd.to_datetime(df_risky["Date"]).apply(lambda x: x.strftime("%d/%m/%Y"))
df_risky.columns = ["Date","Price","Dividends"]
# Riskfree asset dataframe (df_Tbond)
price_Tbond = [(1 + 0.02)**(1/365) - 1 for i in range(df_risky.shape[0])]
df_Tbond = pd.DataFrame({"Date":df_risky["Date"].to_list(), "Tbond Price":price_Tbond})
riskfree_returns = np.array([0.02 for i in range(df_risky.shape[0]-1)])
##################################### TITLE ####################################
st.markdown("## 01 - One risky and one risk-free asset")
st.info("In this exercise, assume that there exists a risk-free asset (a T-bond) with an annual rate of return of 2%. You are given information on daily prices and dividends of individual (risky) stocks. You are asked to choose one risky stock and to compute its expected return and standard deviation of return. Then you have to find the (standard deviation of return, expected return) pairs you can obtain by combining this risky stock with the risk-free asset into portfolios.")
st.markdown(" ")
st.markdown(" ")
#################################### QUESTION 1 ###################################
st.subheader("Question 1 📝")
#################### Part 1
## Title of PART 1
st.markdown('''<p style="font-size: 22px;"> Please select one stock and <b>compute its realized (holding-period) returns.</b>
Assume that holding, is one day. <br> Next, please <b>compute the expected return</b> and <b>standard deviation</b> of the holding-period returns</b></p>''',
unsafe_allow_html=True)
st.markdown(" ")
# ## View risky dataset
st.markdown(f"**View the {risky_asset} data** with Date, Closing Price and Dividends.")
st.dataframe(df_risky.reset_index(drop=True))
## Download dataset as xlsx
# Set the headers to force the browser to download the file
headers = {
'Content-Disposition': 'attachment; filename=dataset.xlsx',
'Content-Type': 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet'
}
# Create a Pandas Excel writer object
excel_writer = pd.ExcelWriter(f"{risky_asset}.xlsx", engine='xlsxwriter')
df_risky.to_excel(excel_writer, index=False, sheet_name='Sheet1')
excel_writer.close()
# Download the file
with open(f"{risky_asset}.xlsx", "rb") as f:
st.download_button(
label=f"📥 Download the **{risky_asset}** data",
data=f,
file_name=f"{risky_asset}.xlsx",
mime="application/vnd.openxmlformats-officedocument.spreadsheetml.sheet",
)
st.markdown(" ")
st.markdown(" ")
# Compute holding-period returns, expected returns, std
asset1_returns = (df_risky["Price"][1:].to_numpy() - df_risky["Price"][:-1].to_numpy() + df_risky["Dividends"].to_numpy()[1:])/df_risky["Price"][:-1].to_numpy()
asset_expected_return = np.mean(asset1_returns)
asset_std_dev = np.std(asset1_returns, ddof=1)
# Holding-period returns
st.write(f"**Compute the holding-period returns of {risky_asset}**")
upload_expected_return = st.file_uploader("Drop your results in an excel file (.xlsx)", key="Q1",type=['xlsx'])
answer_1_Q1_1 = upload_expected_return
if upload_expected_return is not None:
returns_portfolios = pd.read_csv(upload_expected_return)
st.dataframe(returns_portfolios)
# answer = st.text_input("Enter your results",0, key="AQ1.1")
st.markdown(" ")
solution = st.checkbox('**Solution** ✅',key="SQ1.1")
if solution:
returns_result = pd.DataFrame({"Date":df_risky["Date"].iloc[1:], "Return":asset1_returns})
st.dataframe(returns_result)
#answer_text = f'The realized returns of {dictionary_symbols[risky_asset]} is {np.round(asset1_returns,4)}.'
#st.success(answer_text)
st.markdown(" ")
st.markdown(" ")
# Expected returns
st.write(f"**Compute the expected returns of {risky_asset}**")
answer_1_Q1_2 = st.text_input("Enter your results",0, key="AQ1.2a")
st.markdown(" ")
solution = st.checkbox('**Solution** ✅',key="SQ1.2a")
if solution:
answer_text = f'The expected return of {dictionary_symbols[risky_asset]} is {np.round(asset_expected_return,4)}.'
st.success(answer_text)
st.markdown(" ")
st.markdown(" ")
# Standard deviation
st.write(f"**Compute the standard deviation of {risky_asset}**")
answer_1_Q1_3 = st.text_input("Enter your results ",0, key="AUQ1.2b")
st.markdown(" ")
solution = st.checkbox('**Solution** ✅',key="SQ1.2b")
if solution:
answer_text = f'The standard deviation of {dictionary_symbols[risky_asset]} is {np.round(asset_std_dev,4)}.'
st.success(answer_text)
st.markdown(" ")
st.markdown(" ")
st.markdown(" ")
st.markdown(" ")
st.markdown(" ")
###################################### QUESTION 2 ##########################################
st.subheader("Question 2 📝")
### Part 1
st.markdown('''<p style="font-size: 22px;"> Assume that you have a capital of 1000 EUR that you fully invest in a portfolio. <b>Combine two assets</b> (one risky and one risk-free asset) into a <b>portfolio</b>. Next, <b>compute the expected returns</b> and <b>standard deviation</b> of the portfolio.</p>''',
unsafe_allow_html=True)
st.info("In this question, assume that short-sale constraints are in place (that is, the weight of each asset in your portfolio must be between 0 and 1). ")
st.markdown(" ")
st.markdown(" ")
st.subheader(f"1. Create a portfolio with {risky_asset} and a risk-free asset")
st.markdown(" ")
# Concatenate graphs for plot
df_master = df_risky.merge(df_Tbond, how="inner", on="Date")[["Date","Price","Tbond Price"]].rename(columns={"Price": risky_asset, "Tbond Price": "Risk free"})
df_master = df_master.melt(id_vars="Date").rename(columns={"variable":"Asset","value":"Price"})
#df_master.columns = ["Date","Stock","Price"]
chart = alt.Chart(df_master, title="Evolution of stock prices").mark_line().encode(x="Date",y="Price",
color="Asset")
st.altair_chart((chart).interactive(),use_container_width=True)
# df_master = pd.concat([df_risky,df_Tbond]).reset_index(drop=True)
# df_master = df_master[pd.to_datetime(df_master['Date']) > pd.to_datetime(start_date)]
# df_master["Date"] = pd.to_datetime(df_master["Date"])
# chart = alt.Chart(df_master, title="Evolution of stock prices").mark_line().encode(x="Date",y=kpi,
# color="symbol",
# # strokeDash="symbol",
# )
# st.altair_chart((chart).interactive(), use_container_width=True)
# csv_df = convert_df(df_master)
st.markdown(" ")
# Create a portfolio by selecting amount (EUR) in risky asset
st.write(f"**Select the amount you want to put in {risky_asset}**")
risky_amount = st.slider(f"**Select the amount you want to put in {risky_asset}**", min_value=0, max_value=1000, step=50, value=500, label_visibility="collapsed")
riskfree_amount = 1000 - risky_amount
st.write(f"You've invested {risky_amount} EUR in {risky_asset} and {riskfree_amount} EUR in the risky-free asset.")
st.markdown(" ")
st.markdown(" ")
# Weight of assets in the portfolio
st.write("**Compute the weight of each asset in your portfolio**")
risky_weight = risky_amount/1000
riskfree_weight = riskfree_amount/1000
weight1_input = st.number_input(f'Enter the weight of the {risky_asset} asset')
answer_1_Q2_1 = weight1_input
solution = st.checkbox('**Solution** ✅', key="SQ2.1w1")
if solution:
answer_text1 = f'The weight of the {risky_asset} stock is {np.round(risky_weight,2)}.'
st.success(answer_text1)
st.markdown(" ")
weight2_input = st.number_input(f'Enter the weight of the risk-free*asset')
answer_1_Q2_2 = weight2_input
solution = st.checkbox('**Solution** ✅',key="SQ2.1w2")
if solution:
answer_text = f'The weight of the risk free asset is {np.round(riskfree_weight,2)}.'
st.success(answer_text)
st.markdown(" ")
st.markdown(" ")
st.markdown(" ")
st.subheader(f"2. Compute the expected return and standard deviation of the portfolio")
st.markdown(" ")
####### Result: Portfolio expected return
# Compute portfolio returns, expected ret, std
portfolio_returns = (risky_weight*asset1_returns) + (riskfree_weight*riskfree_returns)
portfolio_expected_returns = np.mean(portfolio_returns)
portfolio_std = np.std(portfolio_returns,ddof=1)
# Enter portfolio expected returns
st.write("**Compute the expected return of the portfolio**")
answer_1_Q2_3 = st.text_input("Enter your results",0, key="AQ2.21")
solution = st.checkbox('**Solution** ✅',key="SQ2.21")
if solution:
answer_text = f"The portfolio's expected return is {np.round(portfolio_expected_returns,4)}"
st.success(answer_text)
st.markdown(" ")
st.markdown(" ")
# Enter portfolio standard deviation
st.write("**Compute the standard deviation of the portfolio**")
answer_1_Q2_4 = st.text_input("Enter your results",0, key="AQ2.22")
solution = st.checkbox('**Solution** ✅',key="SQ2.22")
if solution:
answer_text = f"The portfolio's standard deviation is {np.round(portfolio_std,4)}"
st.success(answer_text)
st.markdown(" ")
st.markdown(" ")
st.markdown(" ")
st.markdown(" ")
st.markdown(" ")
################## QUESTION 3
st.subheader("Question 3 📝")
#### PART 1
st.markdown('''<p style="font-size: 22px;"> Using Excel, <b> construct portfolios </b> that contain x% of the risky asset and (1-x)% of the risk-free asset, with x varying between 0 and 100% with 1% increments.
For each portfolio, calculate its <b>standard deviation</b> of return and its <b>expected return</b>.
Represent these combinations in a graph, that is <b>draw the set of feasible portfolios</b>.''',
unsafe_allow_html=True)
# Weights of risky/riskfree in portfolios
weight_risky_portfolios = np.arange(0,1.01,0.01)
weight_riskfree_portfolios = 1 - weight_risky_portfolios
# Expected returns/std of portfolios
expected_returns_portfolios = np.array([w*asset_expected_return + (1-w)*0.02 for w in weight_risky_portfolios])
std_portfolios = np.array([w*asset_std_dev + (1-w)*np.std(riskfree_returns, ddof=1) for w in weight_risky_portfolios])
# Portfolio dataframe to plot
df_portfolios = pd.DataFrame({f"{risky_asset}":weight_risky_portfolios,
"Risk-free":weight_riskfree_portfolios,
"Expected return":expected_returns_portfolios,
"Standard deviation":std_portfolios})
chart_portfolios = alt.Chart(df_portfolios).mark_circle(size=20).encode(y="Expected return",x="Standard deviation")
st.markdown(" ")
st.write("**Compute the expected return and standard deviation for each portfolio**")
upload_expected_return = st.file_uploader("Drop your results in an excel file (.xlsx)", key="Q3.21",type=['xlsx'])
answer_1_Q3_1 = upload_expected_return
solution = st.checkbox('**Solution** ✅',key="SQ3.1")
if solution:
st.dataframe(df_portfolios)
# Create a Pandas Excel writer object
excel_writer = pd.ExcelWriter(f"portfolios_q3.xlsx", engine='xlsxwriter')
df_portfolios.to_excel(excel_writer, index=False, sheet_name='Sheet1')
excel_writer.close()
# Download the file
with open(f"portfolios_q3.xlsx", "rb") as f:
st.download_button(
label=f"📥 Download the solution as xlsx",
data=f,
file_name=f"portfolios_q3.xlsx",
mime="application/vnd.openxmlformats-officedocument.spreadsheetml.sheet",
)
st.markdown(" ")
st.markdown(" ")
st.write("**Draw the set of feasible portfolios**")
upload_graph = st.file_uploader("Drop graph as an image (jpg, jpeg, png)", key="Q3.23", type=['jpg','jpeg','png'])
answer_1_Q3_2 = upload_graph
if upload_graph is not None:
image = Image.open(upload_graph)
#answer_1_Q3_2 = image
#st.image(image, caption='Graph of the set of feasible portfolios')
solution = st.checkbox('**Solution** ✅',key="SQ3.23")
if solution:
st.altair_chart(chart_portfolios.interactive(), use_container_width=True)
st.markdown(" ")
st.markdown(" ")
st.markdown(" ")
st.markdown(" ")
st.markdown(" ")
################## QUESTION 4
st.subheader("Question 4")
st.markdown('''<p style="font-size: 22px;"> Consider the feasible portfolios from Question 3 and <b> answer the following questions. </b> </p>''',
unsafe_allow_html=True)
st.info("Provide specific answers, that is, **characterize the portfolios in terms of the weights on both assets**")
# View portfolio dataset
#st.dataframe(df_portfolios)
st.markdown(" ")
###### PART 1
user_input_1 = st.text_area("**Can you find which portfolio has the highest expected return ?**", default_text)
answer_1_Q4_1 = user_input_1
solution = st.checkbox('**Solution** ✅',key="SQ4.1")
if solution:
st.success(f"The portfolio with **1** in the risky asset ({risky_asset}) and **0** in the risk free asset.")
# st.success(f"The portfolio's expected return is {np.round(np.sum(expected_return_risky),3)}") ?????
st.markdown(" ")
st.markdown(" ")
###### PART 2
user_input_2 = st.text_area("**Can you find which portfolio has the lowest expected return ?**", default_text)
answer_1_Q4_2 = user_input_2
solution = st.checkbox('**Solution** ✅',key="SQ4.2")
if solution:
st.success(f"The portfolio with **0** in the risky asset ({risky_asset}) and **1** in the risk free asset")
# st.success(f"The portfolio's expected return is {np.round(np.sum(expected_return_riskfree),3)}") ?????
st.markdown(" ")
st.markdown(" ")
###### PART 3
user_input_3 = st.text_area("**Can you find which portfolio has the highest standard deviation ?**", default_text)
answer_1_Q4_3 = user_input_3
solution = st.checkbox('**Solution** ✅',key="SQ4.3")
if solution:
st.success(f"The portfolio with **1** in the risky asset ({risky_asset}) and **0** in the risk free asset")
st.success(f"The highest standard deviation is **{np.round(asset_std_dev,4)}**")
st.markdown(" ")
st.markdown(" ")
###### PART 4
user_input_4 = st.text_area("**Can you find which portfolio has the lowest standard deviation ?**", default_text)
answer_1_Q4_4 = user_input_4
solution = st.checkbox('**Solution** ✅',key="SQ4.4")
if solution:
st.success(f"The portfolio with **0** in the risky asset ({risky_asset}) and **1** in the risk free asset.")
st.success(f"The lowest standard deviation is **{np.std(riskfree_returns,ddof=1)}**")
st.markdown(" ")
st.markdown(" ")
st.markdown(" ")
st.markdown(" ")
st.markdown(" ")
##################################### QUESTION 5 #####################################
st.subheader("Question 5")
st.markdown('''<p style="font-size: 22px;"> <b>Repeat the exercise of Question 3</b>, but with the possibility of selling short one of the two assets. That is, vary x, for example, from -100% to 100%.''',
unsafe_allow_html=True)
# Compute expected return for each portfolio
# Weights of risky/riskfree in portfolios
weight_risky_portfolios = np.arange(-1,2.01,0.01)
weight_riskfree_portfolios = 1 - weight_risky_portfolios
# Expected returns/std of portfolios
expected_returns_portfolios = np.array([w*asset_expected_return + (1-w)*0.02 for w in weight_risky_portfolios])
std_portfolios = np.array([w*asset_std_dev + (1-w)*np.std(riskfree_returns, ddof=1) for w in weight_risky_portfolios])
# Portfolio dataframe to plot
df_portfolios = pd.DataFrame({f"{risky_asset}":weight_risky_portfolios,
"Risk-free":weight_riskfree_portfolios,
"Expected return":expected_returns_portfolios,
"Standard deviation":std_portfolios})
# Plot set feasible portfolios
chart_portfolios = alt.Chart(df_portfolios).mark_circle(size=20).encode(y="Expected return",x="Standard deviation")
st.markdown(" ")
st.write("**Compute the expected return and standard deviation for each portfolio**")
upload_expected_return = st.file_uploader("Drop results in an excel file (.xlsx)", key="UQ5.1", type=['xlsx'])
answer_1_Q5_1 = upload_expected_return
if upload_expected_return is not None:
expected_return_portfolios = pd.read_csv(upload_expected_return)
st.write(expected_return_portfolios.head())
solution = st.checkbox('**Solution** ✅', key="SQ5.1")
if solution:
st.dataframe(df_portfolios)
# # Create a Pandas Excel writer object
# excel_writer = pd.ExcelWriter(f"portfolios_q5.xlsx", engine='xlsxwriter')
# df_portfolios.to_excel(excel_writer, index=False, sheet_name='Sheet1')
# excel_writer.close()
# # Download the file
# with open(f"portfolios_q5.xlsx", "rb") as f:
# st.download_button(
# label=f"📥 Download the solution as xlsx",
# data=f,
# file_name=f"portfolios_q5.xlsx",
# mime="application/vnd.openxmlformats-officedocument.spreadsheetml.sheet",
# )
st.markdown(" ")
st.markdown(" ")
st.write("**Draw the set of feasible portfolios**")
answer_1_Q5_2 = st.file_uploader("Drop graph as an image (jpg, jpeg, png)", key="UQ5.2", type=['jpg','jpeg','png'])
# if upload_graph is not None:
# image = Image.open(upload_graph)
# st.image(image, caption='Graph of the set of feasible portfolios')
solution = st.checkbox('**Solution** ✅',key="SQ5.2")
if solution:
st.altair_chart(chart_portfolios.interactive(), use_container_width=True)
st.markdown(" ")
st.markdown(" ")
st.markdown(" ")
st.markdown(" ")
st.markdown(" ")
################## QUESTION 6
st.subheader("Question 6")
st.markdown('''<p style="font-size: 22px;"> <b>Repeat the exercise of Question 4</b>, but with the possibility of <b>selling short</b> one of the two assets. That is, analyze feasible portfolios from Question 5.''',
unsafe_allow_html=True)
# st.dataframe(df_portfolios)
st.markdown(" ")
###### PART 1
#answer_1_Q4_2 = user_input_2
answer_1_Q6_1 = st.text_area("**Can you find which portfolio has the highest expected return?**", default_text, key="Q6.1")
solution = st.checkbox('**Solution** ✅',key="SQ6.1")
if solution:
st.success(f"The portfolio with **2** in the risky asset ({risky_asset}) and **-1** in the risk free asset.")
#st.success(f"The portfolio's expected return is {np.round(np.sum(expected_return_risky),3)}")
st.markdown(" ")
###### PART 2
answer_1_Q6_2 = st.text_area("**Can you find which portfolio has the lowest expected return?**", default_text, key="Q6.2")
solution = st.checkbox('**Solution** ✅',key="SQ6.2")
if solution:
st.success(f"The portfolio with **2** in the risky-free asset and **-1** in {risky_asset}.")
#st.success(f"The portfolio's expected return is {np.round(np.sum(expected_return_riskfree),3)}")
st.markdown(" ")
###### PART 3
answer_1_Q6_3 = st.text_area("**Can you find which portfolio has the highest standard deviation?**", default_text, key="Q6.3")
solution = st.checkbox('**Solution** ✅',key="SQ6.3")
if solution:
st.success(f"The portfolio with **2** in {risky_asset} and **-1** in the risk-free asset")
st.success(f"The portfolio's standard deviation is **{np.round(df_portfolios.tail(1)['Standard deviation'].to_numpy()[0],4)}**")
st.markdown(" ")
###### PART 4
answer_1_Q6_4 = st.text_area("**Can you find which portfolio has the lowest standard deviation?**", default_text, key="Q6.4")
solution = st.checkbox('**Solution** ✅',key="SQ6.4")
if solution:
st.success(f"The portfolio where you invest **2** in the risky-free asset and **-1** in {risky_asset}")
st.success(f"The portfolio's standard deviation is **{np.round(df_portfolios['Standard deviation'].to_numpy()[0],4)}**")
st.markdown(" ")
st.markdown(" ")
st.markdown("#### Congratulations you finished Exercise 1 🎉")
list_answer = [answer_1_Q1_1,
answer_1_Q1_2,
answer_1_Q1_3,
answer_1_Q2_1,
answer_1_Q2_2,
answer_1_Q2_3,
answer_1_Q2_4,
answer_1_Q3_1,
answer_1_Q3_2,
answer_1_Q4_1,
answer_1_Q4_2,
answer_1_Q4_3,
answer_1_Q4_4,
answer_1_Q5_1,
answer_1_Q5_2,
answer_1_Q6_1,
answer_1_Q6_2,
answer_1_Q6_3,
answer_1_Q6_4,]
count = len([x for x in list_answer if x not in [0, 0.0, None, "Write the answer in this box","0"]])
df_1 = pd.DataFrame({
'Professor': select_teacher,
'Section': select_code,
'Group': select_student,
'Part1': 1,
'Start time':'05/09/2023 09:40',
'End time': '05/09/2023 10:40',
'Completed':count,
'Completed %':round(count/19*100,2),
'Q1_1':answer_1_Q1_1,
'Q1_2':answer_1_Q1_2,
'Q1_3':answer_1_Q1_3,
'Q2_1':answer_1_Q2_1,
'Q2_2':answer_1_Q2_2,
'Q2_3':answer_1_Q2_3,
'Q2_4':answer_1_Q2_4,
'Q3_1':answer_1_Q3_1,
'Q3_2':answer_1_Q3_2,
'Q4_1':answer_1_Q4_1,
'Q4_2':answer_1_Q4_2,
'Q4_3':answer_1_Q4_3,
'Q4_4':answer_1_Q4_4,
'Q5_1':answer_1_Q5_1,
'Q5_2':answer_1_Q5_2,
'Q6_1':answer_1_Q6_1,
'Q6_2':answer_1_Q6_2,
'Q6_3':answer_1_Q6_3,
'Q6_4':answer_1_Q6_4
})
st.dataframe(df_1)
if st.sidebar.button('**Submit answers Ex1**'):
df_old = pd.read_csv("master.csv")
result = pd.concat([df_old, df_1], ignore_index=True)
result.to_csv("master.csv",index=False)
st.sidebar.info('Your answers have been submitted !')
#################################################################################################################
# EXERCICE 2 - Two risky assets
#################################################################################################################
if lab_numbers == "02 - Two risky assets":
##################################### SIDEBAR ##########################################
output_multiselect = st.sidebar.multiselect("Select two risky stocks", list_risky_assets, ["AAPL","NVDA"])
if len(output_multiselect) != 2:
st.warning("Please select exactly two risky stocks")
else:
risky_asset1_ex2, risky_asset2_ex2 = output_multiselect
st.sidebar.markdown(" ")
##################################### TITLE ##########################################
st.markdown("## 02 - Two risky assets")
st.info("The purpose of this exercise is to understand how to **construct efficient portfolios** if you can invest in two risky assets or in two risky and one risk-free asset.")
st.markdown(" ")
st.markdown(" ")
##################################### QUESTION 1 #####################################
st.subheader("Question 1 📝")
########### Q1 PART 1
st.markdown('''<p style="font-size: 22px;"> Download prices for two risky stocks. <b>Compute their realized returns</b>.
Next, estimate the <b>expected returns</b> and <b>standard deviations of returns</b> on these two stocks.
Finally, compute the <b>correlation of the returns</b> on these two stocks.''',
unsafe_allow_html=True)
st.markdown(" ")
st.markdown(" ")
# st.markdown('''<p style="font-size: 20px;"> <b>First asset</b></p>''',
# unsafe_allow_html=True)
#st.divider()
st.subheader(f"1. First risky stock ({risky_asset1_ex2}) 📋")
st.markdown(" ")
#st.warning(f"First risky asset: **{risky_asset1_ex2}**")
######################## RISKY ASSET 1 ############################
## Dataframe
data_asset1_ex2 = yf.Ticker(risky_asset1_ex2)
df_asset1_ex2 = data_asset1_ex2.history(period="16mo").reset_index()[["Date","Close","Dividends"]]
df_asset1_ex2 = df_asset1_ex2.loc[(df_asset1_ex2["Date"]<="2023-07-26") & (df_asset1_ex2["Date"]>"2022-03-08")]
df_asset1_ex2["Date"] = pd.to_datetime(df_asset1_ex2["Date"]).apply(lambda x: x.strftime("%d/%m/%Y"))