Spaces:
Sleeping
Sleeping
Update app.py
Browse files
app.py
CHANGED
|
@@ -3,6 +3,12 @@ import yfinance as yf
|
|
| 3 |
import pandas as pd
|
| 4 |
import plotly.graph_objects as go
|
| 5 |
import streamlit as st
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 6 |
|
| 7 |
st.set_page_config(page_title="Expected Stock Price Movement Using Volatility Multipliers", layout="wide")
|
| 8 |
st.title('Expected Stock Price Movement Using Volatility Multipliers')
|
|
@@ -11,7 +17,6 @@ st.title('Expected Stock Price Movement Using Volatility Multipliers')
|
|
| 11 |
st.sidebar.title('Input Parameters')
|
| 12 |
|
| 13 |
with st.sidebar.expander("How to use:", expanded=False):
|
| 14 |
-
#st.subheader('How to Use')
|
| 15 |
st.markdown("""
|
| 16 |
1. **Input Parameters**: Enter the stock ticker or cryptocurrency pair, date range, time horizon, standard deviation multipliers, and rolling window period.
|
| 17 |
2. **Run the Analysis**: Click the "Run" button to perform the analyses and visualize the results.
|
|
@@ -26,10 +31,9 @@ with st.sidebar.expander("Ticker and Date Settings", expanded=True):
|
|
| 26 |
# Wrapping parameter settings in an expander
|
| 27 |
with st.sidebar.expander("Parameter Settings", expanded=True):
|
| 28 |
time_horizon = st.slider('Time Horizon (Days)', min_value=1, max_value=60, value=30, help="Set the number of days into the future for which you want to estimate asset prices.")
|
| 29 |
-
std_multipliers = st.multiselect('Select Std Multipliers', [1, 1.25, 1.5, 1.75, 2,2.25,2.5,2.75,3], default=[1, 1.25, 1.5, 1.75], help="Choose the standard deviation multipliers to calculate future price ranges.")
|
| 30 |
rolling_window = st.slider('Rolling Window (Days)', min_value=10, max_value=90, value=30, step=5, help="Set the number of days to use for calculating rolling volatility.")
|
| 31 |
|
| 32 |
-
|
| 33 |
st.write("""
|
| 34 |
This tool estimates the potential price movement of a selected stock or cryptocurrency pair over a specified time horizon.
|
| 35 |
The predictions are based on historical volatility, calculated from the asset's daily returns.
|
|
@@ -47,20 +51,24 @@ with st.expander("Click here to read more about the methodology", expanded=False
|
|
| 47 |
- **σ (sigma)**: Standard deviation of the stock's returns, representing volatility
|
| 48 |
- **t**: Time horizon in days
|
| 49 |
- **z**: Multiplier corresponding to the desired confidence level, which adjusts for standard deviation
|
| 50 |
-
|
| 51 |
To read more about the methodologies, visit [this link](https://entreprenerdly.com/expected-stock-price-movement-with-volatility-multipliers/).
|
| 52 |
""")
|
| 53 |
|
| 54 |
if st.sidebar.button('Run Analysis'):
|
| 55 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 56 |
|
| 57 |
if not stock_data.empty:
|
| 58 |
-
stock_data['Returns'] = stock_data['Close'].pct_change()
|
| 59 |
-
current_price = stock_data.iloc[-1]
|
| 60 |
|
| 61 |
# Method 1: Volatility over dynamic periods
|
| 62 |
fig1 = go.Figure()
|
| 63 |
-
plot_data = stock_data[-rolling_window:]
|
| 64 |
date_range = pd.date_range(plot_data.index[-1] + pd.DateOffset(1), periods=time_horizon, freq='D')
|
| 65 |
|
| 66 |
st.markdown("""
|
|
@@ -77,9 +85,9 @@ if st.sidebar.button('Run Analysis'):
|
|
| 77 |
|
| 78 |
for i in range(time_horizon):
|
| 79 |
if i == 0:
|
| 80 |
-
volatility = stock_data
|
| 81 |
else:
|
| 82 |
-
volatility = stock_data
|
| 83 |
expected_price_movement = current_price * volatility * np.sqrt(i + 1) * std_multiplier
|
| 84 |
expected_upper_bounds.iloc[i] = current_price + expected_price_movement
|
| 85 |
expected_lower_bounds.iloc[i] = current_price - expected_price_movement
|
|
@@ -89,11 +97,11 @@ if st.sidebar.button('Run Analysis'):
|
|
| 89 |
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))
|
| 90 |
|
| 91 |
fig1.update_layout(title=f'{ticker} - Dynamic Volatility Expected Price Movement',
|
| 92 |
-
|
| 93 |
-
|
| 94 |
-
|
| 95 |
-
|
| 96 |
-
|
| 97 |
|
| 98 |
# Method 2: Single volatility measure over the period
|
| 99 |
fig2 = go.Figure()
|
|
@@ -106,7 +114,7 @@ if st.sidebar.button('Run Analysis'):
|
|
| 106 |
expected_lower_bounds = pd.Series(index=date_range)
|
| 107 |
|
| 108 |
for i in range(time_horizon):
|
| 109 |
-
volatility = stock_data
|
| 110 |
expected_price_movement = current_price * volatility * np.sqrt(i + 1)
|
| 111 |
expected_upper_bounds.iloc[i] = current_price + expected_price_movement
|
| 112 |
expected_lower_bounds.iloc[i] = current_price - expected_price_movement
|
|
@@ -116,11 +124,11 @@ if st.sidebar.button('Run Analysis'):
|
|
| 116 |
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))
|
| 117 |
|
| 118 |
fig2.update_layout(title=f'{ticker} - Single Volatility Measure Expected Price Movement',
|
| 119 |
-
|
| 120 |
-
|
| 121 |
-
|
| 122 |
-
|
| 123 |
-
|
| 124 |
|
| 125 |
st.plotly_chart(fig1)
|
| 126 |
|
|
@@ -128,7 +136,6 @@ if st.sidebar.button('Run Analysis'):
|
|
| 128 |
### Method 2: Single Volatility Measure
|
| 129 |
This method calculates stock price movement based on a single, constant measure of volatility derived from the entire historical data set available.
|
| 130 |
""")
|
| 131 |
-
|
| 132 |
st.plotly_chart(fig2)
|
| 133 |
else:
|
| 134 |
st.write("No data found for the given ticker and date range.")
|
|
|
|
| 3 |
import pandas as pd
|
| 4 |
import plotly.graph_objects as go
|
| 5 |
import streamlit as st
|
| 6 |
+
from plotly.subplots import make_subplots
|
| 7 |
+
from itertools import product
|
| 8 |
+
import warnings
|
| 9 |
+
from datetime import datetime
|
| 10 |
+
|
| 11 |
+
warnings.filterwarnings("ignore")
|
| 12 |
|
| 13 |
st.set_page_config(page_title="Expected Stock Price Movement Using Volatility Multipliers", layout="wide")
|
| 14 |
st.title('Expected Stock Price Movement Using Volatility Multipliers')
|
|
|
|
| 17 |
st.sidebar.title('Input Parameters')
|
| 18 |
|
| 19 |
with st.sidebar.expander("How to use:", expanded=False):
|
|
|
|
| 20 |
st.markdown("""
|
| 21 |
1. **Input Parameters**: Enter the stock ticker or cryptocurrency pair, date range, time horizon, standard deviation multipliers, and rolling window period.
|
| 22 |
2. **Run the Analysis**: Click the "Run" button to perform the analyses and visualize the results.
|
|
|
|
| 31 |
# Wrapping parameter settings in an expander
|
| 32 |
with st.sidebar.expander("Parameter Settings", expanded=True):
|
| 33 |
time_horizon = st.slider('Time Horizon (Days)', min_value=1, max_value=60, value=30, help="Set the number of days into the future for which you want to estimate asset prices.")
|
| 34 |
+
std_multipliers = st.multiselect('Select Std Multipliers', [1, 1.25, 1.5, 1.75, 2, 2.25, 2.5, 2.75, 3], default=[1, 1.25, 1.5, 1.75], help="Choose the standard deviation multipliers to calculate future price ranges.")
|
| 35 |
rolling_window = st.slider('Rolling Window (Days)', min_value=10, max_value=90, value=30, step=5, help="Set the number of days to use for calculating rolling volatility.")
|
| 36 |
|
|
|
|
| 37 |
st.write("""
|
| 38 |
This tool estimates the potential price movement of a selected stock or cryptocurrency pair over a specified time horizon.
|
| 39 |
The predictions are based on historical volatility, calculated from the asset's daily returns.
|
|
|
|
| 51 |
- **σ (sigma)**: Standard deviation of the stock's returns, representing volatility
|
| 52 |
- **t**: Time horizon in days
|
| 53 |
- **z**: Multiplier corresponding to the desired confidence level, which adjusts for standard deviation
|
|
|
|
| 54 |
To read more about the methodologies, visit [this link](https://entreprenerdly.com/expected-stock-price-movement-with-volatility-multipliers/).
|
| 55 |
""")
|
| 56 |
|
| 57 |
if st.sidebar.button('Run Analysis'):
|
| 58 |
+
# Updated get_data: use "Close" and squeeze the result to ensure a 1D Series.
|
| 59 |
+
def get_data(ticker, start, end):
|
| 60 |
+
data = yf.download(ticker, start=start, end=end)
|
| 61 |
+
return data['Close'].squeeze()
|
| 62 |
+
|
| 63 |
+
stock_data = get_data(ticker, start_date, end_date)
|
| 64 |
|
| 65 |
if not stock_data.empty:
|
| 66 |
+
stock_data['Returns'] = stock_data.pct_change() if isinstance(stock_data, pd.Series) else stock_data['Close'].pct_change()
|
| 67 |
+
current_price = stock_data.iloc[-1]
|
| 68 |
|
| 69 |
# Method 1: Volatility over dynamic periods
|
| 70 |
fig1 = go.Figure()
|
| 71 |
+
plot_data = stock_data[-rolling_window:]
|
| 72 |
date_range = pd.date_range(plot_data.index[-1] + pd.DateOffset(1), periods=time_horizon, freq='D')
|
| 73 |
|
| 74 |
st.markdown("""
|
|
|
|
| 85 |
|
| 86 |
for i in range(time_horizon):
|
| 87 |
if i == 0:
|
| 88 |
+
volatility = stock_data.iloc[-rolling_window:].pct_change().std()
|
| 89 |
else:
|
| 90 |
+
volatility = stock_data.iloc[-(rolling_window + i):-i].pct_change().std()
|
| 91 |
expected_price_movement = current_price * volatility * np.sqrt(i + 1) * std_multiplier
|
| 92 |
expected_upper_bounds.iloc[i] = current_price + expected_price_movement
|
| 93 |
expected_lower_bounds.iloc[i] = current_price - expected_price_movement
|
|
|
|
| 97 |
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))
|
| 98 |
|
| 99 |
fig1.update_layout(title=f'{ticker} - Dynamic Volatility Expected Price Movement',
|
| 100 |
+
xaxis_title='Date',
|
| 101 |
+
yaxis_title='Price',
|
| 102 |
+
legend_title='Legend',
|
| 103 |
+
width=1600,
|
| 104 |
+
height=800)
|
| 105 |
|
| 106 |
# Method 2: Single volatility measure over the period
|
| 107 |
fig2 = go.Figure()
|
|
|
|
| 114 |
expected_lower_bounds = pd.Series(index=date_range)
|
| 115 |
|
| 116 |
for i in range(time_horizon):
|
| 117 |
+
volatility = stock_data.pct_change().std() * std_multiplier
|
| 118 |
expected_price_movement = current_price * volatility * np.sqrt(i + 1)
|
| 119 |
expected_upper_bounds.iloc[i] = current_price + expected_price_movement
|
| 120 |
expected_lower_bounds.iloc[i] = current_price - expected_price_movement
|
|
|
|
| 124 |
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))
|
| 125 |
|
| 126 |
fig2.update_layout(title=f'{ticker} - Single Volatility Measure Expected Price Movement',
|
| 127 |
+
xaxis_title='Date',
|
| 128 |
+
yaxis_title='Price',
|
| 129 |
+
legend_title='Legend',
|
| 130 |
+
width=1600,
|
| 131 |
+
height=800)
|
| 132 |
|
| 133 |
st.plotly_chart(fig1)
|
| 134 |
|
|
|
|
| 136 |
### Method 2: Single Volatility Measure
|
| 137 |
This method calculates stock price movement based on a single, constant measure of volatility derived from the entire historical data set available.
|
| 138 |
""")
|
|
|
|
| 139 |
st.plotly_chart(fig2)
|
| 140 |
else:
|
| 141 |
st.write("No data found for the given ticker and date range.")
|