Hi, I am having issues with a flask web api I deployed on Vercel. The deployment and upload works fine.
So if I go to the API url works and shows the JSON data (see below screenshot):

If I include the link into a JS code to show the data in an HTML file doesnt work:

In the FLask Python code I include the allow CORS, infact when I tested the flask api locally works fine and shows the data correctly. The python code I deployed on vercel is the following:
1from flask import Flask, jsonify2from flask_cors import CORS3import yfinance as yf4from datetime import date, datetime, timedelta5import pandas as pd6import numpy as np78app = Flask(__name__)9CORS(app)101112@app.route('/')13def home():14 return "Marcello Personal Portfolio Dashboard API"1516@app.route('/stock-data')17def get_stock_data():18 tickers = ['VHYL.L', 'MSFT', 'SGLN.L', 'IMEU.L', 'BABA', 'SAAA.L', 'XYZ']19 20 # weights of the stocks21 22 weights = np.array([0.2164, 0.1797, 0.1536, 0.1304, 0.1289, 0.1275, 0.0635])23 24 today = date.today()25 data = yf.download(tickers, start='2021-01-19', end="2025-02-21", interval="1mo", auto_adjust = False)['Adj Close']26 27 # normalize the price28 normalized_data = data / data.iloc[0]29 30 # portfolio performance31 portfolio_performance = (normalized_data * weights).sum(axis=1) # weighted sum of all shares in the portfolio32 33 # Calculate the percentage change34 pct_change = (portfolio_performance.pct_change().fillna(0) * 100).tolist()35 36 37 # Prepare JSON response38 response_data = {39 "labels": normalized_data.index.strftime("%Y-%m-%d").tolist(),40 41 42 43 # add the percentage change to the response44 "pct_change": pct_change, # percentage change45 46 # add the weights to the response to show the weights of the stocks showing also the ticker of the stock47 "portfolio_weights": {48 "tickers": tickers,49 "weights": weights.tolist()50 }51 52 53 }54 55 return jsonify(response_data)5657PORTFOLIO = ['VHYL.L', 'MSFT', 'SGLN.L', 'IMEU.L', 'BABA', 'SAAA.L', 'XYZ']585960def calculate_performance(ticker_data, periods):61 """Calculate performance for different time periods"""62 63 results = {}64 latest_price = ticker_data.iloc[-1]65 66 for period_name, days in periods.items():67 if days > len(ticker_data):68 results[period_name] = None69 continue70 71 start_price = ticker_data.iloc[-days]72 performance = ((latest_price - start_price) / start_price) * 10073 results[period_name] = round(performance, 2)74 75 return results7677@app.route('/portfolio-performance')78def portfolio_performance():79 today = datetime.now()80 81 # Define time periods in trading days (approximations)82 periods = {83 '1_month': 21,84 'ytd': max(1, (today - datetime(today.year, 1, 1)).days), # Year-to-date (from Jan 1st) excluding weekends85 '1_year': 252,86 '3_year': 756,87 '5_year': 126088 }89 # Calculate start date for data retrieval (add some buffer)90 start_date = (today - timedelta(days=1900)).strftime('%Y-%m-%d')91 end_date = today.strftime('%Y-%m-%d')92 93 portfolio_data = []94 95 for ticker in PORTFOLIO:96 try:97 # Get historical data98 stock_data = yf.Ticker(ticker)99 hist = stock_data.history(start=start_date, end=end_date)100 101 # Skip if no data102 if hist.empty:103 continue104 105 # Get adjusted close prices106 adj_close = hist['Close']107 108 # Calculate performance for different periods109 performance = calculate_performance(adj_close, periods)110 111 # Get current price112 current_price = round(float(adj_close.iloc[-1]), 2)113 114 # Get company name115 info = stock_data.info116 company_name = info.get('shortName', ticker)117 118 portfolio_data.append({119 'ticker': ticker,120 'name': company_name,121 'current_price': current_price,122 'performance': performance123 })124 125 except Exception as e:126 print(f"Error processing {ticker}: {e}")127 128 return jsonify(portfolio_data)129130if __name__ == '__main__':131 #app.run(debug=True) # run the app in debug mode locally132 app.run() # run the app in production mode
Hope someone can help thanks. Marcello