Spaces:
Sleeping
Sleeping
Update app.py
Browse files
app.py
CHANGED
@@ -1,512 +1,491 @@
|
|
1 |
-
import streamlit as st
|
2 |
-
import sqlite3
|
3 |
-
import hashlib
|
4 |
-
import threading
|
5 |
-
import pygame
|
6 |
-
from yfinance import Ticker
|
7 |
-
import pandas as pd
|
8 |
-
import plotly.express as px
|
9 |
-
import requests
|
10 |
-
|
11 |
-
import
|
12 |
-
|
13 |
-
import
|
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 |
-
username
|
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 |
-
conn.
|
98 |
-
|
99 |
-
|
100 |
-
# Ensure
|
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 |
-
username
|
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 |
-
return
|
200 |
-
|
201 |
-
|
202 |
-
|
203 |
-
|
204 |
-
return amount
|
205 |
-
|
206 |
-
|
207 |
-
|
208 |
-
|
209 |
-
|
210 |
-
|
211 |
-
|
212 |
-
|
213 |
-
|
214 |
-
|
215 |
-
|
216 |
-
|
217 |
-
|
218 |
-
|
219 |
-
|
220 |
-
|
221 |
-
|
222 |
-
|
223 |
-
|
224 |
-
|
225 |
-
|
226 |
-
|
227 |
-
|
228 |
-
|
229 |
-
|
230 |
-
|
231 |
-
|
232 |
-
|
233 |
-
|
234 |
-
|
235 |
-
|
236 |
-
|
237 |
-
|
238 |
-
|
239 |
-
|
240 |
-
|
241 |
-
|
242 |
-
|
243 |
-
|
244 |
-
|
245 |
-
|
246 |
-
|
247 |
-
|
248 |
-
|
249 |
-
|
250 |
-
|
251 |
-
|
252 |
-
|
253 |
-
|
254 |
-
|
255 |
-
|
256 |
-
|
257 |
-
|
258 |
-
|
259 |
-
|
260 |
-
|
261 |
-
|
262 |
-
|
263 |
-
|
264 |
-
|
265 |
-
|
266 |
-
|
267 |
-
|
268 |
-
|
269 |
-
|
270 |
-
|
271 |
-
|
272 |
-
|
273 |
-
|
274 |
-
|
275 |
-
|
276 |
-
|
277 |
-
|
278 |
-
|
279 |
-
|
280 |
-
|
281 |
-
|
282 |
-
|
283 |
-
|
284 |
-
|
285 |
-
|
286 |
-
|
287 |
-
|
288 |
-
|
289 |
-
|
290 |
-
|
291 |
-
|
292 |
-
|
293 |
-
|
294 |
-
|
295 |
-
|
296 |
-
|
297 |
-
|
298 |
-
|
299 |
-
|
300 |
-
|
301 |
-
|
302 |
-
|
303 |
-
|
304 |
-
|
305 |
-
|
306 |
-
|
307 |
-
|
308 |
-
|
309 |
-
|
310 |
-
|
311 |
-
|
312 |
-
|
313 |
-
|
314 |
-
|
315 |
-
|
316 |
-
|
317 |
-
|
318 |
-
|
319 |
-
|
320 |
-
|
321 |
-
|
322 |
-
|
323 |
-
|
324 |
-
|
325 |
-
|
326 |
-
|
327 |
-
|
328 |
-
|
329 |
-
|
330 |
-
|
331 |
-
|
332 |
-
|
333 |
-
|
334 |
-
|
335 |
-
|
336 |
-
|
337 |
-
|
338 |
-
|
339 |
-
|
340 |
-
|
341 |
-
|
342 |
-
|
343 |
-
|
344 |
-
|
345 |
-
|
346 |
-
|
347 |
-
|
348 |
-
|
349 |
-
|
350 |
-
|
351 |
-
|
352 |
-
|
353 |
-
|
354 |
-
|
355 |
-
|
356 |
-
|
357 |
-
|
358 |
-
|
359 |
-
|
360 |
-
|
361 |
-
|
362 |
-
|
363 |
-
|
364 |
-
|
365 |
-
|
366 |
-
|
367 |
-
|
368 |
-
|
369 |
-
|
370 |
-
|
371 |
-
|
372 |
-
|
373 |
-
|
374 |
-
|
375 |
-
|
376 |
-
|
377 |
-
|
378 |
-
|
379 |
-
|
380 |
-
|
381 |
-
|
382 |
-
|
383 |
-
|
384 |
-
|
385 |
-
|
386 |
-
|
387 |
-
|
388 |
-
|
389 |
-
|
390 |
-
|
391 |
-
|
392 |
-
|
393 |
-
|
394 |
-
|
395 |
-
|
396 |
-
|
397 |
-
|
398 |
-
|
399 |
-
|
400 |
-
|
401 |
-
|
402 |
-
|
403 |
-
|
404 |
-
|
405 |
-
|
406 |
-
|
407 |
-
|
408 |
-
|
409 |
-
|
410 |
-
if
|
411 |
-
st.
|
412 |
-
|
413 |
-
|
414 |
-
|
415 |
-
|
416 |
-
|
417 |
-
|
418 |
-
|
419 |
-
|
420 |
-
|
421 |
-
|
422 |
-
|
423 |
-
|
424 |
-
|
425 |
-
|
426 |
-
|
427 |
-
|
428 |
-
|
429 |
-
|
430 |
-
|
431 |
-
|
432 |
-
|
433 |
-
|
434 |
-
|
435 |
-
|
436 |
-
|
437 |
-
|
438 |
-
|
439 |
-
|
440 |
-
|
441 |
-
|
442 |
-
|
443 |
-
|
444 |
-
|
445 |
-
|
446 |
-
|
447 |
-
|
448 |
-
|
449 |
-
|
450 |
-
|
451 |
-
|
452 |
-
|
453 |
-
|
454 |
-
|
455 |
-
|
456 |
-
|
457 |
-
|
458 |
-
|
459 |
-
|
460 |
-
|
461 |
-
|
462 |
-
|
463 |
-
|
464 |
-
|
465 |
-
|
466 |
-
|
467 |
-
|
468 |
-
|
469 |
-
|
470 |
-
|
471 |
-
|
472 |
-
|
473 |
-
|
474 |
-
|
475 |
-
|
476 |
-
|
477 |
-
|
478 |
-
|
479 |
-
|
480 |
-
|
481 |
-
|
482 |
-
|
483 |
-
|
484 |
-
|
485 |
-
|
486 |
-
|
487 |
-
|
488 |
-
|
489 |
-
|
490 |
-
|
491 |
-
|
492 |
-
st.write("No data available for this ticker.")
|
493 |
-
|
494 |
-
st.markdown('<div class="sub-title">Stock Market News</div>', unsafe_allow_html=True)
|
495 |
-
news_ticker = st.text_input("Enter Stock Ticker for News")
|
496 |
-
news_api_key = st.text_input("Enter NewsAPI Key")
|
497 |
-
if st.button("Get News"):
|
498 |
-
if news_api_key:
|
499 |
-
newsapi = NewsApiClient(api_key=news_api_key)
|
500 |
-
articles = newsapi.get_everything(q=news_ticker, language='en', sort_by='publishedAt', page_size=5)
|
501 |
-
if articles:
|
502 |
-
for article in articles['articles']:
|
503 |
-
st.subheader(article['title'])
|
504 |
-
st.write(article['description'])
|
505 |
-
st.write(f"[Read more]({article['url']})")
|
506 |
-
else:
|
507 |
-
st.write("No news available for this ticker.")
|
508 |
-
else:
|
509 |
-
st.write("Please enter a valid NewsAPI key.")
|
510 |
-
|
511 |
-
if __name__ == "__main__":
|
512 |
-
main()
|
|
|
1 |
+
import streamlit as st
|
2 |
+
import sqlite3
|
3 |
+
import hashlib
|
4 |
+
import threading
|
5 |
+
import pygame
|
6 |
+
from yfinance import Ticker
|
7 |
+
import pandas as pd
|
8 |
+
import plotly.express as px
|
9 |
+
import requests
|
10 |
+
import os
|
11 |
+
from pathlib import Path
|
12 |
+
import base64
|
13 |
+
from datetime import datetime
|
14 |
+
import time
|
15 |
+
|
16 |
+
# Constants
|
17 |
+
INITIAL_BALANCE = 10000
|
18 |
+
UPDATE_INTERVAL = 60
|
19 |
+
DEFAULT_CURRENCY = 'USD'
|
20 |
+
STOCK_LIST = ["AAPL", "MSFT", "GOOGL", "AMZN", "TSLA", "META", "NVDA", "BRK-B", "V", "JPM"]
|
21 |
+
TIME_RANGES = {
|
22 |
+
'1 Day': '1d',
|
23 |
+
'5 Days': '5d',
|
24 |
+
'1 Month': '1mo',
|
25 |
+
'3 Months': '3mo',
|
26 |
+
'6 Months': '6mo',
|
27 |
+
'1 Year': '1y',
|
28 |
+
'5 Years': '5y',
|
29 |
+
'10 Years': '10y',
|
30 |
+
'Max': 'max'
|
31 |
+
}
|
32 |
+
CURRENCIES = ["USD", "EUR", "GBP", "JPY", "AUD"]
|
33 |
+
|
34 |
+
# Initialize pygame for music
|
35 |
+
def initialize_music():
|
36 |
+
if 'music_initialized' not in st.session_state:
|
37 |
+
try:
|
38 |
+
pygame.mixer.init()
|
39 |
+
pygame.mixer.music.load('trade.mp3')
|
40 |
+
pygame.mixer.music.play(-1)
|
41 |
+
st.session_state['music_initialized'] = True
|
42 |
+
except pygame.error as e:
|
43 |
+
st.error(f"Failed to load or play the music: {str(e)}. Please check that 'trade.mp3' exists in the correct directory.")
|
44 |
+
|
45 |
+
# Database setup
|
46 |
+
def setup_database():
|
47 |
+
conn = sqlite3.connect('trading_game.db', check_same_thread=False)
|
48 |
+
cursor = conn.cursor()
|
49 |
+
|
50 |
+
# Create tables if they don't exist
|
51 |
+
cursor.execute('''
|
52 |
+
CREATE TABLE IF NOT EXISTS users (
|
53 |
+
username TEXT PRIMARY KEY,
|
54 |
+
password TEXT,
|
55 |
+
balance REAL,
|
56 |
+
initial_balance REAL,
|
57 |
+
currency TEXT DEFAULT 'USD'
|
58 |
+
)
|
59 |
+
''')
|
60 |
+
|
61 |
+
cursor.execute('''
|
62 |
+
CREATE TABLE IF NOT EXISTS portfolios (
|
63 |
+
username TEXT,
|
64 |
+
ticker TEXT,
|
65 |
+
shares REAL,
|
66 |
+
initial_investment REAL,
|
67 |
+
PRIMARY KEY (username, ticker),
|
68 |
+
FOREIGN KEY (username) REFERENCES users (username)
|
69 |
+
)
|
70 |
+
''')
|
71 |
+
|
72 |
+
cursor.execute('''
|
73 |
+
CREATE TABLE IF NOT EXISTS financial_logs (
|
74 |
+
username TEXT,
|
75 |
+
timestamp DATETIME DEFAULT CURRENT_TIMESTAMP,
|
76 |
+
total_value REAL,
|
77 |
+
FOREIGN KEY (username) REFERENCES users (username)
|
78 |
+
)
|
79 |
+
''')
|
80 |
+
|
81 |
+
cursor.execute('''
|
82 |
+
CREATE TABLE IF NOT EXISTS transactions (
|
83 |
+
username TEXT,
|
84 |
+
action TEXT,
|
85 |
+
ticker TEXT,
|
86 |
+
amount REAL,
|
87 |
+
price REAL,
|
88 |
+
timestamp DATETIME DEFAULT CURRENT_TIMESTAMP
|
89 |
+
)
|
90 |
+
''')
|
91 |
+
|
92 |
+
conn.commit()
|
93 |
+
return conn
|
94 |
+
|
95 |
+
# Ensure Database Schema
|
96 |
+
def ensure_database_schema():
|
97 |
+
conn = sqlite3.connect('trading_game.db')
|
98 |
+
c = conn.cursor()
|
99 |
+
|
100 |
+
# Ensure the users table exists and has the required columns
|
101 |
+
c.execute('''
|
102 |
+
CREATE TABLE IF NOT EXISTS users (
|
103 |
+
username TEXT PRIMARY KEY,
|
104 |
+
password TEXT,
|
105 |
+
balance REAL,
|
106 |
+
initial_balance REAL,
|
107 |
+
currency TEXT DEFAULT 'USD'
|
108 |
+
)
|
109 |
+
''')
|
110 |
+
|
111 |
+
# Check if the initial_balance column exists, if not, add it
|
112 |
+
c.execute("PRAGMA table_info(users)")
|
113 |
+
columns = [column[1] for column in c.fetchall()]
|
114 |
+
if 'initial_balance' not in columns:
|
115 |
+
c.execute(f"ALTER TABLE users ADD COLUMN initial_balance REAL DEFAULT {INITIAL_BALANCE}")
|
116 |
+
conn.commit()
|
117 |
+
|
118 |
+
# Ensure the portfolios table exists and has the required columns
|
119 |
+
c.execute('''
|
120 |
+
CREATE TABLE IF NOT EXISTS portfolios (
|
121 |
+
username TEXT,
|
122 |
+
ticker TEXT,
|
123 |
+
shares REAL,
|
124 |
+
initial_investment REAL,
|
125 |
+
PRIMARY KEY (username, ticker),
|
126 |
+
FOREIGN KEY (username) REFERENCES users (username)
|
127 |
+
)
|
128 |
+
''')
|
129 |
+
|
130 |
+
# Check if the initial_investment column exists, if not, add it
|
131 |
+
c.execute("PRAGMA table_info(portfolios)")
|
132 |
+
columns = [column[1] for column in c.fetchall()]
|
133 |
+
if 'initial_investment' not in columns:
|
134 |
+
c.execute(f"ALTER TABLE portfolios ADD COLUMN initial_investment REAL")
|
135 |
+
conn.commit()
|
136 |
+
|
137 |
+
conn.close()
|
138 |
+
|
139 |
+
# Function to hash passwords
|
140 |
+
def hash_password(password):
|
141 |
+
return hashlib.sha256(password.encode()).hexdigest()
|
142 |
+
|
143 |
+
# Function to set the background image
|
144 |
+
def set_background_image(image_path):
|
145 |
+
if Path(image_path).exists():
|
146 |
+
try:
|
147 |
+
with open(image_path, "rb") as img_file:
|
148 |
+
encoded_img = base64.b64encode(img_file.read()).decode('utf-8')
|
149 |
+
st.markdown(
|
150 |
+
f"""
|
151 |
+
<style>
|
152 |
+
.stApp {{
|
153 |
+
position: relative;
|
154 |
+
background-image: url(data:image/png;base64,{encoded_img});
|
155 |
+
background-size: cover;
|
156 |
+
background-position: center;
|
157 |
+
background-repeat: no-repeat;
|
158 |
+
}}
|
159 |
+
.stApp::before {{
|
160 |
+
content: '';
|
161 |
+
position: absolute;
|
162 |
+
top: 0;
|
163 |
+
left: 0;
|
164 |
+
right: 0;
|
165 |
+
bottom: 0;
|
166 |
+
background-color: rgba(255, 255, 255, 0.8); /* White overlay with 0.8 opacity */
|
167 |
+
z-index: 0;
|
168 |
+
}}
|
169 |
+
.main-title, .sub-title, .metric-box, .blue-background {{
|
170 |
+
position: relative;
|
171 |
+
z-index: 1;
|
172 |
+
}}
|
173 |
+
</style>
|
174 |
+
""",
|
175 |
+
unsafe_allow_html=True
|
176 |
+
)
|
177 |
+
except Exception as e:
|
178 |
+
st.error(f"Error loading image: {str(e)}")
|
179 |
+
else:
|
180 |
+
st.error('Image not found. Please check the file name and path.')
|
181 |
+
|
182 |
+
# Function to fetch the current price of stocks or currencies
|
183 |
+
def get_stock_data(ticker, period='1d'):
|
184 |
+
try:
|
185 |
+
stock = Ticker(ticker)
|
186 |
+
df = stock.history(period=period)
|
187 |
+
if not df.empty:
|
188 |
+
df.reset_index(inplace=True)
|
189 |
+
return df
|
190 |
+
else:
|
191 |
+
return None
|
192 |
+
except Exception as e:
|
193 |
+
print(f"Error fetching data: {str(e)}")
|
194 |
+
return None
|
195 |
+
|
196 |
+
# Function to convert currency
|
197 |
+
def convert_currency(amount, from_currency, to_currency):
|
198 |
+
if from_currency == to_currency:
|
199 |
+
return amount
|
200 |
+
try:
|
201 |
+
response = requests.get(f'https://api.exchangerate-api.com/v4/latest/{from_currency}')
|
202 |
+
rates = response.json()['rates']
|
203 |
+
conversion_rate = rates.get(to_currency, 1)
|
204 |
+
return amount * conversion_rate
|
205 |
+
except Exception as e:
|
206 |
+
print(f"Error converting currency: {str(e)}")
|
207 |
+
return amount
|
208 |
+
|
209 |
+
# Function to get market status
|
210 |
+
def get_market_status():
|
211 |
+
market_status = {}
|
212 |
+
for ticker in STOCK_LIST:
|
213 |
+
df = get_stock_data(ticker, period='1d')
|
214 |
+
if df is not None:
|
215 |
+
open_price = df['Open'].iloc[0]
|
216 |
+
current_price = df['Close'].iloc[-1]
|
217 |
+
change = (current_price - open_price) / open_price * 100
|
218 |
+
market_status[ticker] = change
|
219 |
+
return market_status
|
220 |
+
|
221 |
+
# Function to fetch and plot historical data for holdings
|
222 |
+
def plot_holdings(holdings, time_range):
|
223 |
+
fig = px.line(title=f"Holdings - {time_range}")
|
224 |
+
for ticker in holdings:
|
225 |
+
df = get_stock_data(ticker, period=TIME_RANGES[time_range])
|
226 |
+
if df is not None and not df.empty:
|
227 |
+
initial_investment = holdings[ticker]['initial_investment']
|
228 |
+
fig.add_scatter(x=df['Date'], y=df['Close'], mode='lines', name=f"{ticker} (Invested: ${initial_investment:.2f})")
|
229 |
+
st.plotly_chart(fig, use_container_width=True)
|
230 |
+
|
231 |
+
# Function to display the market overview ticker
|
232 |
+
def market_overview_ticker(market_status):
|
233 |
+
ticker_text = ''.join([
|
234 |
+
f"<span style='color: {'green' if change > 0 else 'red'};'>{ticker}: {change:.2f}%</span> | "
|
235 |
+
for ticker, change in market_status.items()
|
236 |
+
])
|
237 |
+
st.markdown(f"""
|
238 |
+
<style>
|
239 |
+
.ticker {{
|
240 |
+
overflow: hidden;
|
241 |
+
white-space: nowrap;
|
242 |
+
width: 100%;
|
243 |
+
background-color: black;
|
244 |
+
color: white;
|
245 |
+
padding: 5px;
|
246 |
+
font-size: 14px;
|
247 |
+
}}
|
248 |
+
.ticker span {{
|
249 |
+
display: inline-block;
|
250 |
+
animation: ticker 20s linear infinite;
|
251 |
+
}}
|
252 |
+
@keyframes ticker {{
|
253 |
+
0% {{ transform: translateX(100%); }}
|
254 |
+
100% {{ transform: translateX(-100%); }}
|
255 |
+
}}
|
256 |
+
</style>
|
257 |
+
<div class="ticker">
|
258 |
+
<span>{ticker_text}</span>
|
259 |
+
</div>
|
260 |
+
""", unsafe_allow_html=True)
|
261 |
+
|
262 |
+
# Function to fetch currency values
|
263 |
+
def get_currency_values():
|
264 |
+
currencies = ['EUR', 'GBP', 'JPY', 'AUD']
|
265 |
+
currency_data = {}
|
266 |
+
for currency in currencies:
|
267 |
+
rate = convert_currency(1, 'USD', currency)
|
268 |
+
currency_data[currency] = rate
|
269 |
+
return currency_data
|
270 |
+
|
271 |
+
# Function to fetch gold price from yfinance
|
272 |
+
def get_gold_price():
|
273 |
+
gold_ticker = Ticker("GC=F")
|
274 |
+
df = gold_ticker.history(period="1d")
|
275 |
+
if not df.empty:
|
276 |
+
return df['Close'].iloc[-1]
|
277 |
+
else:
|
278 |
+
st.error("Failed to fetch the goldprice.")
|
279 |
+
return None
|
280 |
+
|
281 |
+
# Function to display currency and gold values
|
282 |
+
def display_currency_and_gold():
|
283 |
+
st.markdown('<div class="sub-title">Currency and Gold Values</div>', unsafe_allow_html=True)
|
284 |
+
currency_data = get_currency_values()
|
285 |
+
gold_price = get_gold_price()
|
286 |
+
for currency, value in currency_data.items():
|
287 |
+
st.markdown(f'<div class="metric-box">{currency}/USD: {value:.2f}</div>', unsafe_allow_html=True)
|
288 |
+
if gold_price:
|
289 |
+
st.markdown(f'<div class="metric-box">Gold/USD: ${gold_price:.2f}</div>', unsafe_allow_html=True)
|
290 |
+
|
291 |
+
# Function to display the user's financial overview
|
292 |
+
def display_financial_overview(username, conn):
|
293 |
+
st.subheader("Your Financial Overview")
|
294 |
+
total_value, invested_value, initial_balance = calculate_total_value(username, conn)
|
295 |
+
st.markdown(f'<div class="metric-box">Total Value (Including Investments): ${total_value:.2f}</div>', unsafe_allow_html=True)
|
296 |
+
st.markdown(f'<div class="metric-box">Invested Value: ${invested_value:.2f}</div>', unsafe_allow_html=True)
|
297 |
+
st.markdown(f'<div class="metric-box">Initial Investment: ${initial_balance:.2f}</div>', unsafe_allow_html=True)
|
298 |
+
|
299 |
+
# Reintroducing get_user_data with initial_investment
|
300 |
+
def get_user_data(username, conn):
|
301 |
+
c = conn.cursor()
|
302 |
+
c.execute("SELECT balance, currency, initial_balance FROM users WHERE username = ?", (username,))
|
303 |
+
balance, currency, initial_balance = c.fetchone()
|
304 |
+
|
305 |
+
c.execute("SELECT ticker, shares, initial_investment FROM portfolios WHERE username = ?", (username,))
|
306 |
+
portfolio_data = c.fetchall()
|
307 |
+
portfolio = {ticker: {"shares": shares, "initial_investment": initial_investment} for ticker, shares, initial_investment in portfolio_data}
|
308 |
+
|
309 |
+
return balance, currency, initial_balance, portfolio
|
310 |
+
|
311 |
+
# Function to calculate total value with comparison to initial investment
|
312 |
+
def calculate_total_value(username, conn):
|
313 |
+
balance, currency, initial_balance, portfolio = get_user_data(username, conn)
|
314 |
+
total_value = balance
|
315 |
+
invested_value = 0
|
316 |
+
for ticker, data in portfolio.items():
|
317 |
+
if data['shares'] > 0:
|
318 |
+
stock_data = get_stock_data(ticker, '1d')
|
319 |
+
if stock_data is not None:
|
320 |
+
last_close = stock_data['Close'].iloc[-1]
|
321 |
+
invested_value += last_close * data['shares']
|
322 |
+
total_value += invested_value
|
323 |
+
total_value = convert_currency(total_value, 'USD', currency)
|
324 |
+
invested_value = convert_currency(invested_value, 'USD', currency)
|
325 |
+
initial_balance_converted = convert_currency(initial_balance, 'USD', currency)
|
326 |
+
return total_value, invested_value, initial_balance_converted
|
327 |
+
|
328 |
+
# Function to buy stock
|
329 |
+
def buy_stock(username, ticker, amount, conn, currency):
|
330 |
+
current_price = get_stock_data(ticker, period='1d')
|
331 |
+
|
332 |
+
if current_price is None or current_price empty:
|
333 |
+
return "Invalid ticker symbol."
|
334 |
+
|
335 |
+
total_cost = current_price['Close'].iloc[-1] * amount
|
336 |
+
|
337 |
+
c = conn.cursor()
|
338 |
+
c.execute("SELECT balance, currency FROM users WHERE username = ?", (username,))
|
339 |
+
user_balance, user_currency = c.fetchone()
|
340 |
+
|
341 |
+
total_cost_in_user_currency = convert_currency(total_cost, 'USD', user_currency)
|
342 |
+
|
343 |
+
if user_balance < total_cost_in_user_currency:
|
344 |
+
return "Insufficient funds."
|
345 |
+
|
346 |
+
new_balance = user_balance - total_cost_in_user_currency
|
347 |
+
c.execute("UPDATE users SET balance = ? WHERE username = ?", (new_balance, username))
|
348 |
+
|
349 |
+
c.execute("SELECT shares FROM portfolios WHERE username = ? AND ticker = ?", (username, ticker))
|
350 |
+
existing_shares = c.fetchone()
|
351 |
+
|
352 |
+
if existing_shares:
|
353 |
+
new_shares = existing_shares[0] + amount
|
354 |
+
c.execute("UPDATE portfolios SET shares = ?, initial_investment = initial_investment + ? WHERE username = ? AND ticker = ?", (new_shares, total_cost, username, ticker))
|
355 |
+
else:
|
356 |
+
c.execute("INSERT INTO portfolios (username, ticker, shares, initial_investment) VALUES (?, ?, ?, ?)", (username, ticker, amount, total_cost))
|
357 |
+
|
358 |
+
c.execute("INSERT INTO transactions (username, action, ticker, amount, price) VALUES (?, ?, ?, ?, ?)",
|
359 |
+
(username, 'Buy', ticker, amount, current_price['Close'].iloc[-1]))
|
360 |
+
|
361 |
+
conn.commit()
|
362 |
+
return f"Successfully bought {amount} shares of {ticker} for ${total_cost_in_user_currency:.2f} {user_currency}"
|
363 |
+
|
364 |
+
# Function to sell stock
|
365 |
+
def sell_stock(username, ticker, amount, conn, currency):
|
366 |
+
current_price = get_stock_data(ticker, period='1d')
|
367 |
+
|
368 |
+
if current_price is None or current_price empty:
|
369 |
+
return "Invalid ticker symbol."
|
370 |
+
|
371 |
+
total_value = current_price['Close'].iloc[-1] * amount
|
372 |
+
|
373 |
+
c = conn.cursor()
|
374 |
+
c.execute("SELECT shares FROM portfolios WHERE username = ? AND ticker = ?", (username, ticker))
|
375 |
+
existing_shares = c.fetchone()
|
376 |
+
|
377 |
+
if not existing_shares or existing_shares[0] < amount:
|
378 |
+
return "Insufficient shares to sell."
|
379 |
+
|
380 |
+
new_shares = existing_shares[0] - amount
|
381 |
+
if new_shares == 0:
|
382 |
+
c.execute("DELETE FROM portfolios WHERE username = ? AND ticker = ?", (username, ticker))
|
383 |
+
else:
|
384 |
+
c.execute("UPDATE portfolios SET shares = ? WHERE username = ? AND ticker = ?", (new_shares, username, ticker))
|
385 |
+
|
386 |
+
c.execute("SELECT balance, currency FROM users WHERE username = ?", (username,))
|
387 |
+
user_balance, user_currency = c.fetchone()
|
388 |
+
total_value_in_user_currency = convert_currency(total_value, 'USD', user_currency)
|
389 |
+
new_balance = user_balance + total_value_in_user_currency
|
390 |
+
c.execute("UPDATE users SET balance = ? WHERE username = ?", (new_balance, username))
|
391 |
+
|
392 |
+
c.execute("INSERT INTO transactions (username, action, ticker, amount, price) VALUES (?, ?, ?, ?, ?)",
|
393 |
+
(username, 'Sell', ticker, amount, current_price['Close'].iloc[-1]))
|
394 |
+
|
395 |
+
conn.commit()
|
396 |
+
return f"Successfully sold {amount} shares of {ticker} for ${total_value_in_user_currency:.2f} {user_currency}"
|
397 |
+
|
398 |
+
# Main function with enhanced layout and features
|
399 |
+
def main():
|
400 |
+
ensure_database_schema()
|
401 |
+
initialize_music()
|
402 |
+
|
403 |
+
if 'logged_in' not in st.session_state:
|
404 |
+
st.session_state.logged_in = False
|
405 |
+
if 'username' not in st.session_state:
|
406 |
+
st.session_state.username = None
|
407 |
+
|
408 |
+
st.markdown('<div class="main-title" style="background-color: blue; color: white; padding: 10px;">Charging Bull Trader</div>', unsafe_allow_html=True)
|
409 |
+
|
410 |
+
if not st.session_state.logged_in:
|
411 |
+
st.markdown('<div class="sub-title">Login</div>', unsafe_allow_html=True)
|
412 |
+
username_input = st.text_input("Username")
|
413 |
+
password_input = st.text_input("Password", type="password")
|
414 |
+
if st.button("Login"):
|
415 |
+
conn = setup_database()
|
416 |
+
c = conn.cursor()
|
417 |
+
c.execute("SELECT * FROM users WHERE username=? AND password=?", (username_input, hash_password(password_input)))
|
418 |
+
if c.fetchone():
|
419 |
+
st.session_state.logged_in = True
|
420 |
+
st.session_state.username = username_input
|
421 |
+
else:
|
422 |
+
st.error("Invalid username or password")
|
423 |
+
|
424 |
+
if st.button("Create Account"):
|
425 |
+
conn = setup_database()
|
426 |
+
c = conn.cursor()
|
427 |
+
try:
|
428 |
+
c.execute("INSERT INTO users (username, password, balance, initial_balance, currency) VALUES (?, ?, ?, ?, ?)",
|
429 |
+
(username_input, hash_password(password_input), INITIAL_BALANCE, INITIAL_BALANCE, DEFAULT_CURRENCY))
|
430 |
+
for ticker in STOCK_LIST:
|
431 |
+
c.execute("INSERT INTO portfolios (username, ticker, shares, initial_investment) VALUES (?, ?, 0, 0)", (username_input, ticker))
|
432 |
+
conn.commit()
|
433 |
+
st.success("Account created successfully!")
|
434 |
+
except sqlite3.IntegrityError:
|
435 |
+
st.error("Username already exists.")
|
436 |
+
else:
|
437 |
+
username = st.session_state.username
|
438 |
+
conn = setup_database()
|
439 |
+
st.sidebar.write(f"Welcome, {username}!")
|
440 |
+
if st.sidebar.button("Logout"):
|
441 |
+
st.session_state.logged_in = False
|
442 |
+
st.session_state.username = None
|
443 |
+
|
444 |
+
# Add the small Charging Bull image under the Logout button
|
445 |
+
st.sidebar.image("trade.png", width=150)
|
446 |
+
|
447 |
+
display_financial_overview(username, conn)
|
448 |
+
|
449 |
+
col1, col2 = st.columns(2)
|
450 |
+
|
451 |
+
with col1:
|
452 |
+
st.markdown('<div class="sub-title">Personal Holdings and Stocks</div>', unsafe_allow_html=True)
|
453 |
+
time_range = st.selectbox("Select Time Range for Holdings", list(TIME_RANGES.keys()))
|
454 |
+
_, _, _, portfolio = get_user_data(username, conn)
|
455 |
+
if portfolio:
|
456 |
+
plot_holdings(portfolio, time_range)
|
457 |
+
else:
|
458 |
+
st.write("No stocks in your portfolio.")
|
459 |
+
|
460 |
+
st.markdown('<div class="sub-title">Buy/Sell Stocks</div>', unsafe_allow_html=True)
|
461 |
+
action = st.selectbox("Choose Action", ["Buy", "Sell"])
|
462 |
+
ticker = st.text_input("Ticker")
|
463 |
+
amount = st.number_input("Amount", min_value=1, step=1)
|
464 |
+
selected_currency = st.selectbox("Currency", CURRENCIES)
|
465 |
+
|
466 |
+
if st.button(f"{action} Stocks"):
|
467 |
+
if action == "Buy":
|
468 |
+
result = buy_stock(username, ticker, amount, conn, selected_currency)
|
469 |
+
else:
|
470 |
+
result = sell_stock(username, ticker, amount, conn, selected_currency)
|
471 |
+
st.write(result)
|
472 |
+
|
473 |
+
with col2:
|
474 |
+
market_status = get_market_status()
|
475 |
+
```python
|
476 |
+
market_overview_ticker(market_status)
|
477 |
+
display_currency_and_gold()
|
478 |
+
|
479 |
+
st.markdown('<div class="sub-title">Stock Lookup</div>', unsafe_allow_html=True)
|
480 |
+
stock_ticker = st.text_input("Enter Stock Ticker for Lookup")
|
481 |
+
time_range_lookup = st.selectbox("Select Time Range", list(TIME_RANGES.keys()), key="lookup")
|
482 |
+
if st.button("Lookup"):
|
483 |
+
df = get_stock_data(stock_ticker, period=TIME_RANGES[time_range_lookup])
|
484 |
+
if df is not None and not df.empty:
|
485 |
+
fig = px.line(df, x='Date', y='Close', title=f"{stock_ticker} - {time_range_lookup}")
|
486 |
+
st.plotly_chart(fig, use_container_width=True)
|
487 |
+
else:
|
488 |
+
st.write("No data available for this ticker.")
|
489 |
+
|
490 |
+
if __name__ == "__main__":
|
491 |
+
main()
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|