QuantumLearner commited on
Commit
5a4149f
·
verified ·
1 Parent(s): 928b15d

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +47 -41
app.py CHANGED
@@ -4,6 +4,7 @@ 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:
@@ -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'Stock Price for {ticker}'),
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,62 +42,67 @@ 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 Stock Price for {ticker}", xaxis_title='Date', yaxis_title='Adjusted Close Price')
45
 
46
  return fig, up_frequency, down_frequency
47
 
48
  # Streamlit app
49
- st.set_page_config(page_title="Stock Probability Analysis", layout="wide")
50
- st.title('Stock Probability Analysis')
51
 
52
  # Sidebar for method selection
53
  st.sidebar.header("Input Parameters")
54
- ticker = st.sidebar.text_input('Enter Stock Ticker', 'SAP.DE')
55
- start_date = st.sidebar.date_input('Start Date', pd.to_datetime('2020-01-01'))
56
- end_date = st.sidebar.date_input('End Date', pd.to_datetime('2025-12-02'))
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
- default_initial_price = data['Adj Close'].iloc[-1]
65
- default_up_target = default_initial_price + 10
66
- default_down_target = default_initial_price - 10
67
 
68
- # Sidebar for dynamic inputs
69
- n_days = st.sidebar.slider('Number of Days', min_value=1, max_value=100, value=30, step=1)
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')
99
-
100
  # Fetch data and display results
101
  if run_button:
102
  st.session_state.data = fetch_stock_data(ticker, start_date, end_date)
@@ -105,9 +111,9 @@ if run_button:
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)
@@ -119,7 +125,7 @@ if run_button:
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 +134,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 data
10
  def fetch_stock_data(ticker: str, start_date: str, end_date: str) -> pd.DataFrame:
 
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')
52
 
53
  # Sidebar for method selection
54
  st.sidebar.header("Input Parameters")
 
 
 
55
 
56
+ with st.sidebar.expander("Ticker and Date Settings", expanded=True):
57
+ ticker = st.text_input('Enter Ticker (Stock or Crypto Pair)', 'BTC-USD', help="Enter a stock ticker (e.g., AAPL) or a crypto pair (e.g., BTC-USD)")
58
+ start_date = st.date_input('Start Date', pd.to_datetime('2020-01-01'))
59
+ end_date = st.date_input('End Date', datetime.now().date() + timedelta(days=1))
60
+
61
+ with st.sidebar.expander("Parameter Settings", expanded=True):
62
+ # Fetch data to set default values
63
+ if 'data' not in st.session_state:
64
+ st.session_state.data = fetch_stock_data(ticker, start_date, end_date)
65
+ data = st.session_state.data
66
 
67
+ # Set default values
68
+ default_initial_price = data['Adj Close'].iloc[-1]
69
+ default_up_target = default_initial_price * 1.1
70
+ default_down_target = default_initial_price * 0.9
71
 
72
+ n_days = st.slider('Number of Days', min_value=1, max_value=100, value=30, step=1, help="Number of days for percentage change calculation")
73
+ initial_price = st.number_input('Initial Price', value=default_initial_price, help="Starting price for analysis")
74
+ up_target = st.number_input('Up Target', value=default_up_target, help="Target price for upward move")
75
+ down_target = st.number_input('Down Target', value=default_down_target, help="Target price for downward move")
 
76
 
77
  # Explanation and instructions
78
+ with st.sidebar:
79
+ st.markdown("""
80
+ ### How to Use
81
+
82
+ 1. **Enter Ticker**: Input the stock symbol or crypto pair you want to analyze.
83
+ 2. **Select Date Range**: Choose the start and end dates for the historical data.
84
+ 3. **Set Parameters**:
85
+ - **Number of Days**: Define the period for percentage change calculation.
86
+ - **Initial Price**: The starting price for your analysis.
87
+ - **Up Target**: The target price for an upward move.
88
+ - **Down Target**: The target price for a downward move.
89
+ 4. **Run Analysis**: Click the 'Run Analysis' button to generate the results.
90
+ """)
91
+
92
+ # Run button
93
+ run_button = st.sidebar.button('Run Analysis')
94
+
95
+ # Main content area
96
  st.markdown("""
97
  ### Explanation of the Analysis
98
 
99
+ This app estimates the probability of a stock or cryptocurrency reaching certain price targets within a specified number of days based on historical data.
100
 
101
  - **Distribution of Percentage Changes**: The histogram shows the distribution of percentage changes over the selected number of days.
102
  - **Price Targets**: The vertical lines indicate the price targets for upward and downward moves. The frequencies of reaching these targets are annotated.
103
+ - **Price Plot**: The line chart shows the historical adjusted close prices with markers indicating instances where the price targets were met.
 
 
 
 
 
 
 
 
 
 
 
 
104
  """)
105
 
 
 
 
106
  # Fetch data and display results
107
  if run_button:
108
  st.session_state.data = fetch_stock_data(ticker, start_date, end_date)
 
111
  if initial_price == 0.0:
112
  initial_price = data['Adj Close'].iloc[-1]
113
  if up_target == 0.0:
114
+ up_target = initial_price * 1.1
115
  if down_target == 0.0:
116
+ down_target = initial_price * 0.9
117
 
118
  fig, up_frequency, down_frequency = estimate_probability(data, n_days, initial_price, up_target, down_target)
119
  st.plotly_chart(fig)
 
125
  - Probability of reaching the up target ({up_target:.2f}) in {n_days} days: **{up_frequency * 100:.2f}%**
126
  - Probability of reaching the down target ({down_target:.2f}) in {n_days} days: **{down_frequency * 100:.2f}%**
127
 
128
+ This analysis helps in understanding the historical likelihood of the price reaching certain targets within a specified number of days.
129
  """)
130
 
131
  hide_streamlit_style = """
 
134
  footer {visibility: hidden;}
135
  </style>
136
  """
137
+ st.markdown(hide_streamlit_style, unsafe_allow_html=True)