Skip to content
Merged

new #205

Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Binary file removed Images/osconnect.png
Binary file not shown.
22 changes: 0 additions & 22 deletions backend/AAPL_history.csv

This file was deleted.

139 changes: 5 additions & 134 deletions backend/app.py
Original file line number Diff line number Diff line change
@@ -1,152 +1,23 @@
from flask import Flask, jsonify, request, send_file
from io import BytesIO
import yfinance as yf
import pandas as pd
import numpy as np
import plotly.express as px
from flask import Flask
from flask_cors import CORS
import json
import traceback
import plotly
import requests
from tensorflow.keras.models import load_model
from sklearn.preprocessing import MinMaxScaler
from datetime import datetime, timedelta
from sklearn.linear_model import LinearRegression
import os
from routes.stock_routes import stock_routes
from dotenv import load_dotenv

# Load env
load_dotenv()

app = Flask(__name__)
CORS(app, resources={r"/*": {"origins": ["http://localhost:3000", "https://aistockanalyzer.onrender.com"]}})

# Home route:
@app.route('/')
def home():
return "Welcome to the Stock Analysis API"


@app.route('/api/export/history', methods=['GET'])
def export_stock_history():
ticker = request.args.get('ticker')
period = request.args.get('period', '1mo')
filetype = request.args.get('type', 'csv')

if not ticker:
return jsonify({'error': 'Ticker is required'}), 400

data = fetch_stock_data(ticker, period)
if isinstance(data, str):
return jsonify({'error': data}), 500

data = clean_stock_data(data)

file_io = BytesIO()
if filetype == 'excel':
data.to_excel(file_io, index=False, engine='openpyxl')
mimetype = 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet'
ext = 'xlsx'
else:
data.to_csv(file_io, index=False)
mimetype = 'text/csv'
ext = 'csv'

file_io.seek(0)
return send_file(file_io, mimetype=mimetype, as_attachment=True, download_name=f"{ticker}_history.{ext}")


@app.route('/api/export/prediction', methods=['GET'])
def export_predictions():
ticker = request.args.get('ticker')
if not ticker:
return jsonify({'error': 'Ticker is required'}), 400

try:
data = yf.download(ticker, period='5y')
if data.empty:
return jsonify({'error': 'No data found'}), 404

data['Date'] = data.index
data['Date'] = data['Date'].map(datetime.toordinal)
X = data['Date'].values.reshape(-1, 1)
y = data['Close'].values.flatten()

model = LinearRegression()
model.fit(X, y)

future_dates = [datetime.now() + timedelta(days=i*365) for i in range(1, 11)]
predictions = model.predict(np.array([d.toordinal() for d in future_dates]).reshape(-1, 1))

df_pred = pd.DataFrame({
'Date': [d.strftime('%Y-%m-%d') for d in future_dates],
'Predicted Price': [round(float(p), 2) for p in predictions]
})

file_io = BytesIO()
filetype = request.args.get('type', 'csv')
if filetype == 'excel':
df_pred.to_excel(file_io, index=False, engine='openpyxl')
mimetype = 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet'
ext = 'xlsx'
else:
df_pred.to_csv(file_io, index=False)
mimetype = 'text/csv'
ext = 'csv'

file_io.seek(0)
return send_file(file_io, mimetype=mimetype, as_attachment=True, download_name=f"{ticker}_prediction.{ext}")

except Exception as e:
return jsonify({'error': str(e)}), 500


@app.route('/api/stock/predict', methods=['GET', 'OPTIONS'])
def predict_stock():
ticker = request.args.get('ticker')
if not ticker:
return jsonify({'error': 'Ticker symbol is required'}), 400

try:
data = yf.download(ticker, period='5y')
if data.empty:
return jsonify({'error': 'No data found for the given ticker'}), 404

data['Date'] = data.index
data['Date'] = data['Date'].map(datetime.toordinal)
X = data['Date'].values.reshape(-1, 1)
y = data['Close'].values.flatten()

model = LinearRegression()
model.fit(X, y)

future_dates = [datetime.now() + timedelta(days=i*365) for i in range(1, 11)]
predictions = model.predict(np.array([d.toordinal() for d in future_dates]).reshape(-1, 1))

