Summary
The project retrieves data from yahoo finance using yfinance. I added buttons to have options of selecting data for 1 month, 3 months, 1 year and so on. The user can also define his own dates using sliders. The problem is when a user selects a ticker and presses one of the buttons, he gets his result but if he needs to change the stock ticker everything resets to the dates in the sliders (the if statement in my code to which no button is pressed). Similarly, when the user presses the “download data” button to download the csv file everything goes to the same condition regardless of the button pressed before hitting the download button. Let’s say, the user downloads the data for 5 years (5Y) after pressing on the download button, the app refreshes afterwards and gets him back to the else statement where the range is the one present in the sliders. I understand that Streamlit refreshes the whole code when a button is clicked but I’d like to know if there is a possible fix for this. I guess it has to do with the “session-state” as I googled, but I couldn’t figure it out. I think it’s better to refer to the “stockapp.py” file in my GitHub repo to better understand the script.
Code snippet:
if b1:
stockretrieve(dt.date.today() - timedelta(days = 7))
elif b2:
stockretrieve(dt.date.today() - timedelta(days = 30))
elif b3:
stockretrieve(dt.date.today() - timedelta(days = 90))
elif b4:
stockretrieve(dt.date.today() - timedelta(days = 180))
elif b5:
todaysdate = dt.date.today()
startofyear = todaysdate.replace(month=1, day=1)
stockretrieve(startofyear)
elif b6:
stockretrieve(dt.date.today() - timedelta(days = 365))
elif b7:
stockretrieve(dt.date.today() - timedelta(days = 730))
elif b8:
stockretrieve(dt.date.today() - timedelta(days = 1825))
elif b9:
stockretrieve(dt.date.today() - timedelta(days = 3650))
elif b10:
stockretrieve(dt.date.today() - timedelta(days = 50000))
else:
stockretrieve(start_date)
Resources: