MarketCB / app.py
Harelkarni's picture
Update app.py
34d2240
raw
history blame contribute delete
No virus
7.81 kB
import json
import streamlit as st
import pandas as pd
import yfinance as yf
import matplotlib.pyplot as plt
import requests
url_stocks = "https://financialmodelingprep.com/api/v3/stock/list?apikey="
url_sentiment = "https://yaakovy-fin-proj-docker.hf.space/ticker/"
url_timeGpt = "https://ofirmatzlawi-fin-proj-docker-1.hf.space/ticker/"
url_forecast_eod = "https://yaakovy-lasthourforcast.hf.space/ticker/"
url_forecast_eod24 = "https://ofirmatzlawi-fin-proj-docker-2.hf.space/ticker/"
def get_max_sentiment(row):
if row["sentiment_score"] > 0.05: # Threshold for positive sentiment
return "positive"
elif row["sentiment_score"] < -0.05: # Threshold for negative sentiment
return "negative"
else:
return "neutral"
def get_sentiment_data(stock_info):
symbol = stock_info.info['symbol']
url_sentiment_with_ticker = f"{url_sentiment}{symbol}"
response = requests.get(url_sentiment_with_ticker)
if response.status_code == 200:
json_data = json.loads(response.json())
df = pd.DataFrame(json_data)
df['sentiment'] = df.apply(get_max_sentiment, axis=1)
df = df.drop(['neg', 'neu', 'pos', 'sentiment_score'], axis=1)
return df
else:
return
def print_sentiment(stock_info):
df = get_sentiment_data(stock_info)
#st.write("Market Sentiment")
st.dataframe(df, hide_index =True )
return df
def get_eod_forecast24(stock_info):
symbol = stock_info.info['symbol']
url_forecast_eod_with_ticker = f"{url_forecast_eod24}{symbol}"
response = requests.get(url_forecast_eod_with_ticker)
if response.status_code == 200:
eod_forecast = json.loads(response.json())
#st.write(json_data)
#eod_forecast = json_data["latest_prediction"]
return eod_forecast
else:
return
def get_eod_forecast(stock_info):
symbol = stock_info.info['symbol']
url_forecast_eod_with_ticker = f"{url_forecast_eod}{symbol}"
response = requests.get(url_forecast_eod_with_ticker)
if response.status_code == 200:
json_data = json.loads(response.json())
eod_forecast = json_data["latest_prediction"]
return eod_forecast
else:
return
def print_sentiment_summery(df) :
column_name = "sentiment"
category_counts = df[column_name].value_counts()
df_sentiment = pd.DataFrame({
"Sentiment": category_counts.index,
"Count": category_counts.values
})
st.dataframe(df_sentiment, hide_index =True )
return df_sentiment
def print_stock_info(stock_info):
stock_info_html = get_stock_info_from_html(stock_info.info)
st.write(stock_info_html, unsafe_allow_html=True)
plot_graph(stock_info)
col1, col2 = st.columns([0.8, 0.2])
with col1:
st.pyplot(plt)
with col2:
tf = st.radio(
"Select Time Frame",
["1Y", "3Y", "5Y", "10Y"], index=2,
key="chart_time_frame",
)
def get_stock_info_from_html(stock_info):
si = stock_info
text = (f"<b>Comp. Name: </b> {si['longName']}, {si['city']}, {si.get('state', '')} {si['country']} <br>"
f"<b>Web site: </b> <a href=\"{si['website']}\">{si['website']}</a> <br>"
f"<b>Stock Price: </b> {si['currentPrice']} {str(si['financialCurrency'])}")
return text
def get_forecast_html(stock_info):
currentPrice = stock_info.info['currentPrice']
eod_forecast = get_eod_forecast(stock_info)
eod_forecast_price = currentPrice * (1 + eod_forecast/100)
color = 'red' if eod_forecast < 0 else 'green'
mark = '+' if eod_forecast >= 0 else '-'
eod_forecast_p = abs(round(eod_forecast, 2))
html = (f"<b>Current Price: </b> {stock_info.info['currentPrice']} <br>"
f"<b>EOD Close Price: </b> <span style='color:{color};'> {eod_forecast_price:.2f} </span> &emsp; <span style='color:{color};'> {mark}{eod_forecast_p}% </span> ")
return html
def get_forecast_html24(stock_info):
currentPrice = stock_info.info['currentPrice']
eod_forecast = get_eod_forecast24(stock_info)
eod_forecast_price = currentPrice * (1 + eod_forecast/100)
color = 'red' if eod_forecast < 0 else 'green'
mark = '+' if eod_forecast >= 0 else '-'
eod_forecast_p = abs(round(eod_forecast, 2))
html = (f"<b>EOD Tomorrow Close Price: </b> <span style='color:{color};'> {eod_forecast_price:.2f} </span> &emsp; <span style='color:{color};'> {mark}{eod_forecast_p}% </span> ")
return html
def plot_graph(stock_info):
period = st.session_state.chart_time_frame or "5Y"
history = stock_info.history(period=period)
name = stock_info.info['longName']
plt.plot(history['Close'])
plt.xlabel('Date')
plt.ylabel('Price')
plt.title(f"{name} Stock Price")
return plt
def print_timeGpt(stock_info):
symbol = stock_info.info['symbol']
url_timeGpt_with_ticker = f"{url_timeGpt}{symbol}"
response = requests.get(url_timeGpt_with_ticker)
if response.status_code == 200:
json_data = json.loads(response.json())
#st.write(json_data)
json_data = json.loads(response.json())
data = json_data["data"]
converted_data = []
for row in data:
converted_data.append({"Date": row[0], "TimeGPT": row[1]})
df = pd.DataFrame(converted_data)
st.dataframe(df)
return df
else:
return
st.set_page_config(page_title="Senty Sense")
st.markdown(
"""
<style>
.appview-container .main .block-container {{
padding-top: {padding_top}rem;
padding-bottom: {padding_bottom}rem;
}}
</style>""".format(
padding_top=1, padding_bottom=1
),
unsafe_allow_html=True,
)
st.title('_SentySense_') #PriceProphet, Sentyment, Trendsetter Bullseye
par1 = "Our stock market platform gives you real-time data, historical insights, and in-depth news to help you make informed investment decisions."
st.write(par1, unsafe_allow_html=True)
if 'chart_time_frame' not in st.session_state:
st.session_state['chart_time_frame'] = '5Y'
if 'data_available' not in st.session_state:
st.session_state['data_available'] = False
option = 'Stocks' #st.selectbox("select", ["", "Currencies", "Stocks"], placeholder="Choose an option", label_visibility = "hidden")
if option == "Currencies":
input_text = "Enter currency pair"
else:
input_text = "Enter stock symbol"
text_box: str = None
btn_get_data = None
if option:
text_box = st.text_input(input_text)
with st.spinner('Wait for it...'):
if text_box:
ticker = text_box.upper()
try:
stock_info = yf.Ticker(ticker)
long_name = stock_info.info['longName']
st.write(f"<H4>{long_name}</H4>", unsafe_allow_html=True)
except:
st.error('Ticker not found', icon="🚨")
st.session_state['data_available'] = False
else:
st.session_state['data_available'] = True
print_stock_info(stock_info)
st.write(f"<H4>Market Sentiment</H4>", unsafe_allow_html=True)
df = print_sentiment(stock_info)
st.write(f"<H6>Sentiment summery</H6>", unsafe_allow_html=True)
print_sentiment_summery(df)
st.write(f"<H4>Forecasting</H4>", unsafe_allow_html=True)
st.write(get_forecast_html(stock_info), unsafe_allow_html=True)
st.write(get_forecast_html24(stock_info), unsafe_allow_html=True)
st.write("TimeGPT Monthly forecast")
print_timeGpt(stock_info)