File size: 9,657 Bytes
f2bfb78
 
 
 
 
 
 
bebfd9b
f2bfb78
670bfeb
 
 
f2bfb78
 
bd2abfa
 
 
 
db86ec1
 
 
 
 
 
 
 
 
cb212f1
 
 
 
 
2654178
 
 
 
 
 
 
 
 
 
f2bfb78
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
22f8bc3
f2bfb78
 
 
22f8bc3
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
100861d
22f8bc3
 
 
 
 
 
 
 
 
 
 
 
100861d
f2bfb78
22f8bc3
f2bfb78
 
 
 
 
 
 
 
 
 
 
22f8bc3
 
 
f2bfb78
 
 
 
 
 
 
 
 
 
 
 
 
 
22f8bc3
f2bfb78
22f8bc3
f2bfb78
 
 
 
 
 
 
 
 
 
22f8bc3
 
100861d
 
f2bfb78
 
 
 
 
cb212f1
f2bfb78
 
 
 
cb212f1
 
f2bfb78
 
 
 
 
 
 
 
 
 
670bfeb
f2bfb78
 
 
 
 
 
 
 
 
 
 
 
 
 
 
bd2abfa
b39cfe3
 
 
bd2abfa
b39cfe3
 
2654178
b39cfe3
 
 
2654178
 
b39cfe3
 
bd2abfa
2654178
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
f2bfb78
97d1e0e
01a3506
cb212f1
 
 
f2bfb78
 
 
 
 
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
import streamlit as st
from datetime import date, timedelta
#from rest_api.fetch_data import (get_symbol_data)
import pandas as pd
from plots import (
    beta,
    basic_portfolio,
    # display_portfolio_return,
    display_heat_map,
    #circle_packing,
    ER,
    buble_interactive
)

### Koi
from ef import(
    ef_viz
)
def risk_str(num):
    if num >=5 and num <15:
        return 'Low Risk Aversion'
    elif num >= 15 and num <25:
        return 'Medium Risk Aversion'
    elif num >= 25 and num <=35:
        return 'High Rish Aversion'
#### Koi
        
from sharp_ratio import(
    cumulative_return,
    preprocess,
    sharp_ratio_func
)

def risk_str(num):
    if num >=5 and num <15:
        return 'Low Risk Aversion'
    elif num >= 15 and num <25:
        return 'Medium Risk Aversion'
    elif num >= 25 and num <=35:
        return 'High Rish Aversion'
#### Koi
        
def load_heading():
    """The function that displays the heading.
        Provides instructions to the user
    """
    with st.container():
        st.title('Dataminers')
        header = st.subheader('This App performs historical portfolio analysis and future analysis ')
        st.subheader('Please read the instructions carefully and enjoy!')
        # st.text('This is some text.')


def get_choices():
    """Prompts the dialog to get the All Choices.
    Returns:
        An object of choices and an object of combined dataframes.
    """
    choices = {}
    tab1, tab2, tab3, tab4, tab5 = st.tabs(["Tickers", "Quantity", "Benchmark","Risk Free Return","Risk Aversion"])



    with tab1:

        tickers = st.text_input('Enter stock tickers.', 'GOOG,A,AVOG,AMD')

    with tab2:
        # Set the weights
        weights_str = st.text_input('Enter the investment quantities', '50,30,25,25')

    with tab3:
        benchmark = st.selectbox(
            'Select your ideal benchmark of return',
            ('SP500', 'AOK', 'IXIC'))
        if benchmark == 'IXIC':
            st.warning("You have selected a volatile benchmark.")
        elif benchmark == 'SP500':
            st.success('You have selected a balanced benchmark')
        elif benchmark == 'AOK':
            st.success('You have selected a conservative benchmark')

    with tab4:
        ### koi
        rf = st.number_input('Enter current rate of risk free return', min_value=0.001, max_value=1.00, value=0.041)


    #A_coef_map = 
    with tab5:
        A_coef = st.slider('Enter The Coefficient of Risk Aversion', min_value=5, max_value=35, value=30, step=5)

        if A_coef > 20:
            st.success("You have selected a "+ risk_str(A_coef) +" investing style")
            investing_style = 'Conservative'
        elif A_coef >10 and A_coef <= 20:
            st.success("You have selected a "+risk_str(A_coef) +" investing style")
            investing_style = 'Balanced'
        elif A_coef <= 10:
            st.warning("You have selected a "+ risk_str(A_coef) +" investing style")
            investing_style = 'Risky'

    # Every form must have a submit button.
    submitted = st.button("Calculate")

    symbols = []
    reset = False

    # Reusable Error Button DRY!
    #def reset_app(error):
    #    st.sidebar.write(f"{error}!")
    #    st.sidebar.write(f"Check The Syntax")
    #    reset = st.sidebar.button("RESET APP")

    if submitted:
        with st.spinner('Running the calculations...'):
            time.sleep(8)
            st.success('Done!')
        # convert  strings to lists
        tickers_list = tickers.split(",")
        weights_list = weights_str.split(",")
        #crypto_symbols_list = crypto_symbols.split(",")
        # Create the Symbols List
        symbols.extend(tickers_list)
        #symbols.extend(crypto_symbols_list)
        # Convert Weights To Decimals
        weights = []
        for item in weights_list:
            weights.append(float(item))

        if reset:
        #    # Clears all singleton caches:
            #tickers = st.sidebar.selectbox('Enter 11 stock symbols.', ('GOOG','D','AAP','BLK'))
        #    crypto_symbols = st.sidebar.text_input('Enter 2 crypto symbols only as below', 'BTC-USD,ETH-USD')
            #weights_str = st.sidebar.text_input('Enter The Investment Weights', '0.3,0.3 ,0.3')

            st.experimental_singleton.clear()


        else:
            # Submit an object with choices
            choices = {

                'symbols': symbols,
                'weights': weights,
                'benchmark': benchmark,
                'investing_style': investing_style,
                'risk-free-rate': rf,
                'A-coef': A_coef

            }
            # Load combined_df
            data = pd.read_csv('data_and_sp500.csv')
            combined_df = data[tickers_list]
            raw_data=pd.read_csv('us-shareprices-daily.csv', sep=';')
            # return object of objects
            return {
                'choices': choices,
                'combined_df': combined_df,
                'data': data,
                'raw_data':raw_data
            }


