some changes
This commit is contained in:
commit
3568453103
45 files changed
+4557
No files matched your search
+98
@@ -0,0 +1,98 @@
|
|||||||
|
# Java
|
||||||
|
*.class
|
||||||
|
*.log
|
||||||
|
*.ctxt
|
||||||
|
.mtj.tmp/
|
||||||
|
*.jar
|
||||||
|
*.war
|
||||||
|
*.nar
|
||||||
|
*.ear
|
||||||
|
*.zip
|
||||||
|
*.tar.gz
|
||||||
|
*.rar
|
||||||
|
|
||||||
|
# Maven
|
||||||
|
target/
|
||||||
|
pom.xml.tag
|
||||||
|
pom.xml.releaseBackup
|
||||||
|
pom.xml.versionsBackup
|
||||||
|
pom.xml.next
|
||||||
|
release.properties
|
||||||
|
dependency-reduced-pom.xml
|
||||||
|
buildNumber
|
||||||
|
.mvn/timing.properties
|
||||||
|
.mvn/wrapper/maven-wrapper.properties
|
||||||
|
|
||||||
|
# Spring Boot
|
||||||
|
help.md
|
||||||
|
.mvn/
|
||||||
|
|
||||||
|
# IDEs - IntelliJ IDEA
|
||||||
|
.idea/
|
||||||
|
*.iws
|
||||||
|
*.iml
|
||||||
|
*.ipr
|
||||||
|
out/
|
||||||
|
!**/src/main/**/out/
|
||||||
|
!**/src/test/**/out/
|
||||||
|
|
||||||
|
# IDEs - Eclipse
|
||||||
|
.classpath
|
||||||
|
.project
|
||||||
|
.settings/
|
||||||
|
bin/
|
||||||
|
|
||||||
|
# IDEs - VS Code
|
||||||
|
.vscode/
|
||||||
|
*.code-workspace
|
||||||
|
|
||||||
|
# IDEs - NetBeans
|
||||||
|
nbproject/private/
|
||||||
|
build/
|
||||||
|
nbbuild/
|
||||||
|
dist/
|
||||||
|
nbdist/
|
||||||
|
.nb-gradle/
|
||||||
|
|
||||||
|
# Frontend - Node/Vue
|
||||||
|
node_modules/
|
||||||
|
frontend/node_modules/
|
||||||
|
frontend/dist/
|
||||||
|
frontend/.vite/
|
||||||
|
frontend/.DS_Store
|
||||||
|
npm-debug.log*
|
||||||
|
yarn-debug.log*
|
||||||
|
yarn-error.log*
|
||||||
|
pnpm-debug.log*
|
||||||
|
.npm/
|
||||||
|
|
||||||
|
# OS
|
||||||
|
.DS_Store
|
||||||
|
.DS_Store?
|
||||||
|
._*
|
||||||
|
.Spotlight-V100
|
||||||
|
.Trashes
|
||||||
|
ehthumbs.db
|
||||||
|
Thumbs.db
|
||||||
|
|
||||||
|
# Environment Variables
|
||||||
|
.env
|
||||||
|
.env.local
|
||||||
|
.env.development.local
|
||||||
|
.env.test.local
|
||||||
|
.env.production.local
|
||||||
|
*.env
|
||||||
|
env/
|
||||||
|
venv/
|
||||||
|
|
||||||
|
# Python (Legacy/Scripts)
|
||||||
|
__pycache__/
|
||||||
|
*.py[cod]
|
||||||
|
*$py.class
|
||||||
|
.Python
|
||||||
|
|
||||||
|
# Logs
|
||||||
|
logs/
|
||||||
|
*.log
|
||||||
|
|
||||||
|
backend/target
|
||||||
@@ -0,0 +1,189 @@
|
|||||||
|
# Stock Analyzer - Full Stack Application
|
||||||
|
|
||||||
|
A modern stock analysis application built with **Spring Boot (Java)** backend and **Vue.js** frontend.
|
||||||
|
|
||||||
|
## Features
|
||||||
|
|
||||||
|
- 📊 Real-time stock data analysis using Yahoo Finance
|
||||||
|
- 🤖 AI-powered predictions using OpenAI GPT and Anthropic Claude
|
||||||
|
- 📰 News sentiment analysis via NewsAPI
|
||||||
|
- 🌐 Web sentiment analysis via DuckDuckGo
|
||||||
|
- 📈 Technical indicators (RSI, SMA)
|
||||||
|
- 📉 Fundamental analysis (P/E ratio, Market Cap, etc.)
|
||||||
|
- 📜 Historical analysis tracking with accuracy metrics
|
||||||
|
- 🎯 Watchlist management
|
||||||
|
|
||||||
|
## Tech Stack
|
||||||
|
|
||||||
|
### Backend
|
||||||
|
- **Spring Boot 3.2.1** with Java
|
||||||
|
- **MongoDB** for data persistence
|
||||||
|
- **OkHttp** for HTTP requests
|
||||||
|
- **Jsoup** for web scraping
|
||||||
|
- **Gradle** for build management
|
||||||
|
|
||||||
|
### Frontend
|
||||||
|
- **Vue 3** with Composition API
|
||||||
|
- **TypeScript** for type safety
|
||||||
|
- **Vite** for fast development
|
||||||
|
- **Pinia** for state management
|
||||||
|
- **Axios** for API calls
|
||||||
|
- **Premium CSS** with dark theme and glassmorphism
|
||||||
|
|
||||||
|
## Prerequisites
|
||||||
|
|
||||||
|
- **Java 17+**
|
||||||
|
- **Node.js 18+** (for frontend)
|
||||||
|
- **MongoDB** (local or Docker)
|
||||||
|
- **API Keys**:
|
||||||
|
- OpenAI API Key
|
||||||
|
- Anthropic API Key
|
||||||
|
- NewsAPI Key
|
||||||
|
|
||||||
|
## Quick Start
|
||||||
|
|
||||||
|
### 1. Start MongoDB
|
||||||
|
|
||||||
|
```bash
|
||||||
|
docker run -d -p 27017:27017 --name mongodb mongo:latest
|
||||||
|
```
|
||||||
|
|
||||||
|
### 2. Configure Environment Variables
|
||||||
|
|
||||||
|
Create a `.env` file or set environment variables:
|
||||||
|
|
||||||
|
```bash
|
||||||
|
export MONGO_URI=mongodb://localhost:27017/stock_analyzer
|
||||||
|
export OPENAI_API_KEY=your_openai_key
|
||||||
|
export OPENAI_MODEL=gpt-4o
|
||||||
|
export ANTHROPIC_API_KEY=your_anthropic_key
|
||||||
|
export ANTHROPIC_MODEL=claude-sonnet-4-5
|
||||||
|
export NEWS_API_KEY=your_newsapi_key
|
||||||
|
```
|
||||||
|
|
||||||
|
### 3. Start Backend
|
||||||
|
|
||||||
|
```bash
|
||||||
|
cd backend
|
||||||
|
./gradlew bootRun
|
||||||
|
```
|
||||||
|
|
||||||
|
The backend will start on `http://localhost:8080`
|
||||||
|
|
||||||
|
### 4. Start Frontend
|
||||||
|
|
||||||
|
```bash
|
||||||
|
cd frontend
|
||||||
|
npm install
|
||||||
|
npm run dev
|
||||||
|
```
|
||||||
|
|
||||||
|
The frontend will start on `http://localhost:5173`
|
||||||
|
|
||||||
|
## API Endpoints
|
||||||
|
|
||||||
|
### Watchlist
|
||||||
|
- `GET /api/watchlist` - Get all watchlist stocks
|
||||||
|
- `POST /api/watchlist` - Add stock to watchlist
|
||||||
|
- `DELETE /api/watchlist/{isin}` - Remove stock from watchlist
|
||||||
|
|
||||||
|
### Analysis
|
||||||
|
- `POST /api/analysis/run` - Analyze all watchlist stocks
|
||||||
|
- `GET /api/analysis/history` - Get historical results
|
||||||
|
- `GET /api/analysis/history/{isin}` - Get results for specific ISIN
|
||||||
|
- `DELETE /api/analysis/history` - Delete results by date range
|
||||||
|
- `GET /api/analysis/market-context` - Get S&P 500 market context
|
||||||
|
- `GET /api/analysis/historical-price/{symbol}/{date}` - Get historical price
|
||||||
|
|
||||||
|
## Docker Deployment
|
||||||
|
|
||||||
|
### Build and Run with Docker Compose
|
||||||
|
|
||||||
|
```bash
|
||||||
|
docker-compose up --build
|
||||||
|
```
|
||||||
|
|
||||||
|
This will start:
|
||||||
|
- MongoDB on port 27017
|
||||||
|
- Backend on port 8080
|
||||||
|
- Frontend on port 80
|
||||||
|
|
||||||
|
## Development
|
||||||
|
|
||||||
|
### Backend Development
|
||||||
|
|
||||||
|
```bash
|
||||||
|
cd backend
|
||||||
|
./gradlew build
|
||||||
|
./gradlew test
|
||||||
|
```
|
||||||
|
|
||||||
|
### Frontend Development
|
||||||
|
|
||||||
|
```bash
|
||||||
|
cd frontend
|
||||||
|
npm run dev # Development server
|
||||||
|
npm run build # Production build
|
||||||
|
npm run preview # Preview production build
|
||||||
|
```
|
||||||
|
|
||||||
|
## Project Structure
|
||||||
|
|
||||||
|
```
|
||||||
|
stock-analyzer/
|
||||||
|
├── backend/ # Spring Boot backend
|
||||||
|
│ ├── src/
|
||||||
|
│ │ └── main/
|
||||||
|
│ │ ├── kotlin/
|
||||||
|
│ │ │ └── com/stockanalyzer/
|
||||||
|
│ │ │ ├── controller/
|
||||||
|
│ │ │ ├── service/
|
||||||
|
│ │ │ ├── model/
|
||||||
|
│ │ │ ├── repository/
|
||||||
|
│ │ │ └── config/
|
||||||
|
│ │ └── resources/
|
||||||
|
│ │ └── application.yml
|
||||||
|
│ └── build.gradle.kts
|
||||||
|
├── frontend/ # Vue.js frontend
|
||||||
|
│ ├── src/
|
||||||
|
│ │ ├── components/
|
||||||
|
│ │ ├── views/
|
||||||
|
│ │ ├── store/
|
||||||
|
│ │ ├── router/
|
||||||
|
│ │ ├── App.vue
|
||||||
|
│ │ └── main.ts
|
||||||
|
│ ├── package.json
|
||||||
|
│ └── vite.config.ts
|
||||||
|
└── README-FULLSTACK.md
|
||||||
|
```
|
||||||
|
|
||||||
|
## Features in Detail
|
||||||
|
|
||||||
|
### Stock Analysis
|
||||||
|
- Fetches real-time stock data from Yahoo Finance
|
||||||
|
- Calculates technical indicators (RSI, SMA)
|
||||||
|
- Retrieves fundamental data (P/E ratio, Market Cap, etc.)
|
||||||
|
- Gets analyst ratings and target prices
|
||||||
|
|
||||||
|
### AI Predictions
|
||||||
|
- Uses both OpenAI GPT and Anthropic Claude for predictions
|
||||||
|
- Predicts stock movement for the next 24 hours
|
||||||
|
- Provides probability scores and reasoning
|
||||||
|
|
||||||
|
### News & Sentiment
|
||||||
|
- Fetches recent news headlines via NewsAPI
|
||||||
|
- Scrapes web sentiment from Reddit and Yahoo Finance
|
||||||
|
- Analyzes overall market context (S&P 500)
|
||||||
|
|
||||||
|
### Historical Tracking
|
||||||
|
- Stores all analysis results in MongoDB
|
||||||
|
- Tracks prediction accuracy over time
|
||||||
|
- Allows deletion of historical data by date range
|
||||||
|
|
||||||
|
## License
|
||||||
|
|
||||||
|
MIT
|
||||||
|
|
||||||
|
## Contributing
|
||||||
|
|
||||||
|
Contributions are welcome! Please feel free to submit a Pull Request.
|
||||||
@@ -0,0 +1,99 @@
|
|||||||
|
# Deploying Stock Analyzer to TrueNAS Scale
|
||||||
|
|
||||||
|
This guide explains how to deploy the Stock Analyzer application to TrueNAS Scale using the "Custom App" feature.
|
||||||
|
|
||||||
|
## Prerequisites
|
||||||
|
|
||||||
|
1. **TrueNAS Scale** installed and running.
|
||||||
|
2. **Docker Hub Account**: You need an account to host your container images.
|
||||||
|
3. **Terminal Access**: Access to a terminal where you have the project code and Docker installed (to run the build script).
|
||||||
|
|
||||||
|
## Step 1: Build and Push Images
|
||||||
|
|
||||||
|
Before deploying, you need to build the Docker images and push them to Docker Hub so TrueNAS can download them.
|
||||||
|
|
||||||
|
1. Open your terminal in the project root.
|
||||||
|
2. Make the build script executable:
|
||||||
|
```bash
|
||||||
|
chmod +x build-and-push.sh
|
||||||
|
```
|
||||||
|
3. Run the script with your Docker Hub username and optional version tag:
|
||||||
|
```bash
|
||||||
|
./build-and-push.sh your_dockerhub_username [version]
|
||||||
|
```
|
||||||
|
*Replace `your_dockerhub_username` with your actual Docker Hub username. If version is omitted, it defaults to `latest`.*
|
||||||
|
|
||||||
|
Wait for the script to finish. It will build both backend and frontend images and push them to your account.
|
||||||
|
|
||||||
|
## Step 2: Deploy MongoDB
|
||||||
|
|
||||||
|
The application requires a MongoDB database.
|
||||||
|
|
||||||
|
1. Log in to your TrueNAS Scale web interface.
|
||||||
|
2. Go to **Apps**.
|
||||||
|
3. Click **Discover Apps**.
|
||||||
|
4. Search for **MongoDB** (or use the "Custom App" button if you prefer a raw container).
|
||||||
|
* **Recommended**: Use the official TrueCharts or iXsystems MongoDB chart if available for easier management.
|
||||||
|
* **Alternative (Custom App)**:
|
||||||
|
* Application Name: `mongodb`
|
||||||
|
* Image repository: `mongo`
|
||||||
|
* Image Tag: `latest`
|
||||||
|
* Port Forwarding: Container Port `27017` -> Node Port `27017` (or any available port).
|
||||||
|
* Storage: Configure a Host Path or PVC to `/data/db` to persist data.
|
||||||
|
|
||||||
|
## Step 3: Deploy Backend
|
||||||
|
|
||||||
|
1. Go to **Apps** -> **Discover Apps** -> **Custom App**.
|
||||||
|
2. **Application Name**: `stock-analyzer-backend`
|
||||||
|
3. **Container Image**:
|
||||||
|
* Repository: `your_dockerhub_username/stock-analyzer-backend`
|
||||||
|
* Tag: `latest`
|
||||||
|
4. **Port Forwarding**:
|
||||||
|
* Container Port: `8080`
|
||||||
|
* Node Port: `8080` (or another available port, e.g., `9000`. If you change this, remember it for the frontend config).
|
||||||
|
5. **Environment Variables**:
|
||||||
|
Add the following name/value pairs:
|
||||||
|
* `MONGO_URI`: `mongodb://<truenas-ip>:27017/stock_analyzer` (Replace `<truenas-ip>` with your TrueNAS IP address).
|
||||||
|
* `OPENAI_API_KEY`: Your OpenAI API Key.
|
||||||
|
* `OPENAI_MODEL`: `gpt-4o` (or your preferred model).
|
||||||
|
* `ANTHROPIC_API_KEY`: Your Anthropic API Key.
|
||||||
|
* `ANTHROPIC_MODEL`: `claude-3-5-sonnet-20240620` (or your preferred model).
|
||||||
|
* `NEWS_API_KEY`: Your NewsAPI Key.
|
||||||
|
6. **Save/Install**.
|
||||||
|
|
||||||
|
## Step 4: Deploy Frontend
|
||||||
|
|
||||||
|
1. Go to **Apps** -> **Discover Apps** -> **Custom App**.
|
||||||
|
2. **Application Name**: `stock-analyzer-frontend`
|
||||||
|
3. **Container Image**:
|
||||||
|
* Repository: `your_dockerhub_username/stock-analyzer-frontend`
|
||||||
|
* Tag: `latest`
|
||||||
|
4. **Port Forwarding**:
|
||||||
|
* Container Port: `80`
|
||||||
|
* Node Port: `3000` (or any available port you want to access the app from).
|
||||||
|
5. **Networking**:
|
||||||
|
* The frontend is an SPA (Single Page Application). It runs in the user's browser.
|
||||||
|
* **Important**: The frontend needs to know where the backend is.
|
||||||
|
* By default, the nginx config in the frontend container proxies `/api` calls to `http://backend:8080`.
|
||||||
|
* **TrueNAS Specific**: Since Kubernetes/Docker networking in TrueNAS can be complex for simple service discovery without a proper chart, you might need to adjust the Nginx configuration or use a reverse proxy (like Traefik) if the internal DNS `backend` doesn't resolve.
|
||||||
|
* **Simple Fix**: If the default proxying doesn't work, you might need to expose the backend directly and update the frontend code to point to the full URL, OR ensure both apps are in the same namespace/network where `backend` resolves.
|
||||||
|
|
||||||
|
*For a standard "Custom App" deployment where containers can't easily talk via DNS names like `backend`:*
|
||||||
|
You may need to update the `nginx.conf` in the source code to point to your TrueNAS IP and the Backend Node Port, then rebuild/push.
|
||||||
|
|
||||||
|
*Edit `frontend/nginx.conf` before building:*
|
||||||
|
```nginx
|
||||||
|
location /api {
|
||||||
|
proxy_pass http://<YOUR_TRUENAS_IP>:<BACKEND_NODE_PORT>;
|
||||||
|
...
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
6. **Save/Install**.
|
||||||
|
|
||||||
|
## Step 5: Access the Application
|
||||||
|
|
||||||
|
Open your browser and navigate to:
|
||||||
|
`http://<YOUR_TRUENAS_IP>:<FRONTEND_NODE_PORT>`
|
||||||
|
|
||||||
|
Example: `http://192.168.1.100:3000`
|
||||||
@@ -0,0 +1,15 @@
|
|||||||
|
# Build stage
|
||||||
|
FROM maven:3.9-eclipse-temurin-21 AS build
|
||||||
|
WORKDIR /app
|
||||||
|
COPY pom.xml .
|
||||||
|
COPY src ./src
|
||||||
|
RUN mvn clean package -DskipTests
|
||||||
|
|
||||||
|
# Run stage
|
||||||
|
FROM eclipse-temurin:21-jre-alpine
|
||||||
|
WORKDIR /app
|
||||||
|
COPY --from=build /app/target/*.jar app.jar
|
||||||
|
|
||||||
|
EXPOSE 8080
|
||||||
|
|
||||||
|
ENTRYPOINT ["java", "-jar", "app.jar"]
|
||||||
+101
@@ -0,0 +1,101 @@
|
|||||||
|
<?xml version="1.0" encoding="UTF-8"?>
|
||||||
|
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
|
||||||
|
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd">
|
||||||
|
<modelVersion>4.0.0</modelVersion>
|
||||||
|
<parent>
|
||||||
|
<groupId>org.springframework.boot</groupId>
|
||||||
|
<artifactId>spring-boot-starter-parent</artifactId>
|
||||||
|
<version>3.4.1</version>
|
||||||
|
<relativePath/> <!-- lookup parent from repository -->
|
||||||
|
</parent>
|
||||||
|
<groupId>com.stockanalyzer</groupId>
|
||||||
|
<artifactId>backend</artifactId>
|
||||||
|
<version>0.0.1-SNAPSHOT</version>
|
||||||
|
<name>stock-analyzer-backend</name>
|
||||||
|
<description>Stock Analyzer Backend</description>
|
||||||
|
<properties>
|
||||||
|
<java.version>21</java.version>
|
||||||
|
<lombok.version>1.18.38</lombok.version>
|
||||||
|
<maven-compiler-plugin.version>3.13.0</maven-compiler-plugin.version>
|
||||||
|
</properties>
|
||||||
|
<dependencies>
|
||||||
|
<dependency>
|
||||||
|
<groupId>org.springframework.boot</groupId>
|
||||||
|
<artifactId>spring-boot-starter-web</artifactId>
|
||||||
|
</dependency>
|
||||||
|
<dependency>
|
||||||
|
<groupId>org.springframework.boot</groupId>
|
||||||
|
<artifactId>spring-boot-starter-data-mongodb</artifactId>
|
||||||
|
</dependency>
|
||||||
|
<dependency>
|
||||||
|
<groupId>org.springframework.boot</groupId>
|
||||||
|
<artifactId>spring-boot-starter-actuator</artifactId>
|
||||||
|
</dependency>
|
||||||
|
|
||||||
|
<dependency>
|
||||||
|
<groupId>com.fasterxml.jackson.core</groupId>
|
||||||
|
<artifactId>jackson-databind</artifactId>
|
||||||
|
</dependency>
|
||||||
|
<dependency>
|
||||||
|
<groupId>com.fasterxml.jackson.datatype</groupId>
|
||||||
|
<artifactId>jackson-datatype-jsr310</artifactId>
|
||||||
|
</dependency>
|
||||||
|
|
||||||
|
<dependency>
|
||||||
|
<groupId>com.squareup.okhttp3</groupId>
|
||||||
|
<artifactId>okhttp</artifactId>
|
||||||
|
<version>4.12.0</version>
|
||||||
|
</dependency>
|
||||||
|
|
||||||
|
<dependency>
|
||||||
|
<groupId>org.jsoup</groupId>
|
||||||
|
<artifactId>jsoup</artifactId>
|
||||||
|
<version>1.17.2</version>
|
||||||
|
</dependency>
|
||||||
|
|
||||||
|
<dependency>
|
||||||
|
<groupId>org.projectlombok</groupId>
|
||||||
|
<artifactId>lombok</artifactId>
|
||||||
|
<optional>true</optional>
|
||||||
|
</dependency>
|
||||||
|
<dependency>
|
||||||
|
<groupId>org.springframework.boot</groupId>
|
||||||
|
<artifactId>spring-boot-starter-test</artifactId>
|
||||||
|
<scope>test</scope>
|
||||||
|
</dependency>
|
||||||
|
</dependencies>
|
||||||
|
|
||||||
|
<build>
|
||||||
|
<plugins>
|
||||||
|
<plugin>
|
||||||
|
<groupId>org.apache.maven.plugins</groupId>
|
||||||
|
<artifactId>maven-compiler-plugin</artifactId>
|
||||||
|
<version>${maven-compiler-plugin.version}</version>
|
||||||
|
<configuration>
|
||||||
|
<release>${java.version}</release>
|
||||||
|
<annotationProcessorPaths>
|
||||||
|
<path>
|
||||||
|
<groupId>org.projectlombok</groupId>
|
||||||
|
<artifactId>lombok</artifactId>
|
||||||
|
<version>${lombok.version}</version>
|
||||||
|
</path>
|
||||||
|
</annotationProcessorPaths>
|
||||||
|
</configuration>
|
||||||
|
</plugin>
|
||||||
|
<plugin>
|
||||||
|
<groupId>org.springframework.boot</groupId>
|
||||||
|
<artifactId>spring-boot-maven-plugin</artifactId>
|
||||||
|
<configuration>
|
||||||
|
<mainClass>com.stockanalyzer.StockAnalyzerApplication</mainClass>
|
||||||
|
<excludes>
|
||||||
|
<exclude>
|
||||||
|
<groupId>org.projectlombok</groupId>
|
||||||
|
<artifactId>lombok</artifactId>
|
||||||
|
</exclude>
|
||||||
|
</excludes>
|
||||||
|
</configuration>
|
||||||
|
</plugin>
|
||||||
|
</plugins>
|
||||||
|
</build>
|
||||||
|
|
||||||
|
</project>
|
||||||
@@ -0,0 +1,14 @@
|
|||||||
|
package com.stockanalyzer;
|
||||||
|
|
||||||
|
import org.springframework.boot.SpringApplication;
|
||||||
|
import org.springframework.boot.autoconfigure.SpringBootApplication;
|
||||||
|
import org.springframework.scheduling.annotation.EnableScheduling;
|
||||||
|
|
||||||
|
@SpringBootApplication
|
||||||
|
@EnableScheduling
|
||||||
|
public class StockAnalyzerApplication {
|
||||||
|
|
||||||
|
public static void main(String[] args) {
|
||||||
|
SpringApplication.run(StockAnalyzerApplication.class, args);
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,21 @@
|
|||||||
|
package com.stockanalyzer.config;
|
||||||
|
|
||||||
|
import org.springframework.context.annotation.Configuration;
|
||||||
|
import org.springframework.web.servlet.config.annotation.CorsRegistry;
|
||||||
|
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;
|
||||||
|
|
||||||
|
@Configuration
|
||||||
|
public class CorsConfig implements WebMvcConfigurer {
|
||||||
|
|
||||||
|
@org.springframework.beans.factory.annotation.Value("${cors.allowed-origins:http://localhost:5173}")
|
||||||
|
private String allowedOrigins;
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public void addCorsMappings(CorsRegistry registry) {
|
||||||
|
registry.addMapping("/api/**")
|
||||||
|
.allowedOrigins(allowedOrigins.split(","))
|
||||||
|
.allowedMethods("GET", "POST", "PUT", "DELETE", "OPTIONS")
|
||||||
|
.allowedHeaders("*")
|
||||||
|
.allowCredentials(true);
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,171 @@
|
|||||||
|
package com.stockanalyzer.controller;
|
||||||
|
|
||||||
|
import com.stockanalyzer.model.AnalysisJob;
|
||||||
|
import com.stockanalyzer.model.AnalysisResult;
|
||||||
|
import com.stockanalyzer.model.Stock;
|
||||||
|
import com.stockanalyzer.repository.AnalysisResultRepository;
|
||||||
|
import com.stockanalyzer.repository.StockRepository;
|
||||||
|
import com.stockanalyzer.service.AnalysisService;
|
||||||
|
import com.stockanalyzer.service.JobService;
|
||||||
|
import com.stockanalyzer.service.StockDataService;
|
||||||
|
import com.stockanalyzer.service.StockDataService.MarketContextData;
|
||||||
|
import org.springframework.http.ResponseEntity;
|
||||||
|
import org.springframework.web.bind.annotation.*;
|
||||||
|
|
||||||
|
import java.util.ArrayList;
|
||||||
|
import java.util.List;
|
||||||
|
import java.util.Map;
|
||||||
|
|
||||||
|
@RestController
|
||||||
|
@RequestMapping("/api/analysis")
|
||||||
|
public class AnalysisController {
|
||||||
|
|
||||||
|
private final AnalysisService analysisService;
|
||||||
|
private final AnalysisResultRepository analysisResultRepository;
|
||||||
|
private final StockRepository stockRepository;
|
||||||
|
private final StockDataService stockDataService;
|
||||||
|
private final JobService jobService;
|
||||||
|
|
||||||
|
public AnalysisController(
|
||||||
|
AnalysisService analysisService,
|
||||||
|
AnalysisResultRepository analysisResultRepository,
|
||||||
|
StockRepository stockRepository,
|
||||||
|
StockDataService stockDataService,
|
||||||
|
JobService jobService) {
|
||||||
|
this.analysisService = analysisService;
|
||||||
|
this.analysisResultRepository = analysisResultRepository;
|
||||||
|
this.stockRepository = stockRepository;
|
||||||
|
this.stockDataService = stockDataService;
|
||||||
|
this.jobService = jobService;
|
||||||
|
}
|
||||||
|
|
||||||
|
public record AnalysisProgress(
|
||||||
|
String isin,
|
||||||
|
String status,
|
||||||
|
AnalysisResult result,
|
||||||
|
String error) {
|
||||||
|
}
|
||||||
|
|
||||||
|
public record DeleteByDateRangeRequest(
|
||||||
|
String startDate,
|
||||||
|
String endDate) {
|
||||||
|
}
|
||||||
|
|
||||||
|
@PostMapping("/run")
|
||||||
|
public List<AnalysisJob> runAnalysis() {
|
||||||
|
List<Stock> watchlist = stockRepository.findAll();
|
||||||
|
List<AnalysisJob> jobs = new ArrayList<>();
|
||||||
|
|
||||||
|
// Clear old jobs optionally or just append new ones.
|
||||||
|
// For simplicity, we'll keep history but maybe UI only cares about recent ones.
|
||||||
|
// Let's clear strictly pending/processing ones? No, safer to just create new ones.
|
||||||
|
|
||||||
|
// Actually, to avoid queueing up duplicates if user clicks twice,
|
||||||
|
// we might want to check if there is already a PENDING job for this ISIN.
|
||||||
|
// But for now, simple implementation: just enqueue.
|
||||||
|
|
||||||
|
for (Stock stock : watchlist) {
|
||||||
|
if (!jobService.hasPendingOrProcessingJob(stock.getIsin())) {
|
||||||
|
AnalysisJob job = jobService.createJob(stock.getIsin(), stock.getSymbol());
|
||||||
|
jobs.add(job);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// Return all current jobs (including existing ones) so UI knows status
|
||||||
|
List<AnalysisJob> allJobs = jobService.getAllJobs();
|
||||||
|
// Filter to return only jobs relevant to the watchlist if needed,
|
||||||
|
// but returning all jobs is fine for the status view.
|
||||||
|
return allJobs;
|
||||||
|
}
|
||||||
|
|
||||||
|
@PostMapping("/run/{isin}")
|
||||||
|
public List<AnalysisJob> runSingleAnalysis(@PathVariable String isin) {
|
||||||
|
stockRepository.findByIsin(isin).ifPresent(stock -> {
|
||||||
|
if (!jobService.hasPendingOrProcessingJob(stock.getIsin())) {
|
||||||
|
jobService.createJob(stock.getIsin(), stock.getSymbol());
|
||||||
|
}
|
||||||
|
});
|
||||||
|
return jobService.getAllJobs();
|
||||||
|
}
|
||||||
|
|
||||||
|
@GetMapping("/jobs")
|
||||||
|
public List<AnalysisJob> getJobStatus() {
|
||||||
|
return jobService.getAllJobs();
|
||||||
|
}
|
||||||
|
|
||||||
|
@PostMapping("/stop")
|
||||||
|
public ResponseEntity<Void> stopAnalysis() {
|
||||||
|
jobService.cancelAllJobs();
|
||||||
|
return ResponseEntity.ok().build();
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
@GetMapping("/history")
|
||||||
|
public ResponseEntity<List<AnalysisResult>> getHistory() {
|
||||||
|
List<AnalysisResult> results = analysisResultRepository.findAll().stream()
|
||||||
|
.sorted((r1, r2) -> r2.getAnalyzedAt().compareTo(r1.getAnalyzedAt()))
|
||||||
|
.limit(50)
|
||||||
|
.toList();
|
||||||
|
return ResponseEntity.ok(results);
|
||||||
|
}
|
||||||
|
|
||||||
|
@GetMapping("/history/{isin}")
|
||||||
|
public ResponseEntity<List<AnalysisResult>> getHistoryByIsin(@PathVariable String isin) {
|
||||||
|
List<AnalysisResult> results = analysisResultRepository.findByIsinOrderByAnalyzedAtDesc(isin).stream()
|
||||||
|
.limit(30)
|
||||||
|
.toList();
|
||||||
|
return ResponseEntity.ok(results);
|
||||||
|
}
|
||||||
|
|
||||||
|
@DeleteMapping("/history")
|
||||||
|
public ResponseEntity<Map<String, Object>> deleteByDateRange(@RequestBody DeleteByDateRangeRequest request) {
|
||||||
|
try {
|
||||||
|
long count = analysisResultRepository.deleteByDateBetween(request.startDate(), request.endDate());
|
||||||
|
return ResponseEntity.ok(Map.of("deleted", count));
|
||||||
|
} catch (Exception e) {
|
||||||
|
return ResponseEntity.badRequest()
|
||||||
|
.body(Map.of("error", e.getMessage() != null ? e.getMessage() : "Unknown error"));
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
@GetMapping("/market-context")
|
||||||
|
public ResponseEntity<Map<String, Object>> getMarketContext() {
|
||||||
|
MarketContextData context = stockDataService.getMarketContext();
|
||||||
|
if (context != null) {
|
||||||
|
return ResponseEntity.ok(
|
||||||
|
Map.of(
|
||||||
|
"symbol", context.symbol(),
|
||||||
|
"changePercent", context.changePercent(),
|
||||||
|
"price", context.price()));
|
||||||
|
} else {
|
||||||
|
return ResponseEntity.ok(Map.of("error", "Unable to fetch market context"));
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
@GetMapping("/historical-price/{symbol}/{date}")
|
||||||
|
public ResponseEntity<Map<String, Object>> getHistoricalPrice(
|
||||||
|
@PathVariable String symbol,
|
||||||
|
@PathVariable String date) {
|
||||||
|
Double price = stockDataService.getHistoricalPrice(symbol, date);
|
||||||
|
if (price != null) {
|
||||||
|
return ResponseEntity.ok(Map.of("price", price));
|
||||||
|
} else {
|
||||||
|
return ResponseEntity.ok(Map.of("error", "Price not available"));
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
@PostMapping("/history/{id}/refresh-price")
|
||||||
|
public ResponseEntity<AnalysisResult> refreshPrice(@PathVariable String id) {
|
||||||
|
return analysisResultRepository.findById(id)
|
||||||
|
.map(result -> {
|
||||||
|
Double price = stockDataService.getHistoricalPrice(result.getSymbol(), result.getTargetDate());
|
||||||
|
if (price != null) {
|
||||||
|
result.setRealPrice(price);
|
||||||
|
return ResponseEntity.ok(analysisResultRepository.save(result));
|
||||||
|
}
|
||||||
|
return ResponseEntity.ok(result);
|
||||||
|
})
|
||||||
|
.orElse(ResponseEntity.notFound().build());
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,97 @@
|
|||||||
|
package com.stockanalyzer.controller;
|
||||||
|
|
||||||
|
import com.stockanalyzer.model.Stock;
|
||||||
|
import com.stockanalyzer.repository.StockRepository;
|
||||||
|
import com.stockanalyzer.service.StockDataService;
|
||||||
|
import org.springframework.http.HttpStatus;
|
||||||
|
import org.springframework.http.ResponseEntity;
|
||||||
|
import org.springframework.web.bind.annotation.*;
|
||||||
|
|
||||||
|
import java.util.List;
|
||||||
|
import java.util.Map;
|
||||||
|
import java.util.stream.Collectors;
|
||||||
|
|
||||||
|
@RestController
|
||||||
|
@RequestMapping("/api/watchlist")
|
||||||
|
public class WatchlistController {
|
||||||
|
|
||||||
|
private final StockRepository stockRepository;
|
||||||
|
private final StockDataService stockDataService;
|
||||||
|
|
||||||
|
public WatchlistController(StockRepository stockRepository, StockDataService stockDataService) {
|
||||||
|
this.stockRepository = stockRepository;
|
||||||
|
this.stockDataService = stockDataService;
|
||||||
|
}
|
||||||
|
|
||||||
|
public record AddStockRequest(String isin) {
|
||||||
|
}
|
||||||
|
|
||||||
|
public record StockResponse(
|
||||||
|
String isin,
|
||||||
|
String symbol,
|
||||||
|
String name,
|
||||||
|
String addedAt) {
|
||||||
|
}
|
||||||
|
|
||||||
|
@GetMapping
|
||||||
|
public List<StockResponse> getAllStocks() {
|
||||||
|
return stockRepository.findAll().stream()
|
||||||
|
.sorted((s1, s2) -> s2.getAddedAt().compareTo(s1.getAddedAt()))
|
||||||
|
.map(stock -> new StockResponse(
|
||||||
|
stock.getIsin(),
|
||||||
|
stock.getSymbol(),
|
||||||
|
stock.getName(),
|
||||||
|
stock.getAddedAt().toString()))
|
||||||
|
.collect(Collectors.toList());
|
||||||
|
}
|
||||||
|
|
||||||
|
@PostMapping
|
||||||
|
public ResponseEntity<?> addStock(@RequestBody AddStockRequest request) {
|
||||||
|
String isin = request.isin() != null ? request.isin().trim().toUpperCase() : "";
|
||||||
|
|
||||||
|
if (isin.isBlank()) {
|
||||||
|
return ResponseEntity.badRequest().body(Map.of("error", "ISIN cannot be empty"));
|
||||||
|
}
|
||||||
|
|
||||||
|
if (stockRepository.existsByIsin(isin)) {
|
||||||
|
return ResponseEntity.status(HttpStatus.CONFLICT)
|
||||||
|
.body(Map.of("error", "ISIN already exists in watchlist"));
|
||||||
|
}
|
||||||
|
|
||||||
|
try {
|
||||||
|
// Resolve ISIN to Symbol
|
||||||
|
String symbol = stockDataService.getTickerFromIsin(isin);
|
||||||
|
|
||||||
|
// For now, use symbol as name (could fetch from Yahoo Finance if needed)
|
||||||
|
String name = symbol;
|
||||||
|
|
||||||
|
Stock stock = Stock.builder()
|
||||||
|
.isin(isin)
|
||||||
|
.symbol(symbol)
|
||||||
|
.name(name)
|
||||||
|
.build();
|
||||||
|
|
||||||
|
Stock saved = stockRepository.save(stock);
|
||||||
|
|
||||||
|
return ResponseEntity.status(HttpStatus.CREATED).body(
|
||||||
|
new StockResponse(
|
||||||
|
saved.getIsin(),
|
||||||
|
saved.getSymbol(),
|
||||||
|
saved.getName(),
|
||||||
|
saved.getAddedAt().toString()));
|
||||||
|
} catch (Exception e) {
|
||||||
|
return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR)
|
||||||
|
.body(Map.of("error", "Error adding stock: " + e.getMessage()));
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
@DeleteMapping("/{isin}")
|
||||||
|
public ResponseEntity<?> deleteStock(@PathVariable String isin) {
|
||||||
|
if (stockRepository.existsByIsin(isin)) {
|
||||||
|
stockRepository.deleteByIsin(isin);
|
||||||
|
return ResponseEntity.noContent().build();
|
||||||
|
} else {
|
||||||
|
return ResponseEntity.notFound().build();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,53 @@
|
|||||||
|
package com.stockanalyzer.model;
|
||||||
|
|
||||||
|
import org.springframework.data.annotation.Id;
|
||||||
|
import org.springframework.data.mongodb.core.mapping.Document;
|
||||||
|
import java.time.LocalDateTime;
|
||||||
|
|
||||||
|
@Document(collection = "analysis_jobs")
|
||||||
|
public class AnalysisJob {
|
||||||
|
@Id
|
||||||
|
private String id;
|
||||||
|
private String isin;
|
||||||
|
private String symbol;
|
||||||
|
private JobStatus status;
|
||||||
|
private String error;
|
||||||
|
private LocalDateTime createdAt;
|
||||||
|
private LocalDateTime startedAt;
|
||||||
|
private LocalDateTime completedAt;
|
||||||
|
|
||||||
|
public enum JobStatus {
|
||||||
|
PENDING,
|
||||||
|
PROCESSING,
|
||||||
|
COMPLETED,
|
||||||
|
FAILED,
|
||||||
|
CANCELLED
|
||||||
|
}
|
||||||
|
|
||||||
|
public AnalysisJob() {}
|
||||||
|
|
||||||
|
public AnalysisJob(String isin, String symbol) {
|
||||||
|
this.isin = isin;
|
||||||
|
this.symbol = symbol;
|
||||||
|
this.status = JobStatus.PENDING;
|
||||||
|
this.createdAt = LocalDateTime.now();
|
||||||
|
}
|
||||||
|
|
||||||
|
// Getters and Setters
|
||||||
|
public String getId() { return id; }
|
||||||
|
public void setId(String id) { this.id = id; }
|
||||||
|
public String getIsin() { return isin; }
|
||||||
|
public void setIsin(String isin) { this.isin = isin; }
|
||||||
|
public String getSymbol() { return symbol; }
|
||||||
|
public void setSymbol(String symbol) { this.symbol = symbol; }
|
||||||
|
public JobStatus getStatus() { return status; }
|
||||||
|
public void setStatus(JobStatus status) { this.status = status; }
|
||||||
|
public String getError() { return error; }
|
||||||
|
public void setError(String error) { this.error = error; }
|
||||||
|
public LocalDateTime getCreatedAt() { return createdAt; }
|
||||||
|
public void setCreatedAt(LocalDateTime createdAt) { this.createdAt = createdAt; }
|
||||||
|
public LocalDateTime getStartedAt() { return startedAt; }
|
||||||
|
public void setStartedAt(LocalDateTime startedAt) { this.startedAt = startedAt; }
|
||||||
|
public LocalDateTime getCompletedAt() { return completedAt; }
|
||||||
|
public void setCompletedAt(LocalDateTime completedAt) { this.completedAt = completedAt; }
|
||||||
|
}
|
||||||
@@ -0,0 +1,66 @@
|
|||||||
|
package com.stockanalyzer.model;
|
||||||
|
|
||||||
|
import lombok.AllArgsConstructor;
|
||||||
|
import lombok.Builder;
|
||||||
|
import lombok.Data;
|
||||||
|
import lombok.NoArgsConstructor;
|
||||||
|
import org.springframework.data.annotation.Id;
|
||||||
|
import org.springframework.data.mongodb.core.mapping.Document;
|
||||||
|
|
||||||
|
import java.time.Instant;
|
||||||
|
import java.util.List;
|
||||||
|
|
||||||
|
@Document(collection = "results")
|
||||||
|
@Data
|
||||||
|
@NoArgsConstructor
|
||||||
|
@AllArgsConstructor
|
||||||
|
@Builder
|
||||||
|
public class AnalysisResult {
|
||||||
|
@Id
|
||||||
|
private String id;
|
||||||
|
private String isin;
|
||||||
|
private String symbol;
|
||||||
|
private Double price;
|
||||||
|
private Double realPrice;
|
||||||
|
private Double changePercent;
|
||||||
|
private Fundamentals fundamentals;
|
||||||
|
private Technicals technicals;
|
||||||
|
private MarketContext marketContext;
|
||||||
|
private List<String> newsHeadlines;
|
||||||
|
private List<String> socialPosts;
|
||||||
|
private LLMAnalysis llmAnalysisOpenai;
|
||||||
|
private LLMAnalysis llmAnalysisAnthropic;
|
||||||
|
|
||||||
|
@Builder.Default
|
||||||
|
private Instant analyzedAt = Instant.now();
|
||||||
|
|
||||||
|
private String date;
|
||||||
|
private String targetDate;
|
||||||
|
|
||||||
|
public record Fundamentals(
|
||||||
|
String peRatio,
|
||||||
|
String marketCap,
|
||||||
|
String high52w,
|
||||||
|
String low52w,
|
||||||
|
String targetMeanPrice,
|
||||||
|
String recommendationKey) {
|
||||||
|
}
|
||||||
|
|
||||||
|
public record Technicals(
|
||||||
|
String sma20,
|
||||||
|
String rsi) {
|
||||||
|
}
|
||||||
|
|
||||||
|
public record MarketContext(
|
||||||
|
String symbol,
|
||||||
|
Double changePercent,
|
||||||
|
Double price) {
|
||||||
|
}
|
||||||
|
|
||||||
|
public record LLMAnalysis(
|
||||||
|
String prediction,
|
||||||
|
int probability,
|
||||||
|
String reasoning,
|
||||||
|
String error) {
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,26 @@
|
|||||||
|
package com.stockanalyzer.model;
|
||||||
|
|
||||||
|
import lombok.AllArgsConstructor;
|
||||||
|
import lombok.Builder;
|
||||||
|
import lombok.Data;
|
||||||
|
import lombok.NoArgsConstructor;
|
||||||
|
import org.springframework.data.annotation.Id;
|
||||||
|
import org.springframework.data.mongodb.core.mapping.Document;
|
||||||
|
|
||||||
|
import java.time.Instant;
|
||||||
|
|
||||||
|
@Document(collection = "stocks")
|
||||||
|
@Data
|
||||||
|
@NoArgsConstructor
|
||||||
|
@AllArgsConstructor
|
||||||
|
@Builder
|
||||||
|
public class Stock {
|
||||||
|
@Id
|
||||||
|
private String id;
|
||||||
|
private String isin;
|
||||||
|
private String symbol;
|
||||||
|
private String name;
|
||||||
|
|
||||||
|
@Builder.Default
|
||||||
|
private Instant addedAt = Instant.now();
|
||||||
|
}
|
||||||
@@ -0,0 +1,10 @@
|
|||||||
|
package com.stockanalyzer.repository;
|
||||||
|
|
||||||
|
import com.stockanalyzer.model.AnalysisJob;
|
||||||
|
import org.springframework.data.mongodb.repository.MongoRepository;
|
||||||
|
import java.util.List;
|
||||||
|
|
||||||
|
public interface AnalysisJobRepository extends MongoRepository<AnalysisJob, String> {
|
||||||
|
List<AnalysisJob> findByStatus(AnalysisJob.JobStatus status);
|
||||||
|
boolean existsByIsinAndStatus(String isin, AnalysisJob.JobStatus status);
|
||||||
|
}
|
||||||
@@ -0,0 +1,22 @@
|
|||||||
|
package com.stockanalyzer.repository;
|
||||||
|
|
||||||
|
import com.stockanalyzer.model.AnalysisResult;
|
||||||
|
import org.springframework.data.mongodb.repository.MongoRepository;
|
||||||
|
import org.springframework.data.mongodb.repository.Query;
|
||||||
|
import org.springframework.stereotype.Repository;
|
||||||
|
|
||||||
|
import java.util.List;
|
||||||
|
|
||||||
|
@Repository
|
||||||
|
public interface AnalysisResultRepository extends MongoRepository<AnalysisResult, String> {
|
||||||
|
List<AnalysisResult> findByIsinOrderByAnalyzedAtDesc(String isin);
|
||||||
|
|
||||||
|
@Query("{ 'date': { '$gte': ?0, '$lte': ?1 } }")
|
||||||
|
List<AnalysisResult> findByDateBetween(String startDate, String endDate);
|
||||||
|
|
||||||
|
List<AnalysisResult> findByRealPriceIsNullAndTargetDateLessThan(String date);
|
||||||
|
|
||||||
|
List<AnalysisResult> findByIsinAndRealPriceIsNullAndTargetDateLessThan(String isin, String date);
|
||||||
|
|
||||||
|
long deleteByDateBetween(String startDate, String endDate);
|
||||||
|
}
|
||||||
@@ -0,0 +1,16 @@
|
|||||||
|
package com.stockanalyzer.repository;
|
||||||
|
|
||||||
|
import com.stockanalyzer.model.Stock;
|
||||||
|
import org.springframework.data.mongodb.repository.MongoRepository;
|
||||||
|
import org.springframework.stereotype.Repository;
|
||||||
|
|
||||||
|
import java.util.Optional;
|
||||||
|
|
||||||
|
@Repository
|
||||||
|
public interface StockRepository extends MongoRepository<Stock, String> {
|
||||||
|
Optional<Stock> findByIsin(String isin);
|
||||||
|
|
||||||
|
boolean existsByIsin(String isin);
|
||||||
|
|
||||||
|
void deleteByIsin(String isin);
|
||||||
|
}
|
||||||
@@ -0,0 +1,206 @@
|
|||||||
|
package com.stockanalyzer.service;
|
||||||
|
|
||||||
|
import com.stockanalyzer.model.AnalysisResult;
|
||||||
|
import com.stockanalyzer.model.AnalysisResult.Fundamentals;
|
||||||
|
import com.stockanalyzer.model.AnalysisResult.LLMAnalysis;
|
||||||
|
import com.stockanalyzer.model.AnalysisResult.MarketContext;
|
||||||
|
import com.stockanalyzer.model.AnalysisResult.Technicals;
|
||||||
|
import com.stockanalyzer.repository.AnalysisResultRepository;
|
||||||
|
import com.stockanalyzer.service.StockDataService.MarketContextData;
|
||||||
|
import com.stockanalyzer.service.StockDataService.StockData;
|
||||||
|
import org.springframework.scheduling.annotation.Scheduled;
|
||||||
|
import org.springframework.stereotype.Service;
|
||||||
|
|
||||||
|
import java.time.DayOfWeek;
|
||||||
|
import java.time.Instant;
|
||||||
|
import java.time.LocalDate;
|
||||||
|
import java.time.ZoneOffset;
|
||||||
|
import java.time.format.DateTimeFormatter;
|
||||||
|
import java.util.HashMap;
|
||||||
|
import java.util.List;
|
||||||
|
import java.util.Map;
|
||||||
|
import java.util.Optional;
|
||||||
|
|
||||||
|
@Service
|
||||||
|
public class AnalysisService {
|
||||||
|
|
||||||
|
private final StockDataService stockDataService;
|
||||||
|
private final NewsService newsService;
|
||||||
|
private final SentimentService sentimentService;
|
||||||
|
private final LLMService llmService;
|
||||||
|
private final AnalysisResultRepository analysisResultRepository;
|
||||||
|
|
||||||
|
public AnalysisService(
|
||||||
|
StockDataService stockDataService,
|
||||||
|
NewsService newsService,
|
||||||
|
SentimentService sentimentService,
|
||||||
|
LLMService llmService,
|
||||||
|
AnalysisResultRepository analysisResultRepository) {
|
||||||
|
this.stockDataService = stockDataService;
|
||||||
|
this.newsService = newsService;
|
||||||
|
this.sentimentService = sentimentService;
|
||||||
|
this.llmService = llmService;
|
||||||
|
this.analysisResultRepository = analysisResultRepository;
|
||||||
|
}
|
||||||
|
|
||||||
|
public AnalysisResult analyzeStock(String isin) {
|
||||||
|
// 1. Get Stock Data
|
||||||
|
StockData stockInfo = stockDataService.getStockPrice(isin);
|
||||||
|
if (stockInfo.error() != null) {
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
|
||||||
|
String symbol = stockInfo.symbol();
|
||||||
|
|
||||||
|
// 1.5 Update past results for this stock (fill in missing real prices)
|
||||||
|
updatePastResults(isin, symbol);
|
||||||
|
|
||||||
|
// 2. Get News
|
||||||
|
List<String> news = newsService.getNews(symbol);
|
||||||
|
|
||||||
|
// 3. Get Web Sentiment
|
||||||
|
List<String> social = sentimentService.getWebSentiment(symbol);
|
||||||
|
|
||||||
|
// 4. Get Market Context
|
||||||
|
MarketContextData marketContextData = stockDataService.getMarketContext();
|
||||||
|
MarketContext marketContext = null;
|
||||||
|
if (marketContextData != null) {
|
||||||
|
marketContext = new MarketContext(
|
||||||
|
marketContextData.symbol(),
|
||||||
|
marketContextData.changePercent(),
|
||||||
|
marketContextData.price());
|
||||||
|
}
|
||||||
|
|
||||||
|
// 5. Prepare data for LLM
|
||||||
|
Map<String, Object> stockDataMap = new HashMap<>();
|
||||||
|
stockDataMap.put("symbol", symbol);
|
||||||
|
stockDataMap.put("currentPrice", stockInfo.currentPrice());
|
||||||
|
stockDataMap.put("changePercent", stockInfo.changePercent());
|
||||||
|
stockDataMap.put("fundamentals", stockInfo.fundamentals());
|
||||||
|
stockDataMap.put("technicals", stockInfo.technicals());
|
||||||
|
|
||||||
|
Map<String, Object> marketContextMap = null;
|
||||||
|
if (marketContextData != null) {
|
||||||
|
marketContextMap = new HashMap<>();
|
||||||
|
marketContextMap.put("symbol", marketContextData.symbol());
|
||||||
|
marketContextMap.put("changePercent", marketContextData.changePercent());
|
||||||
|
marketContextMap.put("price", marketContextData.price());
|
||||||
|
}
|
||||||
|
|
||||||
|
// 6. LLM Analysis - Both providers
|
||||||
|
LLMAnalysis llmResultOpenai = llmService.analyzeWithLLM(stockDataMap, news, social, marketContextMap, "openai");
|
||||||
|
LLMAnalysis llmResultAnthropic = llmService.analyzeWithLLM(stockDataMap, news, social, marketContextMap,
|
||||||
|
"anthropic");
|
||||||
|
|
||||||
|
// 7. Calculate dates
|
||||||
|
Instant now = Instant.now();
|
||||||
|
String dateStr = now.atZone(ZoneOffset.UTC).toLocalDate().format(DateTimeFormatter.ISO_LOCAL_DATE);
|
||||||
|
String targetDate = calculateTargetDate(now);
|
||||||
|
|
||||||
|
// 8. Build result
|
||||||
|
Map<String, Object> fundamentalsMap = stockInfo.fundamentals();
|
||||||
|
Fundamentals fundamentals = new Fundamentals(
|
||||||
|
String.valueOf(fundamentalsMap.getOrDefault("pe_ratio", "N/A")),
|
||||||
|
String.valueOf(fundamentalsMap.getOrDefault("market_cap", "N/A")),
|
||||||
|
String.valueOf(fundamentalsMap.getOrDefault("high_52w", "N/A")),
|
||||||
|
String.valueOf(fundamentalsMap.getOrDefault("low_52w", "N/A")),
|
||||||
|
String.valueOf(fundamentalsMap.getOrDefault("target_mean_price", "N/A")),
|
||||||
|
String.valueOf(fundamentalsMap.getOrDefault("recommendation_key", "N/A")));
|
||||||
|
|
||||||
|
Map<String, Object> technicalsMap = stockInfo.technicals();
|
||||||
|
Technicals technicals = new Technicals(
|
||||||
|
String.valueOf(technicalsMap.getOrDefault("sma_20", "N/A")),
|
||||||
|
String.valueOf(technicalsMap.getOrDefault("rsi", "N/A")));
|
||||||
|
|
||||||
|
return AnalysisResult.builder()
|
||||||
|
.isin(isin)
|
||||||
|
.symbol(symbol)
|
||||||
|
.price(stockInfo.currentPrice())
|
||||||
|
.changePercent(stockInfo.changePercent())
|
||||||
|
.fundamentals(fundamentals)
|
||||||
|
.technicals(technicals)
|
||||||
|
.marketContext(marketContext)
|
||||||
|
.newsHeadlines(news)
|
||||||
|
.socialPosts(social)
|
||||||
|
.llmAnalysisOpenai(llmResultOpenai)
|
||||||
|
.llmAnalysisAnthropic(llmResultAnthropic)
|
||||||
|
.analyzedAt(now)
|
||||||
|
.date(dateStr)
|
||||||
|
.targetDate(targetDate)
|
||||||
|
.build();
|
||||||
|
}
|
||||||
|
|
||||||
|
public void saveResult(AnalysisResult result) {
|
||||||
|
// Upsert: update if exists for this ISIN and date, insert otherwise
|
||||||
|
List<AnalysisResult> existingList = analysisResultRepository.findByIsinOrderByAnalyzedAtDesc(result.getIsin());
|
||||||
|
|
||||||
|
Optional<AnalysisResult> existing = existingList.stream()
|
||||||
|
.filter(r -> r.getDate().equals(result.getDate()))
|
||||||
|
.findFirst();
|
||||||
|
|
||||||
|
if (existing.isPresent()) {
|
||||||
|
result.setId(existing.get().getId());
|
||||||
|
analysisResultRepository.save(result);
|
||||||
|
} else {
|
||||||
|
analysisResultRepository.save(result);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
private String calculateTargetDate(Instant instant) {
|
||||||
|
LocalDate date = instant.atZone(ZoneOffset.UTC).toLocalDate();
|
||||||
|
DayOfWeek dayOfWeek = date.getDayOfWeek();
|
||||||
|
|
||||||
|
long daysToAdd;
|
||||||
|
switch (dayOfWeek) {
|
||||||
|
case FRIDAY:
|
||||||
|
daysToAdd = 3;
|
||||||
|
break;
|
||||||
|
case SATURDAY:
|
||||||
|
daysToAdd = 2;
|
||||||
|
break;
|
||||||
|
case SUNDAY:
|
||||||
|
daysToAdd = 1;
|
||||||
|
break;
|
||||||
|
default:
|
||||||
|
daysToAdd = 1;
|
||||||
|
break;
|
||||||
|
}
|
||||||
|
|
||||||
|
return date.plusDays(daysToAdd).format(DateTimeFormatter.ISO_LOCAL_DATE);
|
||||||
|
}
|
||||||
|
|
||||||
|
private void updatePastResults(String isin, String symbol) {
|
||||||
|
String today = LocalDate.now().format(DateTimeFormatter.ISO_LOCAL_DATE);
|
||||||
|
List<AnalysisResult> pastResults = analysisResultRepository.findByIsinAndRealPriceIsNullAndTargetDateLessThan(isin, today);
|
||||||
|
|
||||||
|
for (AnalysisResult result : pastResults) {
|
||||||
|
try {
|
||||||
|
Double price = stockDataService.getHistoricalPrice(symbol, result.getTargetDate());
|
||||||
|
if (price != null) {
|
||||||
|
result.setRealPrice(price);
|
||||||
|
analysisResultRepository.save(result);
|
||||||
|
}
|
||||||
|
} catch (Exception e) {
|
||||||
|
System.err.println("Failed to update past result for " + symbol + ": " + e.getMessage());
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
@Scheduled(fixedDelay = 21600000) // 6 hours
|
||||||
|
public void updateMissingRealPrices() {
|
||||||
|
String today = LocalDate.now().format(DateTimeFormatter.ISO_LOCAL_DATE);
|
||||||
|
List<AnalysisResult> pendingResults = analysisResultRepository.findByRealPriceIsNullAndTargetDateLessThan(today);
|
||||||
|
|
||||||
|
for (AnalysisResult result : pendingResults) {
|
||||||
|
try {
|
||||||
|
Double price = stockDataService.getHistoricalPrice(result.getSymbol(), result.getTargetDate());
|
||||||
|
if (price != null) {
|
||||||
|
result.setRealPrice(price);
|
||||||
|
analysisResultRepository.save(result);
|
||||||
|
}
|
||||||
|
} catch (Exception e) {
|
||||||
|
System.err.println("Failed to update real price for " + result.getSymbol() + ": " + e.getMessage());
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,45 @@
|
|||||||
|
package com.stockanalyzer.service;
|
||||||
|
|
||||||
|
import com.stockanalyzer.model.AnalysisJob;
|
||||||
|
import com.stockanalyzer.model.AnalysisResult;
|
||||||
|
import org.slf4j.Logger;
|
||||||
|
import org.slf4j.LoggerFactory;
|
||||||
|
import org.springframework.scheduling.annotation.Scheduled;
|
||||||
|
import org.springframework.stereotype.Service;
|
||||||
|
|
||||||
|
import java.util.List;
|
||||||
|
|
||||||
|
@Service
|
||||||
|
public class JobProcessor {
|
||||||
|
|
||||||
|
private static final Logger logger = LoggerFactory.getLogger(JobProcessor.class);
|
||||||
|
|
||||||
|
private final JobService jobService;
|
||||||
|
private final AnalysisService analysisService;
|
||||||
|
|
||||||
|
public JobProcessor(JobService jobService, AnalysisService analysisService) {
|
||||||
|
this.jobService = jobService;
|
||||||
|
this.analysisService = analysisService;
|
||||||
|
}
|
||||||
|
|
||||||
|
@Scheduled(fixedDelay = 2000) // Poll every 2 seconds
|
||||||
|
public void processJobs() {
|
||||||
|
List<AnalysisJob> pendingJobs = jobService.getPendingJobs();
|
||||||
|
|
||||||
|
for (AnalysisJob job : pendingJobs) {
|
||||||
|
try {
|
||||||
|
logger.info("Starting analysis for job: {} (Stock: {})", job.getId(), job.getSymbol());
|
||||||
|
jobService.startJob(job);
|
||||||
|
|
||||||
|
AnalysisResult result = analysisService.analyzeStock(job.getIsin());
|
||||||
|
analysisService.saveResult(result);
|
||||||
|
|
||||||
|
jobService.completeJob(job);
|
||||||
|
logger.info("Completed analysis for job: {}", job.getId());
|
||||||
|
} catch (Exception e) {
|
||||||
|
logger.error("Failed to process job: " + job.getId(), e);
|
||||||
|
jobService.failJob(job, e.getMessage());
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,76 @@
|
|||||||
|
package com.stockanalyzer.service;
|
||||||
|
|
||||||
|
import com.stockanalyzer.model.AnalysisJob;
|
||||||
|
import com.stockanalyzer.repository.AnalysisJobRepository;
|
||||||
|
import org.springframework.stereotype.Service;
|
||||||
|
|
||||||
|
import java.time.LocalDateTime;
|
||||||
|
import java.util.List;
|
||||||
|
|
||||||
|
@Service
|
||||||
|
public class JobService {
|
||||||
|
|
||||||
|
private final AnalysisJobRepository jobRepository;
|
||||||
|
|
||||||
|
public JobService(AnalysisJobRepository jobRepository) {
|
||||||
|
this.jobRepository = jobRepository;
|
||||||
|
}
|
||||||
|
|
||||||
|
public AnalysisJob createJob(String isin, String symbol) {
|
||||||
|
AnalysisJob job = new AnalysisJob(isin, symbol);
|
||||||
|
return jobRepository.save(job);
|
||||||
|
}
|
||||||
|
|
||||||
|
public List<AnalysisJob> getAllJobs() {
|
||||||
|
return jobRepository.findAll();
|
||||||
|
}
|
||||||
|
|
||||||
|
public List<AnalysisJob> getPendingJobs() {
|
||||||
|
return jobRepository.findByStatus(AnalysisJob.JobStatus.PENDING);
|
||||||
|
}
|
||||||
|
|
||||||
|
public boolean hasPendingOrProcessingJob(String isin) {
|
||||||
|
return jobRepository.existsByIsinAndStatus(isin, AnalysisJob.JobStatus.PENDING) ||
|
||||||
|
jobRepository.existsByIsinAndStatus(isin, AnalysisJob.JobStatus.PROCESSING);
|
||||||
|
}
|
||||||
|
|
||||||
|
public void startJob(AnalysisJob job) {
|
||||||
|
job.setStatus(AnalysisJob.JobStatus.PROCESSING);
|
||||||
|
job.setStartedAt(LocalDateTime.now());
|
||||||
|
jobRepository.save(job);
|
||||||
|
}
|
||||||
|
|
||||||
|
public void completeJob(AnalysisJob job) {
|
||||||
|
job.setStatus(AnalysisJob.JobStatus.COMPLETED);
|
||||||
|
job.setCompletedAt(LocalDateTime.now());
|
||||||
|
jobRepository.save(job);
|
||||||
|
}
|
||||||
|
|
||||||
|
public void failJob(AnalysisJob job, String error) {
|
||||||
|
job.setStatus(AnalysisJob.JobStatus.FAILED);
|
||||||
|
job.setError(error);
|
||||||
|
job.setCompletedAt(LocalDateTime.now());
|
||||||
|
jobRepository.save(job);
|
||||||
|
}
|
||||||
|
|
||||||
|
public void deleteAllJobs() {
|
||||||
|
jobRepository.deleteAll();
|
||||||
|
}
|
||||||
|
|
||||||
|
public void cancelAllJobs() {
|
||||||
|
List<AnalysisJob> pendingJobs = jobRepository.findByStatus(AnalysisJob.JobStatus.PENDING);
|
||||||
|
List<AnalysisJob> processingJobs = jobRepository.findByStatus(AnalysisJob.JobStatus.PROCESSING);
|
||||||
|
|
||||||
|
for (AnalysisJob job : pendingJobs) {
|
||||||
|
job.setStatus(AnalysisJob.JobStatus.CANCELLED);
|
||||||
|
job.setCompletedAt(LocalDateTime.now());
|
||||||
|
jobRepository.save(job);
|
||||||
|
}
|
||||||
|
|
||||||
|
for (AnalysisJob job : processingJobs) {
|
||||||
|
job.setStatus(AnalysisJob.JobStatus.CANCELLED);
|
||||||
|
job.setCompletedAt(LocalDateTime.now());
|
||||||
|
jobRepository.save(job);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,238 @@
|
|||||||
|
package com.stockanalyzer.service;
|
||||||
|
|
||||||
|
import com.fasterxml.jackson.databind.JsonNode;
|
||||||
|
import com.fasterxml.jackson.databind.ObjectMapper;
|
||||||
|
import com.stockanalyzer.model.AnalysisResult.LLMAnalysis;
|
||||||
|
import okhttp3.MediaType;
|
||||||
|
import okhttp3.OkHttpClient;
|
||||||
|
import okhttp3.Request;
|
||||||
|
import okhttp3.RequestBody;
|
||||||
|
import okhttp3.Response;
|
||||||
|
import org.springframework.beans.factory.annotation.Value;
|
||||||
|
import org.springframework.stereotype.Service;
|
||||||
|
|
||||||
|
import java.util.Collections;
|
||||||
|
import java.util.List;
|
||||||
|
import java.util.Map;
|
||||||
|
|
||||||
|
@Service
|
||||||
|
public class LLMService {
|
||||||
|
|
||||||
|
@Value("${api.openai.key}")
|
||||||
|
private String openaiApiKey;
|
||||||
|
|
||||||
|
@Value("${api.openai.model}")
|
||||||
|
private String openaiModel;
|
||||||
|
|
||||||
|
@Value("${api.anthropic.key}")
|
||||||
|
private String anthropicApiKey;
|
||||||
|
|
||||||
|
@Value("${api.anthropic.model}")
|
||||||
|
private String anthropicModel;
|
||||||
|
|
||||||
|
private final OkHttpClient httpClient;
|
||||||
|
private final ObjectMapper objectMapper;
|
||||||
|
private final MediaType jsonMediaType = MediaType.parse("application/json");
|
||||||
|
|
||||||
|
public LLMService(ObjectMapper objectMapper) {
|
||||||
|
this.httpClient = new OkHttpClient();
|
||||||
|
this.objectMapper = objectMapper;
|
||||||
|
}
|
||||||
|
|
||||||
|
public LLMAnalysis analyzeWithLLM(
|
||||||
|
Map<String, Object> stockData,
|
||||||
|
List<String> newsData,
|
||||||
|
List<String> socialData,
|
||||||
|
Map<String, Object> marketContext,
|
||||||
|
String provider) {
|
||||||
|
String prompt = buildPrompt(stockData, newsData, socialData, marketContext);
|
||||||
|
|
||||||
|
switch (provider.toLowerCase()) {
|
||||||
|
case "openai":
|
||||||
|
return analyzeWithOpenAI(prompt);
|
||||||
|
case "anthropic":
|
||||||
|
return analyzeWithAnthropic(prompt);
|
||||||
|
default:
|
||||||
|
return new LLMAnalysis("", 0, "", "Unknown provider: " + provider);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
private String buildPrompt(
|
||||||
|
Map<String, Object> stockData,
|
||||||
|
List<String> newsData,
|
||||||
|
List<String> socialData,
|
||||||
|
Map<String, Object> marketContext) {
|
||||||
|
String symbol = (String) stockData.getOrDefault("symbol", "Unknown");
|
||||||
|
Object price = stockData.getOrDefault("currentPrice", "Unknown");
|
||||||
|
Object change = stockData.getOrDefault("changePercent", 0.0);
|
||||||
|
|
||||||
|
Map<?, ?> fundamentals = (Map<?, ?>) stockData.getOrDefault("fundamentals", Collections.emptyMap());
|
||||||
|
Map<?, ?> technicals = (Map<?, ?>) stockData.getOrDefault("technicals", Collections.emptyMap());
|
||||||
|
|
||||||
|
String marketChange = "N/A";
|
||||||
|
if (marketContext != null) {
|
||||||
|
marketChange = String.valueOf(marketContext.getOrDefault("changePercent", "N/A"));
|
||||||
|
}
|
||||||
|
|
||||||
|
return """
|
||||||
|
You are a financial analyst. Analyze the following data for stock %s:
|
||||||
|
|
||||||
|
Current Price: %s
|
||||||
|
Recent Change: %s%%
|
||||||
|
|
||||||
|
Fundamentals:
|
||||||
|
- P/E Ratio: %s
|
||||||
|
- Market Cap: %s
|
||||||
|
- 52W High: %s
|
||||||
|
- Analyst Target: %s
|
||||||
|
- Analyst Rating: %s
|
||||||
|
|
||||||
|
Market Context (S&P 500):
|
||||||
|
- Change (24h): %s%%
|
||||||
|
|
||||||
|
Technicals:
|
||||||
|
- RSI (14): %s
|
||||||
|
- SMA (20): %s
|
||||||
|
|
||||||
|
Recent News Headlines:
|
||||||
|
%s
|
||||||
|
|
||||||
|
Recent Web Discussions & Sentiment:
|
||||||
|
%s
|
||||||
|
|
||||||
|
Task:
|
||||||
|
Predict the probability (0-100%%) of the stock rising in the next 24 hours.
|
||||||
|
Provide a concise reasoning (max 3 sentences).
|
||||||
|
|
||||||
|
Output Format:
|
||||||
|
Return ONLY a JSON object with the following keys:
|
||||||
|
{
|
||||||
|
"prediction": "Rise" or "Fall",
|
||||||
|
"probability": <int 0-100>,
|
||||||
|
"reasoning": "<string>"
|
||||||
|
}
|
||||||
|
""".formatted(
|
||||||
|
symbol,
|
||||||
|
price,
|
||||||
|
change,
|
||||||
|
fundamentals.get("pe_ratio"),
|
||||||
|
fundamentals.get("market_cap"),
|
||||||
|
fundamentals.get("high_52w"),
|
||||||
|
fundamentals.get("target_mean_price"),
|
||||||
|
fundamentals.get("recommendation_key"),
|
||||||
|
marketChange,
|
||||||
|
technicals.get("rsi"),
|
||||||
|
technicals.get("sma_20"),
|
||||||
|
String.join("\n", newsData),
|
||||||
|
String.join("\n", socialData));
|
||||||
|
}
|
||||||
|
|
||||||
|
private LLMAnalysis analyzeWithOpenAI(String prompt) {
|
||||||
|
if (openaiApiKey == null || openaiApiKey.isBlank()) {
|
||||||
|
return new LLMAnalysis("", 0, "", "OpenAI API Key missing");
|
||||||
|
}
|
||||||
|
|
||||||
|
try {
|
||||||
|
Map<String, Object> requestMap = Map.of(
|
||||||
|
"model", openaiModel,
|
||||||
|
"messages", List.of(
|
||||||
|
Map.of("role", "system", "content",
|
||||||
|
"You are a helpful financial assistant. Always return valid JSON."),
|
||||||
|
Map.of("role", "user", "content", prompt)),
|
||||||
|
"response_format", Map.of("type", "json_object"));
|
||||||
|
|
||||||
|
String requestBodyString = objectMapper.writeValueAsString(requestMap);
|
||||||
|
RequestBody requestBody = RequestBody.create(requestBodyString, jsonMediaType);
|
||||||
|
|
||||||
|
Request request = new Request.Builder()
|
||||||
|
.url("https://api.openai.com/v1/chat/completions")
|
||||||
|
.header("Authorization", "Bearer " + openaiApiKey)
|
||||||
|
.header("Content-Type", "application/json")
|
||||||
|
.post(requestBody)
|
||||||
|
.build();
|
||||||
|
|
||||||
|
try (Response response = httpClient.newCall(request).execute()) {
|
||||||
|
if (!response.isSuccessful() || response.body() == null) {
|
||||||
|
return new LLMAnalysis("", 0, "", "OpenAI API error: " + response.code());
|
||||||
|
}
|
||||||
|
|
||||||
|
JsonNode json = objectMapper.readTree(response.body().string());
|
||||||
|
JsonNode choices = json.get("choices");
|
||||||
|
if (choices != null && choices.size() > 0) {
|
||||||
|
JsonNode message = choices.get(0).get("message");
|
||||||
|
if (message != null && message.has("content")) {
|
||||||
|
return parseLLMResponse(message.get("content").asText());
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return new LLMAnalysis("", 0, "", "No response from OpenAI");
|
||||||
|
}
|
||||||
|
} catch (Exception e) {
|
||||||
|
return new LLMAnalysis("", 0, "", "Error during OpenAI analysis: " + e.getMessage());
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
private LLMAnalysis analyzeWithAnthropic(String prompt) {
|
||||||
|
if (anthropicApiKey == null || anthropicApiKey.isBlank()) {
|
||||||
|
return new LLMAnalysis("", 0, "", "Anthropic API Key missing");
|
||||||
|
}
|
||||||
|
|
||||||
|
try {
|
||||||
|
Map<String, Object> requestMap = Map.of(
|
||||||
|
"model", anthropicModel,
|
||||||
|
"max_tokens", 1024,
|
||||||
|
"messages", List.of(
|
||||||
|
Map.of("role", "user", "content", prompt)));
|
||||||
|
|
||||||
|
String requestBodyString = objectMapper.writeValueAsString(requestMap);
|
||||||
|
RequestBody requestBody = RequestBody.create(requestBodyString, jsonMediaType);
|
||||||
|
|
||||||
|
Request request = new Request.Builder()
|
||||||
|
.url("https://api.anthropic.com/v1/messages")
|
||||||
|
.header("x-api-key", anthropicApiKey)
|
||||||
|
.header("anthropic-version", "2023-06-01")
|
||||||
|
.header("Content-Type", "application/json")
|
||||||
|
.post(requestBody)
|
||||||
|
.build();
|
||||||
|
|
||||||
|
try (Response response = httpClient.newCall(request).execute()) {
|
||||||
|
if (!response.isSuccessful() || response.body() == null) {
|
||||||
|
return new LLMAnalysis("", 0, "", "Anthropic API error: " + response.code());
|
||||||
|
}
|
||||||
|
|
||||||
|
JsonNode json = objectMapper.readTree(response.body().string());
|
||||||
|
JsonNode contentNode = json.get("content");
|
||||||
|
if (contentNode != null && contentNode.size() > 0) {
|
||||||
|
JsonNode textNode = contentNode.get(0).get("text");
|
||||||
|
if (textNode != null) {
|
||||||
|
return parseLLMResponse(textNode.asText());
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return new LLMAnalysis("", 0, "", "No response from Anthropic");
|
||||||
|
}
|
||||||
|
} catch (Exception e) {
|
||||||
|
return new LLMAnalysis("", 0, "", "Error during Anthropic analysis: " + e.getMessage());
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
private LLMAnalysis parseLLMResponse(String content) {
|
||||||
|
try {
|
||||||
|
String cleanContent = content.trim();
|
||||||
|
|
||||||
|
// Remove markdown code blocks if present
|
||||||
|
if (cleanContent.startsWith("```json")) {
|
||||||
|
cleanContent = cleanContent.replace("```json", "").replace("```", "").trim();
|
||||||
|
} else if (cleanContent.startsWith("```")) {
|
||||||
|
cleanContent = cleanContent.replace("```", "").trim();
|
||||||
|
}
|
||||||
|
|
||||||
|
JsonNode json = objectMapper.readTree(cleanContent);
|
||||||
|
return new LLMAnalysis(
|
||||||
|
json.has("prediction") ? json.get("prediction").asText() : "",
|
||||||
|
json.has("probability") ? json.get("probability").asInt() : 0,
|
||||||
|
json.has("reasoning") ? json.get("reasoning").asText() : "",
|
||||||
|
null);
|
||||||
|
} catch (Exception e) {
|
||||||
|
return new LLMAnalysis("", 0, "", "Failed to parse LLM response: " + e.getMessage());
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,68 @@
|
|||||||
|
package com.stockanalyzer.service;
|
||||||
|
|
||||||
|
import com.fasterxml.jackson.databind.JsonNode;
|
||||||
|
import com.fasterxml.jackson.databind.ObjectMapper;
|
||||||
|
import okhttp3.OkHttpClient;
|
||||||
|
import okhttp3.Request;
|
||||||
|
import okhttp3.Response;
|
||||||
|
import org.springframework.beans.factory.annotation.Value;
|
||||||
|
import org.springframework.stereotype.Service;
|
||||||
|
|
||||||
|
import java.util.ArrayList;
|
||||||
|
import java.util.Collections;
|
||||||
|
import java.util.List;
|
||||||
|
|
||||||
|
@Service
|
||||||
|
public class NewsService {
|
||||||
|
|
||||||
|
@Value("${api.news.key}")
|
||||||
|
private String newsApiKey;
|
||||||
|
|
||||||
|
private final OkHttpClient httpClient;
|
||||||
|
private final ObjectMapper objectMapper;
|
||||||
|
|
||||||
|
public NewsService(ObjectMapper objectMapper) {
|
||||||
|
this.httpClient = new OkHttpClient();
|
||||||
|
this.objectMapper = objectMapper;
|
||||||
|
}
|
||||||
|
|
||||||
|
public List<String> getNews(String query) {
|
||||||
|
if (newsApiKey == null || newsApiKey.isBlank()) {
|
||||||
|
return Collections.singletonList("News API Key missing");
|
||||||
|
}
|
||||||
|
|
||||||
|
try {
|
||||||
|
String url = "https://newsapi.org/v2/everything?q=" + query + "&apiKey=" + newsApiKey
|
||||||
|
+ "&language=en&sortBy=publishedAt&pageSize=5";
|
||||||
|
Request request = new Request.Builder()
|
||||||
|
.url(url)
|
||||||
|
.build();
|
||||||
|
|
||||||
|
try (Response response = httpClient.newCall(request).execute()) {
|
||||||
|
if (!response.isSuccessful() || response.body() == null) {
|
||||||
|
return Collections.singletonList("Error fetching news: " + response.code());
|
||||||
|
}
|
||||||
|
|
||||||
|
JsonNode json = objectMapper.readTree(response.body().string());
|
||||||
|
JsonNode articles = json.get("articles");
|
||||||
|
|
||||||
|
if (articles != null && articles.size() > 0) {
|
||||||
|
List<String> newsList = new ArrayList<>();
|
||||||
|
for (JsonNode article : articles) {
|
||||||
|
String title = article.has("title") ? article.get("title").asText() : "";
|
||||||
|
String source = "";
|
||||||
|
if (article.has("source") && article.get("source").has("name")) {
|
||||||
|
source = article.get("source").get("name").asText();
|
||||||
|
}
|
||||||
|
newsList.add(title + " - " + source);
|
||||||
|
}
|
||||||
|
return newsList;
|
||||||
|
} else {
|
||||||
|
return Collections.singletonList("No news found");
|
||||||
|
}
|
||||||
|
}
|
||||||
|
} catch (Exception e) {
|
||||||
|
return Collections.singletonList("Error fetching news: " + e.getMessage());
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,73 @@
|
|||||||
|
package com.stockanalyzer.service;
|
||||||
|
|
||||||
|
import okhttp3.OkHttpClient;
|
||||||
|
import okhttp3.Request;
|
||||||
|
import okhttp3.Response;
|
||||||
|
import org.jsoup.Jsoup;
|
||||||
|
import org.jsoup.nodes.Document;
|
||||||
|
import org.jsoup.nodes.Element;
|
||||||
|
import org.jsoup.select.Elements;
|
||||||
|
import org.springframework.stereotype.Service;
|
||||||
|
|
||||||
|
import java.net.URLEncoder;
|
||||||
|
import java.nio.charset.StandardCharsets;
|
||||||
|
import java.util.ArrayList;
|
||||||
|
import java.util.Collections;
|
||||||
|
import java.util.List;
|
||||||
|
|
||||||
|
@Service
|
||||||
|
public class SentimentService {
|
||||||
|
|
||||||
|
private final OkHttpClient httpClient;
|
||||||
|
|
||||||
|
public SentimentService() {
|
||||||
|
this.httpClient = new OkHttpClient();
|
||||||
|
}
|
||||||
|
|
||||||
|
public List<String> getWebSentiment(String query) {
|
||||||
|
try {
|
||||||
|
// Use DuckDuckGo HTML search
|
||||||
|
String searchQuery = query + " stock sentiment news discussion site:reddit.com OR site:finance.yahoo.com";
|
||||||
|
String encodedQuery = URLEncoder.encode(searchQuery, StandardCharsets.UTF_8);
|
||||||
|
String url = "https://html.duckduckgo.com/html/?q=" + encodedQuery;
|
||||||
|
|
||||||
|
Request request = new Request.Builder()
|
||||||
|
.url(url)
|
||||||
|
.header("User-Agent", "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36")
|
||||||
|
.build();
|
||||||
|
|
||||||
|
try (Response response = httpClient.newCall(request).execute()) {
|
||||||
|
if (!response.isSuccessful() || response.body() == null) {
|
||||||
|
return Collections.singletonList("Error fetching web sentiment: " + response.code());
|
||||||
|
}
|
||||||
|
|
||||||
|
String html = response.body().string();
|
||||||
|
Document doc = Jsoup.parse(html);
|
||||||
|
|
||||||
|
// Extract search results
|
||||||
|
List<String> results = new ArrayList<>();
|
||||||
|
Elements resultElements = doc.select(".result__body");
|
||||||
|
|
||||||
|
for (Element element : resultElements.subList(0, Math.min(resultElements.size(), 10))) {
|
||||||
|
Element titleEl = element.selectFirst(".result__title");
|
||||||
|
Element snippetEl = element.selectFirst(".result__snippet");
|
||||||
|
|
||||||
|
String title = titleEl != null ? titleEl.text() : "";
|
||||||
|
String snippet = snippetEl != null ? snippetEl.text() : "";
|
||||||
|
|
||||||
|
if (!title.isBlank() && !snippet.isBlank()) {
|
||||||
|
results.add(title + ": " + snippet);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
if (results.isEmpty()) {
|
||||||
|
return Collections.singletonList("No recent web discussions found.");
|
||||||
|
} else {
|
||||||
|
return results;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
} catch (Exception e) {
|
||||||
|
return Collections.singletonList("Error fetching web sentiment: " + e.getMessage());
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,368 @@
|
|||||||
|
package com.stockanalyzer.service;
|
||||||
|
|
||||||
|
import com.fasterxml.jackson.databind.JsonNode;
|
||||||
|
import com.fasterxml.jackson.databind.ObjectMapper;
|
||||||
|
import okhttp3.OkHttpClient;
|
||||||
|
import okhttp3.Request;
|
||||||
|
import okhttp3.Response;
|
||||||
|
import org.springframework.stereotype.Service;
|
||||||
|
|
||||||
|
import java.time.LocalDate;
|
||||||
|
import java.time.format.DateTimeFormatter;
|
||||||
|
import java.util.ArrayList;
|
||||||
|
import java.util.Collections;
|
||||||
|
import java.util.HashMap;
|
||||||
|
import java.util.List;
|
||||||
|
import java.util.Map;
|
||||||
|
|
||||||
|
@Service
|
||||||
|
public class StockDataService {
|
||||||
|
|
||||||
|
private final OkHttpClient httpClient;
|
||||||
|
private final ObjectMapper objectMapper;
|
||||||
|
|
||||||
|
public StockDataService(ObjectMapper objectMapper) {
|
||||||
|
this.httpClient = new OkHttpClient();
|
||||||
|
this.objectMapper = objectMapper;
|
||||||
|
}
|
||||||
|
|
||||||
|
public record StockData(
|
||||||
|
String symbol,
|
||||||
|
Double currentPrice,
|
||||||
|
Double changePercent,
|
||||||
|
Map<String, Object> fundamentals,
|
||||||
|
Map<String, Object> technicals,
|
||||||
|
String error) {
|
||||||
|
}
|
||||||
|
|
||||||
|
public record MarketContextData(
|
||||||
|
String symbol,
|
||||||
|
Double changePercent,
|
||||||
|
Double price) {
|
||||||
|
}
|
||||||
|
|
||||||
|
public String getTickerFromIsin(String isin) {
|
||||||
|
String url = "https://query2.finance.yahoo.com/v1/finance/search?q=" + isin;
|
||||||
|
Request request = new Request.Builder()
|
||||||
|
.url(url)
|
||||||
|
.header("User-Agent", "Mozilla/5.0")
|
||||||
|
.build();
|
||||||
|
|
||||||
|
try (Response response = httpClient.newCall(request).execute()) {
|
||||||
|
if (response.isSuccessful() && response.body() != null) {
|
||||||
|
JsonNode json = objectMapper.readTree(response.body().string());
|
||||||
|
JsonNode quotes = json.get("quotes");
|
||||||
|
if (quotes != null && quotes.size() > 0) {
|
||||||
|
JsonNode symbolNode = quotes.get(0).get("symbol");
|
||||||
|
return symbolNode != null ? symbolNode.asText() : isin;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
} catch (Exception e) {
|
||||||
|
System.out.println("Error resolving ISIN " + isin + ": " + e.getMessage());
|
||||||
|
}
|
||||||
|
return isin;
|
||||||
|
}
|
||||||
|
|
||||||
|
public StockData getStockPrice(String isin) {
|
||||||
|
String tickerSymbol = getTickerFromIsin(isin);
|
||||||
|
System.out.println("Resolved " + isin + " to " + tickerSymbol);
|
||||||
|
|
||||||
|
try {
|
||||||
|
String quoteUrl = "https://query1.finance.yahoo.com/v8/finance/chart/" + tickerSymbol
|
||||||
|
+ "?interval=1d&range=1mo";
|
||||||
|
Request request = new Request.Builder()
|
||||||
|
.url(quoteUrl)
|
||||||
|
.header("User-Agent", "Mozilla/5.0")
|
||||||
|
.build();
|
||||||
|
|
||||||
|
try (Response response = httpClient.newCall(request).execute()) {
|
||||||
|
if (!response.isSuccessful() || response.body() == null) {
|
||||||
|
return new StockData("", 0.0, 0.0, Collections.emptyMap(), Collections.emptyMap(),
|
||||||
|
"Failed to fetch data");
|
||||||
|
}
|
||||||
|
|
||||||
|
JsonNode json = objectMapper.readTree(response.body().string());
|
||||||
|
JsonNode chart = json.get("chart");
|
||||||
|
if (chart == null)
|
||||||
|
return new StockData("", 0.0, 0.0, Collections.emptyMap(), Collections.emptyMap(), "No data found");
|
||||||
|
|
||||||
|
JsonNode resultNode = chart.get("result");
|
||||||
|
if (resultNode == null || resultNode.size() == 0) {
|
||||||
|
return new StockData("", 0.0, 0.0, Collections.emptyMap(), Collections.emptyMap(), "No data found");
|
||||||
|
}
|
||||||
|
|
||||||
|
JsonNode result = resultNode.get(0);
|
||||||
|
JsonNode meta = result.get("meta");
|
||||||
|
|
||||||
|
double currentPrice = meta.has("regularMarketPrice") ? meta.get("regularMarketPrice").asDouble() : 0.0;
|
||||||
|
double previousClose = meta.has("chartPreviousClose") ? meta.get("chartPreviousClose").asDouble()
|
||||||
|
: currentPrice;
|
||||||
|
double changePercent = ((currentPrice - previousClose) / previousClose) * 100;
|
||||||
|
|
||||||
|
// Technicals
|
||||||
|
JsonNode indicators = result.get("indicators");
|
||||||
|
JsonNode quote = indicators != null ? indicators.get("quote") : null;
|
||||||
|
JsonNode closes = (quote != null && quote.size() > 0) ? quote.get(0).get("close") : null;
|
||||||
|
|
||||||
|
Map<String, Object> technicals;
|
||||||
|
if (closes != null && closes.size() > 0) {
|
||||||
|
technicals = calculateTechnicals(closes);
|
||||||
|
} else {
|
||||||
|
technicals = Map.of("sma_20", "N/A", "rsi", "N/A");
|
||||||
|
}
|
||||||
|
|
||||||
|
// Fundamentals
|
||||||
|
Map<String, Object> fundamentals = getFundamentals(tickerSymbol);
|
||||||
|
|
||||||
|
return new StockData(
|
||||||
|
tickerSymbol,
|
||||||
|
currentPrice,
|
||||||
|
changePercent,
|
||||||
|
fundamentals,
|
||||||
|
technicals,
|
||||||
|
null);
|
||||||
|
}
|
||||||
|
} catch (Exception e) {
|
||||||
|
return new StockData("", 0.0, 0.0, Collections.emptyMap(), Collections.emptyMap(), e.getMessage());
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
private Map<String, Object> getFundamentals(String symbol) {
|
||||||
|
try {
|
||||||
|
String url = "https://query1.finance.yahoo.com/v10/finance/quoteSummary/" + symbol
|
||||||
|
+ "?modules=financialData,defaultKeyStatistics,price";
|
||||||
|
Request request = new Request.Builder()
|
||||||
|
.url(url)
|
||||||
|
.header("User-Agent", "Mozilla/5.0")
|
||||||
|
.build();
|
||||||
|
|
||||||
|
try (Response response = httpClient.newCall(request).execute()) {
|
||||||
|
if (!response.isSuccessful() || response.body() == null) {
|
||||||
|
return Collections.emptyMap();
|
||||||
|
}
|
||||||
|
|
||||||
|
JsonNode json = objectMapper.readTree(response.body().string());
|
||||||
|
JsonNode quoteSummary = json.get("quoteSummary");
|
||||||
|
if (quoteSummary == null)
|
||||||
|
return Collections.emptyMap();
|
||||||
|
|
||||||
|
JsonNode resultNode = quoteSummary.get("result");
|
||||||
|
if (resultNode == null || resultNode.size() == 0)
|
||||||
|
return Collections.emptyMap();
|
||||||
|
|
||||||
|
JsonNode result = resultNode.get(0);
|
||||||
|
JsonNode financialData = result.get("financialData");
|
||||||
|
JsonNode keyStats = result.get("defaultKeyStatistics");
|
||||||
|
JsonNode price = result.get("price");
|
||||||
|
|
||||||
|
Map<String, Object> map = new HashMap<>();
|
||||||
|
map.put("pe_ratio", safelyGet(keyStats, "trailingPE", "raw"));
|
||||||
|
map.put("market_cap", safelyGet(price, "marketCap", "raw"));
|
||||||
|
map.put("high_52w", safelyGet(keyStats, "fiftyTwoWeekHigh", "raw"));
|
||||||
|
map.put("low_52w", safelyGet(keyStats, "fiftyTwoWeekLow", "raw"));
|
||||||
|
map.put("target_mean_price", safelyGet(financialData, "targetMeanPrice", "raw"));
|
||||||
|
|
||||||
|
String recommendationKey = "N/A";
|
||||||
|
if (financialData != null && financialData.has("recommendationKey")) {
|
||||||
|
recommendationKey = financialData.get("recommendationKey").asText();
|
||||||
|
}
|
||||||
|
map.put("recommendation_key", recommendationKey);
|
||||||
|
|
||||||
|
return map;
|
||||||
|
}
|
||||||
|
} catch (Exception e) {
|
||||||
|
System.out.println("Error fetching fundamentals: " + e.getMessage());
|
||||||
|
return Collections.emptyMap();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
private String safelyGet(JsonNode node, String key, String subKey) {
|
||||||
|
if (node == null || !node.has(key))
|
||||||
|
return "N/A";
|
||||||
|
JsonNode subNode = node.get(key);
|
||||||
|
if (subNode == null || !subNode.has(subKey))
|
||||||
|
return "N/A";
|
||||||
|
return subNode.get(subKey).asText();
|
||||||
|
}
|
||||||
|
|
||||||
|
private Map<String, Object> calculateTechnicals(JsonNode closes) {
|
||||||
|
List<Double> closesList = new ArrayList<>();
|
||||||
|
for (int i = 0; i < closes.size(); i++) {
|
||||||
|
JsonNode close = closes.get(i);
|
||||||
|
if (close != null && !close.isNull()) {
|
||||||
|
closesList.add(close.asDouble());
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
if (closesList.isEmpty()) {
|
||||||
|
return Map.of("sma_20", "N/A", "rsi", "N/A");
|
||||||
|
}
|
||||||
|
|
||||||
|
// SMA 20
|
||||||
|
String sma20 = "N/A";
|
||||||
|
if (closesList.size() >= 20) {
|
||||||
|
double sum = 0;
|
||||||
|
for (int i = closesList.size() - 20; i < closesList.size(); i++) {
|
||||||
|
sum += closesList.get(i);
|
||||||
|
}
|
||||||
|
sma20 = String.valueOf(sum / 20);
|
||||||
|
}
|
||||||
|
|
||||||
|
// RSI 14
|
||||||
|
String rsi = "N/A";
|
||||||
|
if (closesList.size() >= 15) {
|
||||||
|
rsi = String.valueOf(calculateRSI(closesList, 14));
|
||||||
|
}
|
||||||
|
|
||||||
|
return Map.of("sma_20", sma20, "rsi", rsi);
|
||||||
|
}
|
||||||
|
|
||||||
|
private double calculateRSI(List<Double> prices, int period) {
|
||||||
|
if (prices.size() < period + 1)
|
||||||
|
return 0.0;
|
||||||
|
|
||||||
|
List<Double> changes = new ArrayList<>();
|
||||||
|
for (int i = 1; i < prices.size(); i++) {
|
||||||
|
changes.add(prices.get(i) - prices.get(i - 1));
|
||||||
|
}
|
||||||
|
|
||||||
|
List<Double> gains = new ArrayList<>();
|
||||||
|
List<Double> losses = new ArrayList<>();
|
||||||
|
|
||||||
|
for (Double change : changes) {
|
||||||
|
if (change > 0) {
|
||||||
|
gains.add(change);
|
||||||
|
losses.add(0.0);
|
||||||
|
} else {
|
||||||
|
gains.add(0.0);
|
||||||
|
losses.add(Math.abs(change));
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// Initial average
|
||||||
|
double avgGain = 0;
|
||||||
|
double avgLoss = 0;
|
||||||
|
|
||||||
|
// Use simple average for the first period (standard RSI calculation usually
|
||||||
|
// uses simple average for first step then smoothing)
|
||||||
|
// But the Kotlin code used takeLast(period).average() which is a simple moving
|
||||||
|
// average of the LAST period.
|
||||||
|
// I will replicate the Kotlin logic: "val avgGain =
|
||||||
|
// gains.takeLast(period).average()"
|
||||||
|
|
||||||
|
int startIndex = gains.size() - period;
|
||||||
|
if (startIndex < 0)
|
||||||
|
startIndex = 0; // Should not happen due to check above
|
||||||
|
|
||||||
|
double sumGain = 0;
|
||||||
|
double sumLoss = 0;
|
||||||
|
|
||||||
|
for (int i = startIndex; i < gains.size(); i++) {
|
||||||
|
sumGain += gains.get(i);
|
||||||
|
sumLoss += losses.get(i);
|
||||||
|
}
|
||||||
|
|
||||||
|
avgGain = sumGain / period;
|
||||||
|
avgLoss = sumLoss / period;
|
||||||
|
|
||||||
|
if (avgLoss == 0.0)
|
||||||
|
return 100.0;
|
||||||
|
|
||||||
|
double rs = avgGain / avgLoss;
|
||||||
|
return 100 - (100 / (1 + rs));
|
||||||
|
}
|
||||||
|
|
||||||
|
public MarketContextData getMarketContext() {
|
||||||
|
try {
|
||||||
|
String url = "https://query1.finance.yahoo.com/v8/finance/chart/%5EGSPC?interval=1d&range=5d";
|
||||||
|
Request request = new Request.Builder()
|
||||||
|
.url(url)
|
||||||
|
.header("User-Agent", "Mozilla/5.0")
|
||||||
|
.build();
|
||||||
|
|
||||||
|
try (Response response = httpClient.newCall(request).execute()) {
|
||||||
|
if (!response.isSuccessful() || response.body() == null)
|
||||||
|
return null;
|
||||||
|
|
||||||
|
JsonNode json = objectMapper.readTree(response.body().string());
|
||||||
|
JsonNode chart = json.get("chart");
|
||||||
|
if (chart == null)
|
||||||
|
return null;
|
||||||
|
JsonNode resultNode = chart.get("result");
|
||||||
|
if (resultNode == null || resultNode.size() == 0)
|
||||||
|
return null;
|
||||||
|
|
||||||
|
JsonNode result = resultNode.get(0);
|
||||||
|
JsonNode indicators = result.get("indicators");
|
||||||
|
JsonNode quote = indicators != null ? indicators.get("quote") : null;
|
||||||
|
JsonNode closes = (quote != null && quote.size() > 0) ? quote.get(0).get("close") : null;
|
||||||
|
|
||||||
|
if (closes != null && closes.size() >= 2) {
|
||||||
|
double current = closes.get(closes.size() - 1).asDouble();
|
||||||
|
double prev = closes.get(closes.size() - 2).asDouble();
|
||||||
|
double change = ((current - prev) / prev) * 100;
|
||||||
|
|
||||||
|
return new MarketContextData("^GSPC", change, current);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
} catch (Exception e) {
|
||||||
|
System.out.println("Error fetching market context: " + e.getMessage());
|
||||||
|
}
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
|
||||||
|
public Double getHistoricalPrice(String symbol, String dateStr) {
|
||||||
|
try {
|
||||||
|
LocalDate date = LocalDate.parse(dateStr, DateTimeFormatter.ISO_LOCAL_DATE);
|
||||||
|
// Use UTC start of day for periods
|
||||||
|
long period1 = date.minusDays(5).atStartOfDay(java.time.ZoneOffset.UTC).toEpochSecond();
|
||||||
|
long period2 = date.plusDays(5).atStartOfDay(java.time.ZoneOffset.UTC).toEpochSecond();
|
||||||
|
|
||||||
|
String url = "https://query1.finance.yahoo.com/v8/finance/chart/" + symbol +
|
||||||
|
"?interval=1d&period1=" + period1 +
|
||||||
|
"&period2=" + period2;
|
||||||
|
|
||||||
|
Request request = new Request.Builder()
|
||||||
|
.url(url)
|
||||||
|
.header("User-Agent", "Mozilla/5.0")
|
||||||
|
.build();
|
||||||
|
|
||||||
|
try (Response response = httpClient.newCall(request).execute()) {
|
||||||
|
if (!response.isSuccessful() || response.body() == null)
|
||||||
|
return null;
|
||||||
|
|
||||||
|
JsonNode json = objectMapper.readTree(response.body().string());
|
||||||
|
JsonNode chart = json.get("chart");
|
||||||
|
if (chart == null)
|
||||||
|
return null;
|
||||||
|
JsonNode resultNode = chart.get("result");
|
||||||
|
if (resultNode == null || resultNode.size() == 0)
|
||||||
|
return null;
|
||||||
|
|
||||||
|
JsonNode result = resultNode.get(0);
|
||||||
|
JsonNode timestamps = result.get("timestamp");
|
||||||
|
JsonNode indicators = result.get("indicators");
|
||||||
|
JsonNode quote = indicators != null ? indicators.get("quote") : null;
|
||||||
|
JsonNode closes = (quote != null && quote.size() > 0) ? quote.get(0).get("close") : null;
|
||||||
|
|
||||||
|
if (timestamps != null && closes != null) {
|
||||||
|
for (int i = 0; i < timestamps.size(); i++) {
|
||||||
|
long ts = timestamps.get(i).asLong();
|
||||||
|
// Convert timestamp to LocalDate in UTC to match targetDate logic
|
||||||
|
LocalDate tsDate = java.time.Instant.ofEpochSecond(ts).atZone(java.time.ZoneOffset.UTC).toLocalDate();
|
||||||
|
|
||||||
|
if (tsDate.equals(date)) {
|
||||||
|
JsonNode closeNode = closes.get(i);
|
||||||
|
if (closeNode != null && !closeNode.isNull()) {
|
||||||
|
return closeNode.asDouble();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
} catch (Exception e) {
|
||||||
|
System.out.println("Error fetching historical price: " + e.getMessage());
|
||||||
|
}
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,31 @@
|
|||||||
|
spring:
|
||||||
|
application:
|
||||||
|
name: stock-analyzer
|
||||||
|
data:
|
||||||
|
mongodb:
|
||||||
|
uri: ${MONGO_URI:mongodb://localhost:27017/stock_analyzer}
|
||||||
|
database: stock_analyzer
|
||||||
|
|
||||||
|
server:
|
||||||
|
port: 8080
|
||||||
|
|
||||||
|
# API Keys (from environment variables)
|
||||||
|
api:
|
||||||
|
openai:
|
||||||
|
key: ${OPENAI_API_KEY:}
|
||||||
|
model: ${OPENAI_MODEL:gpt-4o}
|
||||||
|
anthropic:
|
||||||
|
key: ${ANTHROPIC_API_KEY:}
|
||||||
|
model: ${ANTHROPIC_MODEL:claude-sonnet-4-5}
|
||||||
|
news:
|
||||||
|
key: ${NEWS_API_KEY:}
|
||||||
|
|
||||||
|
# CORS Configuration
|
||||||
|
cors:
|
||||||
|
allowed-origins: ${CORS_ORIGINS:http://localhost:5173,http://localhost:3000,http://localhost,http://127.0.0.1,http://192.168.178.42:3000}
|
||||||
|
|
||||||
|
# Logging
|
||||||
|
logging:
|
||||||
|
level:
|
||||||
|
com.stockanalyzer: INFO
|
||||||
|
org.springframework.data.mongodb: DEBUG
|
||||||
Executable
+45
@@ -0,0 +1,45 @@
|
|||||||
|
#!/bin/bash
|
||||||
|
|
||||||
|
# Exit on error
|
||||||
|
set -e
|
||||||
|
|
||||||
|
# Check if username is provided
|
||||||
|
|
||||||
|
if [ -z "$1" ]; then
|
||||||
|
echo "Usage: ./build-and-push.sh <docker-hub-username> [version]"
|
||||||
|
exit 1
|
||||||
|
fi
|
||||||
|
|
||||||
|
USERNAME=$1
|
||||||
|
VERSION=${2:-latest}
|
||||||
|
|
||||||
|
echo "Building and pushing for Docker Hub user: $USERNAME"
|
||||||
|
|
||||||
|
# Build Backend
|
||||||
|
echo "=========================================="
|
||||||
|
echo "Building Backend..."
|
||||||
|
echo "=========================================="
|
||||||
|
cd backend
|
||||||
|
docker build -t $USERNAME/stock-analyzer-backend:$VERSION .
|
||||||
|
cd ..
|
||||||
|
|
||||||
|
# Build Frontend
|
||||||
|
echo "=========================================="
|
||||||
|
echo "Building Frontend..."
|
||||||
|
echo "=========================================="
|
||||||
|
cd frontend
|
||||||
|
docker build -t $USERNAME/stock-analyzer-frontend:$VERSION .
|
||||||
|
cd ..
|
||||||
|
|
||||||
|
# Push Images
|
||||||
|
echo "=========================================="
|
||||||
|
echo "Pushing Images to Docker Hub..."
|
||||||
|
echo "=========================================="
|
||||||
|
docker push $USERNAME/stock-analyzer-backend:$VERSION
|
||||||
|
docker push $USERNAME/stock-analyzer-frontend:$VERSION
|
||||||
|
|
||||||
|
echo "=========================================="
|
||||||
|
echo "Done! Images pushed:"
|
||||||
|
echo " - $USERNAME/stock-analyzer-backend:$VERSION"
|
||||||
|
echo " - $USERNAME/stock-analyzer-frontend:$VERSION"
|
||||||
|
echo "=========================================="
|
||||||
@@ -0,0 +1,51 @@
|
|||||||
|
version: '3.8'
|
||||||
|
|
||||||
|
services:
|
||||||
|
mongodb:
|
||||||
|
image: mongo:latest
|
||||||
|
container_name: stock-analyzer-mongodb
|
||||||
|
ports:
|
||||||
|
- "27017:27017"
|
||||||
|
volumes:
|
||||||
|
- mongodb_data:/data/db
|
||||||
|
networks:
|
||||||
|
- stock-analyzer-network
|
||||||
|
|
||||||
|
backend:
|
||||||
|
build:
|
||||||
|
context: ./backend
|
||||||
|
dockerfile: Dockerfile
|
||||||
|
container_name: stock-analyzer-backend
|
||||||
|
ports:
|
||||||
|
- "8080:8080"
|
||||||
|
environment:
|
||||||
|
- MONGO_URI=mongodb://mongodb:27017/stock_analyzer
|
||||||
|
- OPENAI_API_KEY=${OPENAI_API_KEY}
|
||||||
|
- OPENAI_MODEL=${OPENAI_MODEL:-gpt-4o}
|
||||||
|
- ANTHROPIC_API_KEY=${ANTHROPIC_API_KEY}
|
||||||
|
- ANTHROPIC_MODEL=${ANTHROPIC_MODEL:-claude-sonnet-4-5}
|
||||||
|
- NEWS_API_KEY=${NEWS_API_KEY}
|
||||||
|
depends_on:
|
||||||
|
- mongodb
|
||||||
|
networks:
|
||||||
|
- stock-analyzer-network
|
||||||
|
|
||||||
|
frontend:
|
||||||
|
build:
|
||||||
|
context: ./frontend
|
||||||
|
dockerfile: Dockerfile
|
||||||
|
container_name: stock-analyzer-frontend
|
||||||
|
ports:
|
||||||
|
- "80:80"
|
||||||
|
depends_on:
|
||||||
|
- backend
|
||||||
|
networks:
|
||||||
|
- stock-analyzer-network
|
||||||
|
|
||||||
|
volumes:
|
||||||
|
mongodb_data:
|
||||||
|
|
||||||
|
|
||||||
|
networks:
|
||||||
|
stock-analyzer-network:
|
||||||
|
driver: bridge
|
||||||
@@ -0,0 +1,6 @@
|
|||||||
|
OPENAI_API_KEY=your_openai_key
|
||||||
|
ANTHROPIC_API_KEY=your_anthropic_key
|
||||||
|
NEWS_API_KEY=your_newsapi_key
|
||||||
|
TWITTER_BEARER_TOKEN=your_twitter_token
|
||||||
|
OPENAI_MODEL=gpt-4o
|
||||||
|
ANTHROPIC_MODEL=claude-sonnet-4-5
|
||||||
@@ -0,0 +1,2 @@
|
|||||||
|
node_modules
|
||||||
|
dist
|
||||||
@@ -0,0 +1,16 @@
|
|||||||
|
# Build stage
|
||||||
|
FROM node:18-alpine AS build
|
||||||
|
WORKDIR /app
|
||||||
|
COPY package*.json ./
|
||||||
|
RUN npm install
|
||||||
|
COPY . .
|
||||||
|
RUN npm run build
|
||||||
|
|
||||||
|
# Production stage
|
||||||
|
FROM nginx:alpine
|
||||||
|
COPY --from=build /app/dist /usr/share/nginx/html
|
||||||
|
COPY nginx.conf /etc/nginx/conf.d/default.conf
|
||||||
|
|
||||||
|
EXPOSE 80
|
||||||
|
|
||||||
|
CMD ["nginx", "-g", "daemon off;"]
|
||||||
@@ -0,0 +1,16 @@
|
|||||||
|
<!doctype html>
|
||||||
|
<html lang="en">
|
||||||
|
<head>
|
||||||
|
<meta charset="UTF-8" />
|
||||||
|
<link rel="icon" type="image/svg+xml" href="/vite.svg" />
|
||||||
|
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
|
||||||
|
<title>Stock Sentiment Analyzer</title>
|
||||||
|
<link rel="preconnect" href="https://fonts.googleapis.com">
|
||||||
|
<link rel="preconnect" href="https://fonts.gstatic.com" crossorigin>
|
||||||
|
<link href="https://fonts.googleapis.com/css2?family=Inter:wght@300;400;500;600;700&display=swap" rel="stylesheet">
|
||||||
|
</head>
|
||||||
|
<body>
|
||||||
|
<div id="app"></div>
|
||||||
|
<script type="module" src="/src/main.ts"></script>
|
||||||
|
</body>
|
||||||
|
</html>
|
||||||
@@ -0,0 +1,20 @@
|
|||||||
|
server {
|
||||||
|
listen 80;
|
||||||
|
server_name localhost;
|
||||||
|
root /usr/share/nginx/html;
|
||||||
|
index index.html;
|
||||||
|
|
||||||
|
location / {
|
||||||
|
try_files $uri $uri/ /index.html;
|
||||||
|
}
|
||||||
|
|
||||||
|
location /api {
|
||||||
|
proxy_pass http://192.168.178.42:9000;
|
||||||
|
proxy_http_version 1.1;
|
||||||
|
proxy_set_header Upgrade $http_upgrade;
|
||||||
|
proxy_set_header Connection 'upgrade';
|
||||||
|
proxy_set_header Host $host;
|
||||||
|
proxy_cache_bypass $http_upgrade;
|
||||||
|
proxy_read_timeout 300;
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,26 @@
|
|||||||
|
{
|
||||||
|
"name": "stock-analyzer-frontend",
|
||||||
|
"private": true,
|
||||||
|
"version": "0.0.1",
|
||||||
|
"type": "module",
|
||||||
|
"scripts": {
|
||||||
|
"dev": "vite",
|
||||||
|
"build": "vue-tsc && vite build",
|
||||||
|
"preview": "vite preview"
|
||||||
|
},
|
||||||
|
"dependencies": {
|
||||||
|
"axios": "^1.6.7",
|
||||||
|
"chart.js": "^4.4.1",
|
||||||
|
"pinia": "^2.1.7",
|
||||||
|
"vue": "^3.4.21",
|
||||||
|
"vue-chartjs": "^5.3.0",
|
||||||
|
"vue-router": "^4.3.0"
|
||||||
|
},
|
||||||
|
"devDependencies": {
|
||||||
|
"@types/node": "^24.10.1",
|
||||||
|
"@vitejs/plugin-vue": "^5.0.4",
|
||||||
|
"typescript": "~5.2.2",
|
||||||
|
"vite": "^5.1.6",
|
||||||
|
"vue-tsc": "^1.8.27"
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,91 @@
|
|||||||
|
<script setup lang="ts">
|
||||||
|
import { RouterView } from 'vue-router'
|
||||||
|
</script>
|
||||||
|
|
||||||
|
<template>
|
||||||
|
<div class="app-container">
|
||||||
|
<header class="app-header">
|
||||||
|
<div class="header-content">
|
||||||
|
<h1 class="app-title">
|
||||||
|
<span class="icon">📈</span>
|
||||||
|
Stock Sentiment Analyzer
|
||||||
|
</h1>
|
||||||
|
<!-- Navigation removed as we merged Dashboard into History -->
|
||||||
|
</div>
|
||||||
|
</header>
|
||||||
|
|
||||||
|
<main class="app-main">
|
||||||
|
<RouterView />
|
||||||
|
</main>
|
||||||
|
</div>
|
||||||
|
</template>
|
||||||
|
|
||||||
|
<style scoped>
|
||||||
|
.app-container {
|
||||||
|
min-height: 100vh;
|
||||||
|
background: linear-gradient(135deg, #0f0c29 0%, #302b63 50%, #24243e 100%);
|
||||||
|
}
|
||||||
|
|
||||||
|
.app-header {
|
||||||
|
background: rgba(255, 255, 255, 0.05);
|
||||||
|
backdrop-filter: blur(10px);
|
||||||
|
border-bottom: 1px solid rgba(255, 255, 255, 0.1);
|
||||||
|
position: sticky;
|
||||||
|
top: 0;
|
||||||
|
z-index: 100;
|
||||||
|
}
|
||||||
|
|
||||||
|
.header-content {
|
||||||
|
max-width: 1400px;
|
||||||
|
margin: 0 auto;
|
||||||
|
padding: 1.5rem 2rem;
|
||||||
|
display: flex;
|
||||||
|
justify-content: space-between;
|
||||||
|
align-items: center;
|
||||||
|
}
|
||||||
|
|
||||||
|
.app-title {
|
||||||
|
font-size: 1.5rem;
|
||||||
|
font-weight: 700;
|
||||||
|
color: #fff;
|
||||||
|
margin: 0;
|
||||||
|
display: flex;
|
||||||
|
align-items: center;
|
||||||
|
gap: 0.5rem;
|
||||||
|
}
|
||||||
|
|
||||||
|
.icon {
|
||||||
|
font-size: 1.8rem;
|
||||||
|
}
|
||||||
|
|
||||||
|
.app-nav {
|
||||||
|
display: flex;
|
||||||
|
gap: 1rem;
|
||||||
|
}
|
||||||
|
|
||||||
|
.nav-link {
|
||||||
|
padding: 0.5rem 1.5rem;
|
||||||
|
border-radius: 8px;
|
||||||
|
color: rgba(255, 255, 255, 0.7);
|
||||||
|
text-decoration: none;
|
||||||
|
font-weight: 500;
|
||||||
|
transition: all 0.3s ease;
|
||||||
|
position: relative;
|
||||||
|
}
|
||||||
|
|
||||||
|
.nav-link:hover {
|
||||||
|
color: #fff;
|
||||||
|
background: rgba(255, 255, 255, 0.1);
|
||||||
|
}
|
||||||
|
|
||||||
|
.nav-link.router-link-active {
|
||||||
|
color: #fff;
|
||||||
|
background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
|
||||||
|
}
|
||||||
|
|
||||||
|
.app-main {
|
||||||
|
max-width: 1400px;
|
||||||
|
margin: 0 auto;
|
||||||
|
padding: 2rem;
|
||||||
|
}
|
||||||
|
</style>
|
||||||
@@ -0,0 +1,307 @@
|
|||||||
|
<script setup lang="ts">
|
||||||
|
import { ref } from 'vue'
|
||||||
|
import type { AnalysisResult } from '../store'
|
||||||
|
|
||||||
|
defineProps<{
|
||||||
|
result: AnalysisResult
|
||||||
|
}>()
|
||||||
|
|
||||||
|
const expanded = ref(false)
|
||||||
|
</script>
|
||||||
|
|
||||||
|
<template>
|
||||||
|
<div class="analysis-card glass-card">
|
||||||
|
<!-- Header -->
|
||||||
|
<div class="card-header" @click="expanded = !expanded">
|
||||||
|
<div class="stock-header">
|
||||||
|
<h3 class="stock-symbol">{{ result.symbol }}</h3>
|
||||||
|
<p class="stock-isin">{{ result.isin }}</p>
|
||||||
|
</div>
|
||||||
|
<div class="predictions">
|
||||||
|
<span class="badge badge-info">
|
||||||
|
OpenAI: {{ result.llmAnalysisOpenai?.prediction || 'N/A' }}
|
||||||
|
</span>
|
||||||
|
<span class="badge badge-warning">
|
||||||
|
Anthropic: {{ result.llmAnalysisAnthropic?.prediction || 'N/A' }}
|
||||||
|
</span>
|
||||||
|
</div>
|
||||||
|
<button class="expand-btn">
|
||||||
|
{{ expanded ? '▼' : '▶' }}
|
||||||
|
</button>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<!-- Expanded Content -->
|
||||||
|
<div v-if="expanded" class="card-content">
|
||||||
|
<!-- Price Metrics -->
|
||||||
|
<div class="metrics-grid grid grid-cols-2 mb-3">
|
||||||
|
<div class="metric-card">
|
||||||
|
<div class="metric-label">Current Price</div>
|
||||||
|
<div class="metric-value">
|
||||||
|
{{ result.price !== null && result.price !== undefined ? '$' + result.price.toFixed(2) : 'N/A' }}
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
<div class="metric-card">
|
||||||
|
<div class="metric-label">24h Change</div>
|
||||||
|
<div
|
||||||
|
v-if="result.changePercent !== null && result.changePercent !== undefined"
|
||||||
|
class="metric-value"
|
||||||
|
:style="{ color: result.changePercent >= 0 ? '#4ade80' : '#f87171' }"
|
||||||
|
>
|
||||||
|
{{ result.changePercent >= 0 ? '▲' : '▼' }}
|
||||||
|
{{ Math.abs(result.changePercent).toFixed(2) }}%
|
||||||
|
</div>
|
||||||
|
<div v-else class="metric-value text-muted">N/A</div>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<!-- Fundamentals & Technicals -->
|
||||||
|
<div class="section mb-3">
|
||||||
|
<h4 class="section-title">Fundamentals & Technicals</h4>
|
||||||
|
<div class="grid grid-cols-4 gap-2">
|
||||||
|
<div class="metric-card">
|
||||||
|
<div class="metric-label">P/E Ratio</div>
|
||||||
|
<div class="metric-value" style="font-size: 1.1rem;">
|
||||||
|
{{ result.fundamentals?.peRatio || 'N/A' }}
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
<div class="metric-card">
|
||||||
|
<div class="metric-label">Market Cap</div>
|
||||||
|
<div class="metric-value" style="font-size: 1.1rem;">
|
||||||
|
{{ result.fundamentals?.marketCap && result.fundamentals.marketCap !== 'N/A' && !isNaN(Number(result.fundamentals.marketCap))
|
||||||
|
? '$' + (Number(result.fundamentals.marketCap) / 1e9).toFixed(2) + 'B'
|
||||||
|
: 'N/A' }}
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
<div class="metric-card">
|
||||||
|
<div class="metric-label">RSI (14)</div>
|
||||||
|
<div class="metric-value" style="font-size: 1.1rem;">
|
||||||
|
{{ result.technicals?.rsi && result.technicals.rsi !== 'N/A' && !isNaN(Number(result.technicals.rsi))
|
||||||
|
? Number(result.technicals.rsi).toFixed(2)
|
||||||
|
: 'N/A' }}
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
<div class="metric-card">
|
||||||
|
<div class="metric-label">SMA (20)</div>
|
||||||
|
<div class="metric-value" style="font-size: 1.1rem;">
|
||||||
|
{{ result.technicals?.sma20 && result.technicals.sma20 !== 'N/A' && !isNaN(Number(result.technicals.sma20))
|
||||||
|
? '$' + Number(result.technicals.sma20).toFixed(2)
|
||||||
|
: 'N/A' }}
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<div class="grid grid-cols-2 gap-2 mt-2">
|
||||||
|
<div class="metric-card">
|
||||||
|
<div class="metric-label">Analyst Rating</div>
|
||||||
|
<div class="metric-value" style="font-size: 1rem; text-transform: uppercase;">
|
||||||
|
{{ result.fundamentals?.recommendationKey || 'N/A' }}
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
<div class="metric-card">
|
||||||
|
<div class="metric-label">Target Price</div>
|
||||||
|
<div class="metric-value" style="font-size: 1rem;">
|
||||||
|
{{ result.fundamentals?.targetMeanPrice && result.fundamentals.targetMeanPrice !== 'N/A' && !isNaN(Number(result.fundamentals.targetMeanPrice))
|
||||||
|
? '$' + Number(result.fundamentals.targetMeanPrice).toFixed(2)
|
||||||
|
: 'N/A' }}
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<!-- AI Analysis -->
|
||||||
|
<div class="section mb-3">
|
||||||
|
<h4 class="section-title">AI Analysis</h4>
|
||||||
|
|
||||||
|
<!-- OpenAI -->
|
||||||
|
<div class="analysis-box mb-2">
|
||||||
|
<div class="analysis-header">
|
||||||
|
<span class="badge badge-info">OpenAI (GPT-4o)</span>
|
||||||
|
</div>
|
||||||
|
<div class="analysis-content" v-if="result.llmAnalysisOpenai">
|
||||||
|
<div class="flex gap-2 mb-2">
|
||||||
|
<div class="metric-card" style="flex: 1;">
|
||||||
|
<div class="metric-label">Prediction</div>
|
||||||
|
<div class="metric-value" style="font-size: 1.1rem;">
|
||||||
|
{{ result.llmAnalysisOpenai.prediction }}
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
<div class="metric-card" style="flex: 1;">
|
||||||
|
<div class="metric-label">Probability</div>
|
||||||
|
<div class="metric-value" style="font-size: 1.1rem;">
|
||||||
|
{{ result.llmAnalysisOpenai.probability }}%
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
<div class="reasoning">
|
||||||
|
<strong>Reasoning:</strong> {{ result.llmAnalysisOpenai.reasoning }}
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
<div class="analysis-content" v-else>
|
||||||
|
<div class="text-muted">Analysis not available</div>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<!-- Anthropic -->
|
||||||
|
<div class="analysis-box">
|
||||||
|
<div class="analysis-header">
|
||||||
|
<span class="badge badge-warning">Anthropic (Claude Sonnet 4.5)</span>
|
||||||
|
</div>
|
||||||
|
<div class="analysis-content" v-if="result.llmAnalysisAnthropic">
|
||||||
|
<div class="flex gap-2 mb-2">
|
||||||
|
<div class="metric-card" style="flex: 1;">
|
||||||
|
<div class="metric-label">Prediction</div>
|
||||||
|
<div class="metric-value" style="font-size: 1.1rem;">
|
||||||
|
{{ result.llmAnalysisAnthropic.prediction }}
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
<div class="metric-card" style="flex: 1;">
|
||||||
|
<div class="metric-label">Probability</div>
|
||||||
|
<div class="metric-value" style="font-size: 1.1rem;">
|
||||||
|
{{ result.llmAnalysisAnthropic.probability }}%
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
<div class="reasoning">
|
||||||
|
<strong>Reasoning:</strong> {{ result.llmAnalysisAnthropic.reasoning }}
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
<div class="analysis-content" v-else>
|
||||||
|
<div class="text-muted">Analysis not available</div>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<!-- News & Sentiment -->
|
||||||
|
<div class="section">
|
||||||
|
<h4 class="section-title">News & Sentiment</h4>
|
||||||
|
|
||||||
|
<div class="mb-2">
|
||||||
|
<h5 class="subsection-title">Recent Headlines</h5>
|
||||||
|
<ul class="news-list">
|
||||||
|
<li v-for="(headline, index) in result.newsHeadlines.slice(0, 3)" :key="index">
|
||||||
|
{{ headline }}
|
||||||
|
</li>
|
||||||
|
</ul>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<div>
|
||||||
|
<h5 class="subsection-title">Web Sentiment</h5>
|
||||||
|
<ul class="news-list">
|
||||||
|
<li v-for="(post, index) in result.socialPosts.slice(0, 3)" :key="index">
|
||||||
|
{{ post.substring(0, 200) }}...
|
||||||
|
</li>
|
||||||
|
</ul>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
</template>
|
||||||
|
|
||||||
|
<style scoped>
|
||||||
|
.analysis-card {
|
||||||
|
cursor: pointer;
|
||||||
|
transition: all var(--transition-base);
|
||||||
|
}
|
||||||
|
|
||||||
|
.card-header {
|
||||||
|
display: flex;
|
||||||
|
align-items: center;
|
||||||
|
gap: 1rem;
|
||||||
|
}
|
||||||
|
|
||||||
|
.stock-header {
|
||||||
|
flex: 1;
|
||||||
|
}
|
||||||
|
|
||||||
|
.stock-symbol {
|
||||||
|
color: var(--text-primary);
|
||||||
|
font-size: 1.25rem;
|
||||||
|
margin: 0;
|
||||||
|
}
|
||||||
|
|
||||||
|
.stock-isin {
|
||||||
|
color: var(--text-muted);
|
||||||
|
font-size: 0.875rem;
|
||||||
|
margin: 0.25rem 0 0 0;
|
||||||
|
}
|
||||||
|
|
||||||
|
.predictions {
|
||||||
|
display: flex;
|
||||||
|
gap: 0.5rem;
|
||||||
|
}
|
||||||
|
|
||||||
|
.expand-btn {
|
||||||
|
background: none;
|
||||||
|
border: none;
|
||||||
|
color: var(--text-secondary);
|
||||||
|
font-size: 1.2rem;
|
||||||
|
cursor: pointer;
|
||||||
|
padding: 0.5rem;
|
||||||
|
transition: transform var(--transition-base);
|
||||||
|
}
|
||||||
|
|
||||||
|
.card-content {
|
||||||
|
margin-top: 1.5rem;
|
||||||
|
padding-top: 1.5rem;
|
||||||
|
border-top: 1px solid var(--glass-border);
|
||||||
|
}
|
||||||
|
|
||||||
|
.section {
|
||||||
|
padding: 1rem;
|
||||||
|
background: rgba(255, 255, 255, 0.02);
|
||||||
|
border-radius: var(--radius-md);
|
||||||
|
}
|
||||||
|
|
||||||
|
.section-title {
|
||||||
|
color: var(--text-primary);
|
||||||
|
font-size: 1.1rem;
|
||||||
|
margin-bottom: 1rem;
|
||||||
|
}
|
||||||
|
|
||||||
|
.subsection-title {
|
||||||
|
color: var(--text-secondary);
|
||||||
|
font-size: 0.95rem;
|
||||||
|
margin-bottom: 0.5rem;
|
||||||
|
}
|
||||||
|
|
||||||
|
.metrics-grid {
|
||||||
|
gap: 1rem;
|
||||||
|
}
|
||||||
|
|
||||||
|
.analysis-box {
|
||||||
|
background: rgba(255, 255, 255, 0.03);
|
||||||
|
border-radius: var(--radius-md);
|
||||||
|
padding: 1rem;
|
||||||
|
}
|
||||||
|
|
||||||
|
.analysis-header {
|
||||||
|
margin-bottom: 1rem;
|
||||||
|
}
|
||||||
|
|
||||||
|
.analysis-content {
|
||||||
|
color: var(--text-secondary);
|
||||||
|
}
|
||||||
|
|
||||||
|
.reasoning {
|
||||||
|
color: var(--text-secondary);
|
||||||
|
line-height: 1.6;
|
||||||
|
font-size: 0.9rem;
|
||||||
|
}
|
||||||
|
|
||||||
|
.news-list {
|
||||||
|
list-style: none;
|
||||||
|
padding: 0;
|
||||||
|
}
|
||||||
|
|
||||||
|
.news-list li {
|
||||||
|
color: var(--text-secondary);
|
||||||
|
font-size: 0.875rem;
|
||||||
|
padding: 0.5rem 0;
|
||||||
|
border-bottom: 1px solid rgba(255, 255, 255, 0.05);
|
||||||
|
line-height: 1.5;
|
||||||
|
}
|
||||||
|
|
||||||
|
.news-list li:last-child {
|
||||||
|
border-bottom: none;
|
||||||
|
}
|
||||||
|
</style>
|
||||||
@@ -0,0 +1,228 @@
|
|||||||
|
<script setup lang="ts">
|
||||||
|
import { ref, onMounted } from 'vue'
|
||||||
|
import { useStockStore } from '../store'
|
||||||
|
|
||||||
|
const store = useStockStore()
|
||||||
|
const newIsin = ref('')
|
||||||
|
const adding = ref(false)
|
||||||
|
|
||||||
|
onMounted(async () => {
|
||||||
|
await store.fetchWatchlist()
|
||||||
|
})
|
||||||
|
|
||||||
|
async function handleAdd() {
|
||||||
|
if (!newIsin.value.trim()) {
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
adding.value = true
|
||||||
|
try {
|
||||||
|
await store.addToWatchlist(newIsin.value.trim().toUpperCase())
|
||||||
|
newIsin.value = ''
|
||||||
|
} catch (error: any) {
|
||||||
|
alert('Error adding stock: ' + (error.response?.data?.error || error.message))
|
||||||
|
} finally {
|
||||||
|
adding.value = false
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
async function handleRemove(isin: string) {
|
||||||
|
if (!confirm(`Remove ${isin} from watchlist?`)) {
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
try {
|
||||||
|
await store.removeFromWatchlist(isin)
|
||||||
|
} catch (error: any) {
|
||||||
|
alert('Error removing stock: ' + error.message)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
</script>
|
||||||
|
|
||||||
|
<template>
|
||||||
|
<div class="sidebar glass-card">
|
||||||
|
<h2 class="sidebar-title">Watchlist</h2>
|
||||||
|
|
||||||
|
<!-- Add ISIN Form -->
|
||||||
|
<div class="add-form">
|
||||||
|
<input
|
||||||
|
v-model="newIsin"
|
||||||
|
type="text"
|
||||||
|
placeholder="Enter ISIN (e.g., US0378331005)"
|
||||||
|
class="input"
|
||||||
|
@keyup.enter="handleAdd"
|
||||||
|
:disabled="adding"
|
||||||
|
/>
|
||||||
|
<button
|
||||||
|
@click="handleAdd"
|
||||||
|
:disabled="adding || !newIsin.trim()"
|
||||||
|
class="btn btn-primary btn-sm"
|
||||||
|
style="width: 100%; margin-top: 0.5rem;"
|
||||||
|
>
|
||||||
|
{{ adding ? 'Adding...' : '➕ Add Stock' }}
|
||||||
|
</button>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<!-- Watchlist Items -->
|
||||||
|
<div class="watchlist-section">
|
||||||
|
<div class="watchlist-header">
|
||||||
|
<span class="text-secondary">Stocks ({{ store.watchlist.length }})</span>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<div v-if="store.watchlist.length === 0" class="empty-state">
|
||||||
|
<p class="text-muted" style="font-size: 0.875rem;">No stocks in watchlist</p>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<div v-else class="watchlist-items">
|
||||||
|
<div
|
||||||
|
v-for="stock in store.watchlist"
|
||||||
|
:key="stock.isin"
|
||||||
|
class="watchlist-item"
|
||||||
|
>
|
||||||
|
<div class="stock-info">
|
||||||
|
<div class="stock-name">{{ stock.name || stock.symbol }}</div>
|
||||||
|
<div class="stock-isin">{{ stock.isin }}</div>
|
||||||
|
</div>
|
||||||
|
<button
|
||||||
|
@click="handleRemove(stock.isin)"
|
||||||
|
class="btn-remove"
|
||||||
|
title="Remove from watchlist"
|
||||||
|
>
|
||||||
|
❌
|
||||||
|
</button>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<!-- API Status -->
|
||||||
|
<div class="api-status">
|
||||||
|
<div class="status-header text-secondary">API Status</div>
|
||||||
|
<div class="status-items">
|
||||||
|
<div class="status-item">
|
||||||
|
<span>✅ OpenAI</span>
|
||||||
|
</div>
|
||||||
|
<div class="status-item">
|
||||||
|
<span>✅ Anthropic</span>
|
||||||
|
</div>
|
||||||
|
<div class="status-item">
|
||||||
|
<span>✅ NewsAPI</span>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
</template>
|
||||||
|
|
||||||
|
<style scoped>
|
||||||
|
.sidebar {
|
||||||
|
position: sticky;
|
||||||
|
top: 100px;
|
||||||
|
padding: 1.5rem;
|
||||||
|
max-height: calc(100vh - 120px);
|
||||||
|
overflow-y: auto;
|
||||||
|
}
|
||||||
|
|
||||||
|
.sidebar-title {
|
||||||
|
color: var(--text-primary);
|
||||||
|
margin-bottom: 1.5rem;
|
||||||
|
font-size: 1.25rem;
|
||||||
|
}
|
||||||
|
|
||||||
|
.add-form {
|
||||||
|
margin-bottom: 1.5rem;
|
||||||
|
padding-bottom: 1.5rem;
|
||||||
|
border-bottom: 1px solid var(--glass-border);
|
||||||
|
}
|
||||||
|
|
||||||
|
.watchlist-section {
|
||||||
|
margin-bottom: 1.5rem;
|
||||||
|
padding-bottom: 1.5rem;
|
||||||
|
border-bottom: 1px solid var(--glass-border);
|
||||||
|
}
|
||||||
|
|
||||||
|
.watchlist-header {
|
||||||
|
margin-bottom: 1rem;
|
||||||
|
font-weight: 600;
|
||||||
|
}
|
||||||
|
|
||||||
|
.empty-state {
|
||||||
|
text-align: center;
|
||||||
|
padding: 1rem;
|
||||||
|
}
|
||||||
|
|
||||||
|
.watchlist-items {
|
||||||
|
display: flex;
|
||||||
|
flex-direction: column;
|
||||||
|
gap: 0.75rem;
|
||||||
|
}
|
||||||
|
|
||||||
|
.watchlist-item {
|
||||||
|
display: flex;
|
||||||
|
justify-content: space-between;
|
||||||
|
align-items: center;
|
||||||
|
padding: 0.75rem;
|
||||||
|
background: rgba(255, 255, 255, 0.03);
|
||||||
|
border-radius: var(--radius-md);
|
||||||
|
border: 1px solid rgba(255, 255, 255, 0.05);
|
||||||
|
transition: all var(--transition-base);
|
||||||
|
}
|
||||||
|
|
||||||
|
.watchlist-item:hover {
|
||||||
|
background: rgba(255, 255, 255, 0.05);
|
||||||
|
border-color: rgba(255, 255, 255, 0.1);
|
||||||
|
}
|
||||||
|
|
||||||
|
.stock-info {
|
||||||
|
flex: 1;
|
||||||
|
min-width: 0;
|
||||||
|
}
|
||||||
|
|
||||||
|
.stock-name {
|
||||||
|
color: var(--text-primary);
|
||||||
|
font-weight: 600;
|
||||||
|
font-size: 0.9rem;
|
||||||
|
white-space: nowrap;
|
||||||
|
overflow: hidden;
|
||||||
|
text-overflow: ellipsis;
|
||||||
|
}
|
||||||
|
|
||||||
|
.stock-isin {
|
||||||
|
color: var(--text-muted);
|
||||||
|
font-size: 0.75rem;
|
||||||
|
margin-top: 0.125rem;
|
||||||
|
}
|
||||||
|
|
||||||
|
.btn-remove {
|
||||||
|
background: none;
|
||||||
|
border: none;
|
||||||
|
cursor: pointer;
|
||||||
|
font-size: 1rem;
|
||||||
|
opacity: 0.6;
|
||||||
|
transition: opacity var(--transition-fast);
|
||||||
|
padding: 0.25rem;
|
||||||
|
}
|
||||||
|
|
||||||
|
.btn-remove:hover {
|
||||||
|
opacity: 1;
|
||||||
|
}
|
||||||
|
|
||||||
|
.api-status {
|
||||||
|
padding-top: 1rem;
|
||||||
|
}
|
||||||
|
|
||||||
|
.status-header {
|
||||||
|
font-weight: 600;
|
||||||
|
margin-bottom: 0.75rem;
|
||||||
|
font-size: 0.875rem;
|
||||||
|
}
|
||||||
|
|
||||||
|
.status-items {
|
||||||
|
display: flex;
|
||||||
|
flex-direction: column;
|
||||||
|
gap: 0.5rem;
|
||||||
|
}
|
||||||
|
|
||||||
|
.status-item {
|
||||||
|
font-size: 0.875rem;
|
||||||
|
color: var(--text-secondary);
|
||||||
|
}
|
||||||
|
</style>
|
||||||
@@ -0,0 +1,12 @@
|
|||||||
|
import { createApp } from 'vue'
|
||||||
|
import { createPinia } from 'pinia'
|
||||||
|
import router from './router/index'
|
||||||
|
import App from './App.vue'
|
||||||
|
import './style.css'
|
||||||
|
|
||||||
|
const app = createApp(App)
|
||||||
|
|
||||||
|
app.use(createPinia())
|
||||||
|
app.use(router)
|
||||||
|
|
||||||
|
app.mount('#app')
|
||||||
@@ -0,0 +1,15 @@
|
|||||||
|
import { createRouter, createWebHistory } from 'vue-router'
|
||||||
|
import History from '../views/History.vue'
|
||||||
|
|
||||||
|
const router = createRouter({
|
||||||
|
history: createWebHistory(import.meta.env.BASE_URL),
|
||||||
|
routes: [
|
||||||
|
{
|
||||||
|
path: '/',
|
||||||
|
name: 'history',
|
||||||
|
component: History
|
||||||
|
}
|
||||||
|
]
|
||||||
|
})
|
||||||
|
|
||||||
|
export default router
|
||||||
@@ -0,0 +1,278 @@
|
|||||||
|
import { defineStore } from 'pinia'
|
||||||
|
import axios from 'axios'
|
||||||
|
import { ref } from 'vue'
|
||||||
|
|
||||||
|
export interface Stock {
|
||||||
|
isin: string
|
||||||
|
symbol: string | null
|
||||||
|
name: string | null
|
||||||
|
addedAt: string
|
||||||
|
}
|
||||||
|
|
||||||
|
export interface LLMAnalysis {
|
||||||
|
prediction: string
|
||||||
|
probability: number
|
||||||
|
reasoning: string
|
||||||
|
error?: string
|
||||||
|
}
|
||||||
|
|
||||||
|
export interface Fundamentals {
|
||||||
|
peRatio: string
|
||||||
|
marketCap: string
|
||||||
|
high52w: string
|
||||||
|
low52w: string
|
||||||
|
targetMeanPrice: string
|
||||||
|
recommendationKey: string
|
||||||
|
}
|
||||||
|
|
||||||
|
export interface Technicals {
|
||||||
|
sma20: string
|
||||||
|
rsi: string
|
||||||
|
}
|
||||||
|
|
||||||
|
export interface MarketContext {
|
||||||
|
symbol: string
|
||||||
|
changePercent: number
|
||||||
|
price: number
|
||||||
|
}
|
||||||
|
|
||||||
|
export interface AnalysisResult {
|
||||||
|
id?: string
|
||||||
|
isin: string
|
||||||
|
symbol: string
|
||||||
|
price: number
|
||||||
|
realPrice?: number
|
||||||
|
changePercent: number
|
||||||
|
fundamentals: Fundamentals
|
||||||
|
technicals: Technicals
|
||||||
|
marketContext: MarketContext | null
|
||||||
|
newsHeadlines: string[]
|
||||||
|
socialPosts: string[]
|
||||||
|
llmAnalysisOpenai: LLMAnalysis
|
||||||
|
llmAnalysisAnthropic: LLMAnalysis
|
||||||
|
analyzedAt: string
|
||||||
|
date: string
|
||||||
|
targetDate: string
|
||||||
|
}
|
||||||
|
|
||||||
|
export interface AnalysisJob {
|
||||||
|
id: string
|
||||||
|
isin: string
|
||||||
|
symbol: string
|
||||||
|
status: 'PENDING' | 'PROCESSING' | 'COMPLETED' | 'FAILED' | 'CANCELLED'
|
||||||
|
error?: string
|
||||||
|
createdAt: string
|
||||||
|
startedAt?: string
|
||||||
|
completedAt?: string
|
||||||
|
}
|
||||||
|
|
||||||
|
export const useStockStore = defineStore('stock', () => {
|
||||||
|
const watchlist = ref<Stock[]>([])
|
||||||
|
const analysisResults = ref<AnalysisResult[]>([])
|
||||||
|
const analysisJobs = ref<AnalysisJob[]>([])
|
||||||
|
const marketContext = ref<MarketContext | null>(null)
|
||||||
|
const loading = ref(false)
|
||||||
|
const error = ref<string | null>(null)
|
||||||
|
|
||||||
|
const apiClient = axios.create({
|
||||||
|
baseURL: '/api'
|
||||||
|
})
|
||||||
|
|
||||||
|
async function fetchWatchlist() {
|
||||||
|
try {
|
||||||
|
const response = await apiClient.get<Stock[]>('/watchlist')
|
||||||
|
watchlist.value = response.data
|
||||||
|
} catch (e: any) {
|
||||||
|
error.value = e.message
|
||||||
|
throw e
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
async function addToWatchlist(isin: string) {
|
||||||
|
try {
|
||||||
|
loading.value = true
|
||||||
|
await apiClient.post('/watchlist', { isin })
|
||||||
|
await fetchWatchlist()
|
||||||
|
} catch (e: any) {
|
||||||
|
error.value = e.response?.data?.error || e.message
|
||||||
|
throw e
|
||||||
|
} finally {
|
||||||
|
loading.value = false
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
async function removeFromWatchlist(isin: string) {
|
||||||
|
try {
|
||||||
|
await apiClient.delete(`/watchlist/${isin}`)
|
||||||
|
await fetchWatchlist()
|
||||||
|
} catch (e: any) {
|
||||||
|
error.value = e.message
|
||||||
|
throw e
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
async function startAnalysis(isin?: string) {
|
||||||
|
try {
|
||||||
|
loading.value = true
|
||||||
|
error.value = null
|
||||||
|
|
||||||
|
const url = isin ? `/analysis/run/${isin}` : '/analysis/run'
|
||||||
|
// This now returns a list of created jobs
|
||||||
|
const response = await apiClient.post<AnalysisJob[]>(url)
|
||||||
|
analysisJobs.value = response.data
|
||||||
|
|
||||||
|
// Start polling
|
||||||
|
pollJobs()
|
||||||
|
|
||||||
|
return response.data
|
||||||
|
} catch (e: any) {
|
||||||
|
error.value = e.message
|
||||||
|
loading.value = false // Stop loading if start failed
|
||||||
|
throw e
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
async function stopAnalysis() {
|
||||||
|
try {
|
||||||
|
await apiClient.post('/analysis/stop')
|
||||||
|
await fetchJobs() // Refresh status immediately
|
||||||
|
} catch (e: any) {
|
||||||
|
error.value = e.message
|
||||||
|
throw e
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
async function fetchJobs() {
|
||||||
|
try {
|
||||||
|
const response = await apiClient.get<AnalysisJob[]>('/analysis/jobs')
|
||||||
|
analysisJobs.value = response.data
|
||||||
|
|
||||||
|
// If there are active jobs, set loading to true and start polling
|
||||||
|
const hasActiveJobs = analysisJobs.value.some(job =>
|
||||||
|
job.status === 'PENDING' || job.status === 'PROCESSING'
|
||||||
|
)
|
||||||
|
|
||||||
|
if (hasActiveJobs) {
|
||||||
|
loading.value = true
|
||||||
|
pollJobs()
|
||||||
|
}
|
||||||
|
} catch (e) {
|
||||||
|
console.error("Failed to fetch jobs", e)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
let pollingInterval: any = null
|
||||||
|
|
||||||
|
async function pollJobs() {
|
||||||
|
if (pollingInterval) return // Already polling
|
||||||
|
|
||||||
|
pollingInterval = setInterval(async () => {
|
||||||
|
try {
|
||||||
|
const response = await apiClient.get<AnalysisJob[]>('/analysis/jobs')
|
||||||
|
analysisJobs.value = response.data
|
||||||
|
|
||||||
|
// Check if all jobs are done (COMPLETED or FAILED)
|
||||||
|
const hasActiveJobs = analysisJobs.value.some(job =>
|
||||||
|
job.status === 'PENDING' || job.status === 'PROCESSING'
|
||||||
|
)
|
||||||
|
|
||||||
|
if (!hasActiveJobs) {
|
||||||
|
clearInterval(pollingInterval)
|
||||||
|
pollingInterval = null
|
||||||
|
loading.value = false
|
||||||
|
|
||||||
|
// Fetch latest results to show them
|
||||||
|
const latestResults = await fetchHistory()
|
||||||
|
analysisResults.value = latestResults.filter(r =>
|
||||||
|
analysisJobs.value.some(j => j.isin === r.isin && j.status === 'COMPLETED')
|
||||||
|
)
|
||||||
|
}
|
||||||
|
} catch (e) {
|
||||||
|
console.error("Polling failed", e)
|
||||||
|
}
|
||||||
|
}, 2000)
|
||||||
|
}
|
||||||
|
|
||||||
|
async function fetchMarketContext() {
|
||||||
|
try {
|
||||||
|
const response = await apiClient.get<MarketContext & { error?: string }>('/analysis/market-context')
|
||||||
|
if (!response.data.error) {
|
||||||
|
marketContext.value = response.data as MarketContext
|
||||||
|
}
|
||||||
|
} catch (e: any) {
|
||||||
|
console.error('Failed to fetch market context:', e)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
async function fetchHistory() {
|
||||||
|
try {
|
||||||
|
const response = await apiClient.get<AnalysisResult[]>('/analysis/history')
|
||||||
|
return response.data
|
||||||
|
} catch (e: any) {
|
||||||
|
error.value = e.message
|
||||||
|
throw e
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
async function fetchHistoryByIsin(isin: string) {
|
||||||
|
try {
|
||||||
|
const response = await apiClient.get<AnalysisResult[]>(`/analysis/history/${isin}`)
|
||||||
|
return response.data
|
||||||
|
} catch (e: any) {
|
||||||
|
error.value = e.message
|
||||||
|
throw e
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
async function deleteHistoryByDateRange(startDate: string, endDate: string) {
|
||||||
|
try {
|
||||||
|
const response = await apiClient.delete('/analysis/history', {
|
||||||
|
data: { startDate, endDate }
|
||||||
|
})
|
||||||
|
return response.data
|
||||||
|
} catch (e: any) {
|
||||||
|
error.value = e.message
|
||||||
|
throw e
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
async function getHistoricalPrice(symbol: string, date: string) {
|
||||||
|
try {
|
||||||
|
const response = await apiClient.get(`/analysis/historical-price/${symbol}/${date}`)
|
||||||
|
return response.data.price || null
|
||||||
|
} catch (e: any) {
|
||||||
|
return null
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
async function refreshRealPrice(id: string) {
|
||||||
|
try {
|
||||||
|
const response = await apiClient.post<AnalysisResult>(`/analysis/history/${id}/refresh-price`)
|
||||||
|
return response.data
|
||||||
|
} catch (e: any) {
|
||||||
|
throw e
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
return {
|
||||||
|
watchlist,
|
||||||
|
analysisResults,
|
||||||
|
analysisJobs,
|
||||||
|
marketContext,
|
||||||
|
loading,
|
||||||
|
error,
|
||||||
|
fetchWatchlist,
|
||||||
|
addToWatchlist,
|
||||||
|
removeFromWatchlist,
|
||||||
|
startAnalysis,
|
||||||
|
stopAnalysis,
|
||||||
|
fetchJobs,
|
||||||
|
fetchMarketContext,
|
||||||
|
fetchHistory,
|
||||||
|
fetchHistoryByIsin,
|
||||||
|
deleteHistoryByDateRange,
|
||||||
|
getHistoricalPrice,
|
||||||
|
refreshRealPrice
|
||||||
|
}
|
||||||
|
})
|
||||||
@@ -0,0 +1,394 @@
|
|||||||
|
:root {
|
||||||
|
/* Color Palette */
|
||||||
|
--primary-gradient: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
|
||||||
|
--secondary-gradient: linear-gradient(135deg, #f093fb 0%, #f5576c 100%);
|
||||||
|
--success-gradient: linear-gradient(135deg, #4facfe 0%, #00f2fe 100%);
|
||||||
|
--danger-gradient: linear-gradient(135deg, #fa709a 0%, #fee140 100%);
|
||||||
|
|
||||||
|
--bg-primary: #0f0c29;
|
||||||
|
--bg-secondary: #302b63;
|
||||||
|
--bg-tertiary: #24243e;
|
||||||
|
|
||||||
|
--text-primary: #ffffff;
|
||||||
|
--text-secondary: rgba(255, 255, 255, 0.7);
|
||||||
|
--text-muted: rgba(255, 255, 255, 0.5);
|
||||||
|
|
||||||
|
--glass-bg: rgba(255, 255, 255, 0.05);
|
||||||
|
--glass-border: rgba(255, 255, 255, 0.1);
|
||||||
|
|
||||||
|
/* Spacing */
|
||||||
|
--spacing-xs: 0.25rem;
|
||||||
|
--spacing-sm: 0.5rem;
|
||||||
|
--spacing-md: 1rem;
|
||||||
|
--spacing-lg: 1.5rem;
|
||||||
|
--spacing-xl: 2rem;
|
||||||
|
|
||||||
|
/* Border Radius */
|
||||||
|
--radius-sm: 4px;
|
||||||
|
--radius-md: 8px;
|
||||||
|
--radius-lg: 12px;
|
||||||
|
--radius-xl: 16px;
|
||||||
|
|
||||||
|
/* Shadows */
|
||||||
|
--shadow-sm: 0 2px 8px rgba(0, 0, 0, 0.1);
|
||||||
|
--shadow-md: 0 4px 16px rgba(0, 0, 0, 0.2);
|
||||||
|
--shadow-lg: 0 8px 32px rgba(0, 0, 0, 0.3);
|
||||||
|
|
||||||
|
/* Transitions */
|
||||||
|
--transition-fast: 0.15s ease;
|
||||||
|
--transition-base: 0.3s ease;
|
||||||
|
--transition-slow: 0.5s ease;
|
||||||
|
}
|
||||||
|
|
||||||
|
* {
|
||||||
|
margin: 0;
|
||||||
|
padding: 0;
|
||||||
|
box-sizing: border-box;
|
||||||
|
}
|
||||||
|
|
||||||
|
body {
|
||||||
|
font-family: 'Inter', -apple-system, BlinkMacSystemFont, 'Segoe UI', sans-serif;
|
||||||
|
color: var(--text-primary);
|
||||||
|
background: linear-gradient(135deg, var(--bg-primary) 0%, var(--bg-secondary) 50%, var(--bg-tertiary) 100%);
|
||||||
|
min-height: 100vh;
|
||||||
|
line-height: 1.6;
|
||||||
|
-webkit-font-smoothing: antialiased;
|
||||||
|
-moz-osx-font-smoothing: grayscale;
|
||||||
|
}
|
||||||
|
|
||||||
|
/* Glass Card */
|
||||||
|
.glass-card {
|
||||||
|
background: var(--glass-bg);
|
||||||
|
backdrop-filter: blur(10px);
|
||||||
|
border: 1px solid var(--glass-border);
|
||||||
|
border-radius: var(--radius-lg);
|
||||||
|
padding: var(--spacing-lg);
|
||||||
|
box-shadow: var(--shadow-md);
|
||||||
|
transition: all var(--transition-base);
|
||||||
|
}
|
||||||
|
|
||||||
|
.glass-card:hover {
|
||||||
|
transform: translateY(-2px);
|
||||||
|
box-shadow: var(--shadow-lg);
|
||||||
|
border-color: rgba(255, 255, 255, 0.2);
|
||||||
|
}
|
||||||
|
|
||||||
|
/* Buttons */
|
||||||
|
.btn {
|
||||||
|
padding: 0.75rem 1.5rem;
|
||||||
|
border: none;
|
||||||
|
border-radius: var(--radius-md);
|
||||||
|
font-weight: 600;
|
||||||
|
font-size: 0.95rem;
|
||||||
|
cursor: pointer;
|
||||||
|
transition: all var(--transition-base);
|
||||||
|
text-decoration: none;
|
||||||
|
display: inline-flex;
|
||||||
|
align-items: center;
|
||||||
|
justify-content: center;
|
||||||
|
gap: 0.5rem;
|
||||||
|
}
|
||||||
|
|
||||||
|
.btn-primary {
|
||||||
|
background: var(--primary-gradient);
|
||||||
|
color: white;
|
||||||
|
box-shadow: 0 4px 15px rgba(102, 126, 234, 0.4);
|
||||||
|
}
|
||||||
|
|
||||||
|
.btn-primary:hover {
|
||||||
|
transform: translateY(-2px);
|
||||||
|
box-shadow: 0 6px 20px rgba(102, 126, 234, 0.6);
|
||||||
|
}
|
||||||
|
|
||||||
|
.btn-primary:active {
|
||||||
|
transform: translateY(0);
|
||||||
|
}
|
||||||
|
|
||||||
|
.btn-secondary {
|
||||||
|
background: var(--glass-bg);
|
||||||
|
color: var(--text-primary);
|
||||||
|
border: 1px solid var(--glass-border);
|
||||||
|
}
|
||||||
|
|
||||||
|
.btn-secondary:hover {
|
||||||
|
background: rgba(255, 255, 255, 0.1);
|
||||||
|
border-color: rgba(255, 255, 255, 0.2);
|
||||||
|
}
|
||||||
|
|
||||||
|
.btn-danger {
|
||||||
|
background: var(--danger-gradient);
|
||||||
|
color: white;
|
||||||
|
box-shadow: 0 4px 15px rgba(250, 112, 154, 0.4);
|
||||||
|
}
|
||||||
|
|
||||||
|
.btn-danger:hover {
|
||||||
|
transform: translateY(-2px);
|
||||||
|
box-shadow: 0 6px 20px rgba(250, 112, 154, 0.6);
|
||||||
|
}
|
||||||
|
|
||||||
|
.btn-sm {
|
||||||
|
padding: 0.5rem 1rem;
|
||||||
|
font-size: 0.875rem;
|
||||||
|
}
|
||||||
|
|
||||||
|
.btn:disabled {
|
||||||
|
opacity: 0.5;
|
||||||
|
cursor: not-allowed;
|
||||||
|
transform: none !important;
|
||||||
|
}
|
||||||
|
|
||||||
|
/* Input Fields */
|
||||||
|
.input {
|
||||||
|
width: 100%;
|
||||||
|
padding: 0.75rem 1rem;
|
||||||
|
background: var(--glass-bg);
|
||||||
|
border: 1px solid var(--glass-border);
|
||||||
|
border-radius: var(--radius-md);
|
||||||
|
color: var(--text-primary);
|
||||||
|
font-size: 0.95rem;
|
||||||
|
transition: all var(--transition-base);
|
||||||
|
}
|
||||||
|
|
||||||
|
.input:focus {
|
||||||
|
outline: none;
|
||||||
|
border-color: #667eea;
|
||||||
|
box-shadow: 0 0 0 3px rgba(102, 126, 234, 0.1);
|
||||||
|
}
|
||||||
|
|
||||||
|
.input::placeholder {
|
||||||
|
color: var(--text-muted);
|
||||||
|
}
|
||||||
|
|
||||||
|
/* Metrics */
|
||||||
|
.metric-card {
|
||||||
|
background: var(--glass-bg);
|
||||||
|
backdrop-filter: blur(10px);
|
||||||
|
border: 1px solid var(--glass-border);
|
||||||
|
border-radius: var(--radius-md);
|
||||||
|
padding: var(--spacing-md);
|
||||||
|
text-align: center;
|
||||||
|
}
|
||||||
|
|
||||||
|
.metric-label {
|
||||||
|
font-size: 0.875rem;
|
||||||
|
color: var(--text-secondary);
|
||||||
|
margin-bottom: 0.5rem;
|
||||||
|
}
|
||||||
|
|
||||||
|
.metric-value {
|
||||||
|
font-size: 1.5rem;
|
||||||
|
font-weight: 700;
|
||||||
|
color: var(--text-primary);
|
||||||
|
}
|
||||||
|
|
||||||
|
.metric-change {
|
||||||
|
font-size: 0.875rem;
|
||||||
|
margin-top: 0.25rem;
|
||||||
|
}
|
||||||
|
|
||||||
|
.metric-change.positive {
|
||||||
|
color: #4ade80;
|
||||||
|
}
|
||||||
|
|
||||||
|
.metric-change.negative {
|
||||||
|
color: #f87171;
|
||||||
|
}
|
||||||
|
|
||||||
|
/* Tables */
|
||||||
|
.table-container {
|
||||||
|
overflow-x: auto;
|
||||||
|
border-radius: var(--radius-lg);
|
||||||
|
background: var(--glass-bg);
|
||||||
|
backdrop-filter: blur(10px);
|
||||||
|
border: 1px solid var(--glass-border);
|
||||||
|
}
|
||||||
|
|
||||||
|
table {
|
||||||
|
width: 100%;
|
||||||
|
border-collapse: collapse;
|
||||||
|
}
|
||||||
|
|
||||||
|
thead {
|
||||||
|
background: rgba(255, 255, 255, 0.05);
|
||||||
|
}
|
||||||
|
|
||||||
|
th {
|
||||||
|
padding: 1rem;
|
||||||
|
text-align: left;
|
||||||
|
font-weight: 600;
|
||||||
|
color: var(--text-primary);
|
||||||
|
border-bottom: 1px solid var(--glass-border);
|
||||||
|
}
|
||||||
|
|
||||||
|
td {
|
||||||
|
padding: 1rem;
|
||||||
|
color: var(--text-secondary);
|
||||||
|
border-bottom: 1px solid rgba(255, 255, 255, 0.05);
|
||||||
|
}
|
||||||
|
|
||||||
|
tbody tr {
|
||||||
|
transition: background var(--transition-fast);
|
||||||
|
}
|
||||||
|
|
||||||
|
tbody tr:hover {
|
||||||
|
background: rgba(255, 255, 255, 0.03);
|
||||||
|
}
|
||||||
|
|
||||||
|
/* Badges */
|
||||||
|
.badge {
|
||||||
|
display: inline-block;
|
||||||
|
padding: 0.25rem 0.75rem;
|
||||||
|
border-radius: var(--radius-sm);
|
||||||
|
font-size: 0.875rem;
|
||||||
|
font-weight: 600;
|
||||||
|
}
|
||||||
|
|
||||||
|
.badge-success {
|
||||||
|
background: linear-gradient(135deg, #4ade80 0%, #22c55e 100%);
|
||||||
|
color: white;
|
||||||
|
}
|
||||||
|
|
||||||
|
.badge-danger {
|
||||||
|
background: linear-gradient(135deg, #f87171 0%, #ef4444 100%);
|
||||||
|
color: white;
|
||||||
|
}
|
||||||
|
|
||||||
|
.badge-warning {
|
||||||
|
background: linear-gradient(135deg, #fbbf24 0%, #f59e0b 100%);
|
||||||
|
color: white;
|
||||||
|
}
|
||||||
|
|
||||||
|
.badge-info {
|
||||||
|
background: linear-gradient(135deg, #60a5fa 0%, #3b82f6 100%);
|
||||||
|
color: white;
|
||||||
|
}
|
||||||
|
|
||||||
|
/* Loading Spinner */
|
||||||
|
.spinner {
|
||||||
|
border: 3px solid var(--glass-border);
|
||||||
|
border-top: 3px solid #667eea;
|
||||||
|
border-radius: 50%;
|
||||||
|
width: 40px;
|
||||||
|
height: 40px;
|
||||||
|
animation: spin 1s linear infinite;
|
||||||
|
}
|
||||||
|
|
||||||
|
@keyframes spin {
|
||||||
|
0% { transform: rotate(0deg); }
|
||||||
|
100% { transform: rotate(360deg); }
|
||||||
|
}
|
||||||
|
|
||||||
|
/* Progress Bar */
|
||||||
|
.progress-bar {
|
||||||
|
width: 100%;
|
||||||
|
height: 8px;
|
||||||
|
background: var(--glass-bg);
|
||||||
|
border-radius: var(--radius-sm);
|
||||||
|
overflow: hidden;
|
||||||
|
}
|
||||||
|
|
||||||
|
.progress-fill {
|
||||||
|
height: 100%;
|
||||||
|
background: var(--primary-gradient);
|
||||||
|
transition: width var(--transition-base);
|
||||||
|
animation: shimmer 2s infinite;
|
||||||
|
}
|
||||||
|
|
||||||
|
@keyframes shimmer {
|
||||||
|
0% { opacity: 0.6; }
|
||||||
|
50% { opacity: 1; }
|
||||||
|
100% { opacity: 0.6; }
|
||||||
|
}
|
||||||
|
|
||||||
|
/* Alerts */
|
||||||
|
.alert {
|
||||||
|
padding: 1rem 1.5rem;
|
||||||
|
border-radius: var(--radius-md);
|
||||||
|
margin-bottom: var(--spacing-md);
|
||||||
|
display: flex;
|
||||||
|
align-items: center;
|
||||||
|
gap: 0.75rem;
|
||||||
|
}
|
||||||
|
|
||||||
|
.alert-info {
|
||||||
|
background: rgba(59, 130, 246, 0.1);
|
||||||
|
border: 1px solid rgba(59, 130, 246, 0.3);
|
||||||
|
color: #60a5fa;
|
||||||
|
}
|
||||||
|
|
||||||
|
.alert-success {
|
||||||
|
background: rgba(34, 197, 94, 0.1);
|
||||||
|
border: 1px solid rgba(34, 197, 94, 0.3);
|
||||||
|
color: #4ade80;
|
||||||
|
}
|
||||||
|
|
||||||
|
.alert-warning {
|
||||||
|
background: rgba(245, 158, 11, 0.1);
|
||||||
|
border: 1px solid rgba(245, 158, 11, 0.3);
|
||||||
|
color: #fbbf24;
|
||||||
|
}
|
||||||
|
|
||||||
|
.alert-error {
|
||||||
|
background: rgba(239, 68, 68, 0.1);
|
||||||
|
border: 1px solid rgba(239, 68, 68, 0.3);
|
||||||
|
color: #f87171;
|
||||||
|
}
|
||||||
|
|
||||||
|
/* Utility Classes */
|
||||||
|
.text-center { text-align: center; }
|
||||||
|
.text-right { text-align: right; }
|
||||||
|
.text-muted { color: var(--text-muted); }
|
||||||
|
.text-secondary { color: var(--text-secondary); }
|
||||||
|
|
||||||
|
.mt-1 { margin-top: var(--spacing-sm); }
|
||||||
|
.mt-2 { margin-top: var(--spacing-md); }
|
||||||
|
.mt-3 { margin-top: var(--spacing-lg); }
|
||||||
|
.mt-4 { margin-top: var(--spacing-xl); }
|
||||||
|
|
||||||
|
.mb-1 { margin-bottom: var(--spacing-sm); }
|
||||||
|
.mb-2 { margin-bottom: var(--spacing-md); }
|
||||||
|
.mb-3 { margin-bottom: var(--spacing-lg); }
|
||||||
|
.mb-4 { margin-bottom: var(--spacing-xl); }
|
||||||
|
|
||||||
|
.flex { display: flex; }
|
||||||
|
.flex-col { flex-direction: column; }
|
||||||
|
.items-center { align-items: center; }
|
||||||
|
.justify-between { justify-content: space-between; }
|
||||||
|
.gap-1 { gap: var(--spacing-sm); }
|
||||||
|
.gap-2 { gap: var(--spacing-md); }
|
||||||
|
.gap-3 { gap: var(--spacing-lg); }
|
||||||
|
|
||||||
|
/* Responsive Grid */
|
||||||
|
.grid {
|
||||||
|
display: grid;
|
||||||
|
gap: var(--spacing-lg);
|
||||||
|
}
|
||||||
|
|
||||||
|
.grid-cols-2 {
|
||||||
|
grid-template-columns: repeat(2, 1fr);
|
||||||
|
}
|
||||||
|
|
||||||
|
.grid-cols-3 {
|
||||||
|
grid-template-columns: repeat(3, 1fr);
|
||||||
|
}
|
||||||
|
|
||||||
|
.grid-cols-4 {
|
||||||
|
grid-template-columns: repeat(4, 1fr);
|
||||||
|
}
|
||||||
|
|
||||||
|
@media (max-width: 1024px) {
|
||||||
|
.grid-cols-4 {
|
||||||
|
grid-template-columns: repeat(2, 1fr);
|
||||||
|
}
|
||||||
|
.grid-cols-3 {
|
||||||
|
grid-template-columns: repeat(2, 1fr);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
@media (max-width: 640px) {
|
||||||
|
.grid-cols-4,
|
||||||
|
.grid-cols-3,
|
||||||
|
.grid-cols-2 {
|
||||||
|
grid-template-columns: 1fr;
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,231 @@
|
|||||||
|
<script setup lang="ts">
|
||||||
|
import { ref, onMounted, computed } from 'vue'
|
||||||
|
import { useStockStore } from '../store'
|
||||||
|
import WatchlistSidebar from '../components/WatchlistSidebar.vue'
|
||||||
|
import AnalysisCard from '../components/AnalysisCard.vue'
|
||||||
|
|
||||||
|
const store = useStockStore()
|
||||||
|
const analyzing = ref(false)
|
||||||
|
|
||||||
|
const recentJobs = computed(() => {
|
||||||
|
const jobsByIsin = new Map();
|
||||||
|
// Sort by creation time to ensure we process in order
|
||||||
|
const sortedJobs = [...store.analysisJobs].sort((a, b) =>
|
||||||
|
new Date(a.createdAt).getTime() - new Date(b.createdAt).getTime()
|
||||||
|
);
|
||||||
|
|
||||||
|
for (const job of sortedJobs) {
|
||||||
|
jobsByIsin.set(job.isin, job);
|
||||||
|
}
|
||||||
|
return Array.from(jobsByIsin.values());
|
||||||
|
});
|
||||||
|
|
||||||
|
onMounted(async () => {
|
||||||
|
await store.fetchWatchlist()
|
||||||
|
await store.fetchMarketContext()
|
||||||
|
await store.fetchJobs()
|
||||||
|
})
|
||||||
|
|
||||||
|
async function handleAnalyze() {
|
||||||
|
if (store.watchlist.length === 0) {
|
||||||
|
alert('Please add stocks to your watchlist first.')
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
analyzing.value = true
|
||||||
|
|
||||||
|
try {
|
||||||
|
await store.startAnalysis()
|
||||||
|
} catch (error: any) {
|
||||||
|
alert('Error starting analysis: ' + error.message)
|
||||||
|
analyzing.value = false
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
async function handleStop() {
|
||||||
|
if (!confirm('Are you sure you want to stop pending analyses?')) {
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
try {
|
||||||
|
await store.stopAnalysis()
|
||||||
|
} catch (error: any) {
|
||||||
|
alert('Error stopping analysis: ' + error.message)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
</script>
|
||||||
|
|
||||||
|
<template>
|
||||||
|
<div class="dashboard">
|
||||||
|
<WatchlistSidebar />
|
||||||
|
|
||||||
|
<div class="main-content">
|
||||||
|
<!-- Market Context -->
|
||||||
|
<div v-if="store.marketContext" class="glass-card mb-3">
|
||||||
|
<div class="flex items-center justify-between">
|
||||||
|
<div>
|
||||||
|
<h3 class="text-secondary">Market Context</h3>
|
||||||
|
<p class="text-muted" style="font-size: 0.875rem;">S&P 500 Performance</p>
|
||||||
|
</div>
|
||||||
|
<div class="text-right">
|
||||||
|
<div class="metric-value">${{ store.marketContext.price.toFixed(2) }}</div>
|
||||||
|
<div
|
||||||
|
class="metric-change"
|
||||||
|
:class="store.marketContext.changePercent >= 0 ? 'positive' : 'negative'"
|
||||||
|
>
|
||||||
|
{{ store.marketContext.changePercent >= 0 ? '▲' : '▼' }}
|
||||||
|
{{ Math.abs(store.marketContext.changePercent).toFixed(2) }}%
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<!-- Analyze Button -->
|
||||||
|
<div class="analyze-section mb-3">
|
||||||
|
<div class="flex gap-2">
|
||||||
|
<button
|
||||||
|
@click="handleAnalyze"
|
||||||
|
:disabled="store.loading || store.watchlist.length === 0"
|
||||||
|
class="btn btn-primary"
|
||||||
|
style="flex: 1;"
|
||||||
|
>
|
||||||
|
<span v-if="!store.loading">🔍 Analyze Watchlist</span>
|
||||||
|
<span v-else>
|
||||||
|
<div class="spinner" style="width: 20px; height: 20px; border-width: 2px;"></div>
|
||||||
|
Analyzing...
|
||||||
|
</span>
|
||||||
|
</button>
|
||||||
|
|
||||||
|
<button
|
||||||
|
v-if="store.loading"
|
||||||
|
@click="handleStop"
|
||||||
|
class="btn btn-danger"
|
||||||
|
style="width: auto;"
|
||||||
|
title="Stop Analysis"
|
||||||
|
>
|
||||||
|
⏹️ Stop
|
||||||
|
</button>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<!-- Job Status -->
|
||||||
|
<div v-if="store.loading && recentJobs.length > 0" class="mt-3">
|
||||||
|
<h4 class="mb-2" style="color: var(--text-secondary);">Analysis Progress</h4>
|
||||||
|
<div class="glass-card p-2">
|
||||||
|
<div v-for="job in recentJobs" :key="job.id" class="flex justify-between items-center mb-1 last:mb-0">
|
||||||
|
<span>{{ job.symbol }}</span>
|
||||||
|
<div>
|
||||||
|
<span v-if="job.status === 'PENDING'" class="badge badge-secondary">Pending</span>
|
||||||
|
<span v-if="job.status === 'PROCESSING'" class="badge badge-info">Processing...</span>
|
||||||
|
<span v-if="job.status === 'COMPLETED'" class="badge badge-success">Done</span>
|
||||||
|
<span v-if="job.status === 'FAILED'" class="badge badge-danger">Failed</span>
|
||||||
|
<span v-if="job.status === 'CANCELLED'" class="badge badge-warning">Cancelled</span>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<!-- Results Summary -->
|
||||||
|
<div v-if="store.analysisResults.length > 0">
|
||||||
|
<h2 class="mb-2" style="color: var(--text-primary);">Analysis Results</h2>
|
||||||
|
|
||||||
|
<div class="table-container mb-3">
|
||||||
|
<table>
|
||||||
|
<thead>
|
||||||
|
<tr>
|
||||||
|
<th>Symbol</th>
|
||||||
|
<th>Price</th>
|
||||||
|
<th>Change</th>
|
||||||
|
<th>OpenAI</th>
|
||||||
|
<th>Anthropic</th>
|
||||||
|
</tr>
|
||||||
|
</thead>
|
||||||
|
<tbody>
|
||||||
|
<tr v-for="result in store.analysisResults" :key="result.isin">
|
||||||
|
<td>
|
||||||
|
<strong style="color: var(--text-primary);">{{ result.symbol }}</strong>
|
||||||
|
<br>
|
||||||
|
<span class="text-muted" style="font-size: 0.75rem;">{{ result.isin }}</span>
|
||||||
|
</td>
|
||||||
|
<td>
|
||||||
|
<span v-if="result.price !== null && result.price !== undefined">${{ result.price.toFixed(2) }}</span>
|
||||||
|
<span v-else class="text-muted">N/A</span>
|
||||||
|
</td>
|
||||||
|
<td>
|
||||||
|
<span
|
||||||
|
v-if="result.changePercent !== null && result.changePercent !== undefined"
|
||||||
|
:class="result.changePercent >= 0 ? 'badge-success' : 'badge-danger'"
|
||||||
|
class="badge"
|
||||||
|
>
|
||||||
|
{{ result.changePercent >= 0 ? '▲' : '▼' }}
|
||||||
|
{{ Math.abs(result.changePercent).toFixed(2) }}%
|
||||||
|
</span>
|
||||||
|
<span v-else class="text-muted">N/A</span>
|
||||||
|
</td>
|
||||||
|
<td>
|
||||||
|
<span v-if="result.llmAnalysisOpenai" class="badge badge-info">
|
||||||
|
{{ result.llmAnalysisOpenai.prediction }}
|
||||||
|
({{ result.llmAnalysisOpenai.probability }}%)
|
||||||
|
</span>
|
||||||
|
<span v-else class="text-muted">N/A</span>
|
||||||
|
</td>
|
||||||
|
<td>
|
||||||
|
<span v-if="result.llmAnalysisAnthropic" class="badge badge-warning">
|
||||||
|
{{ result.llmAnalysisAnthropic.prediction }}
|
||||||
|
({{ result.llmAnalysisAnthropic.probability }}%)
|
||||||
|
</span>
|
||||||
|
<span v-else class="text-muted">N/A</span>
|
||||||
|
</td>
|
||||||
|
</tr>
|
||||||
|
</tbody>
|
||||||
|
</table>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<!-- Detailed Analysis Cards -->
|
||||||
|
<h2 class="mb-2" style="color: var(--text-primary);">Detailed Analysis</h2>
|
||||||
|
<div class="analysis-grid">
|
||||||
|
<AnalysisCard
|
||||||
|
v-for="result in store.analysisResults"
|
||||||
|
:key="result.isin"
|
||||||
|
:result="result"
|
||||||
|
/>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<!-- Empty State -->
|
||||||
|
<div v-else class="glass-card text-center" style="padding: 3rem;">
|
||||||
|
<div style="font-size: 3rem; margin-bottom: 1rem;">📊</div>
|
||||||
|
<h3 style="color: var(--text-primary); margin-bottom: 0.5rem;">No Analysis Yet</h3>
|
||||||
|
<p class="text-secondary">Add stocks to your watchlist and click "Analyze Watchlist" to get started.</p>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
</template>
|
||||||
|
|
||||||
|
<style scoped>
|
||||||
|
.dashboard {
|
||||||
|
display: grid;
|
||||||
|
grid-template-columns: 320px 1fr;
|
||||||
|
gap: 2rem;
|
||||||
|
align-items: start;
|
||||||
|
}
|
||||||
|
|
||||||
|
.main-content {
|
||||||
|
min-height: 600px;
|
||||||
|
}
|
||||||
|
|
||||||
|
.analyze-section {
|
||||||
|
position: relative;
|
||||||
|
}
|
||||||
|
|
||||||
|
.analysis-grid {
|
||||||
|
display: grid;
|
||||||
|
gap: 1.5rem;
|
||||||
|
}
|
||||||
|
|
||||||
|
@media (max-width: 1024px) {
|
||||||
|
.dashboard {
|
||||||
|
grid-template-columns: 1fr;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
</style>
|
||||||
@@ -0,0 +1,543 @@
|
|||||||
|
<script setup lang="ts">
|
||||||
|
import { ref, computed, onMounted } from 'vue'
|
||||||
|
import { useStockStore, type AnalysisResult } from '../store'
|
||||||
|
import WatchlistSidebar from '../components/WatchlistSidebar.vue'
|
||||||
|
|
||||||
|
const store = useStockStore()
|
||||||
|
const historyByIsin = ref<Map<string, AnalysisResult[]>>(new Map())
|
||||||
|
const loading = ref(false)
|
||||||
|
const showDeleteModal = ref(false)
|
||||||
|
const startDate = ref('')
|
||||||
|
const endDate = ref('')
|
||||||
|
|
||||||
|
// Navigation & Filtering
|
||||||
|
const selectedIsin = ref<string | null>(null)
|
||||||
|
const searchQuery = ref('')
|
||||||
|
const sortBy = ref<'date' | 'symbol' | 'accuracy'>('date')
|
||||||
|
|
||||||
|
onMounted(async () => {
|
||||||
|
await store.fetchJobs()
|
||||||
|
await loadHistory()
|
||||||
|
})
|
||||||
|
|
||||||
|
async function loadHistory() {
|
||||||
|
loading.value = true
|
||||||
|
try {
|
||||||
|
await store.fetchWatchlist()
|
||||||
|
|
||||||
|
const historyMap = new Map<string, AnalysisResult[]>()
|
||||||
|
|
||||||
|
for (const stock of store.watchlist) {
|
||||||
|
const results = await store.fetchHistoryByIsin(stock.isin)
|
||||||
|
if (results.length > 0) {
|
||||||
|
historyMap.set(stock.isin, results)
|
||||||
|
} else {
|
||||||
|
historyMap.set(stock.isin, [])
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
historyByIsin.value = historyMap
|
||||||
|
} catch (error: any) {
|
||||||
|
alert('Error loading history: ' + error.message)
|
||||||
|
} finally {
|
||||||
|
loading.value = false
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// Computed Data for Main Table
|
||||||
|
const tableData = computed(() => {
|
||||||
|
const data: any[] = []
|
||||||
|
|
||||||
|
historyByIsin.value.forEach((results, isin) => {
|
||||||
|
// Find symbol from results or watchlist
|
||||||
|
let symbol = results.length > 0 ? results[0].symbol : ''
|
||||||
|
if (!symbol) {
|
||||||
|
const stock = store.watchlist.find(s => s.isin === isin)
|
||||||
|
symbol = stock ? (stock.symbol || isin) : isin
|
||||||
|
}
|
||||||
|
|
||||||
|
if (results.length === 0) {
|
||||||
|
data.push({
|
||||||
|
isin,
|
||||||
|
symbol,
|
||||||
|
latestResult: null,
|
||||||
|
accuracy: { openaiPct: 0, anthropicPct: 0, total: 0 }
|
||||||
|
})
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
// Sort results by date descending to find latest
|
||||||
|
const sortedResults = [...results].sort((a, b) =>
|
||||||
|
new Date(b.analyzedAt).getTime() - new Date(a.analyzedAt).getTime()
|
||||||
|
)
|
||||||
|
|
||||||
|
const latest = sortedResults[0]
|
||||||
|
const accuracy = calculateAccuracy(results)
|
||||||
|
|
||||||
|
data.push({
|
||||||
|
isin,
|
||||||
|
symbol: latest.symbol,
|
||||||
|
latestResult: latest,
|
||||||
|
accuracy
|
||||||
|
})
|
||||||
|
})
|
||||||
|
|
||||||
|
return data
|
||||||
|
})
|
||||||
|
|
||||||
|
const filteredData = computed(() => {
|
||||||
|
let data = tableData.value
|
||||||
|
|
||||||
|
// Filter
|
||||||
|
if (searchQuery.value) {
|
||||||
|
const query = searchQuery.value.toLowerCase()
|
||||||
|
data = data.filter(item =>
|
||||||
|
item.symbol.toLowerCase().includes(query) ||
|
||||||
|
item.isin.toLowerCase().includes(query)
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
|
// Sort
|
||||||
|
data.sort((a, b) => {
|
||||||
|
if (sortBy.value === 'date') {
|
||||||
|
const timeA = a.latestResult ? new Date(a.latestResult.analyzedAt).getTime() : 0
|
||||||
|
const timeB = b.latestResult ? new Date(b.latestResult.analyzedAt).getTime() : 0
|
||||||
|
return timeB - timeA
|
||||||
|
} else if (sortBy.value === 'symbol') {
|
||||||
|
return a.symbol.localeCompare(b.symbol)
|
||||||
|
} else if (sortBy.value === 'accuracy') {
|
||||||
|
return (b.accuracy.openaiPct + b.accuracy.anthropicPct) - (a.accuracy.openaiPct + a.accuracy.anthropicPct)
|
||||||
|
}
|
||||||
|
return 0
|
||||||
|
})
|
||||||
|
|
||||||
|
return data
|
||||||
|
})
|
||||||
|
|
||||||
|
const selectedDetails = computed(() => {
|
||||||
|
if (!selectedIsin.value) return []
|
||||||
|
return historyByIsin.value.get(selectedIsin.value) || []
|
||||||
|
})
|
||||||
|
|
||||||
|
function calculateAccuracy(results: AnalysisResult[]) {
|
||||||
|
let openaiCorrect = 0
|
||||||
|
let anthropicCorrect = 0
|
||||||
|
let total = 0
|
||||||
|
|
||||||
|
for (const result of results) {
|
||||||
|
if (result.realPrice !== undefined && result.realPrice !== null && result.price) {
|
||||||
|
total++
|
||||||
|
const startPrice = result.price
|
||||||
|
const endPrice = result.realPrice
|
||||||
|
|
||||||
|
// OpenAI
|
||||||
|
const openaiPred = result.llmAnalysisOpenai?.prediction?.toUpperCase() || ''
|
||||||
|
if ((openaiPred.includes('BULLISH') && endPrice > startPrice) ||
|
||||||
|
(openaiPred.includes('BEARISH') && endPrice < startPrice)) {
|
||||||
|
openaiCorrect++
|
||||||
|
}
|
||||||
|
|
||||||
|
// Anthropic
|
||||||
|
const anthropicPred = result.llmAnalysisAnthropic?.prediction?.toUpperCase() || ''
|
||||||
|
if ((anthropicPred.includes('BULLISH') && endPrice > startPrice) ||
|
||||||
|
(anthropicPred.includes('BEARISH') && endPrice < startPrice)) {
|
||||||
|
anthropicCorrect++
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
const openaiPct = total > 0 ? Math.round((openaiCorrect / total) * 100) : 0
|
||||||
|
const anthropicPct = total > 0 ? Math.round((anthropicCorrect / total) * 100) : 0
|
||||||
|
|
||||||
|
return { openaiPct, anthropicPct, total }
|
||||||
|
}
|
||||||
|
|
||||||
|
async function handleDeleteByDateRange() {
|
||||||
|
if (!startDate.value || !endDate.value) {
|
||||||
|
alert('Please select both start and end dates')
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
if (new Date(startDate.value) > new Date(endDate.value)) {
|
||||||
|
alert('Start date must be before end date')
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
if (!confirm(`Are you sure you want to delete all records between ${startDate.value} and ${endDate.value}?`)) {
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
try {
|
||||||
|
const result = await store.deleteHistoryByDateRange(startDate.value, endDate.value)
|
||||||
|
alert(`Deleted ${result.deleted} records`)
|
||||||
|
showDeleteModal.value = false
|
||||||
|
await loadHistory()
|
||||||
|
} catch (error: any) {
|
||||||
|
alert('Error deleting records: ' + error.message)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
async function handleRefreshPrice(result: AnalysisResult) {
|
||||||
|
if (!result.id) return
|
||||||
|
|
||||||
|
try {
|
||||||
|
const updatedResult = await store.refreshRealPrice(result.id)
|
||||||
|
// Update local state
|
||||||
|
const results = historyByIsin.value.get(result.isin)
|
||||||
|
if (results) {
|
||||||
|
const index = results.findIndex(r => r.id === result.id)
|
||||||
|
if (index !== -1) {
|
||||||
|
results[index] = updatedResult
|
||||||
|
}
|
||||||
|
}
|
||||||
|
} catch (error: any) {
|
||||||
|
alert('Error refreshing price: ' + error.message)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
function isDateInPast(dateStr: string) {
|
||||||
|
return new Date(dateStr) < new Date()
|
||||||
|
}
|
||||||
|
|
||||||
|
async function handleAnalyzeAll() {
|
||||||
|
try {
|
||||||
|
await store.startAnalysis()
|
||||||
|
} catch (error: any) {
|
||||||
|
alert('Error starting analysis: ' + error.message)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
async function handleAnalyzeSingle(isin: string, event: Event) {
|
||||||
|
event.stopPropagation()
|
||||||
|
try {
|
||||||
|
await store.startAnalysis(isin)
|
||||||
|
} catch (error: any) {
|
||||||
|
alert('Error starting analysis: ' + error.message)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
async function handleStop() {
|
||||||
|
if (!confirm('Are you sure you want to stop pending analyses?')) {
|
||||||
|
return
|
||||||
|
}
|
||||||
|
try {
|
||||||
|
await store.stopAnalysis()
|
||||||
|
} catch (error: any) {
|
||||||
|
alert('Error stopping analysis: ' + error.message)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
function getJobStatus(isin: string) {
|
||||||
|
return store.analysisJobs.find(j => j.isin === isin && (j.status === 'PENDING' || j.status === 'PROCESSING'))?.status
|
||||||
|
}
|
||||||
|
</script>
|
||||||
|
|
||||||
|
<template>
|
||||||
|
<div class="dashboard-layout">
|
||||||
|
<WatchlistSidebar />
|
||||||
|
|
||||||
|
<div class="main-content">
|
||||||
|
<div class="history-view">
|
||||||
|
<!-- Header -->
|
||||||
|
<div class="flex justify-between items-center mb-3">
|
||||||
|
<div class="flex items-center gap-3">
|
||||||
|
<button v-if="selectedIsin" @click="selectedIsin = null" class="btn btn-secondary">
|
||||||
|
⬅️ Back
|
||||||
|
</button>
|
||||||
|
<h1 style="color: var(--text-primary);">
|
||||||
|
{{ selectedIsin ? 'Details: ' + selectedDetails[0]?.symbol : 'History Overview' }}
|
||||||
|
</h1>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<div class="flex gap-2">
|
||||||
|
<button
|
||||||
|
v-if="store.loading"
|
||||||
|
@click="handleStop"
|
||||||
|
class="btn btn-danger"
|
||||||
|
>
|
||||||
|
⏹️ Stop All
|
||||||
|
</button>
|
||||||
|
<button
|
||||||
|
v-else
|
||||||
|
@click="handleAnalyzeAll"
|
||||||
|
class="btn btn-primary"
|
||||||
|
:disabled="store.watchlist.length === 0"
|
||||||
|
>
|
||||||
|
🔍 Analyze All
|
||||||
|
</button>
|
||||||
|
|
||||||
|
<button @click="loadHistory" class="btn btn-secondary">
|
||||||
|
🔄 Refresh
|
||||||
|
</button>
|
||||||
|
<button @click="showDeleteModal = true" class="btn btn-danger">
|
||||||
|
🗑️ Delete by Date
|
||||||
|
</button>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<!-- Main Table View -->
|
||||||
|
<div v-if="!selectedIsin">
|
||||||
|
<div class="glass-card mb-3 p-3 flex gap-3">
|
||||||
|
<div style="flex: 1;">
|
||||||
|
<input
|
||||||
|
v-model="searchQuery"
|
||||||
|
placeholder="Search Symbol or ISIN..."
|
||||||
|
class="input"
|
||||||
|
style="width: 100%;"
|
||||||
|
/>
|
||||||
|
</div>
|
||||||
|
<div style="width: 200px;">
|
||||||
|
<select v-model="sortBy" class="input" style="width: 100%;">
|
||||||
|
<option value="date">Sort by Date</option>
|
||||||
|
<option value="symbol">Sort by Symbol</option>
|
||||||
|
<option value="accuracy">Sort by Accuracy</option>
|
||||||
|
</select>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<div class="glass-card table-container">
|
||||||
|
<table class="history-table">
|
||||||
|
<thead>
|
||||||
|
<tr>
|
||||||
|
<th>Symbol</th>
|
||||||
|
<th>Latest Analysis</th>
|
||||||
|
<th>Target Date</th>
|
||||||
|
<th>Latest Prediction (OpenAI)</th>
|
||||||
|
<th>Latest Prediction (Anthropic)</th>
|
||||||
|
<th>Accuracy</th>
|
||||||
|
<th>History Size</th>
|
||||||
|
<th>Action</th>
|
||||||
|
</tr>
|
||||||
|
</thead>
|
||||||
|
<tbody>
|
||||||
|
<tr v-for="item in filteredData" :key="item.isin" @click="selectedIsin = item.isin" class="clickable-row">
|
||||||
|
<td>
|
||||||
|
<strong style="color: var(--text-primary); font-size: 1.1rem;">{{ item.symbol }}</strong>
|
||||||
|
<div class="text-muted" style="font-size: 0.8rem;">{{ item.isin }}</div>
|
||||||
|
</td>
|
||||||
|
<td>
|
||||||
|
{{ item.latestResult ? new Date(item.latestResult.analyzedAt).toLocaleDateString() : 'Never' }}
|
||||||
|
</td>
|
||||||
|
<td>
|
||||||
|
{{ item.latestResult ? new Date(item.latestResult.targetDate).toLocaleDateString() : '-' }}
|
||||||
|
</td>
|
||||||
|
<td>
|
||||||
|
<span v-if="item.latestResult?.llmAnalysisOpenai" class="badge badge-info">
|
||||||
|
{{ item.latestResult.llmAnalysisOpenai.prediction }}
|
||||||
|
</span>
|
||||||
|
<span v-else class="text-muted">N/A</span>
|
||||||
|
</td>
|
||||||
|
<td>
|
||||||
|
<span v-if="item.latestResult?.llmAnalysisAnthropic" class="badge badge-warning">
|
||||||
|
{{ item.latestResult.llmAnalysisAnthropic.prediction }}
|
||||||
|
</span>
|
||||||
|
<span v-else class="text-muted">N/A</span>
|
||||||
|
</td>
|
||||||
|
<td>
|
||||||
|
<div class="flex flex-col gap-1" style="font-size: 0.75rem;">
|
||||||
|
<span class="text-info">OpenAI: {{ item.accuracy.openaiPct }}%</span>
|
||||||
|
<span class="text-warning">Anthropic: {{ item.accuracy.anthropicPct }}%</span>
|
||||||
|
<span class="text-muted" style="font-size: 0.7rem;">({{ item.accuracy.total }} verified)</span>
|
||||||
|
</div>
|
||||||
|
</td>
|
||||||
|
<td>{{ historyByIsin.get(item.isin)?.length || 0 }} records</td>
|
||||||
|
<td>
|
||||||
|
<div v-if="getJobStatus(item.isin)" class="flex items-center gap-1">
|
||||||
|
<div class="spinner" style="width: 12px; height: 12px; border-width: 2px;"></div>
|
||||||
|
<span class="text-info" style="font-size: 0.8rem;">{{ getJobStatus(item.isin) }}</span>
|
||||||
|
</div>
|
||||||
|
<button v-else @click="handleAnalyzeSingle(item.isin, $event)" class="btn btn-sm btn-primary">
|
||||||
|
Analyze
|
||||||
|
</button>
|
||||||
|
</td>
|
||||||
|
</tr>
|
||||||
|
<tr v-if="filteredData.length === 0">
|
||||||
|
<td colspan="7" class="text-center text-muted" style="padding: 2rem;">
|
||||||
|
No history found matching your criteria.
|
||||||
|
</td>
|
||||||
|
</tr>
|
||||||
|
</tbody>
|
||||||
|
</table>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<!-- Detail View -->
|
||||||
|
<div v-else>
|
||||||
|
<div class="glass-card mb-3">
|
||||||
|
<div class="history-header">
|
||||||
|
<div>
|
||||||
|
<h3 style="color: var(--text-primary);">{{ selectedDetails[0]?.symbol }}</h3>
|
||||||
|
<p class="text-muted" style="font-size: 0.875rem;">{{ selectedIsin }}</p>
|
||||||
|
</div>
|
||||||
|
<div class="accuracy-badges">
|
||||||
|
<span class="badge badge-info">
|
||||||
|
OpenAI Accuracy: {{ calculateAccuracy(selectedDetails).openaiPct }}%
|
||||||
|
</span>
|
||||||
|
<span class="badge badge-warning">
|
||||||
|
Anthropic Accuracy: {{ calculateAccuracy(selectedDetails).anthropicPct }}%
|
||||||
|
</span>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<div class="table-container mt-2">
|
||||||
|
<table>
|
||||||
|
<thead>
|
||||||
|
<tr>
|
||||||
|
<th>Analyzed Date</th>
|
||||||
|
<th>Target Date</th>
|
||||||
|
<th>Analyzed Price</th>
|
||||||
|
<th>Real Price</th>
|
||||||
|
<th>OpenAI</th>
|
||||||
|
<th>Anthropic</th>
|
||||||
|
</tr>
|
||||||
|
</thead>
|
||||||
|
<tbody>
|
||||||
|
<tr v-for="result in selectedDetails" :key="result.id">
|
||||||
|
<td>{{ new Date(result.date).toLocaleDateString() }}</td>
|
||||||
|
<td>{{ new Date(result.targetDate).toLocaleDateString() }}</td>
|
||||||
|
<td>
|
||||||
|
<span v-if="result.price !== null && result.price !== undefined">${{ result.price.toFixed(2) }}</span>
|
||||||
|
<span v-else class="text-muted">N/A</span>
|
||||||
|
</td>
|
||||||
|
<td>
|
||||||
|
<span v-if="result.realPrice !== null && result.realPrice !== undefined">
|
||||||
|
${{ result.realPrice.toFixed(2) }}
|
||||||
|
</span>
|
||||||
|
<button
|
||||||
|
v-else-if="isDateInPast(result.targetDate)"
|
||||||
|
@click="handleRefreshPrice(result)"
|
||||||
|
class="btn btn-sm btn-secondary"
|
||||||
|
style="font-size: 0.75rem; padding: 0.25rem 0.5rem;"
|
||||||
|
>
|
||||||
|
🔄 Fetch
|
||||||
|
</button>
|
||||||
|
<span v-else class="text-muted">Pending</span>
|
||||||
|
</td>
|
||||||
|
<td>
|
||||||
|
<div v-if="result.llmAnalysisOpenai">
|
||||||
|
<span class="badge badge-info">
|
||||||
|
{{ result.llmAnalysisOpenai.prediction }}
|
||||||
|
</span>
|
||||||
|
<span class="text-muted"> ⏳</span>
|
||||||
|
</div>
|
||||||
|
<div v-if="result.llmAnalysisOpenai" class="text-muted" style="font-size: 0.75rem; margin-top: 0.25rem;">
|
||||||
|
{{ result.llmAnalysisOpenai.reasoning.substring(0, 100) }}...
|
||||||
|
</div>
|
||||||
|
<div v-else class="text-muted">N/A</div>
|
||||||
|
</td>
|
||||||
|
<td>
|
||||||
|
<div v-if="result.llmAnalysisAnthropic">
|
||||||
|
<span class="badge badge-warning">
|
||||||
|
{{ result.llmAnalysisAnthropic.prediction }}
|
||||||
|
</span>
|
||||||
|
<span class="text-muted"> ⏳</span>
|
||||||
|
</div>
|
||||||
|
<div v-if="result.llmAnalysisAnthropic" class="text-muted" style="font-size: 0.75rem; margin-top: 0.25rem;">
|
||||||
|
{{ result.llmAnalysisAnthropic.reasoning.substring(0, 100) }}...
|
||||||
|
</div>
|
||||||
|
<div v-else class="text-muted">N/A</div>
|
||||||
|
</td>
|
||||||
|
</tr>
|
||||||
|
</tbody>
|
||||||
|
</table>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<!-- Delete Modal -->
|
||||||
|
<div v-if="showDeleteModal" class="modal-overlay" @click.self="showDeleteModal = false">
|
||||||
|
<div class="modal-content glass-card">
|
||||||
|
<h3 class="mb-2" style="color: var(--text-primary);">Delete Records by Date Range</h3>
|
||||||
|
<div class="alert alert-warning mb-2">
|
||||||
|
⚠️ This action cannot be undone.
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<div class="grid grid-cols-2 gap-2 mb-3">
|
||||||
|
<div>
|
||||||
|
<label class="text-secondary" style="display: block; margin-bottom: 0.5rem;">Start Date</label>
|
||||||
|
<input type="date" v-model="startDate" class="input" />
|
||||||
|
</div>
|
||||||
|
<div>
|
||||||
|
<label class="text-secondary" style="display: block; margin-bottom: 0.5rem;">End Date</label>
|
||||||
|
<input type="date" v-model="endDate" class="input" />
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<div class="flex gap-2">
|
||||||
|
<button @click="handleDeleteByDateRange" class="btn btn-danger" style="flex: 1;">
|
||||||
|
Delete Records
|
||||||
|
</button>
|
||||||
|
<button @click="showDeleteModal = false" class="btn btn-secondary" style="flex: 1;">
|
||||||
|
Cancel
|
||||||
|
</button>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
</template>
|
||||||
|
|
||||||
|
<style scoped>
|
||||||
|
.dashboard-layout {
|
||||||
|
display: grid;
|
||||||
|
grid-template-columns: 320px 1fr;
|
||||||
|
gap: 2rem;
|
||||||
|
align-items: start;
|
||||||
|
}
|
||||||
|
|
||||||
|
.history-view {
|
||||||
|
width: 100%;
|
||||||
|
}
|
||||||
|
|
||||||
|
.clickable-row {
|
||||||
|
cursor: pointer;
|
||||||
|
transition: background-color 0.2s;
|
||||||
|
}
|
||||||
|
|
||||||
|
.clickable-row:hover {
|
||||||
|
background-color: rgba(255, 255, 255, 0.05);
|
||||||
|
}
|
||||||
|
|
||||||
|
.history-header {
|
||||||
|
display: flex;
|
||||||
|
justify-content: space-between;
|
||||||
|
align-items: center;
|
||||||
|
}
|
||||||
|
|
||||||
|
.accuracy-badges {
|
||||||
|
display: flex;
|
||||||
|
gap: 0.5rem;
|
||||||
|
}
|
||||||
|
|
||||||
|
.modal-overlay {
|
||||||
|
position: fixed;
|
||||||
|
top: 0;
|
||||||
|
left: 0;
|
||||||
|
right: 0;
|
||||||
|
bottom: 0;
|
||||||
|
background: rgba(0, 0, 0, 0.7);
|
||||||
|
display: flex;
|
||||||
|
align-items: center;
|
||||||
|
justify-content: center;
|
||||||
|
z-index: 1000;
|
||||||
|
backdrop-filter: blur(5px);
|
||||||
|
}
|
||||||
|
|
||||||
|
.modal-content {
|
||||||
|
max-width: 500px;
|
||||||
|
width: 90%;
|
||||||
|
padding: 2rem;
|
||||||
|
}
|
||||||
|
|
||||||
|
@media (max-width: 1024px) {
|
||||||
|
.dashboard-layout {
|
||||||
|
grid-template-columns: 1fr;
|
||||||
|
}
|
||||||
|
.history-header {
|
||||||
|
flex-direction: column;
|
||||||
|
align-items: flex-start;
|
||||||
|
gap: 1rem;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
</style>
|
||||||
Vendored
+7
@@ -0,0 +1,7 @@
|
|||||||
|
/// <reference types="vite/client" />
|
||||||
|
|
||||||
|
declare module '*.vue' {
|
||||||
|
import type { DefineComponent } from 'vue'
|
||||||
|
const component: DefineComponent<{}, {}, any>
|
||||||
|
export default component
|
||||||
|
}
|
||||||
@@ -0,0 +1,43 @@
|
|||||||
|
{
|
||||||
|
"compilerOptions": {
|
||||||
|
"target": "ES2020",
|
||||||
|
"useDefineForClassFields": true,
|
||||||
|
"module": "ESNext",
|
||||||
|
"lib": [
|
||||||
|
"ES2020",
|
||||||
|
"DOM",
|
||||||
|
"DOM.Iterable"
|
||||||
|
],
|
||||||
|
"skipLibCheck": true,
|
||||||
|
/* Bundler mode */
|
||||||
|
"moduleResolution": "bundler",
|
||||||
|
"allowImportingTsExtensions": true,
|
||||||
|
"resolveJsonModule": true,
|
||||||
|
"isolatedModules": true,
|
||||||
|
"noEmit": true,
|
||||||
|
"jsx": "preserve",
|
||||||
|
/* Linting */
|
||||||
|
"strict": true,
|
||||||
|
"noUnusedLocals": true,
|
||||||
|
"noUnusedParameters": true,
|
||||||
|
"noFallthroughCasesInSwitch": true,
|
||||||
|
/* Path mapping */
|
||||||
|
"baseUrl": ".",
|
||||||
|
"paths": {
|
||||||
|
"@/*": [
|
||||||
|
"./src/*"
|
||||||
|
]
|
||||||
|
}
|
||||||
|
},
|
||||||
|
"include": [
|
||||||
|
"src/**/*.ts",
|
||||||
|
"src/**/*.d.ts",
|
||||||
|
"src/**/*.tsx",
|
||||||
|
"src/**/*.vue"
|
||||||
|
],
|
||||||
|
"references": [
|
||||||
|
{
|
||||||
|
"path": "./tsconfig.node.json"
|
||||||
|
}
|
||||||
|
]
|
||||||
|
}
|
||||||
@@ -0,0 +1,15 @@
|
|||||||
|
{
|
||||||
|
"compilerOptions": {
|
||||||
|
"composite": true,
|
||||||
|
"skipLibCheck": true,
|
||||||
|
"module": "ESNext",
|
||||||
|
"moduleResolution": "bundler",
|
||||||
|
"allowSyntheticDefaultImports": true,
|
||||||
|
"types": [
|
||||||
|
"node"
|
||||||
|
]
|
||||||
|
},
|
||||||
|
"include": [
|
||||||
|
"vite.config.ts"
|
||||||
|
]
|
||||||
|
}
|
||||||
@@ -0,0 +1,21 @@
|
|||||||
|
import { defineConfig } from 'vite'
|
||||||
|
import vue from '@vitejs/plugin-vue'
|
||||||
|
import { fileURLToPath, URL } from 'node:url'
|
||||||
|
|
||||||
|
export default defineConfig({
|
||||||
|
plugins: [vue()],
|
||||||
|
resolve: {
|
||||||
|
alias: {
|
||||||
|
'@': fileURLToPath(new URL('./src', import.meta.url))
|
||||||
|
}
|
||||||
|
},
|
||||||
|
server: {
|
||||||
|
port: 5173,
|
||||||
|
proxy: {
|
||||||
|
'/api': {
|
||||||
|
target: 'http://localhost:8080',
|
||||||
|
changeOrigin: true
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
})
|
||||||
@@ -0,0 +1,87 @@
|
|||||||
|
#!/bin/bash
|
||||||
|
|
||||||
|
# Stock Analyzer - Quick Start Script
|
||||||
|
|
||||||
|
set -e
|
||||||
|
|
||||||
|
echo "🚀 Stock Analyzer - Quick Start"
|
||||||
|
echo "================================"
|
||||||
|
echo ""
|
||||||
|
|
||||||
|
# Check if .env file exists
|
||||||
|
if [ ! -f .env ]; then
|
||||||
|
echo "⚠️ No .env file found. Creating from env.example..."
|
||||||
|
if [ -f env.example ]; then
|
||||||
|
cp env.example .env
|
||||||
|
echo "✅ Created .env file. Please edit it with your API keys."
|
||||||
|
echo ""
|
||||||
|
echo "Required API keys:"
|
||||||
|
echo " - OPENAI_API_KEY"
|
||||||
|
echo " - ANTHROPIC_API_KEY"
|
||||||
|
echo " - NEWS_API_KEY"
|
||||||
|
echo ""
|
||||||
|
read -p "Press Enter after you've configured your API keys..."
|
||||||
|
else
|
||||||
|
echo "❌ env.example not found. Please create a .env file manually."
|
||||||
|
exit 1
|
||||||
|
fi
|
||||||
|
fi
|
||||||
|
|
||||||
|
# Load environment variables
|
||||||
|
export $(cat .env | grep -v '^#' | xargs)
|
||||||
|
|
||||||
|
echo "1️⃣ Starting MongoDB..."
|
||||||
|
docker run -d -p 27017:27017 --name stock-analyzer-mongodb mongo:latest 2>/dev/null || docker start stock-analyzer-mongodb
|
||||||
|
echo "✅ MongoDB started"
|
||||||
|
echo ""
|
||||||
|
|
||||||
|
echo "2️⃣ Starting Backend (Spring Boot)..."
|
||||||
|
cd backend
|
||||||
|
./gradlew bootRun &
|
||||||
|
BACKEND_PID=$!
|
||||||
|
cd ..
|
||||||
|
echo "✅ Backend starting on http://localhost:8080"
|
||||||
|
echo ""
|
||||||
|
|
||||||
|
# Wait for backend to be ready
|
||||||
|
echo "⏳ Waiting for backend to be ready..."
|
||||||
|
for i in {1..30}; do
|
||||||
|
if curl -s http://localhost:8080/actuator/health > /dev/null 2>&1; then
|
||||||
|
echo "✅ Backend is ready!"
|
||||||
|
break
|
||||||
|
fi
|
||||||
|
sleep 2
|
||||||
|
done
|
||||||
|
echo ""
|
||||||
|
|
||||||
|
echo "3️⃣ Installing Frontend Dependencies..."
|
||||||
|
cd frontend
|
||||||
|
if [ ! -d "node_modules" ]; then
|
||||||
|
npm install
|
||||||
|
fi
|
||||||
|
echo "✅ Dependencies installed"
|
||||||
|
echo ""
|
||||||
|
|
||||||
|
echo "4️⃣ Starting Frontend (Vue.js)..."
|
||||||
|
npm run dev &
|
||||||
|
FRONTEND_PID=$!
|
||||||
|
cd ..
|
||||||
|
echo "✅ Frontend starting on http://localhost:5173"
|
||||||
|
echo ""
|
||||||
|
|
||||||
|
echo "================================"
|
||||||
|
echo "✨ Stock Analyzer is running!"
|
||||||
|
echo "================================"
|
||||||
|
echo ""
|
||||||
|
echo "📊 Frontend: http://localhost:5173"
|
||||||
|
echo "🔧 Backend: http://localhost:8080"
|
||||||
|
echo "🗄️ MongoDB: mongodb://localhost:27017"
|
||||||
|
echo ""
|
||||||
|
echo "Press Ctrl+C to stop all services"
|
||||||
|
echo ""
|
||||||
|
|
||||||
|
# Trap Ctrl+C and cleanup
|
||||||
|
trap "echo ''; echo '🛑 Stopping services...'; kill $BACKEND_PID $FRONTEND_PID 2>/dev/null; docker stop stock-analyzer-mongodb 2>/dev/null; echo '✅ All services stopped'; exit 0" INT
|
||||||
|
|
||||||
|
# Wait for processes
|
||||||
|
wait
|
||||||
Reference in new issue
Block a user