Spaces:
Sleeping
Sleeping
Commit Β·
57ee2b0
unverified Β·
0
Parent(s):
Add files via upload
Browse files- .gitignore +8 -0
- README.md +116 -0
- app.js +660 -0
- app.py +352 -0
- index.html +205 -0
- model.py +211 -0
- portfolio.json +8 -0
- sentiment.py +151 -0
- step4_install.sh +12 -0
- stock_data.py +118 -0
- style.css +274 -0
- trader.py +287 -0
.gitignore
ADDED
|
@@ -0,0 +1,8 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
__pycache__/
|
| 2 |
+
*.pyc
|
| 3 |
+
venv/
|
| 4 |
+
.env
|
| 5 |
+
trained_models/
|
| 6 |
+
portfolio.json
|
| 7 |
+
node_modules/
|
| 8 |
+
.DS_Store
|
README.md
ADDED
|
@@ -0,0 +1,116 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# π StockSense AI β AI-Powered Stock Market Prediction
|
| 2 |
+
|
| 3 |
+
> **Hackathon Project** | Built in 48 hours
|
| 4 |
+
|
| 5 |
+
##π€ Elevator Pitch (30 seconds)
|
| 6 |
+
|
| 7 |
+
*"StockSense AI uses deep learning and NLP to predict stock prices 5 days ahead.
|
| 8 |
+
Enter any ticker β our LSTM model analyzes 2 years of market data and technical
|
| 9 |
+
indicators, while FinBERT reads the latest financial news to gauge market
|
| 10 |
+
sentiment. You get an interactive chart with predictions, a confidence score,
|
| 11 |
+
a risk level, and a clear sentiment breakdown β all in seconds."*
|
| 12 |
+
|
| 13 |
+
---
|
| 14 |
+
|
| 15 |
+
## π Quick Start
|
| 16 |
+
|
| 17 |
+
### Prerequisites
|
| 18 |
+
- Python 3.10+
|
| 19 |
+
- Node.js (optional β only if you want a dev server for frontend)
|
| 20 |
+
- ~2 GB disk for FinBERT model weights (auto-downloaded)
|
| 21 |
+
|
| 22 |
+
### 1. Backend Setup
|
| 23 |
+
|
| 24 |
+
```bash
|
| 25 |
+
cd backend
|
| 26 |
+
python -m venv venv
|
| 27 |
+
source venv/bin/activate # Windows: venv\Scripts\activate
|
| 28 |
+
pip install -r requirements.txt
|
| 29 |
+
uvicorn app:app --reload --port 8000
|
| 30 |
+
```
|
| 31 |
+
|
| 32 |
+
The API will be live at **http://localhost:8000**.
|
| 33 |
+
|
| 34 |
+
### 2. Frontend Setup
|
| 35 |
+
|
| 36 |
+
Simply open `frontend/index.html` in your browser, **or** serve it:
|
| 37 |
+
|
| 38 |
+
```bash
|
| 39 |
+
cd frontend
|
| 40 |
+
python -m http.server 3000
|
| 41 |
+
```
|
| 42 |
+
|
| 43 |
+
Then visit **http://localhost:3000**.
|
| 44 |
+
|
| 45 |
+
---
|
| 46 |
+
|
| 47 |
+
## π API Endpoints
|
| 48 |
+
|
| 49 |
+
| Method | Endpoint | Description |
|
| 50 |
+
|--------|----------------------------|------------------------------------|
|
| 51 |
+
| GET | `/api/stock/{ticker}` | Historical data + indicators |
|
| 52 |
+
| GET | `/api/predict/{ticker}` | LSTM 5-day price prediction |
|
| 53 |
+
| GET | `/api/sentiment/{ticker}` | FinBERT news sentiment analysis |
|
| 54 |
+
| GET | `/api/summary/{ticker}` | Combined analysis (all of above) |
|
| 55 |
+
|
| 56 |
+
---
|
| 57 |
+
|
| 58 |
+
## ποΈ Architecture
|
| 59 |
+
|
| 60 |
+
```
|
| 61 |
+
User β React/HTML Frontend β FastAPI Backend
|
| 62 |
+
βββ yfinance (stock data)
|
| 63 |
+
βββ ta (technical indicators)
|
| 64 |
+
βββ PyTorch LSTM (price prediction)
|
| 65 |
+
βββ FinBERT (sentiment analysis)
|
| 66 |
+
```
|
| 67 |
+
|
| 68 |
+
---
|
| 69 |
+
|
| 70 |
+
## π§ ML Pipeline
|
| 71 |
+
|
| 72 |
+
1. **Data**: 2 years of daily OHLCV via Yahoo Finance
|
| 73 |
+
2. **Features**: Close price (normalized via MinMaxScaler)
|
| 74 |
+
3. **Model**: 2-layer LSTM (64 hidden units) β FC β 5-day output
|
| 75 |
+
4. **Training**: 30 epochs, Adam optimizer, MSE loss, 85/15 train/test split
|
| 76 |
+
5. **Inference**: Last 60-day window β next 5 closing prices
|
| 77 |
+
|
| 78 |
+
---
|
| 79 |
+
|
| 80 |
+
## βοΈ Deployment (Optional)
|
| 81 |
+
|
| 82 |
+
### Docker
|
| 83 |
+
|
| 84 |
+
```dockerfile
|
| 85 |
+
FROM python:3.11-slim
|
| 86 |
+
WORKDIR /app
|
| 87 |
+
COPY backend/ .
|
| 88 |
+
RUN pip install --no-cache-dir -r requirements.txt
|
| 89 |
+
EXPOSE 8000
|
| 90 |
+
CMD ["uvicorn", "app:app", "--host", "0.0.0.0", "--port", "8000"]
|
| 91 |
+
```
|
| 92 |
+
|
| 93 |
+
```bash
|
| 94 |
+
docker build -t stocksense-ai .
|
| 95 |
+
docker run -p 8000:8000 stocksense-ai
|
| 96 |
+
```
|
| 97 |
+
|
| 98 |
+
### Cloud (Render / Railway / Fly.io)
|
| 99 |
+
1. Push to GitHub
|
| 100 |
+
2. Connect repo on Render β set build command: `pip install -r requirements.txt`
|
| 101 |
+
3. Set start command: `uvicorn app:app --host 0.0.0.0 --port 8000`
|
| 102 |
+
|
| 103 |
+
---
|
| 104 |
+
|
| 105 |
+
## β οΈ Disclaimer
|
| 106 |
+
|
| 107 |
+
This project is for **educational and hackathon demonstration purposes only**.
|
| 108 |
+
Stock market predictions generated by this tool are **not financial advice**.
|
| 109 |
+
Past performance does not guarantee future results. Always consult a qualified
|
| 110 |
+
financial advisor before making investment decisions.
|
| 111 |
+
|
| 112 |
+
---
|
| 113 |
+
|
| 114 |
+
## π License
|
| 115 |
+
|
| 116 |
+
MIT β feel free to fork and improve!
|
app.js
ADDED
|
@@ -0,0 +1,660 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
/* ββββββββββββββββββββββββββββββββββββββββββββββββββββββ
|
| 2 |
+
StockSense AI β Frontend v3.0 (COMPLETE FILE)
|
| 3 |
+
Live Charts + Prediction + Auto Trading Bot
|
| 4 |
+
ββββββββββββββββββββββββββββββββββββββββββββββββββββββ */
|
| 5 |
+
|
| 6 |
+
const API = "http://127.0.0.1:8000";
|
| 7 |
+
let currentTicker = "";
|
| 8 |
+
let liveInterval = null;
|
| 9 |
+
let portfolioInterval = null;
|
| 10 |
+
let mainChart = null;
|
| 11 |
+
let volumeChart = null;
|
| 12 |
+
let predChart = null;
|
| 13 |
+
let activeTimeframe = "1d";
|
| 14 |
+
|
| 15 |
+
/* ββ INIT ββββββββββββββββββββββββββββββββββββββββββββββ */
|
| 16 |
+
document.addEventListener("DOMContentLoaded", () => {
|
| 17 |
+
loadHighPotential();
|
| 18 |
+
loadPortfolio();
|
| 19 |
+
setupTimeframeButtons();
|
| 20 |
+
portfolioInterval = setInterval(loadPortfolio, 15000);
|
| 21 |
+
|
| 22 |
+
document.getElementById("tickerInput").addEventListener("keydown", (e) => {
|
| 23 |
+
if (e.key === "Enter") loadTicker();
|
| 24 |
+
});
|
| 25 |
+
});
|
| 26 |
+
|
| 27 |
+
/* ββ TAB SWITCHING βββββββββββββββββββββββββββββββββββββ */
|
| 28 |
+
function switchTab(tab) {
|
| 29 |
+
document.querySelectorAll(".nav-tab").forEach((t) => t.classList.remove("active"));
|
| 30 |
+
document.querySelectorAll(".tab-content").forEach((t) => t.classList.add("hidden"));
|
| 31 |
+
|
| 32 |
+
if (tab === "charts") {
|
| 33 |
+
document.getElementById("chartsTab").classList.remove("hidden");
|
| 34 |
+
document.querySelectorAll(".nav-tab")[0].classList.add("active");
|
| 35 |
+
} else {
|
| 36 |
+
document.getElementById("tradingTab").classList.remove("hidden");
|
| 37 |
+
document.querySelectorAll(".nav-tab")[1].classList.add("active");
|
| 38 |
+
loadPortfolio();
|
| 39 |
+
}
|
| 40 |
+
}
|
| 41 |
+
|
| 42 |
+
/* ββ TIMEFRAME BUTTONS βββββββββββββββββββββββββββββββββ */
|
| 43 |
+
function setupTimeframeButtons() {
|
| 44 |
+
document.querySelectorAll(".tf-btn").forEach((btn) => {
|
| 45 |
+
btn.addEventListener("click", () => {
|
| 46 |
+
document.querySelectorAll(".tf-btn").forEach((b) => b.classList.remove("active"));
|
| 47 |
+
btn.classList.add("active");
|
| 48 |
+
activeTimeframe = btn.dataset.tf;
|
| 49 |
+
if (currentTicker) loadChartData(currentTicker, activeTimeframe);
|
| 50 |
+
});
|
| 51 |
+
});
|
| 52 |
+
}
|
| 53 |
+
|
| 54 |
+
/* ββ MAIN LOAD TICKER ββββββββββββββββββββββββββββββββββ */
|
| 55 |
+
async function loadTicker(ticker) {
|
| 56 |
+
ticker = ticker || document.getElementById("tickerInput").value.trim().toUpperCase();
|
| 57 |
+
if (!ticker) return;
|
| 58 |
+
|
| 59 |
+
currentTicker = ticker;
|
| 60 |
+
document.getElementById("tickerInput").value = ticker;
|
| 61 |
+
|
| 62 |
+
if (liveInterval) clearInterval(liveInterval);
|
| 63 |
+
|
| 64 |
+
await Promise.all([
|
| 65 |
+
loadLivePrice(ticker),
|
| 66 |
+
loadChartData(ticker, activeTimeframe),
|
| 67 |
+
loadPrediction(ticker),
|
| 68 |
+
loadSentimentAndIndicators(ticker),
|
| 69 |
+
]);
|
| 70 |
+
|
| 71 |
+
liveInterval = setInterval(() => loadLivePrice(ticker), 10000);
|
| 72 |
+
}
|
| 73 |
+
|
| 74 |
+
/* ββ LIVE PRICE ββββββββββββββββββββββββββββββββββββββββ */
|
| 75 |
+
async function loadLivePrice(ticker) {
|
| 76 |
+
try {
|
| 77 |
+
const res = await fetch(`${API}/api/live/${ticker}`);
|
| 78 |
+
const data = await res.json();
|
| 79 |
+
|
| 80 |
+
document.getElementById("priceBanner").classList.remove("hidden");
|
| 81 |
+
document.getElementById("bannerName").textContent = ticker;
|
| 82 |
+
document.getElementById("bannerPrice").textContent = formatPrice(data.price);
|
| 83 |
+
|
| 84 |
+
const changeEl = document.getElementById("bannerChange");
|
| 85 |
+
const sign = data.change >= 0 ? "+" : "";
|
| 86 |
+
changeEl.textContent = `${sign}${data.change} (${sign}${data.change_pct}%)`;
|
| 87 |
+
changeEl.className = `price-change ${data.direction}`;
|
| 88 |
+
|
| 89 |
+
document.getElementById("statHigh").textContent = formatPrice(data.day_high);
|
| 90 |
+
document.getElementById("statLow").textContent = formatPrice(data.day_low);
|
| 91 |
+
document.getElementById("statVol").textContent = formatVolume(data.volume);
|
| 92 |
+
} catch (e) {
|
| 93 |
+
console.error("Live price error:", e);
|
| 94 |
+
}
|
| 95 |
+
}
|
| 96 |
+
|
| 97 |
+
/* ββ CHART DATA ββββββββββββββββββββββββββββββββββββββββ */
|
| 98 |
+
async function loadChartData(ticker, timeframe) {
|
| 99 |
+
try {
|
| 100 |
+
const [chartRes, infoRes] = await Promise.all([
|
| 101 |
+
fetch(`${API}/api/chart/${ticker}?timeframe=${timeframe}`),
|
| 102 |
+
fetch(`${API}/api/stock/${ticker}`),
|
| 103 |
+
]);
|
| 104 |
+
const chartData = await chartRes.json();
|
| 105 |
+
const stockData = await infoRes.json();
|
| 106 |
+
|
| 107 |
+
if (stockData.info) {
|
| 108 |
+
const info = stockData.info;
|
| 109 |
+
document.getElementById("bannerName").textContent = `${info.name} (${ticker})`;
|
| 110 |
+
document.getElementById("statOpen").textContent = formatPrice(info.open);
|
| 111 |
+
document.getElementById("statHigh").textContent = formatPrice(info.day_high);
|
| 112 |
+
document.getElementById("statLow").textContent = formatPrice(info.day_low);
|
| 113 |
+
document.getElementById("statVol").textContent = formatVolume(info.volume);
|
| 114 |
+
document.getElementById("stat52H").textContent = formatPrice(info.fifty_two_week_high);
|
| 115 |
+
document.getElementById("stat52L").textContent = formatPrice(info.fifty_two_week_low);
|
| 116 |
+
}
|
| 117 |
+
|
| 118 |
+
drawMainChart(chartData.data);
|
| 119 |
+
drawVolumeChart(chartData.data);
|
| 120 |
+
} catch (e) {
|
| 121 |
+
console.error("Chart error:", e);
|
| 122 |
+
}
|
| 123 |
+
}
|
| 124 |
+
|
| 125 |
+
/* ββ DRAW MAIN CHART βββββββββββββββββββββββββββββββββββ */
|
| 126 |
+
function drawMainChart(data) {
|
| 127 |
+
const labels = data.map((d) => d.time);
|
| 128 |
+
const closes = data.map((d) => d.close);
|
| 129 |
+
const highs = data.map((d) => d.high);
|
| 130 |
+
const lows = data.map((d) => d.low);
|
| 131 |
+
|
| 132 |
+
const isUp = closes[closes.length - 1] >= closes[0];
|
| 133 |
+
const lineColor = isUp ? "#22c55e" : "#ef4444";
|
| 134 |
+
const fillColor = isUp ? "rgba(34,197,94,0.08)" : "rgba(239,68,68,0.08)";
|
| 135 |
+
|
| 136 |
+
if (mainChart) mainChart.destroy();
|
| 137 |
+
|
| 138 |
+
mainChart = new Chart(document.getElementById("mainChart").getContext("2d"), {
|
| 139 |
+
type: "line",
|
| 140 |
+
data: {
|
| 141 |
+
labels,
|
| 142 |
+
datasets: [
|
| 143 |
+
{ label: "Close", data: closes, borderColor: lineColor, backgroundColor: fillColor, fill: true, tension: 0.3, pointRadius: 0, borderWidth: 2 },
|
| 144 |
+
{ label: "High", data: highs, borderColor: "rgba(34,197,94,0.2)", borderDash: [2, 4], pointRadius: 0, borderWidth: 1, fill: false },
|
| 145 |
+
{ label: "Low", data: lows, borderColor: "rgba(239,68,68,0.2)", borderDash: [2, 4], pointRadius: 0, borderWidth: 1, fill: false },
|
| 146 |
+
],
|
| 147 |
+
},
|
| 148 |
+
options: {
|
| 149 |
+
responsive: true,
|
| 150 |
+
maintainAspectRatio: false,
|
| 151 |
+
interaction: { mode: "index", intersect: false },
|
| 152 |
+
plugins: {
|
| 153 |
+
legend: { labels: { color: "#6b7280", font: { size: 11 } } },
|
| 154 |
+
tooltip: { backgroundColor: "#1a1f2e", borderColor: "#242a38", borderWidth: 1, titleColor: "#fff", bodyColor: "#d1d5db" },
|
| 155 |
+
},
|
| 156 |
+
scales: {
|
| 157 |
+
x: { ticks: { color: "#4b5563", maxTicksLimit: 10, maxRotation: 0, font: { size: 10 } }, grid: { color: "#1f2937" } },
|
| 158 |
+
y: { ticks: { color: "#4b5563", font: { size: 10 } }, grid: { color: "#1f2937" } },
|
| 159 |
+
},
|
| 160 |
+
},
|
| 161 |
+
});
|
| 162 |
+
}
|
| 163 |
+
|
| 164 |
+
/* ββ DRAW VOLUME CHART βββββββββββββββββββββββββββββββββ */
|
| 165 |
+
function drawVolumeChart(data) {
|
| 166 |
+
const labels = data.map((d) => d.time);
|
| 167 |
+
const volumes = data.map((d) => d.volume);
|
| 168 |
+
const colors = data.map((d, i) => {
|
| 169 |
+
if (i === 0) return "rgba(59,130,246,0.5)";
|
| 170 |
+
return d.close >= data[i - 1].close ? "rgba(34,197,94,0.5)" : "rgba(239,68,68,0.5)";
|
| 171 |
+
});
|
| 172 |
+
|
| 173 |
+
if (volumeChart) volumeChart.destroy();
|
| 174 |
+
|
| 175 |
+
volumeChart = new Chart(document.getElementById("volumeChart").getContext("2d"), {
|
| 176 |
+
type: "bar",
|
| 177 |
+
data: {
|
| 178 |
+
labels,
|
| 179 |
+
datasets: [{ label: "Volume", data: volumes, backgroundColor: colors, borderWidth: 0 }],
|
| 180 |
+
},
|
| 181 |
+
options: {
|
| 182 |
+
responsive: true,
|
| 183 |
+
maintainAspectRatio: false,
|
| 184 |
+
plugins: { legend: { display: false } },
|
| 185 |
+
scales: {
|
| 186 |
+
x: { display: false },
|
| 187 |
+
y: { ticks: { color: "#4b5563", font: { size: 9 } }, grid: { color: "#1f2937" } },
|
| 188 |
+
},
|
| 189 |
+
},
|
| 190 |
+
});
|
| 191 |
+
}
|
| 192 |
+
|
| 193 |
+
/* ββ PREDICTION ββββββββββββββββββββββββββββββββββββββββ */
|
| 194 |
+
async function loadPrediction(ticker) {
|
| 195 |
+
const section = document.getElementById("predSection");
|
| 196 |
+
try {
|
| 197 |
+
const res = await fetch(`${API}/api/predict/${ticker}`);
|
| 198 |
+
const data = await res.json();
|
| 199 |
+
|
| 200 |
+
section.classList.remove("hidden");
|
| 201 |
+
|
| 202 |
+
document.getElementById("predConf").textContent = data.confidence + "%";
|
| 203 |
+
document.getElementById("predConf").style.color =
|
| 204 |
+
data.confidence >= 70 ? "#22c55e" : data.confidence >= 45 ? "#eab308" : "#ef4444";
|
| 205 |
+
|
| 206 |
+
document.getElementById("predRisk").textContent = data.risk;
|
| 207 |
+
document.getElementById("predRisk").style.color =
|
| 208 |
+
data.risk === "Low" ? "#22c55e" : data.risk === "Medium" ? "#eab308" : "#ef4444";
|
| 209 |
+
|
| 210 |
+
document.getElementById("predDay1").textContent = "$" + data.predicted_prices[0];
|
| 211 |
+
document.getElementById("predDay5").textContent = "$" + data.predicted_prices[4];
|
| 212 |
+
|
| 213 |
+
drawPredictionChart(data);
|
| 214 |
+
} catch (e) {
|
| 215 |
+
console.error("Prediction error:", e);
|
| 216 |
+
section.classList.add("hidden");
|
| 217 |
+
}
|
| 218 |
+
}
|
| 219 |
+
|
| 220 |
+
function drawPredictionChart(pred) {
|
| 221 |
+
const hist = pred.historical_last_30;
|
| 222 |
+
const future = pred.predicted_prices;
|
| 223 |
+
|
| 224 |
+
const labels = [];
|
| 225 |
+
for (let i = 0; i < hist.length; i++) labels.push(`D-${hist.length - i}`);
|
| 226 |
+
for (let i = 1; i <= future.length; i++) labels.push(`+${i}d`);
|
| 227 |
+
|
| 228 |
+
const histData = [...hist, ...Array(future.length).fill(null)];
|
| 229 |
+
const predData = [...Array(hist.length - 1).fill(null), hist[hist.length - 1], ...future];
|
| 230 |
+
|
| 231 |
+
if (predChart) predChart.destroy();
|
| 232 |
+
|
| 233 |
+
predChart = new Chart(document.getElementById("predChart").getContext("2d"), {
|
| 234 |
+
type: "line",
|
| 235 |
+
data: {
|
| 236 |
+
labels,
|
| 237 |
+
datasets: [
|
| 238 |
+
{ label: "Historical", data: histData, borderColor: "#3b82f6", backgroundColor: "rgba(59,130,246,0.05)", fill: true, tension: 0.3, pointRadius: 0, borderWidth: 2 },
|
| 239 |
+
{ label: "Predicted", data: predData, borderColor: "#22c55e", borderDash: [6, 3], backgroundColor: "rgba(34,197,94,0.08)", fill: true, tension: 0.3, pointRadius: 4, borderWidth: 2, pointBackgroundColor: "#22c55e" },
|
| 240 |
+
],
|
| 241 |
+
},
|
| 242 |
+
options: {
|
| 243 |
+
responsive: true,
|
| 244 |
+
plugins: { legend: { labels: { color: "#6b7280" } } },
|
| 245 |
+
scales: {
|
| 246 |
+
x: { ticks: { color: "#4b5563", maxTicksLimit: 12, font: { size: 10 } }, grid: { color: "#1f2937" } },
|
| 247 |
+
y: { ticks: { color: "#4b5563", font: { size: 10 } }, grid: { color: "#1f2937" } },
|
| 248 |
+
},
|
| 249 |
+
},
|
| 250 |
+
});
|
| 251 |
+
}
|
| 252 |
+
|
| 253 |
+
/* ββ SENTIMENT + INDICATORS ββββββββββββββββββββββββββββ */
|
| 254 |
+
async function loadSentimentAndIndicators(ticker) {
|
| 255 |
+
try {
|
| 256 |
+
const res = await fetch(`${API}/api/summary/${ticker}`);
|
| 257 |
+
const data = await res.json();
|
| 258 |
+
|
| 259 |
+
// Sentiment
|
| 260 |
+
const sentPanel = document.getElementById("sentPanel");
|
| 261 |
+
sentPanel.classList.remove("hidden");
|
| 262 |
+
|
| 263 |
+
const sent = data.sentiment;
|
| 264 |
+
const gauge = document.getElementById("gaugeCircle");
|
| 265 |
+
gauge.className = `gauge-circle ${sent.overall_sentiment}`;
|
| 266 |
+
document.getElementById("gaugeText").textContent = sent.overall_score;
|
| 267 |
+
document.getElementById("gaugeLabel").textContent = sent.overall_sentiment.toUpperCase();
|
| 268 |
+
document.getElementById("gaugeLabel").style.color =
|
| 269 |
+
sent.overall_sentiment === "positive" ? "#22c55e" :
|
| 270 |
+
sent.overall_sentiment === "negative" ? "#ef4444" : "#eab308";
|
| 271 |
+
|
| 272 |
+
const sentList = document.getElementById("sentList");
|
| 273 |
+
sentList.innerHTML = "";
|
| 274 |
+
(sent.details || []).forEach((d) => {
|
| 275 |
+
const li = document.createElement("li");
|
| 276 |
+
const cls = d.label === "positive" ? "s-pos" : d.label === "negative" ? "s-neg" : "s-neu";
|
| 277 |
+
li.innerHTML = `<span class="${cls}">β ${d.label}</span> ${d.text}`;
|
| 278 |
+
sentList.appendChild(li);
|
| 279 |
+
});
|
| 280 |
+
|
| 281 |
+
// Indicators
|
| 282 |
+
const indPanel = document.getElementById("indPanel");
|
| 283 |
+
indPanel.classList.remove("hidden");
|
| 284 |
+
const indBody = document.getElementById("indBody");
|
| 285 |
+
indBody.innerHTML = "";
|
| 286 |
+
Object.entries(data.indicators).forEach(([key, val]) => {
|
| 287 |
+
const tr = document.createElement("tr");
|
| 288 |
+
tr.innerHTML = `<td>${key}</td><td>${val}</td>`;
|
| 289 |
+
indBody.appendChild(tr);
|
| 290 |
+
});
|
| 291 |
+
} catch (e) {
|
| 292 |
+
console.error("Summary error:", e);
|
| 293 |
+
}
|
| 294 |
+
}
|
| 295 |
+
|
| 296 |
+
/* ββ HIGH POTENTIAL STOCKS βββββββββββββββββββββββββββββ */
|
| 297 |
+
async function loadHighPotential() {
|
| 298 |
+
try {
|
| 299 |
+
const res = await fetch(`${API}/api/high-potential`);
|
| 300 |
+
const data = await res.json();
|
| 301 |
+
|
| 302 |
+
document.getElementById("hpLoader").classList.add("hidden");
|
| 303 |
+
const list = document.getElementById("hpList");
|
| 304 |
+
list.innerHTML = "";
|
| 305 |
+
|
| 306 |
+
data.stocks.forEach((s) => {
|
| 307 |
+
const div = document.createElement("div");
|
| 308 |
+
div.className = "hp-item";
|
| 309 |
+
div.onclick = () => {
|
| 310 |
+
document.getElementById("tickerInput").value = s.ticker;
|
| 311 |
+
loadTicker(s.ticker);
|
| 312 |
+
};
|
| 313 |
+
|
| 314 |
+
const changeClass = s.change_pct >= 0 ? "up" : "down";
|
| 315 |
+
const sign = s.change_pct >= 0 ? "+" : "";
|
| 316 |
+
const scoreClass = s.score >= 70 ? "high" : s.score >= 45 ? "med" : "low";
|
| 317 |
+
|
| 318 |
+
div.innerHTML = `
|
| 319 |
+
<div>
|
| 320 |
+
<div class="hp-ticker">${s.ticker}</div>
|
| 321 |
+
<div class="hp-name">${s.name}</div>
|
| 322 |
+
</div>
|
| 323 |
+
<div>
|
| 324 |
+
<div class="hp-price">$${s.price}</div>
|
| 325 |
+
<div class="hp-change ${changeClass}">${sign}${s.change_pct}%</div>
|
| 326 |
+
</div>
|
| 327 |
+
<div class="hp-score ${scoreClass}">${s.signal}</div>
|
| 328 |
+
`;
|
| 329 |
+
list.appendChild(div);
|
| 330 |
+
});
|
| 331 |
+
} catch (e) {
|
| 332 |
+
document.getElementById("hpLoader").textContent = "β οΈ Scanner unavailable";
|
| 333 |
+
console.error("High potential error:", e);
|
| 334 |
+
}
|
| 335 |
+
}
|
| 336 |
+
|
| 337 |
+
/* ββββββββββββββββββββββββββββββββββββββββββββββββββββββ
|
| 338 |
+
TRADING FUNCTIONS
|
| 339 |
+
ββββββββββββββββββββββββββββββββββββββββββββββββββββββ */
|
| 340 |
+
|
| 341 |
+
/* ββ LOAD PORTFOLIO ββββββββββββββββββββββββββββββββββββ */
|
| 342 |
+
async function loadPortfolio() {
|
| 343 |
+
try {
|
| 344 |
+
const res = await fetch(`${API}/api/trade/portfolio`);
|
| 345 |
+
const data = await res.json();
|
| 346 |
+
|
| 347 |
+
// Portfolio header cards
|
| 348 |
+
document.getElementById("portValue").textContent = "$" + formatNumber(data.total_value || data.balance);
|
| 349 |
+
document.getElementById("portBalance").textContent = "$" + formatNumber(data.balance);
|
| 350 |
+
|
| 351 |
+
const unrealized = data.total_unrealized_pnl || 0;
|
| 352 |
+
const unrealizedEl = document.getElementById("portUnrealized");
|
| 353 |
+
unrealizedEl.textContent = (unrealized >= 0 ? "+$" : "-$") + formatNumber(Math.abs(unrealized));
|
| 354 |
+
unrealizedEl.style.color = unrealized >= 0 ? "#22c55e" : "#ef4444";
|
| 355 |
+
|
| 356 |
+
const realized = data.total_realized_pnl || 0;
|
| 357 |
+
const realizedEl = document.getElementById("portRealized");
|
| 358 |
+
realizedEl.textContent = (realized >= 0 ? "+$" : "-$") + formatNumber(Math.abs(realized));
|
| 359 |
+
realizedEl.style.color = realized >= 0 ? "#22c55e" : "#ef4444";
|
| 360 |
+
|
| 361 |
+
document.getElementById("portWinRate").textContent = (data.win_rate || 0) + "%";
|
| 362 |
+
document.getElementById("portWinRate").style.color = data.win_rate >= 50 ? "#22c55e" : "#ef4444";
|
| 363 |
+
|
| 364 |
+
document.getElementById("portTrades").textContent = data.total_trades || 0;
|
| 365 |
+
|
| 366 |
+
// Bot status
|
| 367 |
+
const botDot = document.getElementById("botDot");
|
| 368 |
+
const botStatus = document.getElementById("botStatus");
|
| 369 |
+
const toggleBtn = document.getElementById("toggleBotBtn");
|
| 370 |
+
|
| 371 |
+
if (data.bot_active) {
|
| 372 |
+
botDot.className = "bot-dot active";
|
| 373 |
+
botStatus.textContent = "Bot: ACTIVE";
|
| 374 |
+
botStatus.style.color = "#22c55e";
|
| 375 |
+
toggleBtn.textContent = "βΉ Deactivate Bot";
|
| 376 |
+
toggleBtn.classList.add("active");
|
| 377 |
+
} else {
|
| 378 |
+
botDot.className = "bot-dot";
|
| 379 |
+
botStatus.textContent = "Bot: OFF";
|
| 380 |
+
botStatus.style.color = "#ef4444";
|
| 381 |
+
toggleBtn.textContent = "β‘ Activate Bot";
|
| 382 |
+
toggleBtn.classList.remove("active");
|
| 383 |
+
}
|
| 384 |
+
|
| 385 |
+
// Open positions table
|
| 386 |
+
renderPositions(data.positions || {});
|
| 387 |
+
|
| 388 |
+
// Trade history
|
| 389 |
+
renderTradeHistory(data.trade_history || []);
|
| 390 |
+
|
| 391 |
+
} catch (e) {
|
| 392 |
+
console.error("Portfolio error:", e);
|
| 393 |
+
}
|
| 394 |
+
}
|
| 395 |
+
|
| 396 |
+
/* ββ RENDER POSITIONS TABLE ββββββββββββββββββββββββββββ */
|
| 397 |
+
function renderPositions(positions) {
|
| 398 |
+
const tbody = document.getElementById("positionsBody");
|
| 399 |
+
|
| 400 |
+
if (Object.keys(positions).length === 0) {
|
| 401 |
+
tbody.innerHTML = '<tr><td colspan="9" class="empty-msg">No open positions β activate the bot or trade manually</td></tr>';
|
| 402 |
+
return;
|
| 403 |
+
}
|
| 404 |
+
|
| 405 |
+
tbody.innerHTML = "";
|
| 406 |
+
Object.entries(positions).forEach(([ticker, pos]) => {
|
| 407 |
+
const pnl = pos.unrealized_pnl || 0;
|
| 408 |
+
const pnlPct = pos.pnl_pct || 0;
|
| 409 |
+
const pnlClass = pnl >= 0 ? "pnl-positive" : "pnl-negative";
|
| 410 |
+
const pnlSign = pnl >= 0 ? "+" : "";
|
| 411 |
+
|
| 412 |
+
const tr = document.createElement("tr");
|
| 413 |
+
tr.innerHTML = `
|
| 414 |
+
<td class="ticker-col">${ticker}</td>
|
| 415 |
+
<td>${pos.shares}</td>
|
| 416 |
+
<td>$${pos.buy_price}</td>
|
| 417 |
+
<td>$${pos.current_price || pos.buy_price}</td>
|
| 418 |
+
<td class="${pnlClass}">${pnlSign}$${formatNumber(Math.abs(pnl))}</td>
|
| 419 |
+
<td class="${pnlClass}">${pnlSign}${pnlPct}%</td>
|
| 420 |
+
<td style="color:#ef4444">$${pos.stop_loss}</td>
|
| 421 |
+
<td style="color:#22c55e">$${pos.take_profit}</td>
|
| 422 |
+
<td><button class="btn-sell-small" onclick="forceSell('${ticker}')">SELL</button></td>
|
| 423 |
+
`;
|
| 424 |
+
tbody.appendChild(tr);
|
| 425 |
+
});
|
| 426 |
+
}
|
| 427 |
+
|
| 428 |
+
/* ββ RENDER TRADE HISTORY ββββββββββββββββββββββββββββββ */
|
| 429 |
+
function renderTradeHistory(trades) {
|
| 430 |
+
const log = document.getElementById("tradeLog");
|
| 431 |
+
|
| 432 |
+
if (trades.length === 0) {
|
| 433 |
+
log.innerHTML = '<div class="empty-msg">No trades yet. Activate the bot or execute a trade.</div>';
|
| 434 |
+
return;
|
| 435 |
+
}
|
| 436 |
+
|
| 437 |
+
log.innerHTML = "";
|
| 438 |
+
// Show most recent first
|
| 439 |
+
[...trades].reverse().forEach((t) => {
|
| 440 |
+
const profitClass = t.profit >= 0 ? "pnl-positive" : "pnl-negative";
|
| 441 |
+
const profitSign = t.profit >= 0 ? "+" : "";
|
| 442 |
+
const time = new Date(t.sell_time).toLocaleString();
|
| 443 |
+
|
| 444 |
+
const entry = document.createElement("div");
|
| 445 |
+
entry.className = "trade-entry";
|
| 446 |
+
entry.innerHTML = `
|
| 447 |
+
<span class="te-time">${time}</span>
|
| 448 |
+
<span>
|
| 449 |
+
<span class="te-ticker">${t.ticker}</span>
|
| 450 |
+
β ${t.shares} shares @ $${t.buy_price} β $${t.sell_price}
|
| 451 |
+
<span style="color:#6b7280;font-size:0.7rem;"> (${t.reason})</span>
|
| 452 |
+
</span>
|
| 453 |
+
<span class="${profitClass}">${profitSign}$${formatNumber(Math.abs(t.profit))}</span>
|
| 454 |
+
<span class="${profitClass}">${profitSign}${t.profit_pct}%</span>
|
| 455 |
+
`;
|
| 456 |
+
log.appendChild(entry);
|
| 457 |
+
});
|
| 458 |
+
}
|
| 459 |
+
|
| 460 |
+
/* ββ ADD TO TRADE FEED βββββββββββββββββββββββββββββββββ */
|
| 461 |
+
function addToFeed(message, type) {
|
| 462 |
+
const feed = document.getElementById("tradeFeed");
|
| 463 |
+
const time = new Date().toLocaleTimeString();
|
| 464 |
+
|
| 465 |
+
const item = document.createElement("div");
|
| 466 |
+
item.className = `feed-item ${type}`;
|
| 467 |
+
item.innerHTML = `<span style="color:#6b7280;font-size:0.7rem;">[${time}]</span> ${message}`;
|
| 468 |
+
|
| 469 |
+
// Add to top
|
| 470 |
+
feed.insertBefore(item, feed.firstChild);
|
| 471 |
+
|
| 472 |
+
// Keep only last 50 entries
|
| 473 |
+
while (feed.children.length > 50) {
|
| 474 |
+
feed.removeChild(feed.lastChild);
|
| 475 |
+
}
|
| 476 |
+
}
|
| 477 |
+
|
| 478 |
+
/* ββ TOGGLE BOT ββββββββββββββββββββββββββββββββββββββββ */
|
| 479 |
+
async function toggleBot() {
|
| 480 |
+
try {
|
| 481 |
+
const res = await fetch(`${API}/api/trade/toggle`, { method: "POST" });
|
| 482 |
+
const data = await res.json();
|
| 483 |
+
|
| 484 |
+
if (data.bot_active) {
|
| 485 |
+
addToFeed("π€ <strong>Auto-trading bot ACTIVATED</strong> β scanning for opportunities...", "buy");
|
| 486 |
+
} else {
|
| 487 |
+
addToFeed("βΉ <strong>Auto-trading bot DEACTIVATED</strong>", "sell");
|
| 488 |
+
}
|
| 489 |
+
|
| 490 |
+
loadPortfolio();
|
| 491 |
+
} catch (e) {
|
| 492 |
+
console.error("Toggle error:", e);
|
| 493 |
+
addToFeed("β Failed to toggle bot", "sell");
|
| 494 |
+
}
|
| 495 |
+
}
|
| 496 |
+
|
| 497 |
+
/* ββ EXECUTE MANUAL TRADE ββββββββββββββββββββββββββββββ */
|
| 498 |
+
async function executeManualTrade() {
|
| 499 |
+
const ticker = currentTicker || document.getElementById("tickerInput").value.trim().toUpperCase();
|
| 500 |
+
if (!ticker) {
|
| 501 |
+
alert("Enter a ticker first!");
|
| 502 |
+
return;
|
| 503 |
+
}
|
| 504 |
+
|
| 505 |
+
addToFeed(`π Analyzing <strong>${ticker}</strong> β running LSTM prediction...`, "hold");
|
| 506 |
+
|
| 507 |
+
try {
|
| 508 |
+
const res = await fetch(`${API}/api/trade/execute/${ticker}`, { method: "POST" });
|
| 509 |
+
const data = await res.json();
|
| 510 |
+
|
| 511 |
+
const action = data.action;
|
| 512 |
+
const price = data.current_price;
|
| 513 |
+
|
| 514 |
+
if (action === "BUY") {
|
| 515 |
+
const tr = data.trade_result;
|
| 516 |
+
addToFeed(
|
| 517 |
+
`π’ <strong>BOUGHT ${tr.shares} x ${ticker}</strong> @ $${price} | ` +
|
| 518 |
+
`SL: $${tr.stop_loss} | TP: $${tr.take_profit} | Cost: $${tr.cost}`,
|
| 519 |
+
"buy"
|
| 520 |
+
);
|
| 521 |
+
} else if (action === "SELL") {
|
| 522 |
+
const tr = data.trade_result;
|
| 523 |
+
const profitSign = tr.profit >= 0 ? "+" : "";
|
| 524 |
+
addToFeed(
|
| 525 |
+
`π΄ <strong>SOLD ${ticker}</strong> @ $${price} | ` +
|
| 526 |
+
`P&L: ${profitSign}$${tr.profit} (${profitSign}${tr.profit_pct}%) | Reason: ${tr.reason}`,
|
| 527 |
+
"sell"
|
| 528 |
+
);
|
| 529 |
+
} else if (action === "HOLD") {
|
| 530 |
+
addToFeed(
|
| 531 |
+
`π‘ <strong>HOLD ${ticker}</strong> @ $${price} β position within thresholds ` +
|
| 532 |
+
`(P&L: ${data.position.current_pnl}%)`,
|
| 533 |
+
"hold"
|
| 534 |
+
);
|
| 535 |
+
} else {
|
| 536 |
+
addToFeed(
|
| 537 |
+
`βͺ <strong>WAIT on ${ticker}</strong> @ $${price} β ${data.reason || "conditions not met for entry"} ` +
|
| 538 |
+
`(Pred: ${data.pred_direction} ${data.pred_change_pct}%, Conf: ${data.confidence}%)`,
|
| 539 |
+
"wait"
|
| 540 |
+
);
|
| 541 |
+
}
|
| 542 |
+
|
| 543 |
+
loadPortfolio();
|
| 544 |
+
} catch (e) {
|
| 545 |
+
console.error("Trade error:", e);
|
| 546 |
+
addToFeed(`β Trade execution failed for ${ticker}: ${e.message}`, "sell");
|
| 547 |
+
}
|
| 548 |
+
}
|
| 549 |
+
|
| 550 |
+
/* ββ AUTO SCAN & TRADE βββββββββββββββββββββββββββββββββ */
|
| 551 |
+
async function runAutoScan() {
|
| 552 |
+
addToFeed("π <strong>Auto-scan started</strong> β scanning 8 stocks with LSTM...", "hold");
|
| 553 |
+
|
| 554 |
+
try {
|
| 555 |
+
const res = await fetch(`${API}/api/trade/auto-scan`, { method: "POST" });
|
| 556 |
+
const data = await res.json();
|
| 557 |
+
|
| 558 |
+
if (data.status === "inactive") {
|
| 559 |
+
addToFeed("β οΈ Bot is OFF β activate it first before scanning", "wait");
|
| 560 |
+
return;
|
| 561 |
+
}
|
| 562 |
+
|
| 563 |
+
addToFeed(`β
<strong>Scan complete</strong> β analyzed ${data.scanned} stocks`, "hold");
|
| 564 |
+
|
| 565 |
+
// Log each result
|
| 566 |
+
(data.results || []).forEach((r) => {
|
| 567 |
+
const action = r.action;
|
| 568 |
+
const ticker = r.ticker;
|
| 569 |
+
|
| 570 |
+
if (action === "BUY" && r.trade_result) {
|
| 571 |
+
const tr = r.trade_result;
|
| 572 |
+
if (tr.status === "bought") {
|
| 573 |
+
addToFeed(
|
| 574 |
+
`π’ <strong>AUTO-BUY ${tr.shares} x ${ticker}</strong> @ $${tr.price} | ` +
|
| 575 |
+
`SL: $${tr.stop_loss} | TP: $${tr.take_profit}`,
|
| 576 |
+
"buy"
|
| 577 |
+
);
|
| 578 |
+
} else {
|
| 579 |
+
addToFeed(`βͺ ${ticker}: ${tr.reason || "skipped"}`, "wait");
|
| 580 |
+
}
|
| 581 |
+
} else if (action === "SELL" && r.trade_result) {
|
| 582 |
+
const tr = r.trade_result || r.result;
|
| 583 |
+
const profitSign = tr.profit >= 0 ? "+" : "";
|
| 584 |
+
addToFeed(
|
| 585 |
+
`π΄ <strong>AUTO-SELL ${ticker}</strong> | P&L: ${profitSign}$${tr.profit} | ${tr.reason}`,
|
| 586 |
+
"sell"
|
| 587 |
+
);
|
| 588 |
+
} else if (action === "WAIT") {
|
| 589 |
+
addToFeed(
|
| 590 |
+
`βͺ ${ticker}: WAIT (Pred: ${r.pred_direction} ${r.pred_change_pct}%, Conf: ${r.confidence}%)`,
|
| 591 |
+
"wait"
|
| 592 |
+
);
|
| 593 |
+
}
|
| 594 |
+
});
|
| 595 |
+
|
| 596 |
+
loadPortfolio();
|
| 597 |
+
} catch (e) {
|
| 598 |
+
console.error("Scan error:", e);
|
| 599 |
+
addToFeed(`β Auto-scan failed: ${e.message}`, "sell");
|
| 600 |
+
}
|
| 601 |
+
}
|
| 602 |
+
|
| 603 |
+
/* ββ FORCE SELL ββββββββββββββββββββββββββββββββββββββββ */
|
| 604 |
+
async function forceSell(ticker) {
|
| 605 |
+
if (!confirm(`Force sell all ${ticker} shares at market price?`)) return;
|
| 606 |
+
|
| 607 |
+
addToFeed(`π Force-selling <strong>${ticker}</strong>...`, "hold");
|
| 608 |
+
|
| 609 |
+
try {
|
| 610 |
+
const res = await fetch(`${API}/api/trade/sell/${ticker}`, { method: "POST" });
|
| 611 |
+
const data = await res.json();
|
| 612 |
+
|
| 613 |
+
if (data.status === "sold") {
|
| 614 |
+
const profitSign = data.profit >= 0 ? "+" : "";
|
| 615 |
+
addToFeed(
|
| 616 |
+
`π΄ <strong>FORCE-SOLD ${ticker}</strong> @ $${data.price} | ` +
|
| 617 |
+
`P&L: ${profitSign}$${data.profit} (${profitSign}${data.profit_pct}%)`,
|
| 618 |
+
"sell"
|
| 619 |
+
);
|
| 620 |
+
} else {
|
| 621 |
+
addToFeed(`β οΈ ${ticker}: ${data.reason}`, "wait");
|
| 622 |
+
}
|
| 623 |
+
|
| 624 |
+
loadPortfolio();
|
| 625 |
+
} catch (e) {
|
| 626 |
+
console.error("Force sell error:", e);
|
| 627 |
+
addToFeed(`β Force sell failed: ${e.message}`, "sell");
|
| 628 |
+
}
|
| 629 |
+
}
|
| 630 |
+
|
| 631 |
+
/* ββ RESET PORTFOLIO βββββββββββββββββββββββββββββββββββ */
|
| 632 |
+
async function resetPortfolio() {
|
| 633 |
+
if (!confirm("Reset portfolio to $100,000? All positions and history will be lost.")) return;
|
| 634 |
+
|
| 635 |
+
try {
|
| 636 |
+
await fetch(`${API}/api/trade/reset`, { method: "POST" });
|
| 637 |
+
addToFeed("π <strong>Portfolio reset</strong> to $100,000.00", "hold");
|
| 638 |
+
loadPortfolio();
|
| 639 |
+
} catch (e) {
|
| 640 |
+
console.error("Reset error:", e);
|
| 641 |
+
}
|
| 642 |
+
}
|
| 643 |
+
|
| 644 |
+
/* ββ HELPERS βββββββββββββββββββββββββββββββββββββββββββ */
|
| 645 |
+
function formatPrice(p) {
|
| 646 |
+
if (!p) return "β";
|
| 647 |
+
return parseFloat(p).toLocaleString("en-US", { minimumFractionDigits: 2, maximumFractionDigits: 2 });
|
| 648 |
+
}
|
| 649 |
+
|
| 650 |
+
function formatVolume(v) {
|
| 651 |
+
if (!v) return "β";
|
| 652 |
+
if (v >= 1e9) return (v / 1e9).toFixed(2) + "B";
|
| 653 |
+
if (v >= 1e6) return (v / 1e6).toFixed(2) + "M";
|
| 654 |
+
if (v >= 1e3) return (v / 1e3).toFixed(1) + "K";
|
| 655 |
+
return v.toString();
|
| 656 |
+
}
|
| 657 |
+
|
| 658 |
+
function formatNumber(n) {
|
| 659 |
+
return parseFloat(n).toLocaleString("en-US", { minimumFractionDigits: 2, maximumFractionDigits: 2 });
|
| 660 |
+
}
|
app.py
ADDED
|
@@ -0,0 +1,352 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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from fastapi.middleware.cors import CORSMiddleware
|
| 8 |
+
from stock_data import fetch_stock_data, add_technical_indicators, get_stock_info, fetch_live_price, fetch_chart_data
|
| 9 |
+
from sentiment import analyze_sentiment
|
| 10 |
+
from model import train_and_predict
|
| 11 |
+
from trader import (
|
| 12 |
+
get_portfolio, reset_portfolio, toggle_bot,
|
| 13 |
+
evaluate_trade_signal, execute_sell, check_position,
|
| 14 |
+
)
|
| 15 |
+
import concurrent.futures
|
| 16 |
+
|
| 17 |
+
app = FastAPI(title="StockSense AI", version="3.0.0")
|
| 18 |
+
|
| 19 |
+
app.add_middleware(
|
| 20 |
+
CORSMiddleware,
|
| 21 |
+
allow_origins=["*"],
|
| 22 |
+
allow_methods=["*"],
|
| 23 |
+
allow_headers=["*"],
|
| 24 |
+
)
|
| 25 |
+
|
| 26 |
+
|
| 27 |
+
@app.get("/")
|
| 28 |
+
def root():
|
| 29 |
+
return {"message": "StockSense AI API v3.0 is running π"}
|
| 30 |
+
|
| 31 |
+
|
| 32 |
+
# ββ STOCK DATA βββββββββββββββββββββββββββββββββββββββ
|
| 33 |
+
@app.get("/api/stock/{ticker}")
|
| 34 |
+
def get_stock(ticker: str):
|
| 35 |
+
try:
|
| 36 |
+
df = fetch_stock_data(ticker)
|
| 37 |
+
df = add_technical_indicators(df)
|
| 38 |
+
records = df.tail(200).to_dict(orient="records")
|
| 39 |
+
for r in records:
|
| 40 |
+
if "Date" in r:
|
| 41 |
+
r["Date"] = str(r["Date"])
|
| 42 |
+
info = get_stock_info(ticker)
|
| 43 |
+
return {"info": info, "data": records}
|
| 44 |
+
except Exception as e:
|
| 45 |
+
raise HTTPException(status_code=400, detail=str(e))
|
| 46 |
+
|
| 47 |
+
|
| 48 |
+
@app.get("/api/live/{ticker}")
|
| 49 |
+
def live_price(ticker: str):
|
| 50 |
+
try:
|
| 51 |
+
return fetch_live_price(ticker)
|
| 52 |
+
except Exception as e:
|
| 53 |
+
raise HTTPException(status_code=400, detail=str(e))
|
| 54 |
+
|
| 55 |
+
|
| 56 |
+
@app.get("/api/chart/{ticker}")
|
| 57 |
+
def chart_data(ticker: str, timeframe: str = Query("1mo", regex="^(1d|5d|1wk|1mo|3mo|6mo|1y|2y)$")):
|
| 58 |
+
try:
|
| 59 |
+
data = fetch_chart_data(ticker, timeframe)
|
| 60 |
+
return {"ticker": ticker, "timeframe": timeframe, "data": data}
|
| 61 |
+
except Exception as e:
|
| 62 |
+
raise HTTPException(status_code=400, detail=str(e))
|
| 63 |
+
|
| 64 |
+
|
| 65 |
+
# ββ ML PREDICTION ββββββββββββββββββββββββββββββββββββ
|
| 66 |
+
# In app.py / predict endpoint
|
| 67 |
+
@app.get("/api/predict/{ticker}")
|
| 68 |
+
def predict(ticker: str):
|
| 69 |
+
try:
|
| 70 |
+
df = fetch_stock_data(ticker)
|
| 71 |
+
df = add_technical_indicators(df)
|
| 72 |
+
result = train_and_predict(df)
|
| 73 |
+
return {"ticker": ticker, **result}
|
| 74 |
+
except Exception as e:
|
| 75 |
+
raise HTTPException(status_code=400, detail=str(e))
|
| 76 |
+
|
| 77 |
+
|
| 78 |
+
# ββ SENTIMENT ββββββββββββββββββββββββββββββββββββββββ
|
| 79 |
+
@app.get("/api/sentiment/{ticker}")
|
| 80 |
+
def sentiment(ticker: str):
|
| 81 |
+
try:
|
| 82 |
+
return analyze_sentiment(ticker)
|
| 83 |
+
except Exception as e:
|
| 84 |
+
raise HTTPException(status_code=400, detail=str(e))
|
| 85 |
+
|
| 86 |
+
|
| 87 |
+
# ββ COMBINED SUMMARY βββββββββββββββββββββββββββββββββ
|
| 88 |
+
@app.get("/api/summary/{ticker}")
|
| 89 |
+
def summary(ticker: str):
|
| 90 |
+
try:
|
| 91 |
+
info = get_stock_info(ticker)
|
| 92 |
+
df = fetch_stock_data(ticker)
|
| 93 |
+
df_ind = add_technical_indicators(df)
|
| 94 |
+
prediction = train_and_predict(df_ind)
|
| 95 |
+
sent = analyze_sentiment(ticker)
|
| 96 |
+
|
| 97 |
+
latest = df_ind.iloc[-1]
|
| 98 |
+
indicators = {
|
| 99 |
+
"RSI": round(float(latest["RSI"]), 2),
|
| 100 |
+
"MACD": round(float(latest["MACD"]), 4),
|
| 101 |
+
"MACD_Signal": round(float(latest["MACD_Signal"]), 4),
|
| 102 |
+
"SMA_20": round(float(latest["SMA_20"]), 2),
|
| 103 |
+
"SMA_50": round(float(latest["SMA_50"]), 2),
|
| 104 |
+
}
|
| 105 |
+
|
| 106 |
+
return {
|
| 107 |
+
"info": info,
|
| 108 |
+
"indicators": indicators,
|
| 109 |
+
"prediction": prediction,
|
| 110 |
+
"sentiment": sent,
|
| 111 |
+
}
|
| 112 |
+
except Exception as e:
|
| 113 |
+
raise HTTPException(status_code=400, detail=str(e))
|
| 114 |
+
|
| 115 |
+
|
| 116 |
+
# ββ HIGH POTENTIAL SCANNER βββββββββββββββββββββββββββ
|
| 117 |
+
SCAN_TICKERS = [
|
| 118 |
+
"AAPL", "TSLA", "MSFT", "GOOGL", "AMZN", "NVDA", "META",
|
| 119 |
+
"NFLX", "AMD", "JPM", "V", "BA", "DIS", "PYPL", "INTC",
|
| 120 |
+
]
|
| 121 |
+
|
| 122 |
+
|
| 123 |
+
def _analyze_one(ticker: str) -> dict | None:
|
| 124 |
+
try:
|
| 125 |
+
info = get_stock_info(ticker)
|
| 126 |
+
df = fetch_stock_data(ticker, period="3mo")
|
| 127 |
+
df = add_technical_indicators(df)
|
| 128 |
+
latest = df.iloc[-1]
|
| 129 |
+
|
| 130 |
+
rsi = float(latest["RSI"])
|
| 131 |
+
macd = float(latest["MACD"])
|
| 132 |
+
macd_signal = float(latest["MACD_Signal"])
|
| 133 |
+
sma_20 = float(latest["SMA_20"])
|
| 134 |
+
price = float(latest["Close"])
|
| 135 |
+
|
| 136 |
+
score = 50
|
| 137 |
+
if rsi < 30: score += 20
|
| 138 |
+
elif rsi < 40: score += 10
|
| 139 |
+
elif rsi > 70: score -= 15
|
| 140 |
+
elif rsi > 60: score -= 5
|
| 141 |
+
|
| 142 |
+
if macd > macd_signal: score += 15
|
| 143 |
+
else: score -= 10
|
| 144 |
+
|
| 145 |
+
if price > sma_20: score += 10
|
| 146 |
+
else: score -= 10
|
| 147 |
+
|
| 148 |
+
vol = float(latest["Volume"])
|
| 149 |
+
vol_avg = float(latest["Volume_SMA_20"])
|
| 150 |
+
if vol_avg > 0 and vol > vol_avg * 1.3: score += 10
|
| 151 |
+
|
| 152 |
+
score = max(0, min(100, score))
|
| 153 |
+
|
| 154 |
+
if score >= 70: signal_text = "π’ Strong Buy"
|
| 155 |
+
elif score >= 55: signal_text = "π΅ Buy"
|
| 156 |
+
elif score >= 40: signal_text = "π‘ Hold"
|
| 157 |
+
else: signal_text = "π΄ Sell"
|
| 158 |
+
|
| 159 |
+
prev_close = float(df.iloc[-2]["Close"])
|
| 160 |
+
change_pct = round(((price - prev_close) / prev_close) * 100, 2)
|
| 161 |
+
|
| 162 |
+
return {
|
| 163 |
+
"ticker": ticker, "name": info.get("name", ticker),
|
| 164 |
+
"price": round(price, 2), "change_pct": change_pct,
|
| 165 |
+
"rsi": round(rsi, 2), "score": score,
|
| 166 |
+
"signal": signal_text, "currency": info.get("currency", "USD"),
|
| 167 |
+
}
|
| 168 |
+
except Exception:
|
| 169 |
+
return None
|
| 170 |
+
|
| 171 |
+
|
| 172 |
+
@app.get("/api/high-potential")
|
| 173 |
+
def high_potential():
|
| 174 |
+
results = []
|
| 175 |
+
with concurrent.futures.ThreadPoolExecutor(max_workers=5) as executor:
|
| 176 |
+
futures = {executor.submit(_analyze_one, t): t for t in SCAN_TICKERS}
|
| 177 |
+
for future in concurrent.futures.as_completed(futures):
|
| 178 |
+
result = future.result()
|
| 179 |
+
if result:
|
| 180 |
+
results.append(result)
|
| 181 |
+
results.sort(key=lambda x: x["score"], reverse=True)
|
| 182 |
+
return {"stocks": results, "count": len(results)}
|
| 183 |
+
|
| 184 |
+
|
| 185 |
+
# ββ AUTO TRADING ENDPOINTS βββββββββββββββββββββββββββ
|
| 186 |
+
|
| 187 |
+
@app.get("/api/trade/portfolio")
|
| 188 |
+
def trade_portfolio():
|
| 189 |
+
"""Get current portfolio state."""
|
| 190 |
+
try:
|
| 191 |
+
portfolio = get_portfolio()
|
| 192 |
+
# Calculate live P&L for open positions
|
| 193 |
+
total_unrealized = 0
|
| 194 |
+
for ticker, pos in portfolio["positions"].items():
|
| 195 |
+
try:
|
| 196 |
+
live = fetch_live_price(ticker)
|
| 197 |
+
current = live["price"]
|
| 198 |
+
pnl = (current - pos["buy_price"]) * pos["shares"]
|
| 199 |
+
pos["current_price"] = current
|
| 200 |
+
pos["unrealized_pnl"] = round(pnl, 2)
|
| 201 |
+
pos["pnl_pct"] = round(((current - pos["buy_price"]) / pos["buy_price"]) * 100, 2)
|
| 202 |
+
total_unrealized += pnl
|
| 203 |
+
except Exception:
|
| 204 |
+
pos["current_price"] = pos["buy_price"]
|
| 205 |
+
pos["unrealized_pnl"] = 0
|
| 206 |
+
pos["pnl_pct"] = 0
|
| 207 |
+
|
| 208 |
+
portfolio["total_unrealized_pnl"] = round(total_unrealized, 2)
|
| 209 |
+
portfolio["total_value"] = round(portfolio["balance"] + total_unrealized + sum(
|
| 210 |
+
p["shares"] * p.get("current_price", p["buy_price"]) for p in portfolio["positions"].values()
|
| 211 |
+
), 2)
|
| 212 |
+
|
| 213 |
+
# Calculate total realized P&L
|
| 214 |
+
portfolio["total_realized_pnl"] = round(
|
| 215 |
+
sum(t["profit"] for t in portfolio["trade_history"]), 2
|
| 216 |
+
)
|
| 217 |
+
portfolio["total_trades"] = len(portfolio["trade_history"])
|
| 218 |
+
portfolio["winning_trades"] = sum(1 for t in portfolio["trade_history"] if t["profit"] > 0)
|
| 219 |
+
portfolio["losing_trades"] = sum(1 for t in portfolio["trade_history"] if t["profit"] <= 0)
|
| 220 |
+
|
| 221 |
+
if portfolio["total_trades"] > 0:
|
| 222 |
+
portfolio["win_rate"] = round(
|
| 223 |
+
(portfolio["winning_trades"] / portfolio["total_trades"]) * 100, 1
|
| 224 |
+
)
|
| 225 |
+
else:
|
| 226 |
+
portfolio["win_rate"] = 0
|
| 227 |
+
|
| 228 |
+
return portfolio
|
| 229 |
+
except Exception as e:
|
| 230 |
+
raise HTTPException(status_code=400, detail=str(e))
|
| 231 |
+
|
| 232 |
+
|
| 233 |
+
@app.post("/api/trade/reset")
|
| 234 |
+
def trade_reset():
|
| 235 |
+
"""Reset portfolio to $100,000."""
|
| 236 |
+
return reset_portfolio()
|
| 237 |
+
|
| 238 |
+
|
| 239 |
+
@app.post("/api/trade/toggle")
|
| 240 |
+
def trade_toggle():
|
| 241 |
+
"""Toggle auto-trading bot ON/OFF."""
|
| 242 |
+
return toggle_bot()
|
| 243 |
+
|
| 244 |
+
|
| 245 |
+
@app.post("/api/trade/execute/{ticker}")
|
| 246 |
+
def trade_execute(ticker: str):
|
| 247 |
+
"""
|
| 248 |
+
Run the LSTM prediction for a ticker and auto-execute
|
| 249 |
+
the trade signal (BUY/SELL/HOLD/WAIT).
|
| 250 |
+
"""
|
| 251 |
+
try:
|
| 252 |
+
# Get current price
|
| 253 |
+
live = fetch_live_price(ticker)
|
| 254 |
+
current_price = live["price"]
|
| 255 |
+
|
| 256 |
+
# Get LSTM prediction
|
| 257 |
+
df = fetch_stock_data(ticker)
|
| 258 |
+
df = add_technical_indicators(df)
|
| 259 |
+
prediction = train_and_predict(df)
|
| 260 |
+
|
| 261 |
+
# Evaluate and execute trade signal
|
| 262 |
+
signal = evaluate_trade_signal(
|
| 263 |
+
ticker=ticker,
|
| 264 |
+
current_price=current_price,
|
| 265 |
+
predicted_prices=prediction["predicted_prices"],
|
| 266 |
+
confidence=prediction["confidence"],
|
| 267 |
+
)
|
| 268 |
+
|
| 269 |
+
signal["live"] = live
|
| 270 |
+
signal["prediction_details"] = prediction
|
| 271 |
+
return signal
|
| 272 |
+
|
| 273 |
+
except Exception as e:
|
| 274 |
+
raise HTTPException(status_code=400, detail=str(e))
|
| 275 |
+
|
| 276 |
+
|
| 277 |
+
@app.post("/api/trade/sell/{ticker}")
|
| 278 |
+
def trade_force_sell(ticker: str):
|
| 279 |
+
"""Force-sell a position at current market price."""
|
| 280 |
+
try:
|
| 281 |
+
live = fetch_live_price(ticker)
|
| 282 |
+
result = execute_sell(ticker, live["price"], "Manual sell (forced)")
|
| 283 |
+
return result
|
| 284 |
+
except Exception as e:
|
| 285 |
+
raise HTTPException(status_code=400, detail=str(e))
|
| 286 |
+
|
| 287 |
+
|
| 288 |
+
@app.get("/api/trade/check/{ticker}")
|
| 289 |
+
def trade_check(ticker: str):
|
| 290 |
+
"""Check if a position should be sold (stop-loss / take-profit)."""
|
| 291 |
+
try:
|
| 292 |
+
live = fetch_live_price(ticker)
|
| 293 |
+
result = check_position(ticker, live["price"])
|
| 294 |
+
result["live"] = live
|
| 295 |
+
return result
|
| 296 |
+
except Exception as e:
|
| 297 |
+
raise HTTPException(status_code=400, detail=str(e))
|
| 298 |
+
|
| 299 |
+
|
| 300 |
+
@app.post("/api/trade/auto-scan")
|
| 301 |
+
def trade_auto_scan():
|
| 302 |
+
"""
|
| 303 |
+
Scan all high-potential stocks, run predictions,
|
| 304 |
+
and auto-execute trades for the best signals.
|
| 305 |
+
Only works when bot is active.
|
| 306 |
+
"""
|
| 307 |
+
try:
|
| 308 |
+
portfolio = get_portfolio()
|
| 309 |
+
if not portfolio["bot_active"]:
|
| 310 |
+
return {"status": "inactive", "message": "Bot is OFF. Toggle it on first."}
|
| 311 |
+
|
| 312 |
+
results = []
|
| 313 |
+
|
| 314 |
+
# First: check existing positions for stop-loss / take-profit
|
| 315 |
+
for ticker in list(portfolio["positions"].keys()):
|
| 316 |
+
try:
|
| 317 |
+
live = fetch_live_price(ticker)
|
| 318 |
+
check = check_position(ticker, live["price"])
|
| 319 |
+
if check["action"] == "sell":
|
| 320 |
+
sell_result = execute_sell(ticker, live["price"], check["reason"])
|
| 321 |
+
results.append({"ticker": ticker, "action": "SELL", "result": sell_result})
|
| 322 |
+
except Exception:
|
| 323 |
+
continue
|
| 324 |
+
|
| 325 |
+
# Then: scan for new buy opportunities
|
| 326 |
+
for scan_ticker in SCAN_TICKERS[:8]: # Limit to top 8 for speed
|
| 327 |
+
if scan_ticker in portfolio["positions"]:
|
| 328 |
+
continue
|
| 329 |
+
try:
|
| 330 |
+
live = fetch_live_price(scan_ticker)
|
| 331 |
+
df = fetch_stock_data(scan_ticker)
|
| 332 |
+
df = add_technical_indicators(df)
|
| 333 |
+
pred = train_and_predict(df, epochs=30) # fewer epochs for speed
|
| 334 |
+
|
| 335 |
+
signal = evaluate_trade_signal(
|
| 336 |
+
ticker=scan_ticker,
|
| 337 |
+
current_price=live["price"],
|
| 338 |
+
predicted_prices=pred["predicted_prices"],
|
| 339 |
+
confidence=pred["confidence"],
|
| 340 |
+
)
|
| 341 |
+
results.append(signal)
|
| 342 |
+
except Exception:
|
| 343 |
+
continue
|
| 344 |
+
|
| 345 |
+
return {
|
| 346 |
+
"status": "completed",
|
| 347 |
+
"scanned": len(results),
|
| 348 |
+
"results": results,
|
| 349 |
+
"portfolio": get_portfolio(),
|
| 350 |
+
}
|
| 351 |
+
except Exception as e:
|
| 352 |
+
raise HTTPException(status_code=400, detail=str(e))
|
index.html
ADDED
|
@@ -0,0 +1,205 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
<!DOCTYPE html>
|
| 2 |
+
<html lang="en">
|
| 3 |
+
<head>
|
| 4 |
+
<meta charset="UTF-8" />
|
| 5 |
+
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
|
| 6 |
+
<title>StockSense AI β Live Trading Dashboard</title>
|
| 7 |
+
<link rel="stylesheet" href="style.css" />
|
| 8 |
+
<script src="https://cdn.jsdelivr.net/npm/chart.js@4.4.0"></script>
|
| 9 |
+
</head>
|
| 10 |
+
<body>
|
| 11 |
+
|
| 12 |
+
<!-- ββ TOP BAR ββββββββββββββββββββββββββββββββββββββ -->
|
| 13 |
+
<nav class="topbar">
|
| 14 |
+
<div class="brand">π <span>StockSense AI</span></div>
|
| 15 |
+
<div class="search-area">
|
| 16 |
+
<input id="tickerInput" type="text" placeholder="Search ticker⦠(AAPL, TSLA, NVDA)" spellcheck="false" />
|
| 17 |
+
<button id="analyzeBtn" onclick="loadTicker()">Analyze</button>
|
| 18 |
+
</div>
|
| 19 |
+
<div class="nav-tabs">
|
| 20 |
+
<button class="nav-tab active" onclick="switchTab('charts')">π Charts</button>
|
| 21 |
+
<button class="nav-tab" onclick="switchTab('trading')">π€ Auto Trade</button>
|
| 22 |
+
</div>
|
| 23 |
+
<div class="live-badge" id="liveBadge">
|
| 24 |
+
<span class="dot"></span> LIVE
|
| 25 |
+
</div>
|
| 26 |
+
</nav>
|
| 27 |
+
|
| 28 |
+
<!-- ββ LIVE PRICE BANNER ββββββββββββββββββββββββββββ -->
|
| 29 |
+
<section class="price-banner hidden" id="priceBanner">
|
| 30 |
+
<div class="price-main">
|
| 31 |
+
<h1 id="bannerName">β</h1>
|
| 32 |
+
<span class="price-value" id="bannerPrice">0.00</span>
|
| 33 |
+
<span class="price-change" id="bannerChange">0.00 (0.00%)</span>
|
| 34 |
+
</div>
|
| 35 |
+
<div class="price-stats">
|
| 36 |
+
<div><label>Open</label><span id="statOpen">β</span></div>
|
| 37 |
+
<div><label>High</label><span id="statHigh">β</span></div>
|
| 38 |
+
<div><label>Low</label><span id="statLow">β</span></div>
|
| 39 |
+
<div><label>Vol</label><span id="statVol">β</span></div>
|
| 40 |
+
<div><label>52W H</label><span id="stat52H">β</span></div>
|
| 41 |
+
<div><label>52W L</label><span id="stat52L">β</span></div>
|
| 42 |
+
</div>
|
| 43 |
+
</section>
|
| 44 |
+
|
| 45 |
+
<!-- ββ TAB: CHARTS ββββββββββββββββββββββββββββββββββ -->
|
| 46 |
+
<div id="chartsTab" class="tab-content">
|
| 47 |
+
<div class="dashboard">
|
| 48 |
+
<div class="chart-area">
|
| 49 |
+
<div class="timeframe-bar">
|
| 50 |
+
<button class="tf-btn active" data-tf="1d">1D</button>
|
| 51 |
+
<button class="tf-btn" data-tf="5d">5D</button>
|
| 52 |
+
<button class="tf-btn" data-tf="1mo">1M</button>
|
| 53 |
+
<button class="tf-btn" data-tf="3mo">3M</button>
|
| 54 |
+
<button class="tf-btn" data-tf="1y">1Y</button>
|
| 55 |
+
<button class="tf-btn" data-tf="2y">2Y</button>
|
| 56 |
+
</div>
|
| 57 |
+
<div class="chart-container"><canvas id="mainChart"></canvas></div>
|
| 58 |
+
<div class="chart-container volume-chart"><canvas id="volumeChart"></canvas></div>
|
| 59 |
+
|
| 60 |
+
<div class="prediction-section hidden" id="predSection">
|
| 61 |
+
<h3>π€ Next 5-Day Price Prediction</h3>
|
| 62 |
+
<div class="chart-container"><canvas id="predChart"></canvas></div>
|
| 63 |
+
<div class="pred-metrics">
|
| 64 |
+
<div class="metric-card">
|
| 65 |
+
<span class="m-label">Confidence</span>
|
| 66 |
+
<span class="m-value" id="predConf">β</span>
|
| 67 |
+
</div>
|
| 68 |
+
<div class="metric-card">
|
| 69 |
+
<span class="m-label">Risk Level</span>
|
| 70 |
+
<span class="m-value" id="predRisk">β</span>
|
| 71 |
+
</div>
|
| 72 |
+
<div class="metric-card">
|
| 73 |
+
<span class="m-label">Pred Day 1</span>
|
| 74 |
+
<span class="m-value" id="predDay1">β</span>
|
| 75 |
+
</div>
|
| 76 |
+
<div class="metric-card">
|
| 77 |
+
<span class="m-label">Pred Day 5</span>
|
| 78 |
+
<span class="m-value" id="predDay5">β</span>
|
| 79 |
+
</div>
|
| 80 |
+
</div>
|
| 81 |
+
</div>
|
| 82 |
+
</div>
|
| 83 |
+
|
| 84 |
+
<aside class="sidebar">
|
| 85 |
+
<div class="panel">
|
| 86 |
+
<h3>π₯ High Potential Stocks</h3>
|
| 87 |
+
<p class="panel-sub">Ranked by momentum + indicators</p>
|
| 88 |
+
<div id="hpLoader" class="mini-loader">Loading scanner...</div>
|
| 89 |
+
<div id="hpList" class="hp-list"></div>
|
| 90 |
+
</div>
|
| 91 |
+
<div class="panel hidden" id="sentPanel">
|
| 92 |
+
<h3>π° News Sentiment</h3>
|
| 93 |
+
<div class="sent-gauge">
|
| 94 |
+
<div class="gauge-circle" id="gaugeCircle"><span id="gaugeText">β</span></div>
|
| 95 |
+
<span class="gauge-label" id="gaugeLabel">Neutral</span>
|
| 96 |
+
</div>
|
| 97 |
+
<ul id="sentList" class="sent-list"></ul>
|
| 98 |
+
</div>
|
| 99 |
+
<div class="panel hidden" id="indPanel">
|
| 100 |
+
<h3>π Technical Indicators</h3>
|
| 101 |
+
<table class="ind-table"><tbody id="indBody"></tbody></table>
|
| 102 |
+
</div>
|
| 103 |
+
</aside>
|
| 104 |
+
</div>
|
| 105 |
+
</div>
|
| 106 |
+
|
| 107 |
+
<!-- ββ TAB: AUTO TRADING ββββββββββββββββββββββββββββ -->
|
| 108 |
+
<div id="tradingTab" class="tab-content hidden">
|
| 109 |
+
<div class="trading-dashboard">
|
| 110 |
+
|
| 111 |
+
<!-- Portfolio Overview -->
|
| 112 |
+
<div class="trade-grid">
|
| 113 |
+
<div class="portfolio-header">
|
| 114 |
+
<div class="port-card balance">
|
| 115 |
+
<span class="pc-label">Portfolio Value</span>
|
| 116 |
+
<span class="pc-value" id="portValue">$100,000.00</span>
|
| 117 |
+
</div>
|
| 118 |
+
<div class="port-card">
|
| 119 |
+
<span class="pc-label">Cash Balance</span>
|
| 120 |
+
<span class="pc-value" id="portBalance">$100,000.00</span>
|
| 121 |
+
</div>
|
| 122 |
+
<div class="port-card">
|
| 123 |
+
<span class="pc-label">Unrealized P&L</span>
|
| 124 |
+
<span class="pc-value" id="portUnrealized">$0.00</span>
|
| 125 |
+
</div>
|
| 126 |
+
<div class="port-card">
|
| 127 |
+
<span class="pc-label">Realized P&L</span>
|
| 128 |
+
<span class="pc-value" id="portRealized">$0.00</span>
|
| 129 |
+
</div>
|
| 130 |
+
<div class="port-card">
|
| 131 |
+
<span class="pc-label">Win Rate</span>
|
| 132 |
+
<span class="pc-value" id="portWinRate">0%</span>
|
| 133 |
+
</div>
|
| 134 |
+
<div class="port-card">
|
| 135 |
+
<span class="pc-label">Total Trades</span>
|
| 136 |
+
<span class="pc-value" id="portTrades">0</span>
|
| 137 |
+
</div>
|
| 138 |
+
</div>
|
| 139 |
+
|
| 140 |
+
<!-- Bot Controls -->
|
| 141 |
+
<div class="bot-controls">
|
| 142 |
+
<div class="bot-status">
|
| 143 |
+
<span class="bot-dot" id="botDot"></span>
|
| 144 |
+
<span id="botStatus">Bot: OFF</span>
|
| 145 |
+
</div>
|
| 146 |
+
<div class="bot-buttons">
|
| 147 |
+
<button class="btn-bot" id="toggleBotBtn" onclick="toggleBot()">β‘ Activate Bot</button>
|
| 148 |
+
<button class="btn-scan" onclick="runAutoScan()">π Auto Scan & Trade</button>
|
| 149 |
+
<button class="btn-trade" onclick="executeManualTrade()">π Trade Current Ticker</button>
|
| 150 |
+
<button class="btn-reset" onclick="resetPortfolio()">π Reset Portfolio</button>
|
| 151 |
+
</div>
|
| 152 |
+
</div>
|
| 153 |
+
|
| 154 |
+
<!-- Open Positions -->
|
| 155 |
+
<div class="trade-panel">
|
| 156 |
+
<h3>π Open Positions</h3>
|
| 157 |
+
<div class="positions-table-wrap">
|
| 158 |
+
<table class="positions-table">
|
| 159 |
+
<thead>
|
| 160 |
+
<tr>
|
| 161 |
+
<th>Ticker</th>
|
| 162 |
+
<th>Shares</th>
|
| 163 |
+
<th>Buy Price</th>
|
| 164 |
+
<th>Current</th>
|
| 165 |
+
<th>P&L</th>
|
| 166 |
+
<th>P&L %</th>
|
| 167 |
+
<th>Stop Loss</th>
|
| 168 |
+
<th>Take Profit</th>
|
| 169 |
+
<th>Action</th>
|
| 170 |
+
</tr>
|
| 171 |
+
</thead>
|
| 172 |
+
<tbody id="positionsBody">
|
| 173 |
+
<tr><td colspan="9" class="empty-msg">No open positions</td></tr>
|
| 174 |
+
</tbody>
|
| 175 |
+
</table>
|
| 176 |
+
</div>
|
| 177 |
+
</div>
|
| 178 |
+
|
| 179 |
+
<!-- Trade Log -->
|
| 180 |
+
<div class="trade-panel">
|
| 181 |
+
<h3>π Trade History</h3>
|
| 182 |
+
<div class="trade-log" id="tradeLog">
|
| 183 |
+
<div class="empty-msg">No trades yet. Activate the bot or execute a trade.</div>
|
| 184 |
+
</div>
|
| 185 |
+
</div>
|
| 186 |
+
|
| 187 |
+
<!-- Live Trade Feed -->
|
| 188 |
+
<div class="trade-panel">
|
| 189 |
+
<h3>β‘ Live Trade Feed</h3>
|
| 190 |
+
<div class="trade-feed" id="tradeFeed"></div>
|
| 191 |
+
</div>
|
| 192 |
+
|
| 193 |
+
</div>
|
| 194 |
+
</div>
|
| 195 |
+
</div>
|
| 196 |
+
|
| 197 |
+
<!-- ββ DISCLAIMER FOOTER ββββββββββββββββββββββββββββ -->
|
| 198 |
+
<footer>
|
| 199 |
+
<p>β οΈ <strong>PAPER TRADING ONLY</strong> β Simulated portfolio with fake money. Not real trades.</p>
|
| 200 |
+
<p>For <strong>educational purposes only</strong>. Not financial advice. | StockSense AI β Hackathon 2026</p>
|
| 201 |
+
</footer>
|
| 202 |
+
|
| 203 |
+
<script src="app.js"></script>
|
| 204 |
+
</body>
|
| 205 |
+
</html>
|
model.py
ADDED
|
@@ -0,0 +1,211 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""
|
| 2 |
+
LSTM-based stock price predictor (v2.0).
|
| 3 |
+
Multi-feature model using Close + technical indicators.
|
| 4 |
+
Trains with mini-batches, LR scheduling, gradient clipping, and early stopping.
|
| 5 |
+
"""
|
| 6 |
+
|
| 7 |
+
import numpy as np
|
| 8 |
+
import pandas as pd
|
| 9 |
+
import torch
|
| 10 |
+
import torch.nn as nn
|
| 11 |
+
from torch.utils.data import DataLoader, TensorDataset
|
| 12 |
+
from sklearn.preprocessing import MinMaxScaler
|
| 13 |
+
|
| 14 |
+
|
| 15 |
+
# ββ Feature columns used by the model βββββββββββββββββββββββββ
|
| 16 |
+
FEATURE_COLS = ["Close", "SMA_20", "EMA_20", "RSI", "MACD", "Volume"]
|
| 17 |
+
LOOK_BACK = 60 # 60 trading days as input window
|
| 18 |
+
PREDICT_DAYS = 5
|
| 19 |
+
|
| 20 |
+
|
| 21 |
+
# ββ LSTM Architecture βββββββββββββββββββββββββββββββββββββββββ
|
| 22 |
+
class StockLSTM(nn.Module):
|
| 23 |
+
def __init__(self, input_size: int = 6, hidden_size: int = 128,
|
| 24 |
+
num_layers: int = 3, output_size: int = 5, dropout: float = 0.3):
|
| 25 |
+
super().__init__()
|
| 26 |
+
self.hidden_size = hidden_size
|
| 27 |
+
self.num_layers = num_layers
|
| 28 |
+
|
| 29 |
+
self.lstm = nn.LSTM(
|
| 30 |
+
input_size, hidden_size, num_layers,
|
| 31 |
+
batch_first=True, dropout=dropout if num_layers > 1 else 0.0,
|
| 32 |
+
)
|
| 33 |
+
|
| 34 |
+
# Deeper head: hidden β hidden/2 β output
|
| 35 |
+
self.head = nn.Sequential(
|
| 36 |
+
nn.Linear(hidden_size, hidden_size // 2),
|
| 37 |
+
nn.ReLU(),
|
| 38 |
+
nn.Dropout(dropout),
|
| 39 |
+
nn.Linear(hidden_size // 2, output_size),
|
| 40 |
+
)
|
| 41 |
+
|
| 42 |
+
def forward(self, x):
|
| 43 |
+
h0 = torch.zeros(self.num_layers, x.size(0), self.hidden_size, device=x.device)
|
| 44 |
+
c0 = torch.zeros(self.num_layers, x.size(0), self.hidden_size, device=x.device)
|
| 45 |
+
out, _ = self.lstm(x, (h0, c0))
|
| 46 |
+
out = self.head(out[:, -1, :]) # last time-step
|
| 47 |
+
return out
|
| 48 |
+
|
| 49 |
+
|
| 50 |
+
# ββ Data helpers ββββββββββββββββββββββββββββββββββββββββββββββ
|
| 51 |
+
def _prepare_features(df: pd.DataFrame):
|
| 52 |
+
"""
|
| 53 |
+
Extract feature matrix and target vector from a DataFrame
|
| 54 |
+
that already contains technical indicators.
|
| 55 |
+
"""
|
| 56 |
+
# Ensure required columns exist; fall back to Close-only if not
|
| 57 |
+
available = [c for c in FEATURE_COLS if c in df.columns]
|
| 58 |
+
if len(available) < 2:
|
| 59 |
+
available = ["Close"]
|
| 60 |
+
|
| 61 |
+
features = df[available].values.astype(np.float32)
|
| 62 |
+
close = df["Close"].values.astype(np.float32)
|
| 63 |
+
return features, close, len(available)
|
| 64 |
+
|
| 65 |
+
|
| 66 |
+
def _prepare_data(features: np.ndarray, close_col_idx: int = 0):
|
| 67 |
+
"""
|
| 68 |
+
Scale features, build sliding-window X/y arrays.
|
| 69 |
+
Returns X, y, scaler, and the split index so the scaler is fit
|
| 70 |
+
ONLY on training data (no data leakage).
|
| 71 |
+
"""
|
| 72 |
+
n_samples = len(features)
|
| 73 |
+
split = int(n_samples * 0.85)
|
| 74 |
+
|
| 75 |
+
# Fit scaler on training portion ONLY
|
| 76 |
+
scaler = MinMaxScaler()
|
| 77 |
+
scaler.fit(features[:split])
|
| 78 |
+
|
| 79 |
+
scaled = scaler.transform(features)
|
| 80 |
+
|
| 81 |
+
X, y = [], []
|
| 82 |
+
# y targets are next-5-day Close prices (column 0 after scaling)
|
| 83 |
+
for i in range(LOOK_BACK, len(scaled) - PREDICT_DAYS):
|
| 84 |
+
X.append(scaled[i - LOOK_BACK:i]) # shape (LOOK_BACK, n_features)
|
| 85 |
+
y.append(scaled[i:i + PREDICT_DAYS, close_col_idx]) # shape (PREDICT_DAYS,)
|
| 86 |
+
|
| 87 |
+
X = np.array(X, dtype=np.float32)
|
| 88 |
+
y = np.array(y, dtype=np.float32)
|
| 89 |
+
|
| 90 |
+
# Adjust split index for the windowed arrays
|
| 91 |
+
adj_split = split - LOOK_BACK
|
| 92 |
+
adj_split = max(1, min(adj_split, len(X) - 1))
|
| 93 |
+
|
| 94 |
+
return X, y, scaler, adj_split
|
| 95 |
+
|
| 96 |
+
|
| 97 |
+
# ββ Train + Predict pipeline βββββββββββββββββββββββββββββββββ
|
| 98 |
+
def train_and_predict(
|
| 99 |
+
df: pd.DataFrame,
|
| 100 |
+
epochs: int = 100,
|
| 101 |
+
lr: float = 0.001,
|
| 102 |
+
batch_size: int = 32,
|
| 103 |
+
patience: int = 10,
|
| 104 |
+
):
|
| 105 |
+
"""
|
| 106 |
+
Train an LSTM on multi-feature data and return the next 5 predicted
|
| 107 |
+
prices, a confidence score, and risk level.
|
| 108 |
+
"""
|
| 109 |
+
features, close, n_features = _prepare_features(df)
|
| 110 |
+
X, y, scaler, split = _prepare_data(features)
|
| 111 |
+
|
| 112 |
+
X_train, y_train = X[:split], y[:split]
|
| 113 |
+
X_test, y_test = X[split:], y[split:]
|
| 114 |
+
|
| 115 |
+
# Torch tensors
|
| 116 |
+
X_train_t = torch.tensor(X_train)
|
| 117 |
+
y_train_t = torch.tensor(y_train)
|
| 118 |
+
X_test_t = torch.tensor(X_test)
|
| 119 |
+
y_test_t = torch.tensor(y_test)
|
| 120 |
+
|
| 121 |
+
# Mini-batch DataLoader
|
| 122 |
+
train_ds = TensorDataset(X_train_t, y_train_t)
|
| 123 |
+
train_loader = DataLoader(train_ds, batch_size=batch_size, shuffle=True)
|
| 124 |
+
|
| 125 |
+
model = StockLSTM(
|
| 126 |
+
input_size=n_features,
|
| 127 |
+
hidden_size=128,
|
| 128 |
+
num_layers=3,
|
| 129 |
+
output_size=PREDICT_DAYS,
|
| 130 |
+
)
|
| 131 |
+
criterion = nn.MSELoss()
|
| 132 |
+
optimizer = torch.optim.Adam(model.parameters(), lr=lr, weight_decay=1e-5)
|
| 133 |
+
scheduler = torch.optim.lr_scheduler.ReduceLROnPlateau(
|
| 134 |
+
optimizer, mode="min", factor=0.5, patience=5, min_lr=1e-6,
|
| 135 |
+
)
|
| 136 |
+
|
| 137 |
+
# ββ Training loop with early stopping ββ
|
| 138 |
+
best_val_loss = float("inf")
|
| 139 |
+
epochs_no_improve = 0
|
| 140 |
+
|
| 141 |
+
for epoch in range(epochs):
|
| 142 |
+
model.train()
|
| 143 |
+
for xb, yb in train_loader:
|
| 144 |
+
optimizer.zero_grad()
|
| 145 |
+
preds = model(xb)
|
| 146 |
+
loss = criterion(preds, yb)
|
| 147 |
+
loss.backward()
|
| 148 |
+
torch.nn.utils.clip_grad_norm_(model.parameters(), max_norm=1.0)
|
| 149 |
+
optimizer.step()
|
| 150 |
+
|
| 151 |
+
# Validation
|
| 152 |
+
model.eval()
|
| 153 |
+
with torch.no_grad():
|
| 154 |
+
val_preds = model(X_test_t)
|
| 155 |
+
val_loss = float(criterion(val_preds, y_test_t))
|
| 156 |
+
|
| 157 |
+
scheduler.step(val_loss)
|
| 158 |
+
|
| 159 |
+
# Early stopping
|
| 160 |
+
if val_loss < best_val_loss:
|
| 161 |
+
best_val_loss = val_loss
|
| 162 |
+
epochs_no_improve = 0
|
| 163 |
+
best_state = {k: v.clone() for k, v in model.state_dict().items()}
|
| 164 |
+
else:
|
| 165 |
+
epochs_no_improve += 1
|
| 166 |
+
if epochs_no_improve >= patience:
|
| 167 |
+
break
|
| 168 |
+
|
| 169 |
+
# Restore best model
|
| 170 |
+
if best_val_loss < float("inf"):
|
| 171 |
+
model.load_state_dict(best_state)
|
| 172 |
+
|
| 173 |
+
# ββ Final test evaluation ββ
|
| 174 |
+
model.eval()
|
| 175 |
+
with torch.no_grad():
|
| 176 |
+
test_preds = model(X_test_t).numpy()
|
| 177 |
+
test_loss = float(criterion(torch.tensor(test_preds), y_test_t))
|
| 178 |
+
|
| 179 |
+
# Confidence & risk (based on test MSE, lower is better)
|
| 180 |
+
confidence = max(0, min(100, round((1 - test_loss * 10) * 100, 1)))
|
| 181 |
+
if confidence >= 70:
|
| 182 |
+
risk = "Low"
|
| 183 |
+
elif confidence >= 45:
|
| 184 |
+
risk = "Medium"
|
| 185 |
+
else:
|
| 186 |
+
risk = "High"
|
| 187 |
+
|
| 188 |
+
# ββ Predict next 5 days ββ
|
| 189 |
+
last_window = features[-LOOK_BACK:]
|
| 190 |
+
last_scaled = scaler.transform(last_window).reshape(1, LOOK_BACK, n_features)
|
| 191 |
+
last_seq = torch.tensor(last_scaled, dtype=torch.float32)
|
| 192 |
+
|
| 193 |
+
with torch.no_grad():
|
| 194 |
+
raw_pred = model(last_seq).numpy().flatten()
|
| 195 |
+
|
| 196 |
+
# Inverse-transform: raw_pred is in scaled Close space (column 0)
|
| 197 |
+
# Build a dummy array with all features set to 0, then set column 0
|
| 198 |
+
dummy = np.zeros((len(raw_pred), n_features), dtype=np.float32)
|
| 199 |
+
dummy[:, 0] = raw_pred
|
| 200 |
+
predicted_prices = scaler.inverse_transform(dummy)[:, 0].tolist()
|
| 201 |
+
|
| 202 |
+
# Historical last 30 days for chart overlay
|
| 203 |
+
historical_prices = close[-30:].tolist()
|
| 204 |
+
|
| 205 |
+
return {
|
| 206 |
+
"predicted_prices": [round(p, 2) for p in predicted_prices],
|
| 207 |
+
"confidence": confidence,
|
| 208 |
+
"risk": risk,
|
| 209 |
+
"test_mse": round(test_loss, 6),
|
| 210 |
+
"historical_last_30": [round(float(p), 2) for p in historical_prices],
|
| 211 |
+
}
|
portfolio.json
ADDED
|
@@ -0,0 +1,8 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
{
|
| 2 |
+
"balance": 100000.0,
|
| 3 |
+
"initial_balance": 100000.0,
|
| 4 |
+
"positions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
|
|
|
|
| 1 |
+
"""
|
| 2 |
+
News sentiment analysis using NLTK VADER + ProsusAI/FinBERT ensemble.
|
| 3 |
+
VADER provides fast rule-based scoring; FinBERT provides deep financial context.
|
| 4 |
+
The final score is a weighted blend (40% VADER, 60% FinBERT).
|
| 5 |
+
"""
|
| 6 |
+
|
| 7 |
+
import torch
|
| 8 |
+
from transformers import BertTokenizer, BertForSequenceClassification
|
| 9 |
+
import numpy as np
|
| 10 |
+
import yfinance as yf
|
| 11 |
+
import nltk
|
| 12 |
+
from nltk.sentiment.vader import SentimentIntensityAnalyzer
|
| 13 |
+
|
| 14 |
+
# ββ Download VADER lexicon if missing ββββββββββββββββββββββββββ
|
| 15 |
+
try:
|
| 16 |
+
nltk.data.find("sentiment/vader_lexicon.zip")
|
| 17 |
+
except LookupError:
|
| 18 |
+
nltk.download("vader_lexicon", quiet=True)
|
| 19 |
+
|
| 20 |
+
# ββ Load models once at import βββββββββββββββββββββββββββββββββ
|
| 21 |
+
# VADER
|
| 22 |
+
_vader = SentimentIntensityAnalyzer()
|
| 23 |
+
|
| 24 |
+
# FinBERT
|
| 25 |
+
MODEL_NAME = "ProsusAI/finbert"
|
| 26 |
+
_tokenizer = BertTokenizer.from_pretrained(MODEL_NAME)
|
| 27 |
+
_finbert = BertForSequenceClassification.from_pretrained(MODEL_NAME)
|
| 28 |
+
_finbert.eval()
|
| 29 |
+
FINBERT_LABELS = ["negative", "neutral", "positive"]
|
| 30 |
+
|
| 31 |
+
# Ensemble weights
|
| 32 |
+
VADER_WEIGHT = 0.4
|
| 33 |
+
FINBERT_WEIGHT = 0.6
|
| 34 |
+
|
| 35 |
+
|
| 36 |
+
# ββ Individual scorers βββββββββββββββββββββββββββββββββββββββββ
|
| 37 |
+
def _score_vader(text: str) -> dict:
|
| 38 |
+
"""VADER compound score mapped to label + confidence."""
|
| 39 |
+
scores = _vader.polarity_scores(text)
|
| 40 |
+
compound = scores["compound"]
|
| 41 |
+
|
| 42 |
+
if compound >= 0.05:
|
| 43 |
+
label = "positive"
|
| 44 |
+
elif compound <= -0.05:
|
| 45 |
+
label = "negative"
|
| 46 |
+
else:
|
| 47 |
+
label = "neutral"
|
| 48 |
+
|
| 49 |
+
confidence = round(abs(compound), 4)
|
| 50 |
+
return {"label": label, "score": round(compound, 4), "confidence": confidence}
|
| 51 |
+
|
| 52 |
+
|
| 53 |
+
def _score_finbert(text: str) -> dict:
|
| 54 |
+
"""FinBERT probability-based label + confidence."""
|
| 55 |
+
tokens = _tokenizer(text, return_tensors="pt", padding=True,
|
| 56 |
+
truncation=True, max_length=128)
|
| 57 |
+
with torch.no_grad():
|
| 58 |
+
logits = _finbert(**tokens).logits
|
| 59 |
+
probs = torch.nn.functional.softmax(logits, dim=-1).squeeze().tolist()
|
| 60 |
+
idx = int(np.argmax(probs))
|
| 61 |
+
|
| 62 |
+
# Convert to a signed score: positive=+1, neutral=0, negative=β1
|
| 63 |
+
signed_score = probs[2] - probs[0] # positive_prob - negative_prob
|
| 64 |
+
return {
|
| 65 |
+
"label": FINBERT_LABELS[idx],
|
| 66 |
+
"score": round(signed_score, 4),
|
| 67 |
+
"confidence": round(probs[idx], 4),
|
| 68 |
+
}
|
| 69 |
+
|
| 70 |
+
|
| 71 |
+
def _score_text(text: str) -> dict:
|
| 72 |
+
"""
|
| 73 |
+
Ensemble: blend VADER and FinBERT scores.
|
| 74 |
+
Returns per-headline detail with both individual and combined scores.
|
| 75 |
+
"""
|
| 76 |
+
vader = _score_vader(text)
|
| 77 |
+
finbert = _score_finbert(text)
|
| 78 |
+
|
| 79 |
+
# Weighted blend of signed scores
|
| 80 |
+
combined_score = (VADER_WEIGHT * vader["score"]) + (FINBERT_WEIGHT * finbert["score"])
|
| 81 |
+
|
| 82 |
+
if combined_score > 0.1:
|
| 83 |
+
label = "positive"
|
| 84 |
+
elif combined_score < -0.1:
|
| 85 |
+
label = "negative"
|
| 86 |
+
else:
|
| 87 |
+
label = "neutral"
|
| 88 |
+
|
| 89 |
+
combined_confidence = (VADER_WEIGHT * vader["confidence"]) + (FINBERT_WEIGHT * finbert["confidence"])
|
| 90 |
+
|
| 91 |
+
return {
|
| 92 |
+
"text": text,
|
| 93 |
+
"label": label,
|
| 94 |
+
"confidence": round(combined_confidence, 4),
|
| 95 |
+
"combined_score": round(combined_score, 4),
|
| 96 |
+
"vader": vader,
|
| 97 |
+
"finbert": finbert,
|
| 98 |
+
}
|
| 99 |
+
|
| 100 |
+
|
| 101 |
+
# ββ News fetcher βββββββββββββββββββββββββββββββββββββββββββββββ
|
| 102 |
+
def fetch_news_headlines(ticker: str, max_items: int = 10) -> list[str]:
|
| 103 |
+
"""Fetch recent news headlines from Yahoo Finance."""
|
| 104 |
+
stock = yf.Ticker(ticker)
|
| 105 |
+
news = stock.news or []
|
| 106 |
+
headlines = []
|
| 107 |
+
for item in news[:max_items]:
|
| 108 |
+
# yfinance v0.2.36+ nests data under "content"
|
| 109 |
+
content = item.get("content", {})
|
| 110 |
+
title = content.get("title", "") or item.get("title", "")
|
| 111 |
+
if title:
|
| 112 |
+
headlines.append(title)
|
| 113 |
+
return headlines
|
| 114 |
+
|
| 115 |
+
|
| 116 |
+
# ββ Public API βββββββββββββββββββββββββββββββββββββββββββββββββ
|
| 117 |
+
def analyze_sentiment(ticker: str) -> dict:
|
| 118 |
+
"""
|
| 119 |
+
End-to-end: fetch headlines β score each with VADER + FinBERT β return aggregate.
|
| 120 |
+
"""
|
| 121 |
+
headlines = fetch_news_headlines(ticker)
|
| 122 |
+
if not headlines:
|
| 123 |
+
return {
|
| 124 |
+
"ticker": ticker,
|
| 125 |
+
"articles_analyzed": 0,
|
| 126 |
+
"details": [],
|
| 127 |
+
"overall_sentiment": "neutral",
|
| 128 |
+
"overall_score": 0.0,
|
| 129 |
+
"method": "VADER (40%) + FinBERT (60%) ensemble",
|
| 130 |
+
}
|
| 131 |
+
|
| 132 |
+
details = [_score_text(h) for h in headlines]
|
| 133 |
+
|
| 134 |
+
# Aggregate combined scores
|
| 135 |
+
avg = float(np.mean([d["combined_score"] for d in details]))
|
| 136 |
+
|
| 137 |
+
if avg > 0.15:
|
| 138 |
+
overall = "positive"
|
| 139 |
+
elif avg < -0.15:
|
| 140 |
+
overall = "negative"
|
| 141 |
+
else:
|
| 142 |
+
overall = "neutral"
|
| 143 |
+
|
| 144 |
+
return {
|
| 145 |
+
"ticker": ticker,
|
| 146 |
+
"articles_analyzed": len(details),
|
| 147 |
+
"details": details,
|
| 148 |
+
"overall_sentiment": overall,
|
| 149 |
+
"overall_score": round(avg, 4),
|
| 150 |
+
"method": "VADER (40%) + FinBERT (60%) ensemble",
|
| 151 |
+
}
|
step4_install.sh
ADDED
|
@@ -0,0 +1,12 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
pip install --upgrade pip
|
| 2 |
+
|
| 3 |
+
pip install fastapi==0.115.0
|
| 4 |
+
pip install uvicorn==0.30.0
|
| 5 |
+
pip install yfinance==1.1.0
|
| 6 |
+
pip install pandas==2.2.0
|
| 7 |
+
pip install numpy==1.26.4
|
| 8 |
+
pip install scikit-learn==1.5.0
|
| 9 |
+
pip install transformers==4.44.0
|
| 10 |
+
pip install requests==2.32.0
|
| 11 |
+
pip install python-dateutil==2.9.0
|
| 12 |
+
pip install ta==0.11.0
|
stock_data.py
ADDED
|
@@ -0,0 +1,118 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""
|
| 2 |
+
Fetches historical stock data from Yahoo Finance and computes
|
| 3 |
+
technical indicators: SMA, EMA, RSI, MACD, and Volume profile.
|
| 4 |
+
"""
|
| 5 |
+
|
| 6 |
+
import yfinance as yf
|
| 7 |
+
import pandas as pd
|
| 8 |
+
import ta
|
| 9 |
+
from datetime import datetime
|
| 10 |
+
|
| 11 |
+
|
| 12 |
+
def fetch_stock_data(ticker: str, period: str = "2y", interval: str = "1d") -> pd.DataFrame:
|
| 13 |
+
"""Download OHLCV data from Yahoo Finance."""
|
| 14 |
+
stock = yf.Ticker(ticker)
|
| 15 |
+
df = stock.history(period=period, interval=interval)
|
| 16 |
+
if df.empty:
|
| 17 |
+
raise ValueError(f"No data found for ticker: {ticker}")
|
| 18 |
+
df.reset_index(inplace=True)
|
| 19 |
+
return df
|
| 20 |
+
|
| 21 |
+
|
| 22 |
+
def add_technical_indicators(df: pd.DataFrame) -> pd.DataFrame:
|
| 23 |
+
"""Add SMA, EMA, RSI, MACD, and volume-based indicators."""
|
| 24 |
+
close = df["Close"]
|
| 25 |
+
volume = df["Volume"]
|
| 26 |
+
|
| 27 |
+
df["SMA_20"] = ta.trend.sma_indicator(close, window=20)
|
| 28 |
+
df["SMA_50"] = ta.trend.sma_indicator(close, window=50)
|
| 29 |
+
df["EMA_20"] = ta.trend.ema_indicator(close, window=20)
|
| 30 |
+
df["RSI"] = ta.momentum.rsi(close, window=14)
|
| 31 |
+
|
| 32 |
+
macd = ta.trend.MACD(close)
|
| 33 |
+
df["MACD"] = macd.macd()
|
| 34 |
+
df["MACD_Signal"] = macd.macd_signal()
|
| 35 |
+
df["MACD_Hist"] = macd.macd_diff()
|
| 36 |
+
|
| 37 |
+
df["Volume_SMA_20"] = ta.trend.sma_indicator(volume, window=20)
|
| 38 |
+
df.dropna(inplace=True)
|
| 39 |
+
return df
|
| 40 |
+
|
| 41 |
+
|
| 42 |
+
def get_stock_info(ticker: str) -> dict:
|
| 43 |
+
"""Return basic stock metadata."""
|
| 44 |
+
stock = yf.Ticker(ticker)
|
| 45 |
+
info = stock.info
|
| 46 |
+
return {
|
| 47 |
+
"name": info.get("shortName", ticker),
|
| 48 |
+
"sector": info.get("sector", "N/A"),
|
| 49 |
+
"currency": info.get("currency", "USD"),
|
| 50 |
+
"current_price": info.get("currentPrice", info.get("regularMarketPrice", 0)),
|
| 51 |
+
"market_cap": info.get("marketCap", 0),
|
| 52 |
+
"day_high": info.get("dayHigh", 0),
|
| 53 |
+
"day_low": info.get("dayLow", 0),
|
| 54 |
+
"prev_close": info.get("previousClose", 0),
|
| 55 |
+
"open": info.get("open", 0),
|
| 56 |
+
"volume": info.get("volume", 0),
|
| 57 |
+
"fifty_two_week_high": info.get("fiftyTwoWeekHigh", 0),
|
| 58 |
+
"fifty_two_week_low": info.get("fiftyTwoWeekLow", 0),
|
| 59 |
+
}
|
| 60 |
+
|
| 61 |
+
|
| 62 |
+
def fetch_live_price(ticker: str) -> dict:
|
| 63 |
+
"""Fetch the latest price snapshot for live ticker display."""
|
| 64 |
+
stock = yf.Ticker(ticker)
|
| 65 |
+
info = stock.info
|
| 66 |
+
|
| 67 |
+
current = info.get("currentPrice", info.get("regularMarketPrice", 0))
|
| 68 |
+
prev_close = info.get("previousClose", 0)
|
| 69 |
+
|
| 70 |
+
change = round(current - prev_close, 2) if current and prev_close else 0
|
| 71 |
+
change_pct = round((change / prev_close) * 100, 2) if prev_close else 0
|
| 72 |
+
|
| 73 |
+
return {
|
| 74 |
+
"ticker": ticker,
|
| 75 |
+
"price": current,
|
| 76 |
+
"change": change,
|
| 77 |
+
"change_pct": change_pct,
|
| 78 |
+
"direction": "up" if change >= 0 else "down",
|
| 79 |
+
"day_high": info.get("dayHigh", 0),
|
| 80 |
+
"day_low": info.get("dayLow", 0),
|
| 81 |
+
"volume": info.get("volume", 0),
|
| 82 |
+
"timestamp": datetime.now().isoformat(),
|
| 83 |
+
}
|
| 84 |
+
|
| 85 |
+
|
| 86 |
+
TIMEFRAME_MAP = {
|
| 87 |
+
"1d": ("1d", "5m"),
|
| 88 |
+
"5d": ("5d", "15m"),
|
| 89 |
+
"1wk": ("5d", "15m"),
|
| 90 |
+
"1mo": ("1mo", "1h"),
|
| 91 |
+
"3mo": ("3mo", "1d"),
|
| 92 |
+
"6mo": ("6mo", "1d"),
|
| 93 |
+
"1y": ("1y", "1d"),
|
| 94 |
+
"2y": ("2y", "1wk"),
|
| 95 |
+
}
|
| 96 |
+
|
| 97 |
+
|
| 98 |
+
def fetch_chart_data(ticker: str, timeframe: str) -> list[dict]:
|
| 99 |
+
"""Return OHLCV records for a given timeframe."""
|
| 100 |
+
period, interval = TIMEFRAME_MAP.get(timeframe, ("1mo", "1h"))
|
| 101 |
+
stock = yf.Ticker(ticker)
|
| 102 |
+
df = stock.history(period=period, interval=interval)
|
| 103 |
+
if df.empty:
|
| 104 |
+
raise ValueError(f"No chart data for {ticker}")
|
| 105 |
+
df.reset_index(inplace=True)
|
| 106 |
+
|
| 107 |
+
records = []
|
| 108 |
+
date_col = "Datetime" if "Datetime" in df.columns else "Date"
|
| 109 |
+
for _, row in df.iterrows():
|
| 110 |
+
records.append({
|
| 111 |
+
"time": str(row[date_col]),
|
| 112 |
+
"open": round(float(row["Open"]), 2),
|
| 113 |
+
"high": round(float(row["High"]), 2),
|
| 114 |
+
"low": round(float(row["Low"]), 2),
|
| 115 |
+
"close": round(float(row["Close"]), 2),
|
| 116 |
+
"volume": int(row["Volume"]),
|
| 117 |
+
})
|
| 118 |
+
return records
|
style.css
ADDED
|
@@ -0,0 +1,274 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
/* ββ RESET & BASE βββββββββββββββββββββββββββββββββββ */
|
| 2 |
+
*, *::before, *::after { box-sizing: border-box; margin: 0; padding: 0; }
|
| 3 |
+
:root {
|
| 4 |
+
--bg: #0b0e14; --bg2: #131720; --bg3: #1a1f2e; --border: #242a38;
|
| 5 |
+
--text: #d1d5db; --text-dim: #6b7280;
|
| 6 |
+
--green: #22c55e; --red: #ef4444; --blue: #3b82f6;
|
| 7 |
+
--cyan: #06b6d4; --yellow: #eab308; --accent: #22c55e;
|
| 8 |
+
--purple: #a855f7;
|
| 9 |
+
}
|
| 10 |
+
body {
|
| 11 |
+
font-family: 'SF Mono', 'Fira Code', 'Consolas', monospace;
|
| 12 |
+
background: var(--bg); color: var(--text);
|
| 13 |
+
min-height: 100vh; font-size: 14px;
|
| 14 |
+
}
|
| 15 |
+
|
| 16 |
+
/* ββ TOP BAR ββββββββββββββββββββββββββββββββββββββββ */
|
| 17 |
+
.topbar {
|
| 18 |
+
display: flex; align-items: center; justify-content: space-between;
|
| 19 |
+
padding: 0.6rem 1.5rem; background: var(--bg2);
|
| 20 |
+
border-bottom: 1px solid var(--border);
|
| 21 |
+
position: sticky; top: 0; z-index: 100;
|
| 22 |
+
}
|
| 23 |
+
.brand { font-size: 1.2rem; font-weight: 700; color: var(--accent); }
|
| 24 |
+
.brand span { color: #fff; }
|
| 25 |
+
.search-area { display: flex; gap: 0.4rem; }
|
| 26 |
+
.search-area input {
|
| 27 |
+
width: 260px; padding: 0.5rem 0.8rem;
|
| 28 |
+
background: var(--bg3); border: 1px solid var(--border);
|
| 29 |
+
border-radius: 6px; color: #fff; font-family: inherit; font-size: 0.9rem;
|
| 30 |
+
}
|
| 31 |
+
.search-area input:focus { outline: none; border-color: var(--accent); }
|
| 32 |
+
.search-area button {
|
| 33 |
+
padding: 0.5rem 1.2rem; border: none; border-radius: 6px;
|
| 34 |
+
background: var(--accent); color: #000; font-weight: 700;
|
| 35 |
+
cursor: pointer; font-family: inherit; transition: 0.2s;
|
| 36 |
+
}
|
| 37 |
+
.search-area button:hover { background: #16a34a; }
|
| 38 |
+
|
| 39 |
+
/* Nav Tabs */
|
| 40 |
+
.nav-tabs { display: flex; gap: 0.3rem; }
|
| 41 |
+
.nav-tab {
|
| 42 |
+
padding: 0.5rem 1rem; border: 1px solid var(--border);
|
| 43 |
+
background: transparent; color: var(--text-dim); border-radius: 6px;
|
| 44 |
+
cursor: pointer; font-family: inherit; font-size: 0.85rem; transition: 0.2s;
|
| 45 |
+
}
|
| 46 |
+
.nav-tab:hover { border-color: var(--text); color: var(--text); }
|
| 47 |
+
.nav-tab.active { background: var(--accent); color: #000; border-color: var(--accent); font-weight: 700; }
|
| 48 |
+
|
| 49 |
+
.live-badge { display: flex; align-items: center; gap: 0.4rem; color: var(--green); font-weight: 700; font-size: 0.8rem; }
|
| 50 |
+
.live-badge .dot {
|
| 51 |
+
width: 8px; height: 8px; background: var(--green); border-radius: 50%;
|
| 52 |
+
animation: pulse 1.5s infinite;
|
| 53 |
+
}
|
| 54 |
+
@keyframes pulse { 0%, 100% { opacity: 1; } 50% { opacity: 0.3; } }
|
| 55 |
+
|
| 56 |
+
/* ββ PRICE BANNER βββββββββββββββββββββββββββββββββββ */
|
| 57 |
+
.price-banner {
|
| 58 |
+
display: flex; justify-content: space-between; align-items: center;
|
| 59 |
+
padding: 1rem 1.5rem; background: var(--bg2); border-bottom: 1px solid var(--border);
|
| 60 |
+
}
|
| 61 |
+
.price-main { display: flex; align-items: baseline; gap: 1rem; }
|
| 62 |
+
.price-main h1 { font-size: 1.3rem; color: #fff; }
|
| 63 |
+
.price-value { font-size: 2rem; font-weight: 700; color: #fff; }
|
| 64 |
+
.price-change { font-size: 1rem; font-weight: 600; padding: 0.2rem 0.6rem; border-radius: 4px; }
|
| 65 |
+
.price-change.up { color: var(--green); background: rgba(34,197,94,0.1); }
|
| 66 |
+
.price-change.down { color: var(--red); background: rgba(239,68,68,0.1); }
|
| 67 |
+
.price-stats { display: flex; gap: 1.5rem; }
|
| 68 |
+
.price-stats div { text-align: center; }
|
| 69 |
+
.price-stats label { display: block; font-size: 0.7rem; color: var(--text-dim); text-transform: uppercase; }
|
| 70 |
+
.price-stats span { font-size: 0.95rem; color: #fff; font-weight: 600; }
|
| 71 |
+
|
| 72 |
+
/* ββ TABS βββββββββββββββββββββββββββββββββββββββββββ */
|
| 73 |
+
.tab-content { display: block; }
|
| 74 |
+
.tab-content.hidden { display: none !important; }
|
| 75 |
+
|
| 76 |
+
/* ββ DASHBOARD GRID βββββββββββββββββββββββββββββββββ */
|
| 77 |
+
.dashboard {
|
| 78 |
+
display: grid; grid-template-columns: 1fr 340px;
|
| 79 |
+
gap: 0; min-height: calc(100vh - 160px);
|
| 80 |
+
}
|
| 81 |
+
.chart-area { padding: 1rem 1.5rem; border-right: 1px solid var(--border); }
|
| 82 |
+
.sidebar { padding: 1rem; overflow-y: auto; max-height: calc(100vh - 160px); }
|
| 83 |
+
|
| 84 |
+
/* ββ TIMEFRAME BAR ββββββββββββββββββββββββββββββββββ */
|
| 85 |
+
.timeframe-bar { display: flex; gap: 0.3rem; margin-bottom: 0.8rem; }
|
| 86 |
+
.tf-btn {
|
| 87 |
+
padding: 0.35rem 0.9rem; border: 1px solid var(--border);
|
| 88 |
+
background: transparent; color: var(--text-dim); border-radius: 4px;
|
| 89 |
+
cursor: pointer; font-family: inherit; font-size: 0.8rem; transition: 0.2s;
|
| 90 |
+
}
|
| 91 |
+
.tf-btn:hover { border-color: var(--text); color: var(--text); }
|
| 92 |
+
.tf-btn.active { background: var(--accent); color: #000; border-color: var(--accent); font-weight: 700; }
|
| 93 |
+
|
| 94 |
+
/* ββ CHART CONTAINERS βββββββββββββββββββββββββββββββ */
|
| 95 |
+
.chart-container { background: var(--bg2); border: 1px solid var(--border); border-radius: 8px; padding: 0.8rem; margin-bottom: 0.8rem; }
|
| 96 |
+
.volume-chart { height: 120px; }
|
| 97 |
+
|
| 98 |
+
/* ββ PREDICTION SECTION βββββββββββββββββββββββββββββ */
|
| 99 |
+
.prediction-section { margin-top: 1rem; }
|
| 100 |
+
.prediction-section h3 { color: var(--cyan); margin-bottom: 0.8rem; }
|
| 101 |
+
.pred-metrics { display: grid; grid-template-columns: repeat(4, 1fr); gap: 0.6rem; margin-top: 0.8rem; }
|
| 102 |
+
.metric-card { background: var(--bg3); border: 1px solid var(--border); border-radius: 8px; padding: 0.8rem; text-align: center; }
|
| 103 |
+
.m-label { display: block; font-size: 0.7rem; color: var(--text-dim); text-transform: uppercase; margin-bottom: 0.3rem; }
|
| 104 |
+
.m-value { font-size: 1.3rem; font-weight: 700; color: #fff; }
|
| 105 |
+
|
| 106 |
+
/* ββ SIDEBAR PANELS βββββββββββββββββββββββββββββββββ */
|
| 107 |
+
.panel { background: var(--bg2); border: 1px solid var(--border); border-radius: 8px; padding: 1rem; margin-bottom: 0.8rem; }
|
| 108 |
+
.panel h3 { font-size: 0.95rem; color: var(--cyan); margin-bottom: 0.3rem; }
|
| 109 |
+
.panel-sub { font-size: 0.75rem; color: var(--text-dim); margin-bottom: 0.8rem; }
|
| 110 |
+
|
| 111 |
+
.hp-list { display: flex; flex-direction: column; gap: 0.4rem; }
|
| 112 |
+
.hp-item {
|
| 113 |
+
display: grid; grid-template-columns: 1fr auto auto;
|
| 114 |
+
align-items: center; gap: 0.5rem; padding: 0.5rem 0.6rem;
|
| 115 |
+
background: var(--bg3); border-radius: 6px; cursor: pointer; transition: 0.2s;
|
| 116 |
+
}
|
| 117 |
+
.hp-item:hover { background: var(--border); }
|
| 118 |
+
.hp-ticker { font-weight: 700; color: #fff; font-size: 0.9rem; }
|
| 119 |
+
.hp-name { font-size: 0.7rem; color: var(--text-dim); }
|
| 120 |
+
.hp-price { text-align: right; font-weight: 600; color: #fff; }
|
| 121 |
+
.hp-change { font-size: 0.8rem; font-weight: 600; text-align: right; }
|
| 122 |
+
.hp-change.up { color: var(--green); }
|
| 123 |
+
.hp-change.down { color: var(--red); }
|
| 124 |
+
.hp-score { font-size: 0.7rem; padding: 0.15rem 0.5rem; border-radius: 10px; font-weight: 700; text-align: center; }
|
| 125 |
+
.hp-score.high { background: rgba(34,197,94,0.15); color: var(--green); }
|
| 126 |
+
.hp-score.med { background: rgba(234,179,8,0.15); color: var(--yellow); }
|
| 127 |
+
.hp-score.low { background: rgba(239,68,68,0.15); color: var(--red); }
|
| 128 |
+
|
| 129 |
+
.sent-gauge { display: flex; align-items: center; gap: 1rem; margin: 0.8rem 0; }
|
| 130 |
+
.gauge-circle {
|
| 131 |
+
width: 64px; height: 64px; border-radius: 50%;
|
| 132 |
+
display: flex; align-items: center; justify-content: center;
|
| 133 |
+
font-weight: 700; font-size: 1rem; color: #fff; border: 3px solid var(--text-dim);
|
| 134 |
+
}
|
| 135 |
+
.gauge-circle.positive { border-color: var(--green); background: rgba(34,197,94,0.1); }
|
| 136 |
+
.gauge-circle.negative { border-color: var(--red); background: rgba(239,68,68,0.1); }
|
| 137 |
+
.gauge-circle.neutral { border-color: var(--yellow); background: rgba(234,179,8,0.1); }
|
| 138 |
+
.gauge-label { font-size: 1.1rem; font-weight: 700; text-transform: uppercase; }
|
| 139 |
+
.sent-list { list-style: none; max-height: 200px; overflow-y: auto; }
|
| 140 |
+
.sent-list li { padding: 0.4rem 0; border-bottom: 1px solid var(--border); font-size: 0.8rem; }
|
| 141 |
+
.s-pos { color: var(--green); } .s-neg { color: var(--red); } .s-neu { color: var(--yellow); }
|
| 142 |
+
|
| 143 |
+
.ind-table { width: 100%; }
|
| 144 |
+
.ind-table td { padding: 0.4rem 0.5rem; border-bottom: 1px solid var(--border); }
|
| 145 |
+
.ind-table td:first-child { color: var(--text-dim); }
|
| 146 |
+
.ind-table td:last-child { text-align: right; font-weight: 600; color: #fff; }
|
| 147 |
+
|
| 148 |
+
.mini-loader { text-align: center; color: var(--text-dim); padding: 1rem; font-size: 0.8rem; }
|
| 149 |
+
|
| 150 |
+
/* ββ TRADING DASHBOARD ββββββββββββββββββββββββββββββ */
|
| 151 |
+
.trading-dashboard { padding: 1rem 1.5rem; }
|
| 152 |
+
.trade-grid { display: flex; flex-direction: column; gap: 1rem; }
|
| 153 |
+
|
| 154 |
+
/* Portfolio header cards */
|
| 155 |
+
.portfolio-header {
|
| 156 |
+
display: grid; grid-template-columns: repeat(6, 1fr); gap: 0.6rem;
|
| 157 |
+
}
|
| 158 |
+
.port-card {
|
| 159 |
+
background: var(--bg2); border: 1px solid var(--border);
|
| 160 |
+
border-radius: 8px; padding: 1rem; text-align: center;
|
| 161 |
+
}
|
| 162 |
+
.port-card.balance { border-color: var(--accent); }
|
| 163 |
+
.pc-label { display: block; font-size: 0.7rem; color: var(--text-dim); text-transform: uppercase; margin-bottom: 0.4rem; }
|
| 164 |
+
.pc-value { font-size: 1.4rem; font-weight: 700; color: #fff; }
|
| 165 |
+
|
| 166 |
+
/* Bot controls */
|
| 167 |
+
.bot-controls {
|
| 168 |
+
display: flex; align-items: center; justify-content: space-between;
|
| 169 |
+
background: var(--bg2); border: 1px solid var(--border);
|
| 170 |
+
border-radius: 8px; padding: 1rem 1.5rem;
|
| 171 |
+
}
|
| 172 |
+
.bot-status { display: flex; align-items: center; gap: 0.6rem; font-size: 1.1rem; font-weight: 700; }
|
| 173 |
+
.bot-dot {
|
| 174 |
+
width: 12px; height: 12px; border-radius: 50%; background: var(--red);
|
| 175 |
+
}
|
| 176 |
+
.bot-dot.active { background: var(--green); animation: pulse 1s infinite; }
|
| 177 |
+
.bot-buttons { display: flex; gap: 0.5rem; }
|
| 178 |
+
|
| 179 |
+
.btn-bot, .btn-scan, .btn-trade, .btn-reset {
|
| 180 |
+
padding: 0.6rem 1rem; border: none; border-radius: 6px;
|
| 181 |
+
font-family: inherit; font-weight: 700; font-size: 0.85rem;
|
| 182 |
+
cursor: pointer; transition: 0.2s;
|
| 183 |
+
}
|
| 184 |
+
.btn-bot { background: var(--purple); color: #fff; }
|
| 185 |
+
.btn-bot:hover { background: #9333ea; }
|
| 186 |
+
.btn-bot.active { background: var(--red); }
|
| 187 |
+
.btn-scan { background: var(--blue); color: #fff; }
|
| 188 |
+
.btn-scan:hover { background: #2563eb; }
|
| 189 |
+
.btn-trade { background: var(--green); color: #000; }
|
| 190 |
+
.btn-trade:hover { background: #16a34a; }
|
| 191 |
+
.btn-reset { background: var(--bg3); color: var(--text-dim); border: 1px solid var(--border); }
|
| 192 |
+
.btn-reset:hover { background: var(--border); color: #fff; }
|
| 193 |
+
|
| 194 |
+
/* Trade panels */
|
| 195 |
+
.trade-panel {
|
| 196 |
+
background: var(--bg2); border: 1px solid var(--border);
|
| 197 |
+
border-radius: 8px; padding: 1rem 1.5rem;
|
| 198 |
+
}
|
| 199 |
+
.trade-panel h3 { color: var(--cyan); margin-bottom: 0.8rem; font-size: 0.95rem; }
|
| 200 |
+
|
| 201 |
+
/* Positions table */
|
| 202 |
+
.positions-table-wrap { overflow-x: auto; }
|
| 203 |
+
.positions-table { width: 100%; border-collapse: collapse; font-size: 0.85rem; }
|
| 204 |
+
.positions-table th {
|
| 205 |
+
padding: 0.5rem 0.6rem; text-align: left; color: var(--text-dim);
|
| 206 |
+
border-bottom: 1px solid var(--border); font-size: 0.75rem; text-transform: uppercase;
|
| 207 |
+
}
|
| 208 |
+
.positions-table td {
|
| 209 |
+
padding: 0.6rem; border-bottom: 1px solid var(--border);
|
| 210 |
+
}
|
| 211 |
+
.positions-table .ticker-col { font-weight: 700; color: #fff; }
|
| 212 |
+
.pnl-positive { color: var(--green); font-weight: 700; }
|
| 213 |
+
.pnl-negative { color: var(--red); font-weight: 700; }
|
| 214 |
+
|
| 215 |
+
.btn-sell-small {
|
| 216 |
+
padding: 0.3rem 0.7rem; border: none; border-radius: 4px;
|
| 217 |
+
background: var(--red); color: #fff; font-weight: 700;
|
| 218 |
+
cursor: pointer; font-family: inherit; font-size: 0.75rem;
|
| 219 |
+
}
|
| 220 |
+
.btn-sell-small:hover { background: #dc2626; }
|
| 221 |
+
|
| 222 |
+
.empty-msg { color: var(--text-dim); text-align: center; padding: 1.5rem; font-size: 0.85rem; }
|
| 223 |
+
|
| 224 |
+
/* Trade log */
|
| 225 |
+
.trade-log { max-height: 300px; overflow-y: auto; }
|
| 226 |
+
.trade-entry {
|
| 227 |
+
display: grid; grid-template-columns: auto 1fr auto auto;
|
| 228 |
+
gap: 0.8rem; align-items: center;
|
| 229 |
+
padding: 0.6rem 0; border-bottom: 1px solid var(--border); font-size: 0.8rem;
|
| 230 |
+
}
|
| 231 |
+
.te-time { color: var(--text-dim); font-size: 0.75rem; }
|
| 232 |
+
.te-ticker { font-weight: 700; color: #fff; }
|
| 233 |
+
.te-action { padding: 0.15rem 0.5rem; border-radius: 4px; font-weight: 700; font-size: 0.75rem; }
|
| 234 |
+
.te-action.buy { background: rgba(34,197,94,0.15); color: var(--green); }
|
| 235 |
+
.te-action.sell { background: rgba(239,68,68,0.15); color: var(--red); }
|
| 236 |
+
|
| 237 |
+
/* Trade feed */
|
| 238 |
+
.trade-feed { max-height: 250px; overflow-y: auto; font-size: 0.8rem; }
|
| 239 |
+
.feed-item {
|
| 240 |
+
padding: 0.5rem 0.6rem; margin-bottom: 0.3rem;
|
| 241 |
+
background: var(--bg3); border-radius: 4px;
|
| 242 |
+
border-left: 3px solid var(--border); animation: fadeIn 0.3s ease;
|
| 243 |
+
}
|
| 244 |
+
.feed-item.buy { border-left-color: var(--green); }
|
| 245 |
+
.feed-item.sell { border-left-color: var(--red); }
|
| 246 |
+
.feed-item.hold { border-left-color: var(--yellow); }
|
| 247 |
+
.feed-item.wait { border-left-color: var(--text-dim); }
|
| 248 |
+
|
| 249 |
+
@keyframes fadeIn { from { opacity: 0; transform: translateY(-5px); } to { opacity: 1; transform: translateY(0); } }
|
| 250 |
+
|
| 251 |
+
/* ββ FOOTER βββββββββββββββββββββββββββββββββββββββββ */
|
| 252 |
+
footer {
|
| 253 |
+
text-align: center; padding: 1.5rem;
|
| 254 |
+
background: var(--bg2); border-top: 1px solid var(--border);
|
| 255 |
+
color: var(--text-dim); font-size: 0.8rem;
|
| 256 |
+
}
|
| 257 |
+
footer p + p { margin-top: 0.3rem; }
|
| 258 |
+
|
| 259 |
+
.hidden { display: none !important; }
|
| 260 |
+
|
| 261 |
+
/* ββ RESPONSIVE βββββββββββββββββββββββββββββββββββββ */
|
| 262 |
+
@media (max-width: 1100px) {
|
| 263 |
+
.portfolio-header { grid-template-columns: repeat(3, 1fr); }
|
| 264 |
+
}
|
| 265 |
+
@media (max-width: 900px) {
|
| 266 |
+
.dashboard { grid-template-columns: 1fr; }
|
| 267 |
+
.sidebar { max-height: none; }
|
| 268 |
+
.price-banner { flex-direction: column; gap: 0.8rem; }
|
| 269 |
+
.price-stats { flex-wrap: wrap; }
|
| 270 |
+
.pred-metrics { grid-template-columns: repeat(2, 1fr); }
|
| 271 |
+
.portfolio-header { grid-template-columns: repeat(2, 1fr); }
|
| 272 |
+
.bot-controls { flex-direction: column; gap: 0.8rem; }
|
| 273 |
+
.bot-buttons { flex-wrap: wrap; }
|
| 274 |
+
}
|
trader.py
ADDED
|
@@ -0,0 +1,287 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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| 1 |
+
"""
|
| 2 |
+
StockSense AI β Auto Trading Engine (Paper Trading)
|
| 3 |
+
Strategy: LSTM Prediction-Based
|
| 4 |
+
- BUY when model predicts price going UP in next 5 days
|
| 5 |
+
- SELL when stop-loss / take-profit / trailing-stop / prediction reversal
|
| 6 |
+
"""
|
| 7 |
+
|
| 8 |
+
import json
|
| 9 |
+
import os
|
| 10 |
+
from datetime import datetime
|
| 11 |
+
from threading import Lock
|
| 12 |
+
|
| 13 |
+
# ββ CONFIG ββββββββββββββββββββββββββββββββοΏ½οΏ½οΏ½ββββββββββββ
|
| 14 |
+
INITIAL_BALANCE = 100_000.00
|
| 15 |
+
STOP_LOSS_PCT = -3.0 # -3% from buy price
|
| 16 |
+
TAKE_PROFIT_PCT = 5.0 # +5% from buy price
|
| 17 |
+
TRAILING_STOP_PCT = -2.0 # -2% from peak after buy
|
| 18 |
+
MAX_HOLD_DAYS = 5 # auto-sell after 5 days
|
| 19 |
+
POSITION_SIZE_PCT = 10.0 # use 10% of balance per trade
|
| 20 |
+
|
| 21 |
+
DATA_FILE = "portfolio.json"
|
| 22 |
+
_lock = Lock()
|
| 23 |
+
|
| 24 |
+
|
| 25 |
+
# ββ PORTFOLIO STATE ββββββββββββββββββββββββββββββββββββ
|
| 26 |
+
def _default_state():
|
| 27 |
+
return {
|
| 28 |
+
"balance": INITIAL_BALANCE,
|
| 29 |
+
"initial_balance": INITIAL_BALANCE,
|
| 30 |
+
"positions": {}, # ticker -> position dict
|
| 31 |
+
"trade_history": [], # list of completed trades
|
| 32 |
+
"bot_active": False,
|
| 33 |
+
"created_at": datetime.now().isoformat(),
|
| 34 |
+
}
|
| 35 |
+
|
| 36 |
+
|
| 37 |
+
def _load_state() -> dict:
|
| 38 |
+
if os.path.exists(DATA_FILE):
|
| 39 |
+
with open(DATA_FILE, "r") as f:
|
| 40 |
+
return json.load(f)
|
| 41 |
+
return _default_state()
|
| 42 |
+
|
| 43 |
+
|
| 44 |
+
def _save_state(state: dict):
|
| 45 |
+
with open(DATA_FILE, "w") as f:
|
| 46 |
+
json.dump(state, f, indent=2, default=str)
|
| 47 |
+
|
| 48 |
+
|
| 49 |
+
def get_portfolio() -> dict:
|
| 50 |
+
"""Return current portfolio state."""
|
| 51 |
+
with _lock:
|
| 52 |
+
state = _load_state()
|
| 53 |
+
return state
|
| 54 |
+
|
| 55 |
+
|
| 56 |
+
def reset_portfolio() -> dict:
|
| 57 |
+
"""Reset portfolio to initial state."""
|
| 58 |
+
with _lock:
|
| 59 |
+
state = _default_state()
|
| 60 |
+
_save_state(state)
|
| 61 |
+
return state
|
| 62 |
+
|
| 63 |
+
|
| 64 |
+
def toggle_bot() -> dict:
|
| 65 |
+
"""Toggle auto-trading bot ON/OFF."""
|
| 66 |
+
with _lock:
|
| 67 |
+
state = _load_state()
|
| 68 |
+
state["bot_active"] = not state["bot_active"]
|
| 69 |
+
_save_state(state)
|
| 70 |
+
return {"bot_active": state["bot_active"]}
|
| 71 |
+
|
| 72 |
+
|
| 73 |
+
# ββ TRADING LOGIC ββββββββββββββββββββββββββββββββββββββ
|
| 74 |
+
def execute_buy(ticker: str, current_price: float, predicted_prices: list,
|
| 75 |
+
confidence: float) -> dict:
|
| 76 |
+
"""
|
| 77 |
+
Execute a BUY order (paper trade).
|
| 78 |
+
"""
|
| 79 |
+
with _lock:
|
| 80 |
+
state = _load_state()
|
| 81 |
+
|
| 82 |
+
# Already holding this ticker?
|
| 83 |
+
if ticker in state["positions"]:
|
| 84 |
+
return {"status": "skipped", "reason": f"Already holding {ticker}"}
|
| 85 |
+
|
| 86 |
+
# Calculate position size
|
| 87 |
+
position_value = state["balance"] * (POSITION_SIZE_PCT / 100)
|
| 88 |
+
if position_value < current_price:
|
| 89 |
+
return {"status": "skipped", "reason": "Insufficient balance"}
|
| 90 |
+
|
| 91 |
+
shares = int(position_value // current_price)
|
| 92 |
+
if shares == 0:
|
| 93 |
+
return {"status": "skipped", "reason": "Cannot afford even 1 share"}
|
| 94 |
+
|
| 95 |
+
cost = shares * current_price
|
| 96 |
+
|
| 97 |
+
# Stop-loss & take-profit prices
|
| 98 |
+
stop_loss = round(current_price * (1 + STOP_LOSS_PCT / 100), 2)
|
| 99 |
+
take_profit = round(current_price * (1 + TAKE_PROFIT_PCT / 100), 2)
|
| 100 |
+
|
| 101 |
+
# Create position
|
| 102 |
+
position = {
|
| 103 |
+
"ticker": ticker,
|
| 104 |
+
"shares": shares,
|
| 105 |
+
"buy_price": current_price,
|
| 106 |
+
"cost": round(cost, 2),
|
| 107 |
+
"stop_loss": stop_loss,
|
| 108 |
+
"take_profit": take_profit,
|
| 109 |
+
"trailing_stop": stop_loss,
|
| 110 |
+
"peak_price": current_price,
|
| 111 |
+
"predicted_prices": predicted_prices,
|
| 112 |
+
"confidence": confidence,
|
| 113 |
+
"buy_time": datetime.now().isoformat(),
|
| 114 |
+
"day_count": 0,
|
| 115 |
+
}
|
| 116 |
+
|
| 117 |
+
state["balance"] -= cost
|
| 118 |
+
state["balance"] = round(state["balance"], 2)
|
| 119 |
+
state["positions"][ticker] = position
|
| 120 |
+
_save_state(state)
|
| 121 |
+
|
| 122 |
+
return {
|
| 123 |
+
"status": "bought",
|
| 124 |
+
"ticker": ticker,
|
| 125 |
+
"shares": shares,
|
| 126 |
+
"price": current_price,
|
| 127 |
+
"cost": round(cost, 2),
|
| 128 |
+
"stop_loss": stop_loss,
|
| 129 |
+
"take_profit": take_profit,
|
| 130 |
+
"balance": state["balance"],
|
| 131 |
+
}
|
| 132 |
+
|
| 133 |
+
|
| 134 |
+
def execute_sell(ticker: str, current_price: float, reason: str) -> dict:
|
| 135 |
+
"""
|
| 136 |
+
Execute a SELL order (paper trade).
|
| 137 |
+
"""
|
| 138 |
+
with _lock:
|
| 139 |
+
state = _load_state()
|
| 140 |
+
|
| 141 |
+
if ticker not in state["positions"]:
|
| 142 |
+
return {"status": "skipped", "reason": f"No position in {ticker}"}
|
| 143 |
+
|
| 144 |
+
pos = state["positions"][ticker]
|
| 145 |
+
revenue = pos["shares"] * current_price
|
| 146 |
+
profit = revenue - pos["cost"]
|
| 147 |
+
profit_pct = (profit / pos["cost"]) * 100
|
| 148 |
+
|
| 149 |
+
# Record trade history
|
| 150 |
+
trade = {
|
| 151 |
+
"ticker": ticker,
|
| 152 |
+
"shares": pos["shares"],
|
| 153 |
+
"buy_price": pos["buy_price"],
|
| 154 |
+
"sell_price": current_price,
|
| 155 |
+
"cost": pos["cost"],
|
| 156 |
+
"revenue": round(revenue, 2),
|
| 157 |
+
"profit": round(profit, 2),
|
| 158 |
+
"profit_pct": round(profit_pct, 2),
|
| 159 |
+
"buy_time": pos["buy_time"],
|
| 160 |
+
"sell_time": datetime.now().isoformat(),
|
| 161 |
+
"reason": reason,
|
| 162 |
+
"confidence": pos["confidence"],
|
| 163 |
+
}
|
| 164 |
+
|
| 165 |
+
state["balance"] += revenue
|
| 166 |
+
state["balance"] = round(state["balance"], 2)
|
| 167 |
+
state["trade_history"].append(trade)
|
| 168 |
+
del state["positions"][ticker]
|
| 169 |
+
_save_state(state)
|
| 170 |
+
|
| 171 |
+
return {
|
| 172 |
+
"status": "sold",
|
| 173 |
+
"ticker": ticker,
|
| 174 |
+
"shares": trade["shares"],
|
| 175 |
+
"price": current_price,
|
| 176 |
+
"profit": trade["profit"],
|
| 177 |
+
"profit_pct": trade["profit_pct"],
|
| 178 |
+
"reason": reason,
|
| 179 |
+
"balance": state["balance"],
|
| 180 |
+
}
|
| 181 |
+
|
| 182 |
+
|
| 183 |
+
def check_position(ticker: str, current_price: float) -> dict:
|
| 184 |
+
"""
|
| 185 |
+
Check if a position should be sold based on stop-loss,
|
| 186 |
+
take-profit, or trailing stop.
|
| 187 |
+
"""
|
| 188 |
+
with _lock:
|
| 189 |
+
state = _load_state()
|
| 190 |
+
|
| 191 |
+
if ticker not in state["positions"]:
|
| 192 |
+
return {"action": "none", "reason": "No position"}
|
| 193 |
+
|
| 194 |
+
pos = state["positions"][ticker]
|
| 195 |
+
buy_price = pos["buy_price"]
|
| 196 |
+
change_pct = ((current_price - buy_price) / buy_price) * 100
|
| 197 |
+
|
| 198 |
+
# ββ STOP LOSS ββ
|
| 199 |
+
if current_price <= pos["stop_loss"]:
|
| 200 |
+
return {"action": "sell", "reason": f"Stop-loss triggered ({STOP_LOSS_PCT}%)"}
|
| 201 |
+
|
| 202 |
+
# ββ TAKE PROFIT ββ
|
| 203 |
+
if current_price >= pos["take_profit"]:
|
| 204 |
+
return {"action": "sell", "reason": f"Take-profit reached (+{TAKE_PROFIT_PCT}%)"}
|
| 205 |
+
|
| 206 |
+
# ββ TRAILING STOP ββ
|
| 207 |
+
if current_price > pos["peak_price"]:
|
| 208 |
+
# Update peak and trailing stop
|
| 209 |
+
with _lock:
|
| 210 |
+
state = _load_state()
|
| 211 |
+
state["positions"][ticker]["peak_price"] = current_price
|
| 212 |
+
new_trailing = round(current_price * (1 + TRAILING_STOP_PCT / 100), 2)
|
| 213 |
+
if new_trailing > state["positions"][ticker]["trailing_stop"]:
|
| 214 |
+
state["positions"][ticker]["trailing_stop"] = new_trailing
|
| 215 |
+
_save_state(state)
|
| 216 |
+
elif current_price <= pos["trailing_stop"]:
|
| 217 |
+
return {"action": "sell", "reason": f"Trailing stop triggered ({TRAILING_STOP_PCT}%)"}
|
| 218 |
+
|
| 219 |
+
# ββ MAX HOLD DAYS ββ
|
| 220 |
+
pos["day_count"] += 1
|
| 221 |
+
if pos["day_count"] >= MAX_HOLD_DAYS:
|
| 222 |
+
return {"action": "sell", "reason": f"Max hold period ({MAX_HOLD_DAYS} days)"}
|
| 223 |
+
|
| 224 |
+
return {
|
| 225 |
+
"action": "hold",
|
| 226 |
+
"reason": "Within thresholds",
|
| 227 |
+
"current_pnl": round(change_pct, 2),
|
| 228 |
+
"current_price": current_price,
|
| 229 |
+
"stop_loss": pos["stop_loss"],
|
| 230 |
+
"take_profit": pos["take_profit"],
|
| 231 |
+
"trailing_stop": pos["trailing_stop"],
|
| 232 |
+
}
|
| 233 |
+
|
| 234 |
+
|
| 235 |
+
def evaluate_trade_signal(ticker: str, current_price: float,
|
| 236 |
+
predicted_prices: list, confidence: float) -> dict:
|
| 237 |
+
"""
|
| 238 |
+
Core strategy: Decide BUY / SELL / HOLD based on LSTM prediction.
|
| 239 |
+
"""
|
| 240 |
+
state = _load_state()
|
| 241 |
+
|
| 242 |
+
# Prediction analysis
|
| 243 |
+
pred_day1 = predicted_prices[0]
|
| 244 |
+
pred_day5 = predicted_prices[-1]
|
| 245 |
+
pred_change_pct = ((pred_day5 - current_price) / current_price) * 100
|
| 246 |
+
pred_direction = "up" if pred_day5 > current_price else "down"
|
| 247 |
+
|
| 248 |
+
# Count how many predicted days are above current price
|
| 249 |
+
days_above = sum(1 for p in predicted_prices if p > current_price)
|
| 250 |
+
|
| 251 |
+
signal = {
|
| 252 |
+
"ticker": ticker,
|
| 253 |
+
"current_price": current_price,
|
| 254 |
+
"predicted_day1": round(pred_day1, 2),
|
| 255 |
+
"predicted_day5": round(pred_day5, 2),
|
| 256 |
+
"pred_change_pct": round(pred_change_pct, 2),
|
| 257 |
+
"pred_direction": pred_direction,
|
| 258 |
+
"days_above_current": days_above,
|
| 259 |
+
"confidence": confidence,
|
| 260 |
+
}
|
| 261 |
+
|
| 262 |
+
# Already holding?
|
| 263 |
+
if ticker in state["positions"]:
|
| 264 |
+
check = check_position(ticker, current_price)
|
| 265 |
+
if check["action"] == "sell":
|
| 266 |
+
result = execute_sell(ticker, current_price, check["reason"])
|
| 267 |
+
signal["action"] = "SELL"
|
| 268 |
+
signal["trade_result"] = result
|
| 269 |
+
elif pred_direction == "down" and days_above <= 1 and confidence > 40:
|
| 270 |
+
result = execute_sell(ticker, current_price, "Prediction reversal (downtrend)")
|
| 271 |
+
signal["action"] = "SELL"
|
| 272 |
+
signal["trade_result"] = result
|
| 273 |
+
else:
|
| 274 |
+
signal["action"] = "HOLD"
|
| 275 |
+
signal["position"] = check
|
| 276 |
+
else:
|
| 277 |
+
# BUY conditions: prediction is UP + enough confidence
|
| 278 |
+
if (pred_direction == "up" and days_above >= 3 and
|
| 279 |
+
confidence >= 35 and pred_change_pct > 0.5):
|
| 280 |
+
result = execute_buy(ticker, current_price, predicted_prices, confidence)
|
| 281 |
+
signal["action"] = "BUY"
|
| 282 |
+
signal["trade_result"] = result
|
| 283 |
+
else:
|
| 284 |
+
signal["action"] = "WAIT"
|
| 285 |
+
signal["reason"] = "Conditions not met for entry"
|
| 286 |
+
|
| 287 |
+
return signal
|