DSProjectAlpha / app.py
Harelkarni's picture
Update app.py
53c15f8 verified
raw
history blame
5.26 kB
import time
import streamlit as st
import pandas as pd
import yfinance as yf
import matplotlib.pyplot as plt
import requests
import json
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/"
def get_max_sentiment(row):
max_value = max(row['neg'], row['neu'], row['pos'])
if max_value == row['neg']:
return 'neg'
elif max_value == row['neu']:
return 'neu'
else:
return 'pos'
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 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 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)
df = print_sentiment(stock_info)
st.write('Sentiment summery')
print_sentiment_summery(df)
st.write('Prediction')
print_timeGpt(stock_info)