File size: 7,808 Bytes
acd39d4
6e5474c
 
 
 
 
4d2bcc0
acd39d4
53c15f8
6e5474c
53c15f8
6735566
518407c
6735566
6e5474c
d751ea4
 
 
 
6e5474c
d751ea4
4d2bcc0
6e5474c
 
 
 
 
 
 
 
 
 
 
 
 
 
6735566
6e5474c
 
6735566
6e5474c
3bb6db2
6735566
 
518407c
 
 
 
 
 
 
 
 
 
 
 
6735566
 
 
 
 
 
518407c
6735566
 
 
 
 
 
3bb6db2
 
 
 
 
 
 
 
 
53c15f8
6e5474c
 
 
 
 
 
 
 
 
 
 
 
3bb6db2
6e5474c
 
 
 
 
d50a99d
6e5474c
 
 
 
518407c
 
6735566
 
 
 
 
 
 
 
 
 
 
 
 
518407c
 
 
 
 
 
 
 
 
 
 
6735566
6e5474c
 
 
 
 
 
 
 
 
 
53c15f8
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
d76be43
53c15f8
d76be43
 
 
 
 
 
 
 
 
 
 
 
 
 
3bb6db2
c141d0b
 
 
6e5474c
 
 
 
 
 
 
3bb6db2
6e5474c
 
 
 
 
 
 
 
 
 
3bb6db2
6e5474c
3bb6db2
6e5474c
 
 
 
 
3bb6db2
 
6e5474c
 
 
 
6735566
6e5474c
6735566
3bb6db2
6735566
3bb6db2
518407c
 
e74b3d3
34d2240
e74b3d3
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
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)