Spaces:
Runtime error
Runtime error
Update app.py
Browse files
app.py
CHANGED
|
@@ -4,10 +4,11 @@ import numpy as np
|
|
| 4 |
import plotly.graph_objects as go
|
| 5 |
from plotly.subplots import make_subplots
|
| 6 |
import streamlit as st
|
|
|
|
| 7 |
|
| 8 |
-
# Helper function to fetch stock data
|
| 9 |
def fetch_stock_data(ticker: str, start_date: str, end_date: str) -> pd.DataFrame:
|
| 10 |
-
"""Fetch stock data from Yahoo Finance."""
|
| 11 |
return yf.download(ticker, start=start_date, end=end_date)
|
| 12 |
|
| 13 |
# Function to estimate probability and plot
|
|
@@ -28,7 +29,7 @@ def estimate_probability(data, n_days, initial_price, up_target, down_target):
|
|
| 28 |
|
| 29 |
# Plotting
|
| 30 |
fig = make_subplots(rows=2, cols=1, shared_xaxes=True, vertical_spacing=0.1,
|
| 31 |
-
subplot_titles=(f'Distribution of {n_days}-day percentage changes', f'
|
| 32 |
specs=[[{"secondary_y": False}], [{"secondary_y": False}]])
|
| 33 |
|
| 34 |
fig.add_trace(go.Histogram(x=data[f'{n_days}d_pct_change'], nbinsx=100, name='Percentage Change'), row=1, col=1)
|
|
@@ -41,58 +42,50 @@ def estimate_probability(data, n_days, initial_price, up_target, down_target):
|
|
| 41 |
fig.add_trace(go.Scatter(x=up_instances.index, y=up_instances['Adj Close'], mode='markers', marker=dict(color='blue', symbol='triangle-up', size=10), name=f"{up_threshold * 100:.2f}% increase"), row=2, col=1)
|
| 42 |
fig.add_trace(go.Scatter(x=down_instances.index, y=down_instances['Adj Close'], mode='markers', marker=dict(color='red', symbol='triangle-down', size=10), name=f"{down_threshold * 100:.2f}% decrease"), row=2, col=1)
|
| 43 |
|
| 44 |
-
fig.update_layout(title_text=f"Probability Estimation and
|
| 45 |
|
| 46 |
return fig, up_frequency, down_frequency
|
| 47 |
|
| 48 |
# Streamlit app
|
| 49 |
-
st.set_page_config(page_title="
|
| 50 |
-
st.title('
|
| 51 |
|
| 52 |
# Sidebar for method selection
|
| 53 |
-
st.sidebar.header("
|
| 54 |
-
|
| 55 |
-
|
| 56 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 57 |
|
| 58 |
# Fetch data to set default values
|
| 59 |
if 'data' not in st.session_state:
|
| 60 |
st.session_state.data = fetch_stock_data(ticker, start_date, end_date)
|
| 61 |
data = st.session_state.data
|
| 62 |
|
| 63 |
-
# Set default values
|
| 64 |
-
|
| 65 |
-
|
| 66 |
-
|
| 67 |
-
|
| 68 |
-
|
| 69 |
-
|
| 70 |
-
initial_price = st.sidebar.number_input('Initial Price', value=default_initial_price)
|
| 71 |
-
up_target = st.sidebar.number_input('Up Target', value=default_up_target)
|
| 72 |
-
down_target = st.sidebar.number_input('Down Target', value=default_down_target)
|
| 73 |
-
|
| 74 |
-
# Explanation and instructions
|
| 75 |
-
st.markdown("""
|
| 76 |
-
### Explanation of the Analysis
|
| 77 |
-
|
| 78 |
-
This app estimates the probability of a stock reaching certain price targets within a specified number of days based on historical data.
|
| 79 |
-
|
| 80 |
-
- **Distribution of Percentage Changes**: The histogram shows the distribution of percentage changes over the selected number of days.
|
| 81 |
-
- **Price Targets**: The vertical lines indicate the price targets for upward and downward moves. The frequencies of reaching these targets are annotated.
|
| 82 |
-
- **Stock Price Plot**: The line chart shows the historical adjusted close prices with markers indicating instances where the price targets were met.
|
| 83 |
-
|
| 84 |
-
### How to Use
|
| 85 |
-
|
| 86 |
-
1. **Enter Stock Ticker**: Input the stock symbol you want to analyze.
|
| 87 |
-
2. **Select Date Range**: Choose the start and end dates for the historical data.
|
| 88 |
-
3. **Set Parameters**:
|
| 89 |
-
- **Number of Days (n_days)**: Define the period over which you want to calculate the percentage change.
|
| 90 |
-
- **Initial Price**: The starting price for your analysis.
|
| 91 |
-
- **Up Target**: The target price for an upward move.
|
| 92 |
-
- **Down Target**: The target price for a downward move.
|
| 93 |
-
4. **Run Analysis**: Click the 'Run Analysis' button to generate the results.
|
| 94 |
-
|
| 95 |
-
""")
|
| 96 |
|
| 97 |
# Run button
|
| 98 |
run_button = st.sidebar.button('Run Analysis')
|
|
@@ -102,24 +95,15 @@ if run_button:
|
|
| 102 |
st.session_state.data = fetch_stock_data(ticker, start_date, end_date)
|
| 103 |
data = st.session_state.data
|
| 104 |
|
| 105 |
-
if initial_price == 0.0:
|
| 106 |
-
initial_price = data['Adj Close'].iloc[-1]
|
| 107 |
-
if up_target == 0.0:
|
| 108 |
-
up_target = initial_price + 10
|
| 109 |
-
if down_target == 0.0:
|
| 110 |
-
down_target = initial_price - 10
|
| 111 |
-
|
| 112 |
fig, up_frequency, down_frequency = estimate_probability(data, n_days, initial_price, up_target, down_target)
|
| 113 |
st.plotly_chart(fig)
|
| 114 |
|
| 115 |
st.markdown(f"""
|
| 116 |
### Results
|
| 117 |
-
|
| 118 |
**Probability of Reaching Targets:**
|
| 119 |
- Probability of reaching the up target ({up_target:.2f}) in {n_days} days: **{up_frequency * 100:.2f}%**
|
| 120 |
- Probability of reaching the down target ({down_target:.2f}) in {n_days} days: **{down_frequency * 100:.2f}%**
|
| 121 |
-
|
| 122 |
-
This analysis helps in understanding the historical likelihood of the stock price reaching certain targets within a specified number of days.
|
| 123 |
""")
|
| 124 |
|
| 125 |
hide_streamlit_style = """
|
|
@@ -128,4 +112,4 @@ hide_streamlit_style = """
|
|
| 128 |
footer {visibility: hidden;}
|
| 129 |
</style>
|
| 130 |
"""
|
| 131 |
-
st.markdown(hide_streamlit_style, unsafe_allow_html=True)
|
|
|
|
| 4 |
import plotly.graph_objects as go
|
| 5 |
from plotly.subplots import make_subplots
|
| 6 |
import streamlit as st
|
| 7 |
+
from datetime import datetime, timedelta
|
| 8 |
|
| 9 |
+
# Helper function to fetch stock or crypto data
|
| 10 |
def fetch_stock_data(ticker: str, start_date: str, end_date: str) -> pd.DataFrame:
|
| 11 |
+
"""Fetch stock or crypto data from Yahoo Finance."""
|
| 12 |
return yf.download(ticker, start=start_date, end=end_date)
|
| 13 |
|
| 14 |
# Function to estimate probability and plot
|
|
|
|
| 29 |
|
| 30 |
# Plotting
|
| 31 |
fig = make_subplots(rows=2, cols=1, shared_xaxes=True, vertical_spacing=0.1,
|
| 32 |
+
subplot_titles=(f'Distribution of {n_days}-day percentage changes', f'Price for {ticker}'),
|
| 33 |
specs=[[{"secondary_y": False}], [{"secondary_y": False}]])
|
| 34 |
|
| 35 |
fig.add_trace(go.Histogram(x=data[f'{n_days}d_pct_change'], nbinsx=100, name='Percentage Change'), row=1, col=1)
|
|
|
|
| 42 |
fig.add_trace(go.Scatter(x=up_instances.index, y=up_instances['Adj Close'], mode='markers', marker=dict(color='blue', symbol='triangle-up', size=10), name=f"{up_threshold * 100:.2f}% increase"), row=2, col=1)
|
| 43 |
fig.add_trace(go.Scatter(x=down_instances.index, y=down_instances['Adj Close'], mode='markers', marker=dict(color='red', symbol='triangle-down', size=10), name=f"{down_threshold * 100:.2f}% decrease"), row=2, col=1)
|
| 44 |
|
| 45 |
+
fig.update_layout(title_text=f"Probability Estimation and Price for {ticker}", xaxis_title='Date', yaxis_title='Adjusted Close Price')
|
| 46 |
|
| 47 |
return fig, up_frequency, down_frequency
|
| 48 |
|
| 49 |
# Streamlit app
|
| 50 |
+
st.set_page_config(page_title="Price Probability Analysis", layout="wide")
|
| 51 |
+
st.title('Price Probability Analysis for Stocks and Cryptocurrencies')
|
| 52 |
|
| 53 |
# Sidebar for method selection
|
| 54 |
+
st.sidebar.header("How to Use")
|
| 55 |
+
st.sidebar.markdown("""
|
| 56 |
+
1. **Enter Symbol:** Input the stock or cryptocurrency symbol you want to analyze.
|
| 57 |
+
2. **Select Date Range:** Choose the start and end dates for the historical data.
|
| 58 |
+
3. **Set Parameters:** Adjust the number of days, initial price, and targets for the analysis.
|
| 59 |
+
4. **Run Analysis:** Click the 'Run Analysis' button to generate the results.
|
| 60 |
+
""")
|
| 61 |
+
|
| 62 |
+
# Sidebar for user inputs with collapsible sections
|
| 63 |
+
with st.sidebar:
|
| 64 |
+
st.header("Input Parameters")
|
| 65 |
+
|
| 66 |
+
with st.expander("Symbol and Date Range", expanded=True):
|
| 67 |
+
ticker = st.text_input('Enter Symbol', 'BTC-USD', help="Enter the stock or cryptocurrency symbol, e.g., AAPL, BTC-USD")
|
| 68 |
+
start_date = st.date_input('Start Date', value=pd.to_datetime('2020-01-01'), help="Select the start date for the analysis.")
|
| 69 |
+
end_date = st.date_input('End Date', value=datetime.now() + timedelta(days=1), help="Select the end date for the analysis.")
|
| 70 |
+
|
| 71 |
+
with st.expander("Parameter Settings", expanded=True):
|
| 72 |
+
n_days = st.slider('Number of Days', min_value=1, max_value=100, value=30, step=1, help="Number of days over which to calculate percentage change.")
|
| 73 |
+
initial_price = st.number_input('Initial Price', value=0.0, help="The initial price to use for target estimation.")
|
| 74 |
+
up_target = st.number_input('Up Target', value=0.0, help="The target price for an upward move.")
|
| 75 |
+
down_target = st.number_input('Down Target', value=0.0, help="The target price for a downward move.")
|
| 76 |
|
| 77 |
# Fetch data to set default values
|
| 78 |
if 'data' not in st.session_state:
|
| 79 |
st.session_state.data = fetch_stock_data(ticker, start_date, end_date)
|
| 80 |
data = st.session_state.data
|
| 81 |
|
| 82 |
+
# Set default values for initial price, up target, and down target
|
| 83 |
+
if initial_price == 0.0:
|
| 84 |
+
initial_price = data['Adj Close'].iloc[-1]
|
| 85 |
+
if up_target == 0.0:
|
| 86 |
+
up_target = initial_price + 10
|
| 87 |
+
if down_target == 0.0:
|
| 88 |
+
down_target = initial_price - 10
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 89 |
|
| 90 |
# Run button
|
| 91 |
run_button = st.sidebar.button('Run Analysis')
|
|
|
|
| 95 |
st.session_state.data = fetch_stock_data(ticker, start_date, end_date)
|
| 96 |
data = st.session_state.data
|
| 97 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 98 |
fig, up_frequency, down_frequency = estimate_probability(data, n_days, initial_price, up_target, down_target)
|
| 99 |
st.plotly_chart(fig)
|
| 100 |
|
| 101 |
st.markdown(f"""
|
| 102 |
### Results
|
|
|
|
| 103 |
**Probability of Reaching Targets:**
|
| 104 |
- Probability of reaching the up target ({up_target:.2f}) in {n_days} days: **{up_frequency * 100:.2f}%**
|
| 105 |
- Probability of reaching the down target ({down_target:.2f}) in {n_days} days: **{down_frequency * 100:.2f}%**
|
| 106 |
+
This analysis helps in understanding the historical likelihood of the price reaching certain targets within a specified number of days.
|
|
|
|
| 107 |
""")
|
| 108 |
|
| 109 |
hide_streamlit_style = """
|
|
|
|
| 112 |
footer {visibility: hidden;}
|
| 113 |
</style>
|
| 114 |
"""
|
| 115 |
+
st.markdown(hide_streamlit_style, unsafe_allow_html=True)
|