def run():
    """The main function for running the script."""

    load_heading()
    choices = get_choices()
    if choices:
        st.success('''** Selected Tickers **''')     
        buble_interactive(choices['data'],choices['choices'])
        st.header('Tickers Beta')
        """
        The Capital Asset Pricing Model (CAPM) utilizes a formula to enable the application to calculate
risk, return, and variability of return with respect to a benchmark. The application uses this
benchmark, currently S&P 500 annual rate of return, to calculate the return of a stock using
Figure 2 in Appendix A. Elements such as beta can be calculated using the formula in Appendix
A Figure 1. The beta variable will serve as a variable to be used for calculating the variability of
the stock with respect to the benchmark. This variability factor will prove useful for a variety of
calculations such as understanding market risk and return. If the beta is equal to 1.0, the stock
price is correlated with the market. When beta is smaller than 1.0, the stock is less volatile than
the market. If beta is greater than 1.0, the stock is more volatile than the market.
The CAPM model was run for 9 stocks, using 10-year daily historical data for initial test analysis.
With this initial analysis, beta was calculated to determine the stock’s risk by measuring the
price changes to the benchmark. By using CAPM model, annual expected return and portfolio
return is calculated. The model results can be found in Appendix A.
        """
        
        beta(choices['data'], choices['choices'])
        ER(choices['data'], choices['choices'])
        ##### EDIT HERE ##### koi
        st.header('CAPM Model and the Efficient Frontier')
        """
    CAPM model measures systematic risks, however many of it's functions have unrealistic assumptions and rely heavily on a linear interpretation 
    of the risks vs. returns relationship. It is better to use CAPM model in conjunction with the Efficient Frontier to better
    graphically depict volatility (a measure of investment risk) for the defined rate of return. \n
    Below we map the linear Utility function from the CAPM economic model along with the Efficient Frontier
    Each circle depicted above is a variation of the portfolio with the same input asset, only different weights. 
    Portfolios with higher volatilities have a yellower shade of hue, while portfolios with a higher return have a larger radius. \n
    As you input different porfolio assets, take note of how diversification can improve a portfolio's risk versus reward profile.
        """
        ef_viz(choices['data'],choices['choices'])
        """
    There are in fact two components of the Efficient Frontier: the Efficient Frontier curve itself and the Minimum Variance Frontier. 
    The lower curve, which is also the Minimum Variance Frontier will contain assets in the portfolio 
    that has the lowest volatility. If our portfolio contains "safer" assets such as Governmental Bonds, the further to the right 
    of the lower curve we will see a portfolio that contains only these "safe" assets, the portfolios on 
    this curve, in theory, will have diminishing returns.\n
    The upper curve, which is also the Efficient Frontier, contains portfolios that have marginally increasing returns as the risks 
    increases. In theory, we want to pick a portfolio on this curve, as these portfolios contain more balanced weights of assets 
    with acceptable trade-offs between risks and returns. \n
    If an investor is more comfortable with investment risks, they can pick a portfolio on the right side of the Efficient Frontier. 
    Whereas, a conservative investor might want to pick a portfolio from the left side of the Efficient Frontier. \n
    Take notes of the assets' Betas and how that changes the shape of the curve as well. \n 
    How does the shape of the curve change when 
    the assets are of similar Beta vs when they are all different?\n 
    Note the behavior of the curve when the portfolio contains only assets with Betas higher than 1 vs. when Betas are lower than 1.\n  

        """
        ##### ##### Koi
        basic_portfolio(choices['combined_df'])
        display_heat_map(choices['data'],choices['choices'])
        #display_portfolio_return(choices['combined_df'], choices['choices'])
        preprocess(choices['raw_data'], choices['choices'])
        cumulative_return(choices['raw_data'], choices['choices'])
        sharp_ratio_func(choices['raw_data'], choices['choices'])
        

if __name__ == "__main__":
    run()