Spaces:
Runtime error
Runtime error
Commit
•
6735566
1
Parent(s):
4d2bcc0
Update app.py
Browse files
app.py
CHANGED
@@ -1,4 +1,3 @@
|
|
1 |
-
import time
|
2 |
import streamlit as st
|
3 |
import pandas as pd
|
4 |
import yfinance as yf
|
@@ -6,69 +5,19 @@ import matplotlib.pyplot as plt
|
|
6 |
import requests
|
7 |
import json
|
8 |
|
9 |
-
|
10 |
-
|
11 |
import pandas as pd
|
12 |
|
13 |
-
import nltk
|
14 |
-
nltk.downloader.download("vader_lexicon")
|
15 |
-
from nltk.sentiment.vader import SentimentIntensityAnalyzer
|
16 |
-
|
17 |
-
|
18 |
|
19 |
|
20 |
url_stocks = "https://financialmodelingprep.com/api/v3/stock/list?apikey="
|
21 |
url_sentiment = "https://yaakovy-fin-proj-docker.hf.space/ticker/"
|
22 |
url_timeGpt = "https://ofirmatzlawi-fin-proj-docker-1.hf.space/ticker/"
|
23 |
-
|
24 |
|
25 |
|
26 |
-
|
27 |
-
url = finviz_url + ticker
|
28 |
-
req = Request(
|
29 |
-
url=url,
|
30 |
-
headers={
|
31 |
-
"User-Agent": "Mozilla/5.0 (Windows NT 6.1; WOW64; rv:20.0) Gecko/20100101 Firefox/20.0"
|
32 |
-
},
|
33 |
-
)
|
34 |
-
response = urlopen(req)
|
35 |
-
if response.status != 200: # Check the response status code
|
36 |
-
raise Exception("Failed to fetch news table")
|
37 |
-
html = BeautifulSoup(response) # Read the contents of the file into 'html'
|
38 |
-
news_table = html.find(id="news-table") # Find 'news-table' in the Soup and load it into 'news_table'
|
39 |
-
return news_table
|
40 |
-
|
41 |
-
|
42 |
-
def parse_news(news_table):
|
43 |
-
parsed_news = []
|
44 |
-
today_string = datetime.datetime.today().strftime("%Y-%m-%d")
|
45 |
-
|
46 |
-
for x in news_table.findAll("tr"):
|
47 |
-
try:
|
48 |
-
# read the text from each tr tag into text
|
49 |
-
text = x.a.get_text() # get text from a only
|
50 |
-
date_scrape = x.td.text.split() # splite text in the td tag into a list
|
51 |
-
if len(date_scrape) == 1: # if the length of 'date_scrape' is 1, load 'time' as the only element
|
52 |
-
time = date_scrape[0]
|
53 |
-
# else load 'date' as the 1st element and 'time' as the second
|
54 |
-
else:
|
55 |
-
date = date_scrape[0]
|
56 |
-
time = date_scrape[1]
|
57 |
-
parsed_news.append([date, time, text]) # Append ticker, date, time and headline as a list to the 'parsed_news' list
|
58 |
-
except:
|
59 |
-
pass
|
60 |
-
columns = ["date", "time", "headline"]
|
61 |
-
parsed_news_df = pd.DataFrame(parsed_news, columns=columns) # Convert the parsed_news list into a DataFrame called 'parsed_and_scored_news'
|
62 |
-
return parsed_news_df
|
63 |
-
|
64 |
-
def score_news(parsed_news_df):
|
65 |
-
vader = SentimentIntensityAnalyzer() # Instantiate the sentiment intensity analyzer
|
66 |
-
scores = parsed_news_df["headline"].apply(vader.polarity_scores).tolist() # Iterate through the headlines and get the polarity scores using vader
|
67 |
-
scores_df = pd.DataFrame(scores) # Convert the 'scores' list of dicts into a DataFrame
|
68 |
-
parsed_and_scored_news = parsed_news_df.join(scores_df, rsuffix="_right") # Join the DataFrames of the news and the list of dicts
|
69 |
-
parsed_and_scored_news = parsed_and_scored_news.rename(columns={"compound": "sentiment"})
|
70 |
-
return parsed_and_scored_news
|
71 |
-
|
72 |
def get_max_sentiment(row):
|
73 |
if row["sentiment_score"] > 0.05: # Threshold for positive sentiment
|
74 |
return "positive"
|
@@ -92,13 +41,28 @@ def get_sentiment_data(stock_info):
|
|
92 |
else:
|
93 |
return
|
94 |
|
|
|
95 |
def print_sentiment(stock_info):
|
96 |
df = get_sentiment_data(stock_info)
|
97 |
-
st.write("Market Sentiment")
|
98 |
st.dataframe(df, hide_index =True )
|
99 |
return df
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
100 |
|
101 |
-
|
|
|
|
|
102 |
column_name = "sentiment"
|
103 |
category_counts = df[column_name].value_counts()
|
104 |
df_sentiment = pd.DataFrame({
|
@@ -127,12 +91,29 @@ def print_stock_info(stock_info):
|
|
127 |
|
128 |
def get_stock_info_from_html(stock_info):
|
129 |
si = stock_info
|
130 |
-
|
131 |
text = (f"<b>Comp. Name: </b> {si['longName']}, {si['city']}, {si.get('state', '')} {si['country']} <br>"
|
132 |
f"<b>Web site: </b> <a href=\"{si['website']}\">{si['website']}</a> <br>"
|
133 |
f"<b>Stock Price: </b> {si['currentPrice']} {str(si['financialCurrency'])}")
|
134 |
return text
|
135 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
136 |
def plot_graph(stock_info):
|
137 |
period = st.session_state.chart_time_frame or "5Y"
|
138 |
history = stock_info.history(period=period)
|
@@ -177,7 +158,6 @@ st.markdown(
|
|
177 |
padding-top: {padding_top}rem;
|
178 |
padding-bottom: {padding_bottom}rem;
|
179 |
}}
|
180 |
-
|
181 |
</style>""".format(
|
182 |
padding_top=1, padding_bottom=1
|
183 |
),
|
@@ -221,15 +201,17 @@ with st.spinner('Wait for it...'):
|
|
221 |
st.error('Ticker not found', icon="🚨")
|
222 |
st.session_state['data_available'] = False
|
223 |
else:
|
224 |
-
|
225 |
-
st.session_state['data_available'] = True
|
226 |
print_stock_info(stock_info)
|
|
|
227 |
df = print_sentiment(stock_info)
|
228 |
-
st.write(
|
229 |
print_sentiment_summery(df)
|
230 |
-
st.write(
|
231 |
-
|
232 |
-
|
233 |
-
|
234 |
-
|
|
|
|
|
235 |
|
|
|
|
|
1 |
import streamlit as st
|
2 |
import pandas as pd
|
3 |
import yfinance as yf
|
|
|
5 |
import requests
|
6 |
import json
|
7 |
|
8 |
+
|
9 |
+
|
10 |
import pandas as pd
|
11 |
|
|
|
|
|
|
|
|
|
|
|
12 |
|
13 |
|
14 |
url_stocks = "https://financialmodelingprep.com/api/v3/stock/list?apikey="
|
15 |
url_sentiment = "https://yaakovy-fin-proj-docker.hf.space/ticker/"
|
16 |
url_timeGpt = "https://ofirmatzlawi-fin-proj-docker-1.hf.space/ticker/"
|
17 |
+
url_forecast_eod = "https://yaakovy-lasthourforcast.hf.space/ticker/"
|
18 |
|
19 |
|
20 |
+
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
21 |
def get_max_sentiment(row):
|
22 |
if row["sentiment_score"] > 0.05: # Threshold for positive sentiment
|
23 |
return "positive"
|
|
|
41 |
else:
|
42 |
return
|
43 |
|
44 |
+
|
45 |
def print_sentiment(stock_info):
|
46 |
df = get_sentiment_data(stock_info)
|
47 |
+
#st.write("Market Sentiment")
|
48 |
st.dataframe(df, hide_index =True )
|
49 |
return df
|
50 |
+
|
51 |
+
|
52 |
+
def get_eod_forecast(stock_info):
|
53 |
+
symbol = stock_info.info['symbol']
|
54 |
+
url_forecast_eod_with_ticker = f"{url_forecast_eod}{symbol}"
|
55 |
+
response = requests.get(url_forecast_eod_with_ticker)
|
56 |
+
if response.status_code == 200:
|
57 |
+
json_data = json.loads(response.json())
|
58 |
+
eod_forecast = json_data["latest_prediction"]
|
59 |
+
return eod_forecast
|
60 |
+
else:
|
61 |
+
return
|
62 |
|
63 |
+
|
64 |
+
|
65 |
+
def print_sentiment_summery(df) :
|
66 |
column_name = "sentiment"
|
67 |
category_counts = df[column_name].value_counts()
|
68 |
df_sentiment = pd.DataFrame({
|
|
|
91 |
|
92 |
def get_stock_info_from_html(stock_info):
|
93 |
si = stock_info
|
|
|
94 |
text = (f"<b>Comp. Name: </b> {si['longName']}, {si['city']}, {si.get('state', '')} {si['country']} <br>"
|
95 |
f"<b>Web site: </b> <a href=\"{si['website']}\">{si['website']}</a> <br>"
|
96 |
f"<b>Stock Price: </b> {si['currentPrice']} {str(si['financialCurrency'])}")
|
97 |
return text
|
98 |
|
99 |
+
def get_forecast_html(stock_info):
|
100 |
+
|
101 |
+
currentPrice = stock_info.info['currentPrice']
|
102 |
+
eod_forecast = get_eod_forecast(stock_info)
|
103 |
+
#st.write(eod_forecast)
|
104 |
+
#eod_forecast = float(get_eod_forecast(stock_info))
|
105 |
+
#st.write(type(eod_forecast))
|
106 |
+
eod_forecast_price = currentPrice * (1 + eod_forecast/100)
|
107 |
+
color = 'red' if eod_forecast < 0 else 'green'
|
108 |
+
mark = '+' if eod_forecast >= 0 else '-'
|
109 |
+
eod_forecast_p = abs(round(eod_forecast, 2))
|
110 |
+
html = (f"<b>Current Price: </b> {stock_info.info['currentPrice']} <br>"
|
111 |
+
f"<b>EOD Close Price: </b> <span style='color:{color};'> {eod_forecast_price:.2f} </span>   <span style='color:{color};'> {mark}{eod_forecast_p}% </span> ")
|
112 |
+
|
113 |
+
return html
|
114 |
+
|
115 |
+
|
116 |
+
|
117 |
def plot_graph(stock_info):
|
118 |
period = st.session_state.chart_time_frame or "5Y"
|
119 |
history = stock_info.history(period=period)
|
|
|
158 |
padding-top: {padding_top}rem;
|
159 |
padding-bottom: {padding_bottom}rem;
|
160 |
}}
|
|
|
161 |
</style>""".format(
|
162 |
padding_top=1, padding_bottom=1
|
163 |
),
|
|
|
201 |
st.error('Ticker not found', icon="🚨")
|
202 |
st.session_state['data_available'] = False
|
203 |
else:
|
204 |
+
st.session_state['data_available'] = True
|
|
|
205 |
print_stock_info(stock_info)
|
206 |
+
st.write(f"<H4>Market Sentiment</H4>", unsafe_allow_html=True)
|
207 |
df = print_sentiment(stock_info)
|
208 |
+
st.write(f"<H6>Sentiment summery</H6>", unsafe_allow_html=True)
|
209 |
print_sentiment_summery(df)
|
210 |
+
st.write(f"<H4>Prediction</H4>", unsafe_allow_html=True)
|
211 |
+
st.write(get_forecast_html(stock_info), unsafe_allow_html=True)
|
212 |
+
|
213 |
+
|
214 |
+
#st.write(stock_info)
|
215 |
+
#st.write(eod_forecast)
|
216 |
+
#print_timeGpt(stock_info)
|
217 |
|