File size: 3,704 Bytes
4748960
4369bdd
0719d15
645fc26
 
 
 
 
 
 
 
b6b8b61
ac915a1
1accf76
645fc26
ac915a1
 
 
 
 
1accf76
645fc26
 
 
ac915a1
 
 
 
 
 
 
 
 
42a8d52
645fc26
 
ac915a1
 
 
 
 
 
42a8d52
645fc26
 
ac915a1
 
 
 
 
 
 
42a8d52
645fc26
 
ac915a1
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
42a8d52
645fc26
 
ac915a1
 
 
 
 
 
 
 
 
 
 
1accf76
645fc26
 
bc51dd8
 
645fc26
0719d15
bc51dd8
 
 
 
ac915a1
 
 
 
0719d15
4748960
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
#from waitress import serve
from flask import Flask, jsonify, request, render_template
from flask_cors import CORS
from services.stock_service import get_stock_data, get_live_stock_price
from services.news_service import get_market_news
from database.db_operations import (
    get_user_portfolio,
    add_stock_to_portfolio,
    update_user_settings,
    get_user_settings
)
from config import Config
import logging

app = Flask(__name__, static_folder='../frontend/static', template_folder='../frontend/templates')
CORS(app, resources={r"/api/*": {"origins": "*", "methods": ["GET", "POST", "PUT"]}})

# Set up logging
logging.basicConfig(level=logging.INFO)
logger = logging.getLogger(__name__)

# API Routes
@app.route('/api/stocks/<symbol>', methods=['GET'])
def get_stock(symbol):
    try:
        period = request.args.get('period', '1mo')
        if period not in ['1d', '5d', '1mo', '3mo', '6mo', '1y', '2y', '5y', '10y', 'ytd', 'max']:
            return jsonify({'error': 'Invalid period'}), 400
        data = get_stock_data(symbol, period)
        return jsonify(data)
    except Exception as e:
        logger.error(f"Error getting stock data: {e}")
        return jsonify({'error': 'Failed to get stock data'}), 500

@app.route('/api/stocks/live/<symbol>', methods=['GET'])
def get_live_stock(symbol):
    try:
        price = get_live_stock_price(symbol)
        return jsonify({'price': price})
    except Exception as e:
        logger.error(f"Error getting live stock price: {e}")
        return jsonify({'error': 'Failed to get live stock price'}), 500

@app.route('/api/news', methods=['GET'])
def get_news():
    try:
        category = request.args.get('category', 'general')
        news = get_market_news(category)
        return jsonify(news)
    except Exception as e:
        logger.error(f"Error getting news: {e}")
        return jsonify({'error': 'Failed to get news'}), 500

@app.route('/api/portfolio', methods=['GET', 'POST'])
def portfolio():
    try:
        user_id = 1  # In a real app, get from session/auth
        if request.method == 'GET':
            return jsonify(get_user_portfolio(user_id))
        else:
            data = request.json
            required_fields = ['symbol', 'name', 'shares', 'avg_price']
            if not all(field in data for field in required_fields):
                return jsonify({'error': 'Missing required fields'}), 400
            add_stock_to_portfolio(
                user_id,
                data['symbol'],
                data['name'],
                data['shares'],
                data['avg_price']
            )
            return jsonify({'status': 'success'})
    except Exception as e:
        logger.error(f"Error updating portfolio: {e}")
        return jsonify({'error': 'Failed to update portfolio'}), 500

@app.route('/api/settings', methods=['GET', 'PUT'])
def settings():
    try:
        user_id = 1  # In a real app, get from session/auth
        if request.method == 'GET':
            return jsonify(get_user_settings(user_id))
        else:
            data = request.json
            update_user_settings(user_id, data)
            return jsonify({'status': 'success'})
    except Exception as e:
        logger.error(f"Error updating settings: {e}")
        return jsonify({'error': 'Failed to update settings'}), 500

# Serve frontend
@app.route('/', defaults={'path': ''})
@app.route('/')
def home():
    return render_template('index.html')

@app.route('/login')
def login():
    return render_template('login.html')

@app.errorhandler(404)
def page_not_found(e):
    return jsonify({'error': 'Page not found'}), 404

if __name__ == '__main__':
    app.run(debug=Config.DEBUG, port=Config.PORT)