-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathapp.py
More file actions
3837 lines (3248 loc) · 151 KB
/
Copy pathapp.py
File metadata and controls
3837 lines (3248 loc) · 151 KB
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
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
411
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
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
import os
import csv
import json
import uuid
import logging
import traceback
import sys
import time
from datetime import datetime, timedelta
from flask import Flask, render_template, request, redirect, url_for, jsonify, flash, session, send_from_directory
import pandas as pd
import sqlite3
import yfinance as yf
import time
from init_db import init_db
from openai import OpenAI
import openai
from dotenv import load_dotenv
import threading
import markdown
import requests
from itertools import groupby
from dateutil.relativedelta import relativedelta
import shutil
from concurrent.futures import ThreadPoolExecutor, TimeoutError
import re
# Configure logging
logging.basicConfig(
level=logging.INFO,
format='%(asctime)s - %(name)s - %(levelname)s - %(message)s',
handlers=[
logging.StreamHandler(sys.stdout),
logging.FileHandler('app.log')
]
)
logger = logging.getLogger('tradelens')
# Create the logo storage directory if it doesn't exist
LOGO_DIR = os.path.join('static', 'img', 'logos')
os.makedirs(LOGO_DIR, exist_ok=True)
# Define MAG7 stocks
MAG7_STOCKS = {
'AAPL': 'Apple Inc.',
'MSFT': 'Microsoft Corporation',
'GOOGL': 'Alphabet Inc.',
'AMZN': 'Amazon.com Inc.',
'META': 'Meta Platforms Inc.',
'NVDA': 'NVIDIA Corporation',
'TSLA': 'Tesla Inc.'
}
# Define Perplexity AI model options
PERPLEXITY_MODELS = {
'sonar': 'sonar',
'sonar-pro': 'sonar-pro',
'sonar-reasoning': 'sonar-reasoning',
'sonar-reasoning-pro': 'sonar-reasoning-pro',
'sonar-deep-research': 'sonar-deep-research',
'r1-1776': 'r1-1776',
'llama-3.1-sonar-small': 'llama-3.1-sonar-small'
}
# Investment thesis examples for dropdown
INVESTMENT_THESES = [
"AI stocks will outperform in Q3 2025",
"Renewable energy sector will see growth due to recent policy changes",
"Semiconductor stocks will face headwinds from supply chain disruptions",
"Fintech companies will benefit from rising interest rates",
"Healthcare innovation stocks will outperform due to aging demographics",
"E-commerce stocks will decline with return to brick-and-mortar shopping",
"Cybersecurity stocks will surge due to increased corporate spending",
"Small-cap stocks will outperform large-caps in the next fiscal year",
"Cloud computing providers will face margin pressure from competition",
"Electric vehicle stocks will underperform due to raw material costs"
]
# Set default model
DEFAULT_PERPLEXITY_MODEL = 'sonar'
# Load environment variables from .env file
load_dotenv()
# Get OpenAI API key
openai_api_key = os.getenv('OPENAI_API_KEY')
# Initialize OpenAI client
openai_client = OpenAI(api_key=openai_api_key)
# Initialize Perplexity client (fallback)
perplexity_client = None
if os.getenv('PERPLEXITY_API_KEY'):
perplexity_client = OpenAI(
api_key=os.getenv('PERPLEXITY_API_KEY'),
base_url="https://api.perplexity.ai"
)
# Cache for stock splits
split_cache = {}
SPLIT_CACHE_TIMEOUT = 86400 # 24 hours
# Set default settings
DEFAULT_SETTINGS = {
'ai_provider': 'perplexity', # 'openai' or 'perplexity'
'perplexity_model': 'sonar' # Default Perplexity model
}
# Function to get current settings
def get_settings():
try:
# Check if we have a Flask request context
if 'settings' not in session:
session['settings'] = DEFAULT_SETTINGS.copy()
return session['settings']
except RuntimeError:
# If there's no request context, return default settings
logger.warning("No request context available for settings, using defaults")
return DEFAULT_SETTINGS.copy()
def get_stock_splits(symbol, start_date=None):
"""
Fetch stock split history for a given symbol.
Returns a list of tuples (date, ratio) sorted by date.
"""
cache_key = f"{symbol}:{start_date}"
# Check cache
if cache_key in split_cache:
cached_data = split_cache[cache_key]
if time.time() - cached_data['timestamp'] < SPLIT_CACHE_TIMEOUT:
return cached_data['data']
try:
stock = yf.Ticker(symbol)
# Get stock split data
if start_date:
splits = stock.splits[start_date:]
else:
splits = stock.splits
# Convert to list of tuples (date, ratio)
split_data = [(date.strftime('%Y-%m-%d'), ratio) for date, ratio in splits.items()]
split_data.sort(key=lambda x: x[0]) # Sort by date
# Cache the result
split_cache[cache_key] = {
'data': split_data,
'timestamp': time.time()
}
return split_data
except Exception as e:
print(f"Error fetching stock splits for {symbol}: {e}")
return []
def adjust_for_splits(price, quantity, transaction_date, splits):
"""
Adjust price and quantity based on stock splits.
Since yfinance returns split-adjusted prices, we need to:
- For transactions BEFORE a split: Leave them as is (they're already adjusted by yfinance)
- For transactions AFTER a split: Multiply price by split ratio, divide quantity by split ratio
This ensures consistency with yfinance's adjusted prices
"""
if not splits:
return price, quantity
transaction_date = datetime.strptime(transaction_date, '%Y-%m-%d').date()
adjustment_ratio = 1.0
# Sort splits by date to process them in chronological order
splits.sort(key=lambda x: datetime.strptime(x[0], '%Y-%m-%d').date())
# Only adjust for splits that happened before the transaction
for split_date, split_ratio in splits:
split_date = datetime.strptime(split_date, '%Y-%m-%d').date()
if split_date < transaction_date:
adjustment_ratio *= split_ratio
if adjustment_ratio != 1.0:
# For transactions after splits:
# - Multiply the price by the split ratio (to match historical prices)
# - Divide the quantity by the split ratio (to reflect historical shares)
adjusted_price = price * adjustment_ratio
adjusted_quantity = quantity / adjustment_ratio
return adjusted_price, adjusted_quantity
return price, quantity
def categorize_stock(symbol, name):
try:
# Check if it's a MAG7 stock first (no API call needed)
if symbol in MAG7_STOCKS:
return 'mag7'
# Check if stock is still trading
stock = yf.Ticker(symbol)
info = stock.info
# Check if we can get any price data
try:
# Try multiple price fields as different stocks might use different fields
price_fields = ['regularMarketPrice', 'currentPrice', 'previousClose', 'open']
has_price = any(info.get(field) is not None for field in price_fields)
if not has_price:
return 'unlisted'
return 'other'
except (KeyError, AttributeError, TypeError):
return 'unlisted'
except Exception as e:
print(f"Error categorizing stock {symbol}: {e}")
# If we can't determine the status, assume it's unlisted
return 'unlisted'
app = Flask(__name__)
app.secret_key = os.getenv('SECRET_KEY', 'dev_secret_key_change_in_production')
# Add custom Jinja2 filter for strptime
@app.template_filter('strptime')
def strptime_filter(date_str, format_str):
"""Convert a date string to a datetime object using the given format"""
return datetime.strptime(date_str, format_str)
# Add custom Jinja2 filter for strftime
@app.template_filter('strftime')
def strftime_filter(date_obj, format_str):
"""Format a datetime object as a string using the given format"""
return date_obj.strftime(format_str)
# Add markdown filter for rendering markdown content
@app.template_filter('markdown')
def markdown_filter(text):
"""Convert markdown text to HTML with better handling of citations and sources"""
try:
# Install markdown package if not present
import markdown
import re
# Check if there's a sources section and properly format it
if "## Sources" in text:
# Handle citation references
def replace_citation_refs(match):
citation_num = match.group(1)
return f'<sup class="citation-ref">{citation_num}</sup>'
# Replace citations like [1], [2], etc. with proper superscript
text = re.sub(r'\[(\d+)\](?!\()', replace_citation_refs, text)
# Convert markdown to HTML
html = markdown.markdown(
text,
extensions=['tables', 'fenced_code', 'nl2br', 'extra']
)
return html
else:
# If no sources section, just convert normally
return markdown.markdown(
text,
extensions=['tables', 'fenced_code', 'nl2br', 'extra']
)
except ImportError:
# Fallback if markdown package is not installed
return text.replace('\n', '<br>')
# Add more aggressive caching
chart_cache = {}
price_cache = {}
stock_category_cache = {}
CACHE_TIMEOUT = 300 # 5 minutes
# Load the CSV data
def load_data():
transactions = []
with open('stock_orders.csv', 'r') as file:
reader = csv.DictReader(file)
for row in reader:
# Convert date string to datetime object for sorting
row['Date'] = datetime.strptime(row['Date'], '%m/%d/%Y')
transactions.append(row)
# Sort by Date in descending order (newest first)
transactions.sort(key=lambda x: x['Date'], reverse=True)
return transactions
# Get unique stocks
def get_unique_stocks(transactions):
# Get unique stock symbols and names
stocks = {}
for transaction in transactions:
symbol = transaction['Symbol']
name = transaction['Name']
if symbol not in stocks:
stocks[symbol] = name
# Convert to list of tuples and sort alphabetically by Symbol
stock_list = [(symbol, name) for symbol, name in stocks.items()]
stock_list.sort(key=lambda x: x[0])
return stock_list
def get_db_connection():
conn = sqlite3.connect('stock_transactions.db')
conn.row_factory = sqlite3.Row
# Add custom converter functions to handle TEXT to numeric conversions
def convert_to_float(value):
if value is None or value == "null" or value == "":
return None
try:
return float(value)
except (ValueError, TypeError):
return None
# Register adapter and converter for REAL type
sqlite3.register_adapter(float, lambda val: str(val))
sqlite3.register_converter("REAL", convert_to_float)
return conn
def get_categorized_stocks(cursor):
# Check if we have cached results
if 'categorized_stocks' in stock_category_cache:
return stock_category_cache['categorized_stocks']
cursor.execute('SELECT DISTINCT Symbol, Name FROM transactions ORDER BY Symbol')
all_stocks = cursor.fetchall()
categorized_stocks = {
'mag7': [],
'other': [],
'unlisted': []
}
for stock in all_stocks:
category = categorize_stock(stock['Symbol'], stock['Name'])
categorized_stocks[category].append({
'symbol': stock['Symbol'],
'name': stock['Name']
})
# Cache the results
stock_category_cache['categorized_stocks'] = categorized_stocks
return categorized_stocks
def get_stock_price(symbol, start_date=None, end_date=None):
# Generate cache key
cache_key = f"{symbol}:{start_date}:{end_date}"
# Check cache
if cache_key in price_cache:
cached_data = price_cache[cache_key]
if time.time() - cached_data['timestamp'] < CACHE_TIMEOUT:
return cached_data['data']
try:
stock = yf.Ticker(symbol)
if start_date and end_date:
# Get historical data for specific date range
hist = stock.history(start=start_date, end=end_date)
elif start_date:
# Get historical data from start date to now
hist = stock.history(start=start_date)
else:
# Get current price data
hist = stock.history(period="1d")
if not hist.empty:
current_price = hist['Close'].iloc[-1]
previous_close = hist['Close'].iloc[0]
change = current_price - previous_close
change_percent = (change / previous_close * 100)
result = {
'current_price': current_price,
'change': change,
'change_percent': change_percent,
'previous_close': previous_close,
'error': None
}
else:
result = {
'current_price': None,
'change': None,
'change_percent': None,
'previous_close': None,
'error': 'No price data available'
}
except Exception as e:
print(f"Error fetching stock price: {e}")
result = {
'current_price': None,
'change': None,
'change_percent': None,
'previous_close': None,
'error': str(e)
}
# Cache the result
price_cache[cache_key] = {
'data': result,
'timestamp': time.time()
}
return result
def get_stock_chart(symbol, start_date, end_date):
"""
Get stock chart data and adjust prices to show historical prices.
yfinance returns split-adjusted prices, so we need to unadjust older prices
to show the actual historical prices that were seen at the time.
"""
try:
stock = yf.Ticker(symbol)
# Get historical data
hist = stock.history(
start=start_date,
end=end_date,
auto_adjust=True # This gives us split-adjusted prices
)
if hist.empty:
print(f"No historical data found for {symbol}")
return {
'dates': [],
'prices': [],
'error': 'No historical data found'
}
# Get the dates and prices
dates = hist.index.strftime('%Y-%m-%d').tolist()
prices = hist['Close'].tolist()
# Get splits that occurred in our date range
splits = get_stock_splits(symbol, start_date.strftime('%Y-%m-%d'))
print(f"Found splits for {symbol}: {splits}")
if splits:
# Calculate cumulative split ratio for each date
# For dates before a split, we need to multiply the price by the split ratio
# to show the actual historical price
cumulative_ratios = []
for date in dates:
date_dt = datetime.strptime(date, '%Y-%m-%d').date()
# Start with ratio 1
current_ratio = 1.0
# For each split that happened after this date,
# multiply by the split ratio to get the historical price
for split_date, ratio in splits:
split_dt = datetime.strptime(split_date, '%Y-%m-%d').date()
if date_dt < split_dt:
current_ratio *= ratio
cumulative_ratios.append(current_ratio)
# Multiply prices by their cumulative ratios to get historical prices
prices = [price * ratio for price, ratio in zip(prices, cumulative_ratios)]
# Debug output
print("Sample of price adjustments:")
for i in range(min(5, len(dates))):
print(f"Date: {dates[i]}, Ratio: {cumulative_ratios[i]}, Price: {prices[i]}")
# Ensure we have valid data
if not dates or not prices or len(dates) != len(prices):
print(f"Invalid data for {symbol}: dates={len(dates)}, prices={len(prices)}")
return {
'dates': [],
'prices': [],
'error': 'Invalid data received'
}
# Debug output
print(f"Chart data for {symbol}:")
print(f"Date range: {dates[0]} to {dates[-1]}")
print(f"Price range: ${min(prices):.2f} to ${max(prices):.2f}")
print(f"Number of points: {len(dates)}")
return {
'dates': dates,
'prices': prices,
'error': None,
'split_events': [{
'date': split_date,
'ratio': ratio,
'price': next((p for d, p in zip(dates, prices)
if d == split_date), None)
} for split_date, ratio in splits]
}
except Exception as e:
print(f"Error fetching stock chart for {symbol}: {e}")
import traceback
traceback.print_exc()
return {
'dates': [],
'prices': [],
'error': str(e)
}
def process_transactions(transactions):
"""Process transactions without any split adjustments"""
processed = []
for t in transactions:
try:
# Convert date string to datetime object
date_obj = datetime.strptime(t['Date'], '%Y-%m-%d') if isinstance(t['Date'], str) else t['Date']
# Convert text values to float, handling possible null values
try:
price = float(t['AveragePrice']) if t['AveragePrice'] and str(t['AveragePrice']).lower() != 'null' else None
except (ValueError, TypeError, AttributeError):
price = None
try:
qty = float(t['Qty']) if t['Qty'] and str(t['Qty']).lower() != 'null' else None
except (ValueError, TypeError, AttributeError):
qty = None
processed.append({
'Id': t['Id'],
'Date': date_obj,
'Time': t['Time'],
'Symbol': t['Symbol'],
'Name': t['Name'],
'Type': t['Type'],
'Side': t['Side'],
'AveragePrice': price, # Always use the converted float or None
'Qty': qty,
'State': t['State'],
'Fees': t['Fees'],
'HasSplitAdjustment': False
})
except (ValueError, TypeError) as e:
print(f"Error processing transaction: {t}, Error: {e}")
# Even in error case, try to convert price and quantity
try:
price = float(t['AveragePrice']) if t['AveragePrice'] and str(t['AveragePrice']).lower() != 'null' else None
except (ValueError, TypeError, AttributeError):
price = None
try:
qty = float(t['Qty']) if t['Qty'] and str(t['Qty']).lower() != 'null' else None
except (ValueError, TypeError, AttributeError):
qty = None
processed.append({
'Id': t['Id'],
'Date': date_obj if 'date_obj' in locals() else None,
'Time': t['Time'],
'Symbol': t['Symbol'],
'Name': t['Name'],
'Type': t['Type'],
'Side': t['Side'],
'AveragePrice': price, # Use converted float or None, not raw string
'Qty': qty,
'State': t['State'],
'Fees': t['Fees'],
'HasSplitAdjustment': False
})
return processed
def calculate_transaction_stats(transactions):
stats = {
'total_stocks_bought': 0,
'total_stocks_sold': 0,
'total_amount_bought': 0,
'total_amount_sold': 0
}
for tx in transactions:
try:
# Safely convert text values to float
try:
qty = float(tx['Qty']) if tx['Qty'] and str(tx['Qty']).lower() != 'null' else 0
except (ValueError, TypeError):
qty = 0
try:
price = float(tx['AveragePrice']) if tx['AveragePrice'] and str(tx['AveragePrice']).lower() != 'null' else 0
except (ValueError, TypeError):
price = 0
amount = price * qty
if tx['Side'].lower() == 'buy':
stats['total_stocks_bought'] += qty
stats['total_amount_bought'] += amount
elif tx['Side'].lower() == 'sell':
stats['total_stocks_sold'] += qty
stats['total_amount_sold'] += amount
except (ValueError, TypeError) as e:
print(f"Error processing transaction stats: {tx}, Error: {e}")
continue
# Round the values for display
stats['total_stocks_bought'] = round(stats['total_stocks_bought'], 2)
stats['total_stocks_sold'] = round(stats['total_stocks_sold'], 2)
stats['total_amount_bought'] = round(stats['total_amount_bought'], 2)
stats['total_amount_sold'] = round(stats['total_amount_sold'], 2)
return stats
@app.route('/api/stock_chart/<symbol>')
def api_stock_chart(symbol):
range_ = request.args.get('range', 'ytd')
today = datetime.today()
# Get transactions for this symbol
conn = get_db_connection()
cursor = conn.cursor()
if range_ == 'all':
# For 'all', get the date range from actual transactions
cursor.execute('''
SELECT MIN(Date), MAX(Date)
FROM transactions
WHERE Symbol = ?
''', (symbol,))
min_date, max_date = cursor.fetchone()
if min_date and max_date:
start_date = datetime.strptime(min_date, '%Y-%m-%d')
end_date = datetime.strptime(max_date, '%Y-%m-%d') + timedelta(days=1) # Include the last day
else:
start_date = today - timedelta(days=30) # Default to last 30 days if no transactions
end_date = today
elif range_ == 'ytd':
start_date = datetime(today.year, 1, 1)
end_date = today
elif range_ == '1y':
start_date = today - timedelta(days=365)
end_date = today
elif range_ == '2y':
start_date = today - timedelta(days=2*365)
end_date = today
elif range_ == '5y':
start_date = today - timedelta(days=5*365)
end_date = today
elif range_ == 'max':
# For max, get the earliest transaction date
cursor.execute('SELECT MIN(Date) FROM transactions WHERE Symbol = ?', (symbol,))
earliest_date = cursor.fetchone()[0]
if earliest_date:
start_date = datetime.strptime(earliest_date, '%Y-%m-%d')
else:
start_date = today - timedelta(days=365) # Default to 1 year if no transactions
end_date = today
else: # Default to YTD if unknown range
start_date = datetime(today.year, 1, 1)
end_date = today
# Get transactions within the date range
query = '''
SELECT Id, Date, Time, Side, AveragePrice, Qty
FROM transactions
WHERE Symbol = ? AND Date >= ? AND Date <= ?
ORDER BY Date ASC, Time ASC
'''
cursor.execute(query, (symbol, start_date.strftime('%Y-%m-%d'), end_date.strftime('%Y-%m-%d')))
transactions = cursor.fetchall()
conn.close()
# Process transactions for charting
buy_transactions = []
sell_transactions = []
for tx in transactions:
try:
# Safely convert AveragePrice to float
if tx['AveragePrice'] is None or (isinstance(tx['AveragePrice'], str) and (not tx['AveragePrice'] or tx['AveragePrice'].lower() == 'null')):
continue
try:
price = float(tx['AveragePrice'])
except (ValueError, TypeError):
continue
point = {
'id': tx['Id'],
'date': tx['Date'],
'time': tx['Time'],
'price': price,
'qty': tx['Qty']
}
if tx['Side'].lower() == 'buy':
buy_transactions.append(point)
else:
sell_transactions.append(point)
except (ValueError, TypeError) as e:
print(f"Error processing transaction: {tx}, Error: {e}")
continue
# Get chart data for the specified date range
chart_data = get_stock_chart(symbol, start_date, end_date)
# Get split data
splits = get_stock_splits(symbol, start_date.strftime('%Y-%m-%d'))
split_events = []
# Process splits for chart annotations
for split_date, split_ratio in splits:
split_date_obj = datetime.strptime(split_date, '%Y-%m-%d')
if start_date <= split_date_obj <= end_date:
# Find the closest price to the split date
closest_date_index = min(range(len(chart_data['dates'])),
key=lambda i: abs(datetime.strptime(chart_data['dates'][i], '%Y-%m-%d') - split_date_obj))
if closest_date_index < len(chart_data['prices']):
price = chart_data['prices'][closest_date_index]
split_events.append({
'date': split_date,
'ratio': split_ratio,
'price': price
})
# Add split events to chart data
chart_data['split_events'] = split_events
# Add transaction data
chart_data['buy_transactions'] = buy_transactions
chart_data['sell_transactions'] = sell_transactions
# Cache the data
cache_key = f"{symbol}:{range_}"
now = time.time()
chart_cache[cache_key] = {'data': {
'dates': chart_data['dates'],
'prices': chart_data['prices'],
'error': chart_data['error']
}, 'timestamp': now}
return jsonify(chart_data)
@app.route('/')
def index():
page = request.args.get('page', 1, type=int)
per_page = 20
active_tab = request.args.get('tab', 'mag7')
conn = get_db_connection()
cursor = conn.cursor()
cursor.execute('SELECT COUNT(*) FROM transactions')
total_transactions = cursor.fetchone()[0]
total_pages = (total_transactions + per_page - 1) // per_page
offset = (page - 1) * per_page
cursor.execute('''
SELECT * FROM transactions
ORDER BY Date DESC, Time DESC
LIMIT ? OFFSET ?
''', (per_page, offset))
transactions = cursor.fetchall()
cursor.execute('''
SELECT DISTINCT Symbol, Name
FROM transactions
ORDER BY Symbol
''')
stocks = cursor.fetchall()
conn.close()
# Categorize stocks
categorized_stocks = {
'mag7': [],
'other': [],
'unlisted': []
}
for stock in stocks:
category = categorize_stock(stock['Symbol'], stock['Name'])
categorized_stocks[category].append({
'symbol': stock['Symbol'],
'name': stock['Name']
})
processed_transactions = process_transactions(transactions)
return render_template('index.html',
transactions=processed_transactions,
stocks=categorized_stocks,
page=page,
total_pages=total_pages,
per_page=per_page,
current_filter=None,
active_tab=active_tab)
@app.route('/stock/<symbol>')
def stock_detail(symbol):
page = request.args.get('page', 1, type=int)
per_page = 20
side = request.args.get('side', 'all')
range_ = request.args.get('range', 'ytd')
active_tab = request.args.get('tab', 'mag7')
today = datetime.today()
start_date = None
conn = get_db_connection()
cursor = conn.cursor()
# Get the stock name and transactions in a single query
cursor.execute('''
SELECT t.*,
(SELECT DISTINCT Name FROM transactions WHERE Symbol = ? LIMIT 1) as stock_name
FROM transactions t
WHERE t.Symbol = ?
''', (symbol, symbol))
result = cursor.fetchone()
# Handle case where no transactions are found for this symbol
if result is None:
flash(f"No transactions found for symbol {symbol}", "warning")
return redirect(url_for('index'))
# Get stock name with a fallback if not found
stock_name = result['stock_name'] if result and result['stock_name'] else symbol
# Build the base query for transactions
base_query = 'SELECT * FROM transactions WHERE Symbol = ?'
params = [symbol]
# Handle side filter
if side in ['buy', 'sell']:
base_query += ' AND LOWER(Side) = ?'
params.append(side)
# Handle date range
if range_ == 'all':
# For 'all' filter, we want all transactions without date filtering
pass
elif range_ == 'max':
# For 'max' filter, we want the entire stock history
# Get the earliest transaction date
cursor.execute('SELECT MIN(Date) FROM transactions WHERE Symbol = ?', (symbol,))
earliest_date = cursor.fetchone()[0]
if earliest_date:
start_date = datetime.strptime(earliest_date, '%Y-%m-%d')
elif range_ == 'ytd':
start_date = datetime(today.year, 1, 1)
elif range_ == '1y':
start_date = today - timedelta(days=365)
elif range_ == '2y':
start_date = today - timedelta(days=2*365)
elif range_ == '5y':
start_date = today - timedelta(days=5*365)
elif range_ == '1mo':
start_date = today - timedelta(days=30)
# Add date filter if needed
if start_date and range_ != 'all':
base_query += ' AND Date >= ?'
params.append(start_date.strftime('%Y-%m-%d'))
# Get total count for pagination
count_query = f'SELECT COUNT(*) FROM ({base_query})'
cursor.execute(count_query, params)
total_transactions = cursor.fetchone()[0]
total_pages = (total_transactions + per_page - 1) // per_page
# Ensure page is within valid range
if page < 1:
page = 1
elif page > total_pages and total_pages > 0:
page = total_pages
# Calculate offset for pagination
offset = (page - 1) * per_page
# First get all transactions for stats (without pagination)
cursor.execute(base_query, params)
all_transactions = cursor.fetchall()
# Calculate stats from all transactions
transaction_stats = calculate_transaction_stats(all_transactions)
# Add pagination to the query for display
final_query = f'{base_query} ORDER BY Date DESC, Time DESC LIMIT ? OFFSET ?'
params += [per_page, offset]
# Execute the final query
cursor.execute(final_query, params)
transactions = cursor.fetchall()
# Get categorized stocks from cache
categorized_stocks = get_categorized_stocks(cursor)
conn.close()
processed_transactions = process_transactions(transactions)
# Get price data with appropriate date range
if range_ == 'all':
# For 'all' filter, we want to show price data for transaction dates only
# Get unique transaction dates
transaction_dates = sorted(set(t['Date'] for t in all_transactions))
if transaction_dates:
start_date = datetime.strptime(transaction_dates[0], '%Y-%m-%d')
end_date = datetime.strptime(transaction_dates[-1], '%Y-%m-%d')
price_data = get_stock_price(symbol, start_date=start_date, end_date=end_date)
else:
price_data = get_stock_price(symbol)
else:
price_data = get_stock_price(symbol, start_date=start_date)
return render_template('index.html',
transactions=processed_transactions,
stocks=categorized_stocks,
current_filter=symbol,
stock_name=stock_name,
page=page,
total_pages=total_pages,
per_page=per_page,
price_data=price_data,
selected_side=side,
selected_range=range_,
active_tab=active_tab,
transaction_stats=transaction_stats)
@app.route('/upload', methods=['POST'])
def upload_file():
if 'file' not in request.files:
flash('No file selected', 'error')
return redirect(url_for('index'))
file = request.files['file']
if file.filename == '':
flash('No file selected', 'error')
return redirect(url_for('index'))
if not file.filename.endswith('.csv'):
flash('Please upload a CSV file', 'error')
return redirect(url_for('index'))
# Save the file
file.save('stock_orders.csv')
try:
# Reinitialize the database with the new file
init_db()
# Populate earnings calendar data to ensure it's not empty
try:
from populate_earnings_data import populate_sample_earnings_data
populate_sample_earnings_data()
flash('File uploaded and database processed successfully! Earnings calendar has been refreshed.', 'success')
except Exception as e:
flash(f'File uploaded, but error refreshing earnings data: {str(e)}', 'warning')
except Exception as e:
flash(f'Error processing file: {str(e)}', 'error')
# Clean up the uploaded file
if os.path.exists('stock_orders.csv'):
os.remove('stock_orders.csv')
return redirect(url_for('index'))
@app.route('/settings', methods=['GET', 'POST'])
def settings():
"""Route to display and update application settings"""
if request.method == 'POST':
# Update settings
settings = get_settings()
# Update AI provider
settings['ai_provider'] = request.form.get('ai_provider', 'perplexity')
# Update Perplexity model if applicable
if settings['ai_provider'] == 'perplexity':
perplexity_model = request.form.get('perplexity_model')
if perplexity_model in PERPLEXITY_MODELS:
settings['perplexity_model'] = perplexity_model
# Save settings to session
session['settings'] = settings
# Redirect back to settings page with success message
flash('Settings updated successfully!', 'success')
return redirect(url_for('settings'))
# GET method
settings = get_settings()
# Check API availability
openai_available = bool(os.getenv('OPENAI_API_KEY'))
perplexity_available = bool(os.getenv('PERPLEXITY_API_KEY'))
return render_template('settings.html',
settings=settings,
perplexity_models=list(PERPLEXITY_MODELS.keys()),
openai_available=openai_available,
perplexity_available=perplexity_available)
@app.route('/risk-review')
def risk_review():
"""Portfolio risk review page that analyzes tariff and other risks for current holdings."""
conn = get_db_connection()
cursor = conn.cursor()
# Get current portfolio positions by aggregating buy/sell transactions