QuantumLearner commited on
Commit
bb22238
·
verified ·
1 Parent(s): 523c5eb

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +24 -49
app.py CHANGED
@@ -9,7 +9,6 @@ from numpy import average as npAverage, nan as npNaN, log as npLog, power as npP
9
  from pandas_ta.utils import get_offset, verify_series
10
  from datetime import datetime
11
  from matplotlib.dates import date2num
12
- from datetime import datetime
13
 
14
  st.set_page_config(layout="wide")
15
 
@@ -36,7 +35,13 @@ with st.sidebar.expander("How to Use:", expanded=False):
36
  # Function to fetch data
37
  @st.cache_data
38
  def get_data(ticker, start_date, end_date):
39
- data = yf.download(ticker, start=start_date, end=end_date)
 
 
 
 
 
 
40
  return data
41
 
42
  # Function to create the base plot with the stock price
@@ -459,29 +464,28 @@ end_date = st.sidebar.date_input(
459
 
460
  # Fetch Data button
461
  if st.sidebar.button('Fetch Data'):
462
- # Only fetch if the ticker or date range has changed
463
- if (
464
- ticker_symbol != st.session_state.get('ticker_symbol') or
465
- start_date != st.session_state.get('start_date') or
466
- end_date != st.session_state.get('end_date')
467
- ):
468
- data = get_data(ticker_symbol, start_date, end_date)
469
- st.session_state['data'] = data
470
- st.session_state['ticker_symbol'] = ticker_symbol
471
- st.session_state['start_date'] = start_date
472
- st.session_state['end_date'] = end_date
473
- st.session_state['price_plot'] = create_price_plot(data, ticker_symbol)
474
- st.session_state['current_fig'] = st.session_state['price_plot']
 
 
 
475
 
476
  # Check if data is fetched and stored in session state
477
  if 'data' in st.session_state:
478
  data = st.session_state['data']
479
 
480
  # Moving average method selection
481
- #st.sidebar.header("Moving Average Methods")
482
-
483
-
484
-
485
  # SMA with tooltip
486
  with st.sidebar.expander("Simple Moving Average", expanded=False):
487
  use_sma = st.checkbox(
@@ -1079,21 +1083,6 @@ if 'data' in st.session_state:
1079
  help="Specify the period (in days) for the FMA."
1080
  )
1081
 
1082
-
1083
- # Anchored Moving Average (AMA) with tooltip
1084
- #use_ama = st.sidebar.checkbox(
1085
- # 'Anchored Moving Average (AMA)',
1086
- # value=st.session_state.get('use_ama', False),
1087
- # help="Select to apply Anchored Moving Average (AMA) to the stock price."
1088
- #)
1089
- #ama_anchor_date = st.sidebar.date_input(
1090
- # 'AMA Anchor Date',
1091
- # value=pd.to_datetime(st.session_state.get('ama_anchor_date', '2021-01-01')),
1092
- # disabled=not use_ama,
1093
- # help="Select the anchor date for the AMA."
1094
- #)
1095
-
1096
-
1097
  # Grid toggle with tooltip
1098
  show_grid = st.sidebar.checkbox(
1099
  "Show Grid",
@@ -1176,11 +1165,8 @@ if 'data' in st.session_state:
1176
  st.session_state['use_cma'] = use_cma
1177
  st.session_state['use_mcginley_dynamic'] = use_mcginley_dynamic
1178
  st.session_state['mcginley_dynamic_period'] = mcginley_dynamic_period
1179
- #st.session_state['use_ama'] = use_ama
1180
- #st.session_state['ama_anchor_date'] = ama_anchor_date
1181
  st.session_state['use_fma'] = use_fma
1182
  st.session_state['fma_period'] = fma_period
1183
- # (Save all previous moving average settings here)
1184
 
1185
  # Start with the base price plot
1186
  fig = go.Figure(data=st.session_state['price_plot'].data)
@@ -1205,12 +1191,6 @@ if 'data' in st.session_state:
1205
  st.session_state['McGinley_Dynamic'] = calculate_mcginley_dynamic(data['Close'].tolist(), mcginley_dynamic_period)
1206
  fig.add_trace(go.Scatter(x=data.index, y=st.session_state['McGinley_Dynamic'], mode='lines', name=f'McGinley Dynamic (n={mcginley_dynamic_period})', line=dict(dash='dash', color='orange')))
1207
 
1208
- # Add AMA if selected
1209
- #if use_ama:
1210
- # st.session_state['AMA'] = calculate_AMA(data['Close'].tolist(), ama_anchor_date, data)
1211
- # fig.add_trace(go.Scatter(x=data.index, y=st.session_state['AMA'], mode='lines', name=f'Anchored MA (Anchor Date={ama_anchor_date})', line=dict(dash='dash', color='red')))
1212
- # fig.add_shape(type="line", x0=ama_anchor_date, y0=data['Close'].min(), x1=ama_anchor_date, y1=data['Close'].max(), line=dict(color="blue", width=2, dash="dash"))
1213
-
1214
  # Add FMA if selected
1215
  if use_fma:
1216
  st.session_state['FMA'] = filtered_moving_average(data['Close'].values, fma_period)
@@ -1385,7 +1365,6 @@ if 'data' in st.session_state:
1385
  st.session_state['PWMA'] = np.concatenate([np.array([np.nan]*(pwma_period-1)), pwma_values])
1386
  fig.add_trace(go.Scatter(x=data.index, y=st.session_state['PWMA'], mode='lines', name=f'PWMA (n={pwma_period})', line=dict(dash='dash', color='red')))
1387
 
1388
-
1389
  # Update layout with grid toggle
1390
  fig.update_layout(
1391
  title=f'{ticker_symbol} Stock Price with Moving Averages',
@@ -1404,9 +1383,6 @@ if 'data' in st.session_state:
1404
  if 'current_fig' in st.session_state:
1405
  st.plotly_chart(st.session_state['current_fig'], use_container_width=True)
1406
 
1407
-
1408
-
1409
-
1410
  st.markdown(
1411
  """
1412
  <style>
@@ -1419,11 +1395,10 @@ st.markdown(
1419
  unsafe_allow_html=True
1420
  )
1421
 
1422
-
1423
  hide_streamlit_style = """
1424
  <style>
1425
  #MainMenu {visibility: hidden;}
1426
  footer {visibility: hidden;}
1427
  </style>
1428
  """
1429
- st.markdown(hide_streamlit_style, unsafe_allow_html=True)
 
9
  from pandas_ta.utils import get_offset, verify_series
10
  from datetime import datetime
11
  from matplotlib.dates import date2num
 
12
 
13
  st.set_page_config(layout="wide")
14
 
 
35
  # Function to fetch data
36
  @st.cache_data
37
  def get_data(ticker, start_date, end_date):
38
+ data = yf.download(ticker, start=start_date, end=end_date, auto_adjust=False)
39
+ if isinstance(data.columns, pd.MultiIndex):
40
+ data.columns = data.columns.get_level_values(0)
41
+ if data.empty:
42
+ raise ValueError(f"No data retrieved for {ticker}")
43
+ if len(data) < 512: # Ensure enough data for largest possible Rainbow MA period
44
+ raise ValueError(f"Insufficient data points for {ticker}. Need at least 512 days.")
45
  return data
46
 
47
  # Function to create the base plot with the stock price
 
464
 
465
  # Fetch Data button
466
  if st.sidebar.button('Fetch Data'):
467
+ try:
468
+ # Only fetch if the ticker or date range has changed
469
+ if (
470
+ ticker_symbol != st.session_state.get('ticker_symbol') or
471
+ start_date != st.session_state.get('start_date') or
472
+ end_date != st.session_state.get('end_date')
473
+ ):
474
+ data = get_data(ticker_symbol, start_date, end_date)
475
+ st.session_state['data'] = data
476
+ st.session_state['ticker_symbol'] = ticker_symbol
477
+ st.session_state['start_date'] = start_date
478
+ st.session_state['end_date'] = end_date
479
+ st.session_state['price_plot'] = create_price_plot(data, ticker_symbol)
480
+ st.session_state['current_fig'] = st.session_state['price_plot']
481
+ except Exception as e:
482
+ st.error(f"An error occurred while fetching data: {e}")
483
 
484
  # Check if data is fetched and stored in session state
485
  if 'data' in st.session_state:
486
  data = st.session_state['data']
487
 
488
  # Moving average method selection
 
 
 
 
489
  # SMA with tooltip
490
  with st.sidebar.expander("Simple Moving Average", expanded=False):
491
  use_sma = st.checkbox(
 
1083
  help="Specify the period (in days) for the FMA."
1084
  )
1085
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1086
  # Grid toggle with tooltip
1087
  show_grid = st.sidebar.checkbox(
1088
  "Show Grid",
 
1165
  st.session_state['use_cma'] = use_cma
1166
  st.session_state['use_mcginley_dynamic'] = use_mcginley_dynamic
1167
  st.session_state['mcginley_dynamic_period'] = mcginley_dynamic_period
 
 
1168
  st.session_state['use_fma'] = use_fma
1169
  st.session_state['fma_period'] = fma_period
 
1170
 
1171
  # Start with the base price plot
1172
  fig = go.Figure(data=st.session_state['price_plot'].data)
 
1191
  st.session_state['McGinley_Dynamic'] = calculate_mcginley_dynamic(data['Close'].tolist(), mcginley_dynamic_period)
1192
  fig.add_trace(go.Scatter(x=data.index, y=st.session_state['McGinley_Dynamic'], mode='lines', name=f'McGinley Dynamic (n={mcginley_dynamic_period})', line=dict(dash='dash', color='orange')))
1193
 
 
 
 
 
 
 
1194
  # Add FMA if selected
1195
  if use_fma:
1196
  st.session_state['FMA'] = filtered_moving_average(data['Close'].values, fma_period)
 
1365
  st.session_state['PWMA'] = np.concatenate([np.array([np.nan]*(pwma_period-1)), pwma_values])
1366
  fig.add_trace(go.Scatter(x=data.index, y=st.session_state['PWMA'], mode='lines', name=f'PWMA (n={pwma_period})', line=dict(dash='dash', color='red')))
1367
 
 
1368
  # Update layout with grid toggle
1369
  fig.update_layout(
1370
  title=f'{ticker_symbol} Stock Price with Moving Averages',
 
1383
  if 'current_fig' in st.session_state:
1384
  st.plotly_chart(st.session_state['current_fig'], use_container_width=True)
1385
 
 
 
 
1386
  st.markdown(
1387
  """
1388
  <style>
 
1395
  unsafe_allow_html=True
1396
  )
1397
 
 
1398
  hide_streamlit_style = """
1399
  <style>
1400
  #MainMenu {visibility: hidden;}
1401
  footer {visibility: hidden;}
1402
  </style>
1403
  """
1404
+ st.markdown(hide_streamlit_style, unsafe_allow_html=True)