QuantumLearner commited on
Commit
aa598ab
·
verified ·
1 Parent(s): c9461af

Create app.py

Browse files
Files changed (1) hide show
  1. app.py +173 -0
app.py ADDED
@@ -0,0 +1,173 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import numpy as np
2
+ import yfinance as yf
3
+ import pandas as pd
4
+ import plotly.graph_objects as go
5
+ import streamlit as st
6
+
7
+ #st.title('Expected Stock Price Movement Using Volatility Multipliers')
8
+ st.set_page_config(page_title = "Expected Stock Price Movement Using Volatility Multipliers", layout = "wide")
9
+
10
+ # Sidebar inputs with standard labels
11
+ st.sidebar.header('Input Parameters')
12
+ ticker = st.sidebar.text_input('Enter Stock Ticker', 'ADS.DE')
13
+ start_date = st.sidebar.date_input('Start Date', pd.to_datetime('2020-01-01'))
14
+ end_date = st.sidebar.date_input('End Date', pd.to_datetime('2025-12-30'))
15
+ time_horizon = st.sidebar.slider('Time Horizon (Days)', min_value=1, max_value=60, value=30)
16
+ std_multipliers = st.sidebar.multiselect('Select Std Multipliers', [1, 1.25, 1.5, 1.75, 2], default=[1, 1.25, 1.5])
17
+ rolling_window = st.sidebar.slider('Rolling Window (Days)', min_value=10, max_value=90, value=30, step=5)
18
+
19
+
20
+ # Inject CSS for custom styling
21
+ st.markdown("""
22
+ <style>
23
+ /* Slider track */
24
+ .stSlider > div > div > div > div:nth-of-type(2) > div {
25
+ background: green !important; /* Change the slider track color */
26
+ }
27
+ /* Slider handle */
28
+ .stSlider > div > div > div > div:nth-of-type(2) > div > div {
29
+ background: green !important; /* Change the slider handle color */
30
+ }
31
+ /* Multi-select tags */
32
+ .stMultiSelect [data-baseweb="tag"] {
33
+ background-color: green !important; /* Change background color of selected tags */
34
+ color: white !important; /* Change text color of selected tags */
35
+ }
36
+ </style>
37
+ """, unsafe_allow_html=True)
38
+
39
+
40
+ st.write("""
41
+ This analysis estimates the potential price movement of a selected stock over a specified time horizon.
42
+ The predictions are based on historical volatility, calculated from the stock's daily returns.
43
+ You can adjust the time horizon and standard deviation multipliers to see how the expected price range changes.
44
+ """)
45
+
46
+ st.markdown("""
47
+ ### How to Use This App
48
+ 1. **Input Parameters**: Use the sidebar to enter the stock ticker, date range, time horizon, standard deviation multipliers, and rolling window period for the analysis.
49
+ 2. **Run the Analysis**: Click the "Run" button to perform the analyses and visualize the results.
50
+
51
+ Each analysis is accompanied by a detailed explanation and visual representation, providing insights into the stock's price behavior and helping you make informed decisions regarding potential price movements.
52
+ """)
53
+
54
+ # Display the main formula with clear, basic LaTeX
55
+ st.latex(r'''
56
+ P_t = P_0 \times e^{\sigma \times \sqrt{t} \times z}
57
+ ''')
58
+
59
+ # Provide detailed explanations using plain text
60
+ st.markdown("""
61
+ **Formula for price movement estimation explained:**
62
+
63
+ - **P_t**: Estimated price at time (t)
64
+ - **P_0**: Current price
65
+ - **σ (sigma)**: Standard deviation of the stock's returns, representing volatility
66
+ - **t**: Time horizon in days
67
+ - **z**: Multiplier corresponding to the desired confidence level, which adjusts for standard deviation
68
+
69
+ The formula calculates the future stock price P_t based on the exponential growth affected by the volatility (σ), time (t), and the confidence level multiplier (z). This approach assumes a log-normal distribution of prices, common in financial modeling for stock prices.
70
+ """)
71
+
72
+ if st.sidebar.button('Run'):
73
+ stock_data = yf.download(ticker, start=start_date, end=end_date)
74
+
75
+ if not stock_data.empty:
76
+ stock_data['Returns'] = stock_data['Close'].pct_change()
77
+ current_price = stock_data.iloc[-1]['Close']
78
+
79
+ # Method 1: Volatility over dynamic periods
80
+ fig1 = go.Figure()
81
+ plot_data = stock_data[-rolling_window:]['Close']
82
+ date_range = pd.date_range(plot_data.index[-1] + pd.DateOffset(1), periods=time_horizon, freq='D')
83
+
84
+ st.markdown("""
85
+ <h3 style='color: green; font-size: 24px;'>Method 1: Dynamic Volatility</h3>
86
+
87
+ **Description:**
88
+ This method assesses stock price movement by calculating volatility over dynamically changing periods based on a rolling window. It adjusts for recent market behaviors, making the estimation sensitive to the latest trends.
89
+
90
+ **Technical Explanation:**
91
+ The application calculates the standard deviation (volatility) of the stock’s daily returns over the past rolling window period, then shifts this window one day at a time through the desired forecasting period. This dynamic calculation helps in adapting to recent market volatility which could impact future price movements significantly.
92
+
93
+ **Visualization:**
94
+ The method plots the past days of stock prices and overlays the expected upper and lower bounds for the price over the forecast horizon. This visual representation uses different colors to distinguish between past prices and forecasted boundaries, enhancing understanding of volatility impacts.
95
+ """, unsafe_allow_html=True)
96
+
97
+ # Plot historical prices once
98
+ fig1.add_trace(go.Scatter(x=plot_data.index, y=plot_data, mode='lines', name='Historical Prices'))
99
+
100
+ for std_multiplier in std_multipliers:
101
+ expected_upper_bounds = pd.Series(index=date_range)
102
+ expected_lower_bounds = pd.Series(index=date_range)
103
+
104
+ for i in range(time_horizon):
105
+ if i == 0:
106
+ volatility = stock_data['Returns'].iloc[-rolling_window:].std()
107
+ else:
108
+ volatility = stock_data['Returns'].iloc[-(rolling_window + i):-i].std()
109
+ expected_price_movement = current_price * volatility * np.sqrt(i + 1) * std_multiplier
110
+ expected_upper_bounds.iloc[i] = current_price + expected_price_movement
111
+ expected_lower_bounds.iloc[i] = current_price - expected_price_movement
112
+
113
+ fig1.add_trace(go.Scatter(x=date_range, y=expected_upper_bounds, mode='lines', line=dict(dash='dash', color='green'), name=f'Upper Bound ({std_multiplier}x std)'))
114
+ fig1.add_trace(go.Scatter(x=date_range, y=expected_lower_bounds, mode='lines', line=dict(dash='dash', color='red'), name=f'Lower Bound ({std_multiplier}x std)'))
115
+ fig1.add_trace(go.Scatter(x=date_range, y=expected_upper_bounds, fill='tonexty', fillcolor='rgba(128, 128, 128, 0.3)', mode='none', showlegend=False))
116
+
117
+ fig1.update_layout(title=f'{ticker} - Dynamic Volatility Expected Price Movement',
118
+ xaxis_title='Date',
119
+ yaxis_title='Price',
120
+ legend_title='Legend')
121
+
122
+ # Method 2: Single volatility measure over the period
123
+ fig2 = go.Figure()
124
+
125
+ # Plot historical prices once
126
+ fig2.add_trace(go.Scatter(x=plot_data.index, y=plot_data, mode='lines', name='Historical Prices'))
127
+
128
+ for std_multiplier in std_multipliers:
129
+ expected_upper_bounds = pd.Series(index=date_range)
130
+ expected_lower_bounds = pd.Series(index=date_range)
131
+
132
+ for i in range(time_horizon):
133
+ volatility = stock_data['Returns'].std() * std_multiplier
134
+ expected_price_movement = current_price * volatility * np.sqrt(i + 1)
135
+ expected_upper_bounds.iloc[i] = current_price + expected_price_movement
136
+ expected_lower_bounds.iloc[i] = current_price - expected_price_movement
137
+
138
+ fig2.add_trace(go.Scatter(x=date_range, y=expected_upper_bounds, mode='lines', line=dict(dash='dash', color='green'), name=f'Upper Bound ({std_multiplier}x std)'))
139
+ fig2.add_trace(go.Scatter(x=date_range, y=expected_lower_bounds, mode='lines', line=dict(dash='dash', color='red'), name=f'Lower Bound ({std_multiplier}x std)'))
140
+ fig2.add_trace(go.Scatter(x=date_range, y=expected_upper_bounds, fill='tonexty', fillcolor='rgba(128, 128, 128, 0.3)', mode='none', showlegend=False))
141
+
142
+ fig2.update_layout(title=f'{ticker} - Single Volatility Measure Expected Price Movement',
143
+ xaxis_title='Date',
144
+ yaxis_title='Price',
145
+ legend_title='Legend')
146
+
147
+ st.plotly_chart(fig1)
148
+
149
+ st.markdown("""
150
+ <h3 style='color: green; font-size: 24px;'>Method 2: Single Volatility Measure</h3>
151
+
152
+ **Description:**
153
+ This method calculates stock price movement based on a single, constant measure of volatility derived from the entire historical data set available. By using this approach, it simplifies the calculation but may not reflect recent market dynamics as effectively as the dynamic method.
154
+
155
+ **Technical Explanation:**
156
+ The application calculates the standard deviation (volatility) of the stock's daily returns across the entire period for which data is available. This constant measure of volatility is then used to estimate the price range over the forecasting period, assuming that the past long-term volatility will continue into the future.
157
+
158
+ **Visualization:**
159
+ The method plots the historical data and overlays expected upper and lower price boundaries based on this single measure of volatility. The visualization clearly marks these projected bounds with different colors to illustrate potential future price movements based on historical volatility levels, providing a straightforward visual interpretation of risk and variability over time.
160
+ """, unsafe_allow_html=True)
161
+
162
+ st.plotly_chart(fig2)
163
+ else:
164
+ st.write("No data found for the given ticker and date range.")
165
+
166
+
167
+ hide_streamlit_style = """
168
+ <style>
169
+ #MainMenu {visibility: hidden;}
170
+ footer {visibility: hidden;}
171
+ </style>
172
+ """
173
+ st.markdown(hide_streamlit_style, unsafe_allow_html=True)