stocks = [10, 20, 50, 100]
returns = []
current_price = float(y[-1])

for stock in stocks:
returns.append({
'stocks_bought': stock,
'current_price': round(current_price * stock, 2),
'after_1_year': round(float(predictions[0]) * stock, 0),
'after_5_years': round(float(predictions[4]) * stock, 0),
'after_10_years': round(float(predictions[9]) * stock, 0)
})

return jsonify({
"future_predictions": [round(float(p), 2) for p in predictions],
"returns": returns
})

except Exception as e:
return jsonify({'error': str(e)}), 500


# Register blueprint
app.register_blueprint(stock_routes, url_prefix="/api")

if __name__ == '__main__':
port = int(os.environ.get('PORT', 10000))
app.run(host='0.0.0.0', port=port)
app.run(host='0.0.0.0', port=port)
64 changes: 31 additions & 33 deletions backend/requirements.txt
Original file line number Diff line number Diff line change
@@ -1,43 +1,41 @@
Flask==3.1.1
flask-cors==6.0.1
gunicorn==23.0.0
python-dotenv
numpy==2.3.2
pandas==2.3.1
scikit-learn==1.7.1
scipy==1.16.1
tensorflow==2.17.0
joblib==1.5.1
threadpoolctl==3.6.0
yfinance==0.2.65
requests==2.32.4
beautifulsoup4==4.13.4
textblob
plotly==6.2.0
openpyxl
frozendict==2.4.6
typing_extensions==4.14.1
packaging==25.0
blinker==1.9.0
certifi==2025.8.3
cffi==1.17.1
charset-normalizer==3.4.2
click==8.2.1
curl_cffi==0.12.0
dotenv
Flask==3.1.1
flask-cors==6.0.1
frozendict==2.4.6
idna==3.10
urllib3==2.5.0
pytz==2025.2
tzdata==2025.2
itsdangerous==2.2.0
Jinja2==3.1.6
joblib==1.5.1
MarkupSafe==3.0.2
multitasking==0.0.12
narwhals==2.0.1
numpy==2.3.2
packaging==25.0
pandas==2.3.1
peewee==3.18.2
platformdirs==4.3.8
blinker==1.9.0
click==8.2.1
itsdangerous==2.2.0
Jinja2==3.1.6
MarkupSafe==3.0.2
Werkzeug==3.1.3
redis>=5.0.0
websockets==15.0.1
soupsieve==2.7
curl_cffi==0.12.0
plotly==6.2.0
protobuf==6.31.1
pycparser==2.22
six==1.17.0
python-dateutil==2.9.0.post0
pytz==2025.2
requests==2.32.4
scikit-learn==1.7.1
scipy==1.16.1
six==1.17.0
soupsieve==2.7
threadpoolctl==3.6.0
typing_extensions==4.14.1
tzdata==2025.2
urllib3==2.5.0
websockets==15.0.1
Werkzeug==3.1.3
yfinance==0.2.65
textblob
6 changes: 3 additions & 3 deletions src/components/StockList.jsx
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,7 @@ import { auth } from "./firebase";
import stockData from "./data/stockData.json";
import BackToTopBtn from "./BackToTopBtn";
import styles from "./StockList.module.css";
import stockBg2 from "../Images/stock2.png";
import stockBg2 from "./images/bg.png";

const StocksList = () => {
const [stocks, setStocks] = useState([]);
Expand Down Expand Up @@ -54,13 +54,13 @@ const StocksList = () => {
animate={{ opacity: 1 }}
>
{/* 🚀 Hero Section */}
<section
<section
className={styles.hero}
style={{
backgroundImage: `linear-gradient(135deg, rgba(33,84,214,0.63), rgba(29,30,41,0.46)), url(${stockBg2})`,
backgroundSize: "contain", // CHANGED from 'cover' to 'contain'
backgroundPosition: "center bottom", // Focus lower part (the phone/hand)
backgroundRepeat: "no-repeat"
backgroundRepeat: "no-repeat",
}}
>
<h1>Welcome to Stock Analyzer!</h1>
Expand Down