2024-11-09 13:54:37,659 INFO main Thread-2 (process_request_thread) : Portfolio loaded: portfolio_20241109_132032.json
2024-11-09 13:54:37,660 INFO main Thread-2 (process_request_thread) : Portfolios listed successfully
2024-11-09 13:54:37,663 INFO werkzeug Thread-2 (process_request_thread) : 127.0.0.1 - - [09/Nov/2024 13:54:37] "GET /api/portfolio/load HTTP/1.1" 200 -
2024-11-09 13:54:41,543 INFO werkzeug Thread-3 (process_request_thread) : 127.0.0.1 - - [09/Nov/2024 13:54:41] "OPTIONS /api/backtest HTTP/1.1" 200 -
2024-11-09 13:54:41,848 INFO werkzeug Thread-4 (process_request_thread) : 127.0.0.1 - - [09/Nov/2024 13:54:41] "OPTIONS /api/attribution HTTP/1.1" 200 -
2024-11-09 13:54:41,852 INFO werkzeug Thread-5 (process_request_thread) : 127.0.0.1 - - [09/Nov/2024 13:54:41] "OPTIONS /api/rebalance HTTP/1.1" 200 -
2024-11-09 13:54:41,856 INFO werkzeug Thread-6 (process_request_thread) : 127.0.0.1 - - [09/Nov/2024 13:54:41] "OPTIONS /api/correlation HTTP/1.1" 200 -
2024-11-09 13:54:41,859 INFO main Thread-7 (process_request_thread) : === Starting Backtest ===
2024-11-09 13:54:41,859 INFO main Thread-7 (process_request_thread) : Request data: {'portfolio': [{'ticker': 'AAPL', 'weight': 40}, {'ticker': 'TSLA', 'weight': 60}], 'benchmark': 'SPY', 'startDate': '2021-11-10'}
2024-11-09 13:54:41,859 INFO main Thread-7 (process_request_thread) : Processing portfolio: [{'ticker': 'AAPL', 'weight': 40}, {'ticker': 'TSLA', 'weight': 60}]
2024-11-09 13:54:41,859 INFO main Thread-7 (process_request_thread) : Start date: 2021-11-10
2024-11-09 13:54:41,859 INFO main Thread-7 (process_request_thread) : Benchmark: SPY
C:\Users\calvi\Downloads\react\backend.py:144: FutureWarning: 'M' is deprecated and will be removed in a future version, please use 'ME' instead.
monthly_returns = portfolio_returns.resample('M').apply(
C:\Users\calvi\Downloads\react\backend.py:144: FutureWarning: 'M' is deprecated and will be removed in a future version, please use 'ME' instead.
monthly_returns = portfolio_returns.resample('M').apply(
2024-11-09 13:54:41,934 INFO main Thread-7 (process_request_thread) : Response data prepared successfully
2024-11-09 13:54:41,936 INFO werkzeug Thread-7 (process_request_thread) : 127.0.0.1 - - [09/Nov/2024 13:54:41] "POST /api/backtest HTTP/1.1" 200 -
2024-11-09 13:54:42,178 INFO main Thread-8 (process_request_thread) : Calculating null strategy...
2024-11-09 13:54:42,186 INFO main Thread-10 (process_request_thread) : Starting attribution analysis...
2024-11-09 13:54:42,256 INFO main Thread-10 (process_request_thread) : Fetching benchmark data...
2024-11-09 13:54:42,304 INFO main Thread-9 (process_request_thread) : Correlation calculation completed.
2024-11-09 13:54:42,306 INFO main Thread-10 (process_request_thread) : Finding common dates...
2024-11-09 13:54:42,309 INFO werkzeug Thread-9 (process_request_thread) : 127.0.0.1 - - [09/Nov/2024 13:54:42] "POST /api/correlation HTTP/1.1" 200 -
2024-11-09 13:54:42,311 INFO Thread-8 (process_request_thread) : Strategy: null
2024-11-09 13:54:42,312 INFO Thread-10 (process_request_thread) : Calculating attribution...
2024-11-09 13:54:42,313 INFO Thread-8 (process_request_thread) : Final Value: 0.00
2024-11-09 13:54:42,313 INFO Thread-10 (process_request_thread) : Starting attribution calculation...
2024-11-09 13:54:42,314 INFO Thread-8 (process_request_thread) : Annualized Return: 2.15%
2024-11-09 13:54:42,316 INFO Thread-8 (process_request_thread) : Volatility: 38.34%
2024-11-09 13:54:42,318 INFO Thread-8 (process_request_thread) : Max Drawdown: -57.59%
2024-11-09 13:54:42,318 INFO Thread-8 (process_request_thread) : Calculating M strategy...
2024-11-09 13:54:42,446 INFO Thread-8 (process_request_thread) : Strategy: M
2024-11-09 13:54:42,446 INFO Thread-8 (process_request_thread) : Final Value: 12.68
2024-11-09 13:54:42,447 INFO Thread-8 (process_request_thread) : Annualized Return: 3.35%
2024-11-09 13:54:42,447 INFO Thread-8 (process_request_thread) : Volatility: 41.91%
2024-11-09 13:54:42,447 INFO Thread-8 (process_request_thread) : Max Drawdown: -59.12%
2024-11-09 13:54:42,448 INFO Thread-8 (process_request_thread) : Calculating Q strategy...
2024-11-09 13:54:42,566 INFO Thread-8 (process_request_thread) : Strategy: Q
2024-11-09 13:54:42,566 INFO Thread-8 (process_request_thread) : Final Value: 5.60
2024-11-09 13:54:42,567 INFO Thread-8 (process_request_thread) : Annualized Return: 3.38%
2024-11-09 13:54:42,567 INFO Thread-8 (process_request_thread) : Volatility: 40.10%
2024-11-09 13:54:42,567 INFO Thread-8 (process_request_thread) : Max Drawdown: -56.50%
2024-11-09 13:54:42,568 INFO Thread-8 (process_request_thread) : Calculating Y strategy...
2024-11-09 13:54:42,684 INFO Thread-8 (process_request_thread) : Strategy: Y
2024-11-09 13:54:42,684 INFO Thread-8 (process_request_thread) : Final Value: 0.14
2024-11-09 13:54:42,687 INFO Thread-8 (process_request_thread) : Annualized Return: 2.03%
2024-11-09 13:54:42,687 INFO Thread-8 (process_request_thread) : Volatility: 38.59%
2024-11-09 13:54:42,687 INFO Thread-8 (process_request_thread) : Max Drawdown: -57.86%
2024-11-09 13:54:42,691 INFO werkzeug Thread-8 (process_request_thread) : 127.0.0.1 - - [09/Nov/2024 13:54:42] "POST /api/rebalance HTTP/1.1" 200 -
2024-11-09 13:54:43,927 ERROR Thread-10 (process_request_thread) : Error in calculate_attribution: all the input array dimensions except for the concatenation axis must match exactly, but along dimension 1, the array at index 0 has size 1 and the array at index 1 has size 754
Traceback (most recent call last):
File "C:\Users\calvi\Downloads\react\backend.py", line 638, in calculate_attribution
model = stats.linregress(benchmark_returns, weighted_returns.sum(axis=1))
File "C:\Users\calvi\Downloads\react\venv\lib\site-packages\scipy\stats_stats_py.py", line 10904, in linregress
ssxm, ssxym, _, ssym = np.cov(x, y, bias=1).flat
File "C:\Users\calvi\Downloads\react\venv\lib\site-packages\numpy\lib_function_base_impl.py", line 2783, in cov
X = np.concatenate((X, y), axis=0)
ValueError: all the input array dimensions except for the concatenation axis must match exactly, but along dimension 1, the array at index 0 has size 1 and the array at index 1 has size 754
2024-11-09 13:54:43,931 ERROR Thread-10 (process_request_thread) : Error in get_attribution: all the input array dimensions except for the concatenation axis must match exactly, but along dimension 1, the array at index 0 has size 1 and the array at index 1 has size 754
Traceback (most recent call last):
File "C:\Users\calvi\Downloads\react\backend.py", line 987, in get_attribution
attribution = calculate_attribution(
File "C:\Users\calvi\Downloads\react\backend.py", line 638, in calculate_attribution
model = stats.linregress(benchmark_returns, weighted_returns.sum(axis=1))
File "C:\Users\calvi\Downloads\react\venv\lib\site-packages\scipy\stats_stats_py.py", line 10904, in linregress
ssxm, ssxym, _, ssym = np.cov(x, y, bias=1).flat
File "C:\Users\calvi\Downloads\react\venv\lib\site-packages\numpy\lib_function_base_impl.py", line 2783, in cov
X = np.concatenate((X, y), axis=0)
ValueError: all the input array dimensions except for the concatenation axis must match exactly, but along dimension 1, the array at index 0 has size 1 and the array at index 1 has size 754
2024-11-09 13:54:43,932 INFO werkzeug Thread-10 (process_request_thread) : 127.0.0.1 - - [09/Nov/2024 13:54:43] "[31m[1mPOST /api/attribution HTTP/1.1[0m" 400 -
Assistant
main
main
main
10,654.99
2024-11-09 13:54:42,313 INFO __main__ Thread-8 (process_request_thread) : Total Transaction Costs:
main
main
main
main
main
main
main
11,033.87
2024-11-09 13:54:42,447 INFO __main__ Thread-8 (process_request_thread) : Total Transaction Costs:
main
main
main
main
main
main
11,043.55
2024-11-09 13:54:42,567 INFO __main__ Thread-8 (process_request_thread) : Total Transaction Costs:
main
main
main
main
main
main
10,618.30
2024-11-09 13:54:42,686 INFO __main__ Thread-8 (process_request_thread) : Total Transaction Costs:
main
main
main
main
main
from flask import Flask, request, jsonify
from flask_cors import CORS
import yfinance as yf
import pandas as pd
import numpy as np
from datetime import datetime, timedelta
import json
import os
from scipy import stats
from functools import lru_cache
import hashlib
import pickle
import empyrical as ep
import traceback
import io
import csv
import logging
if cached_data is not None:
return cached_data
try:
stock_data = yf.download(ticker, start=start_date, progress=False)
if not stock_data.empty:
save_to_cache(cache_key, stock_data)
logger.info(f"Data fetched and cached for {ticker} from {start_date}")
else:
logger.warning(f"No data fetched for {ticker} from {start_date}")
return stock_data
except Exception as e:
logger.error(f"Failed to fetch data for {ticker}: {str(e)}")
return pd.DataFrame()
def clean_for_json(obj):
if isinstance(obj, (np.integer, np.floating)):
return float(obj) if not (np.isnan(obj) or np.isinf(obj)) else None
elif isinstance(obj, dict):
return {k: clean_for_json(v) for k, v in obj.items()}
elif isinstance(obj, (list, tuple)):
return [clean_for_json(x) for x in obj]
elif isinstance(obj, pd.Series):
return [clean_for_json(x) for x in obj.values]
elif isinstance(obj, pd.DataFrame):
return {col: clean_for_json(obj[col]) for col in obj.columns}
elif isinstance(obj, np.ndarray):
return [clean_for_json(x) for x in obj.flatten()]
elif pd.isna(obj):
return None
return obj
writer.writerow(['Portfolio Metrics'])
writer.writerow(['Metric', 'Portfolio', 'Benchmark'])
for key in results.get('portfolio_metrics', {}):
writer.writerow([
key,
results['portfolio_metrics'][key],
results['benchmark_metrics'].get(key, 'N/A')
])
writer.writerow([])
writer.writerow(['Historical Performance'])
writer.writerow(['Date', 'Portfolio Value', 'Benchmark Value'])
for i, date in enumerate(results['historical_performance']['dates']):
writer.writerow([
date,
results['historical_performance']['portfolio_values'][i],
results['historical_performance']['benchmark_values'][i]
])
csv_content = output.getvalue()
output.close()
logger.info("CSV report generated successfully")
return csv_content
def get_sector_info(ticker):
try:
info = get_ticker_info(ticker)
return info.get('sector', 'Unknown')
except Exception as e:
logger.error(f"Failed to get sector info for {ticker}: {str(e)}")
return 'Unknown'
def calculate_attribution(portfolio_data, weights, benchmark_data):
try:
logger.info("Starting attribution calculation...")
logger.debug(f"Portfolio data shape: {portfolio_data.shape}")
logger.debug(f"Weights length: {len(weights)}")
logger.debug(f"Benchmark data shape: {benchmark_data.shape}")
portfolio = data['portfolio']
start_date = data.get('startDate')
benchmark = data.get('benchmark', 'SPY')
logger.info(f"Processing portfolio: {portfolio}")
logger.info(f"Start date: {start_date}")
logger.info(f"Benchmark: {benchmark}")
# Get portfolio data
portfolio_data = pd.DataFrame()
start_date = pd.to_datetime(start_date)
# Fetch data using fetch_stock_data and calculate weights
stock_data_dict = {}
weights = []
for stock in portfolio:
ticker = stock['ticker'].strip().upper()
weight = float(stock['weight']) / 100
stock_data = fetch_stock_data(ticker, start_date)
if stock_data is None or stock_data.empty:
logger.error(f"No data available for {ticker}")
return jsonify({
'success': False,
'error': f'No data available for {ticker}'
}), 400
stock_data_dict[ticker] = stock_data['Adj Close']
weights.append(weight)
# Validate that weights sum to 1
total_weight = sum(weights)
if not np.isclose(total_weight, 1.0):
logger.error(f"Portfolio weights sum to {total_weight * 100:.2f}%, which is not 100%.")
return jsonify({
'success': False,
'error': f'Portfolio weights must sum to 100%. Current sum: {total_weight * 100:.2f}%'
}), 400
# Fetch benchmark data
benchmark_data = fetch_stock_data(benchmark, start_date)
if benchmark_data is None or benchmark_data.empty:
logger.error(f"No data available for benchmark {benchmark}")
return jsonify({
'success': False,
'error': f'No data available for benchmark {benchmark}'
}), 400
benchmark_data = benchmark_data['Adj Close']
# Create aligned portfolio data
common_dates = None
for ticker, data in stock_data_dict.items():
if common_dates is None:
common_dates = data.index
else:
common_dates = common_dates.intersection(data.index)
# Add benchmark dates to intersection
common_dates = common_dates.intersection(benchmark_data.index)
# Align all data to common dates
for ticker in stock_data_dict:
portfolio_data[ticker] = stock_data_dict[ticker].reindex(common_dates)
benchmark_data = benchmark_data.reindex(common_dates)
# Drop any remaining NaNs
portfolio_data = portfolio_data.dropna()
benchmark_data = benchmark_data.dropna()
if portfolio_data.empty or benchmark_data.empty:
logger.error("Insufficient overlapping data between portfolio and benchmark.")
return jsonify({
'success': False,
'error': 'Insufficient overlapping data between portfolio and benchmark.'
}), 400
# Calculate returns
portfolio_returns = portfolio_data.pct_change().fillna(0)
benchmark_returns = benchmark_data.pct_change().fillna(0) # Already a Series
# Calculate metrics
portfolio_metrics = calculate_portfolio_metrics(
portfolio_data=portfolio_data,
weights=weights,
benchmark_returns=benchmark_returns
)
# Create benchmark DataFrame with proper dimensions
benchmark_df = pd.DataFrame()
benchmark_df[benchmark] = benchmark_data
benchmark_metrics = calculate_portfolio_metrics(
portfolio_data=benchmark_df,
weights=[1.0],
benchmark_returns=None
)
# Calculate historical performance
initial_investment = 10000
portfolio_values = initial_investment * (1 + portfolio_returns.dot(weights)).cumprod()
benchmark_values = initial_investment * (1 + benchmark_returns).cumprod()
# Ensure both series have the same index
common_dates = portfolio_values.index.intersection(benchmark_values.index)
portfolio_values = portfolio_values.reindex(common_dates)
benchmark_values = benchmark_values.reindex(common_dates)
response_data = {
'success': True,
'portfolio_metrics': clean_for_json(portfolio_metrics),
'benchmark_metrics': clean_for_json(benchmark_metrics),
'historical_performance': {
'dates': common_dates.strftime('%Y-%m-%d').tolist(),
'portfolio_values': clean_for_json(portfolio_values.values), # Use .values to get numpy array
'benchmark_values': clean_for_json(benchmark_values.values), # Use .values to get numpy array
'initial_investment': initial_investment
}
}
logger.info("Response data prepared successfully")
return jsonify(response_data)
except Exception as e:
logger.error(f"Error in backtest: {str(e)}", exc_info=True)
return jsonify({
'success': False,
'error': str(e)
}), 400
portfolio_data = pd.DataFrame()
for stock in portfolio:
ticker = stock['ticker'].strip().upper()
stock_data = fetch_stock_data(ticker, start_date)
if stock_data is None or stock_data.empty:
logger.error(f"No data available for {ticker}")
return jsonify({
'success': False,
'error': f'No data available for {ticker}'
}), 400
portfolio_data[ticker] = stock_data['Adj Close']
logger.info("Fetching benchmark data...")
benchmark_data = fetch_stock_data(benchmark, start_date)['Adj Close']
if benchmark_data.empty:
logger.error(f"No data available for benchmark {benchmark}")
return jsonify({
'success': False,
'error': f'No data available for benchmark {benchmark}'
}), 400
# Find common dates
logger.info("Finding common dates...")
common_dates = portfolio_data.index.intersection(benchmark_data.index)
if len(common_dates) == 0:
logger.error("No overlapping dates found for the selected securities")
return jsonify({
'success': False,
'error': 'No overlapping dates found for the selected securities'
}), 400
portfolio_data = portfolio_data.reindex(common_dates).dropna()
benchmark_data = benchmark_data.reindex(common_dates).dropna()
if portfolio_data.empty or benchmark_data.empty:
logger.error("Insufficient overlapping data after reindexing.")
return jsonify({
'success': False,
'error': 'Insufficient overlapping data after reindexing.'
}), 400
weights = [float(stock['weight']) / 100 for stock in portfolio]
# Validate that weights sum to 1
total_weight = sum(weights)
if not np.isclose(total_weight, 1.0):
logger.error(f"Portfolio weights sum to {total_weight * 100:.2f}%, which is not 100%.")
return jsonify({
'success': False,
'error': f'Portfolio weights must sum to 100%. Current sum: {total_weight * 100:.2f}%'
}), 400
logger.info("Calculating attribution...")
attribution = calculate_attribution(
portfolio_data=portfolio_data,
weights=np.array(weights, dtype=float),
benchmark_data=benchmark_data
)
return jsonify({
'success': True,
'attribution': attribution
})
except Exception as e:
logger.error(f"Error in get_attribution: {str(e)}", exc_info=True)
return jsonify({
'success': False,
'error': str(e)
}), 400
portfolio_data = pd.DataFrame()
weights = []
for stock in portfolio:
ticker = stock['ticker'].strip().upper()
weight = float(stock['weight']) / 100
stock_data = fetch_stock_data(ticker, start_date)
if stock_data is None or stock_data.empty:
logger.error(f"No data available for {ticker}")
return jsonify({
'success': False,
'error': f'No data available for {ticker}'
}), 400
portfolio_data[ticker] = stock_data['Adj Close']
weights.append(weight)
# Validate that weights sum to 1
total_weight = sum(weights)
if not np.isclose(total_weight, 1.0):
logger.error(f"Portfolio weights sum to {total_weight * 100:.2f}%, which is not 100%.")
return jsonify({
'success': False,
'error': f'Portfolio weights must sum to 100%. Current sum: {total_weight * 100:.2f}%'
}), 400
weights = np.array(weights)
rebalancing_results = calculate_rebalancing_impact(portfolio_data, weights)
return jsonify({
'success': True,
'rebalancing_results': rebalancing_results
})
except Exception as e:
logger.error(f"Error in analyze_rebalancing: {str(e)}", exc_info=True)
return jsonify({
'success': False,
'error': str(e)
}), 400
@app.route('/api/cache/clear', methods=['POST'])
def clear_cache():
try:
for file in os.listdir(CACHE_DIR):
if file.endswith('.pkl'):
os.remove(os.path.join(CACHE_DIR, file))
logger.debug(f"Cache file removed: {file}")
logger.info("Cache cleared successfully")
return jsonify({
'success': True,
'message': 'Cache cleared successfully'
})
except Exception as e:
logger.error(f"Error in clear_cache: {str(e)}", exc_info=True)
return jsonify({
'success': False,
'error': str(e)
}), 400
@app.route('/api/cache/status', methods=['GET'])
def cache_status():
try:
cache_files = [f for f in os.listdir(CACHE_DIR) if f.endswith('.pkl')]
total_size = sum(os.path.getsize(os.path.join(CACHE_DIR, f)) for f in cache_files)
portfolio_data = pd.DataFrame()
for stock in portfolio:
ticker = stock['ticker'].strip().upper()
stock_data = fetch_stock_data(ticker, start_date)
if stock_data is None or stock_data.empty:
logger.error(f"No data available for {ticker}")
return jsonify({
'success': False,
'error': f'No data available for {ticker}'
}), 400
portfolio_data[ticker] = stock_data['Adj Close']
if portfolio_data.empty:
logger.error("No data available for correlation calculation")
return jsonify({
'success': False,
'error': 'No data available for correlation calculation'
}), 400
correlations = calculate_correlation_matrix(portfolio_data)
return jsonify({
'success': True,
'correlations': correlations
})
except Exception as e:
logger.error(f"Error in get_correlation: {str(e)}", exc_info=True)
return jsonify({
'success': False,
'error': str(e)
}), 400
if name == 'main':
app.run(debug=True)
The error you're encountering stems from a mismatch in the dimensions of the arrays being passed to the stats.linregress function in your calculate_attribution method. Specifically, the error message indicates that one array has a size of 1 along a particular dimension, while the other has a size of 754, leading to a ValueError during the concatenation process inside numpy.
Upon reviewing your provided code, there are a few key issues and improvements to address:
Duplicate Function Definitions:
Issue: The calculate_attribution function is defined twice in your backend.py. This redundancy can lead to unexpected behaviors and bugs.
Solution: Remove the duplicate definition to ensure only one, correctly implemented calculate_attribution function exists.
Mismatch in Array Dimensions:
Issue: The benchmark_returns and weighted_returns.sum(axis=1) may not be properly aligned or might have different shapes when passed to stats.linregress.
Solution: Ensure both series are one-dimensional and of equal length before performing regression.
Data Alignment and Cleaning:
Issue: There might be misaligned dates or residual NaN values after reindexing, leading to unexpected shapes.
Solution: Carefully align the data and handle any missing values appropriately.
Deprecation Warning:
Issue: The warning about 'M' being deprecated in your resample method usage.
Solution: Update the resampling frequency from 'M' to 'ME' as recommended.
Let's address these issues step-by-step.
1. Remove Duplicate calculate_attribution Function
Having two definitions of the same function can lead to confusion and unintended overwrites. Remove one of the calculate_attribution functions to maintain clarity and prevent potential bugs.
Action:
Delete the second definition of calculate_attribution in your backend.py.
2. Ensure Correct Dimensions Before Regression
Before performing linear regression, both benchmark_returns and weighted_returns.sum(axis=1) must be one-dimensional arrays of the same length. Here's how you can modify the calculate_attribution function to ensure this:
python
Explanation of Changes:
Flattening the Arrays:
benchmark_returns_aligned and portfolio_returns_aligned are explicitly flattened to ensure they are one-dimensional.
Length Check:
A check is added to confirm both arrays have the same length post-alignment. If not, an error is raised with a clear message.
Consistent Naming:
Variables are renamed to *_aligned to signify that they are aligned and ready for processing.
3. Update the Resampling Frequency
The FutureWarning indicates that the frequency 'M' is deprecated. Replace 'M' with 'ME' as follows:
Note: Ensure that 'ME' correctly represents the desired frequency in your context. If 'ME' is not valid, refer to the Pandas Resample Documentation to choose an appropriate frequency string.
4. Additional Recommendations
Logging Enhancements:
Utilize more granular logging (e.g., logger.debug) to capture intermediate states and data shapes. This aids in debugging.
Exception Handling:
Provide more descriptive error messages where possible to facilitate easier debugging.
Data Validation:
Before performing critical operations like regression, validate the data to ensure it meets the necessary requirements.
Code Clean-Up:
Ensure unused imports or redundant code segments are removed to keep the codebase clean and maintainable.
5. Final Revised calculate_attribution Function
Here's the complete revised calculate_attribution function incorporating all the above changes:
python
6. Update Resampling in calculate_portfolio_metrics
Address the deprecation warning by updating the resampling frequency from 'M' to 'ME' or another appropriate frequency.
Note: Verify that 'ME' aligns with your intended resampling frequency. Alternatively, you might consider 'MS' for month start or another suitable frequency based on your requirements.
7. Summary of Actions
Remove the duplicated calculate_attribution function to prevent overriding and potential inconsistencies.
Ensure both benchmark_returns and weighted_returns.sum(axis=1) are one-dimensional arrays of the same length before passing them to stats.linregress.
Update the resampling frequency from 'M' to 'ME' or a more appropriate value to eliminate the FutureWarning.
Enhance logging and error handling to capture more detailed information for easier debugging in the future.
Validate data alignment thoroughly to ensure all operations are performed on correctly matched datasets.
By implementing these changes, you should resolve the ValueError related to mismatched dimensions and improve the overall robustness and maintainability of your Flask backend.
If you continue to experience issues, consider adding more detailed debug logs to inspect the shapes and contents of your data at each processing step.