# Project export: Tradegentix

This document was generated by HackStack to give an AI agent context about a hackathon project. Sections are labeled with their provenance; content marked as truncated was cut to keep this document small.

## Project metadata

- Hackathon: TreeHacks 2025
- Tagline: High-Frequency Trading with Agentic Workflows and GPU parallelization.
- Devpost: https://devpost.com/software/agentictraders
- GitHub: https://github.com/danielgao20/tradegentix
- Demo: https://github.com/assasin2gamer/treehack25
- Team: 1 GitHub contributor(s) — danielgao20 (6 commits)

## Devpost submission (written by the team)

### Overview

(scroll for FlutterFlow, Perplexity, Rox, Tesla, and Agentic Workflows!) Let's say Stock A goes up at t=0 (where time is t). The idea is that there is a latency between a related/correlated Stock B that may be positively or negatively correlated at t = 3. We would use this tool to predict this correlation and buy at t=2 before Stock B response to some market force affecting Stock A. More specifically, our team developed a semi-high frequency trading system leveraging CUDA C++ accelerated computing that allowed for an agent network based chain of reasoning in order to use qualitative factors to explain the quantitative phenomena. Our agentic workflow allows us to benefit from market research and news analysis for a robust report. NVIDIA Technology: Our semi-high frequency trading system, powered by CUDA and chain of reasoning, comprises the following components: CUDA-Accelerated ICA: We implemented a custom CUDA-based Independent Component Analysis (ICA) module to extract statistical market forces from mixed signals. This approach is based on the concept that while independent source signals are non-Gaussian, their mixtures tend to exhibit a more normal distribution. For further reading, refer to this quick guide. CUDA-Accelerated ICA: We implemented a custom CUDA-based Independent Component Analysis (ICA) module to extract statistical market forces from mixed signals. This approach is based on the concept that while independent source signals are non-Gaussian, their mixtures tend to exhibit a more normal distribution. For further reading, refer to this quick guide. Accelerated Monte Carlo Simulation: Using CUDA acceleration, our system runs an implementation of a Monte Carlo simulation that models variant BM and JP inclusive sequence. The simulations are weighted based on a feedback cycle derived from the ICA process. Accelerated Monte Carlo Simulation: Using CUDA acceleration, our system runs an implementation of a Monte Carlo simulation that models variant BM and JP inclusive sequence. The simulations are weighted based on a feedback cycle derived from the ICA process. High-Performance Processing: By focusing on parallelization, the entire system completes computations in just a few milliseconds. High-Performance Processing: By focusing on parallelization, the entire system completes computations in just a few milliseconds. Predictive Filtering with HMM: A Hidden Markov Model (HMM) is employed to filter and identify the most reliable predictive paths. This ensures that trading decisions are based on a reward-based estimation of interval delays to set an optimal position lifetime. Predictive Filtering with HMM: A Hidden Markov Model (HMM) is employed to filter and identify the most reliable predictive paths. This ensures that trading decisions are based on a reward-based estimation of interval delays to set an optimal position lifetime. Together, these components form an integrated system capable of high-speed, data-driven trading decisions. FlutterFlow! : To effectively visualize key components of our trading system—Best Case, Best Path, Last Price, Original Values, and Worst Case—which consists of over 4.8 million computed data points, we used FlutterFlow for a clean, interactive interface. Why FlutterFlow? We chose FlutterFlow for its seamless Firebase integration, allowing us to easily fetch, store, and display real-time stock data without extra complexity. Additionally, FlutterFlow offers powerful graph rendering, ideal for our stock trend visualizations. Why FlutterFlow? We chose FlutterFlow for its seamless Firebase integration, allowing us to easily fetch, store, and display real-time stock data without extra complexity. Additionally, FlutterFlow offers powerful graph rendering, ideal for our stock trend visualizations. Visualization & Explanation Generation By integrating agentic web scraping capabilities, we enhanced our explanations with real-time analytics and relevant news articles, providing a comprehensive, data-backed decision-making tool. Visualization & Explanation Generation By integrating agentic web scraping capabilities, we enhanced our explanations with real-time analytics and relevant news articles, providing a comprehensive, data-backed decision-making tool. Perplexity: We integrated Perplexity Sonar to enhance our decision-making process by fetching real-time financial news relevant to each stock. This allowed our analysis agent to incorporate market sentiment and recent events, providing contextual explanations for each trading decision. By combining quantitative predictions from our CUDA-accelerated models with qualitative insights from Perplexity, we created a more comprehensive and transparent trading system. Rox & Agentic Workflow: Our project aligns with Rox's focus on agentic workflows, leveraging LLMs for context fetching, prompt orchestration, and tool calling to complete a complex financial workflow. Our trading system integrates real-time market analysis, predictive modeling, and automated decision-making to streamline stock market insights. More details on our system diagram and architecture can be found on this document. Tesla Challenge: Kaggle Link Analyzing video with VLMs is hard. Gemini and Qwen provide decent models that can process video, but in our testing we found them to be lackluster for Tesla's needs. Given the time constraints, we attempted to optimize our challenge approach through an orchestration of image chunking and prompting. The idea: Instead of processing a video, we split the mp4 into jpeg frames -- the attached Tesla diagram visualizes the following: In chunks of 3, we analyze a subset of frames from the video in parallel. This allows the VLM to see how the video changes within a short interval (for example, 3 frames may show the car moving forward or turning right). If we cut the entire video into frames and run it all through a VLM in parallel, we can quickly gain a holistic analysis of the video contents and how it changes over time. We then combine all of this information and pass it into an LLM to reason on the information. Finally, it works with an output validation LLM to choose an option from {A, B, C, D, E}.

## README (from the GitHub repository)

# Analysis agent for stock decision system

## Backend Overview  
This project automates stock decision-making using **real-time stock data**, **news analysis**, and **AI-driven explanations**. The frontend was built with flutter.

## Features
- **Fetches stock data** from Alpaca API (stored in Firebase Firestore).  
- **Analyzes stock trends** using a CUDA-powered Decision Model.  
- **Generates AI-powered explanations** via Perplexity AI.  
- **Stores decisions & analysis** in Firestore for easy retrieval.  

## Installation
### **1. Clone the repository**  
```
git clone https://github.com/yourusername/explain-agent.git
cd explain-agent/backend
```

### **2. Set up python environment**  
```
python -m venv venv
source venv/bin/activate  # On Windows: venv\Scripts\activate
pip install -r requirements.txt
```

### **3. Configure Firebase**  
- Add your credentials.json inside the /config folder.
- Ensure Firestore is enabled in the Firebase Console.

## Usage
Run the main pipeline
```
python main.py
```

Run the API
```
python api/app.py
```
This will start a flask server to expose the decision results.


## Detected evidence (automated analysis)

Indexed codebase: 55 recognized source files, 64 KB.
- C (language) — detected in the code
- C++ (language) — detected in the code
- Dart (language) — detected in the code
- HTML (language) — detected in the code
- Kotlin (language) — detected in the code
- Python (language) — detected in the code
- Swift (language) — detected in the code

## Codebase structure (from repository index)

### Files (120 of 122)

```
.vscode/c_cpp_properties.json
.vscode/settings.json
backend/__init__.py
backend/.gitignore
backend/api/app.py
backend/config/firebase_setup.py
backend/data_processing/__init__.py
backend/data_processing/decision_logic.py
backend/data_processing/fetch_news.py
backend/data_processing/fetch_stock_data.py
backend/data_processing/generate_analysis.py
backend/data_processing/store_analysis.py
backend/main.py
backend/requirements.txt
backend/testing/test_fetch_news.py
backend/testing/test_firebase.py
backend/testing/test_firestore.py
cpp/decision
cpp/decision.cpp
frontend/explain_agent/.firebase/hosting.YnVpbGQvd2Vi.cache
frontend/explain_agent/.firebaserc
frontend/explain_agent/.gitignore
frontend/explain_agent/.metadata
frontend/explain_agent/analysis_options.yaml
frontend/explain_agent/android/.gitignore
frontend/explain_agent/android/app/build.gradle
frontend/explain_agent/android/app/src/debug/AndroidManifest.xml
frontend/explain_agent/android/app/src/main/AndroidManifest.xml
frontend/explain_agent/android/app/src/main/kotlin/com/example/explain_agent/MainActivity.kt
frontend/explain_agent/android/app/src/main/res/drawable-v21/launch_background.xml
frontend/explain_agent/android/app/src/main/res/drawable/launch_background.xml
frontend/explain_agent/android/app/src/main/res/values-night/styles.xml
frontend/explain_agent/android/app/src/main/res/values/styles.xml
frontend/explain_agent/android/app/src/profile/AndroidManifest.xml
frontend/explain_agent/android/build.gradle
frontend/explain_agent/android/gradle.properties
frontend/explain_agent/android/gradle/wrapper/gradle-wrapper.properties
frontend/explain_agent/android/settings.gradle
frontend/explain_agent/firebase.json
frontend/explain_agent/firestore.indexes.json
frontend/explain_agent/firestore.rules
frontend/explain_agent/ios/.gitignore
frontend/explain_agent/ios/Flutter/AppFrameworkInfo.plist
frontend/explain_agent/ios/Flutter/Debug.xcconfig
frontend/explain_agent/ios/Flutter/Release.xcconfig
frontend/explain_agent/ios/Podfile
frontend/explain_agent/ios/Runner.xcodeproj/project.pbxproj
frontend/explain_agent/ios/Runner.xcodeproj/project.xcworkspace/contents.xcworkspacedata
frontend/explain_agent/ios/Runner.xcodeproj/project.xcworkspace/xcshareddata/IDEWorkspaceChecks.plist
frontend/explain_agent/ios/Runner.xcodeproj/project.xcworkspace/xcshareddata/WorkspaceSettings.xcsettings
frontend/explain_agent/ios/Runner.xcodeproj/xcshareddata/xcschemes/Runner.xcscheme
frontend/explain_agent/ios/Runner.xcworkspace/contents.xcworkspacedata
frontend/explain_agent/ios/Runner.xcworkspace/xcshareddata/IDEWorkspaceChecks.plist
frontend/explain_agent/ios/Runner.xcworkspace/xcshareddata/WorkspaceSettings.xcsettings
frontend/explain_agent/ios/Runner/AppDelegate.swift
frontend/explain_agent/ios/Runner/Assets.xcassets/AppIcon.appiconset/Contents.json
frontend/explain_agent/ios/Runner/Assets.xcassets/LaunchImage.imageset/Contents.json
frontend/explain_agent/ios/Runner/Assets.xcassets/LaunchImage.imageset/README.md
frontend/explain_agent/ios/Runner/Base.lproj/LaunchScreen.storyboard
frontend/explain_agent/ios/Runner/Base.lproj/Main.storyboard
frontend/explain_agent/ios/Runner/Info.plist
frontend/explain_agent/ios/Runner/Runner-Bridging-Header.h
frontend/explain_agent/lib/firebase_options.dart
frontend/explain_agent/lib/firestore_service.dart
frontend/explain_agent/lib/main.dart
frontend/explain_agent/lib/screens/home_screen.dart
frontend/explain_agent/lib/widgets/stock_chart.dart
frontend/explain_agent/lib/widgets/stock_dropdown.dart
frontend/explain_agent/linux/.gitignore
frontend/explain_agent/linux/CMakeLists.txt
frontend/explain_agent/linux/flutter/CMakeLists.txt
frontend/explain_agent/linux/flutter/generated_plugin_registrant.cc
frontend/explain_agent/linux/flutter/generated_plugin_registrant.h
frontend/explain_agent/linux/flutter/generated_plugins.cmake
frontend/explain_agent/linux/main.cc
frontend/explain_agent/linux/my_application.cc
frontend/explain_agent/linux/my_application.h
frontend/explain_agent/macos/.gitignore
frontend/explain_agent/macos/Flutter/Flutter-Debug.xcconfig
frontend/explain_agent/macos/Flutter/Flutter-Release.xcconfig
frontend/explain_agent/macos/Flutter/GeneratedPluginRegistrant.swift
frontend/explain_agent/macos/Podfile
frontend/explain_agent/macos/Runner.xcodeproj/project.pbxproj
frontend/explain_agent/macos/Runner.xcodeproj/project.xcworkspace/xcshareddata/IDEWorkspaceChecks.plist
frontend/explain_agent/macos/Runner.xcodeproj/xcshareddata/xcschemes/Runner.xcscheme
frontend/explain_agent/macos/Runner.xcworkspace/contents.xcworkspacedata
frontend/explain_agent/macos/Runner.xcworkspace/xcshareddata/IDEWorkspaceChecks.plist
frontend/explain_agent/macos/Runner/AppDelegate.swift
frontend/explain_agent/macos/Runner/Assets.xcassets/AppIcon.appiconset/Contents.json
frontend/explain_agent/macos/Runner/Base.lproj/MainMenu.xib
frontend/explain_agent/macos/Runner/Configs/AppInfo.xcconfig
frontend/explain_agent/macos/Runner/Configs/Debug.xcconfig
frontend/explain_agent/macos/Runner/Configs/Release.xcconfig
frontend/explain_agent/macos/Runner/Configs/Warnings.xcconfig
frontend/explain_agent/macos/Runner/DebugProfile.entitlements
frontend/explain_agent/macos/Runner/Info.plist
frontend/explain_agent/macos/Runner/MainFlutterWindow.swift
frontend/explain_agent/macos/Runner/Release.entitlements
frontend/explain_agent/pubspec.lock
frontend/explain_agent/pubspec.yaml
frontend/explain_agent/README.md
frontend/explain_agent/test/widget_test.dart
frontend/explain_agent/web/index.html
frontend/explain_agent/web/manifest.json
frontend/explain_agent/windows/.gitignore
frontend/explain_agent/windows/CMakeLists.txt
frontend/explain_agent/windows/flutter/CMakeLists.txt
frontend/explain_agent/windows/flutter/generated_plugin_registrant.cc
frontend/explain_agent/windows/flutter/generated_plugin_registrant.h
frontend/explain_agent/windows/flutter/generated_plugins.cmake
frontend/explain_agent/windows/runner/CMakeLists.txt
frontend/explain_agent/windows/runner/flutter_window.cpp
frontend/explain_agent/windows/runner/flutter_window.h
frontend/explain_agent/windows/runner/main.cpp
frontend/explain_agent/windows/runner/resource.h
frontend/explain_agent/windows/runner/runner.exe.manifest
frontend/explain_agent/windows/runner/Runner.rc
frontend/explain_agent/windows/runner/utils.cpp
frontend/explain_agent/windows/runner/utils.h
frontend/explain_agent/windows/runner/win32_window.cpp
[2 more files omitted for size]
```

### Dependencies

- backend/requirements.txt: firebase-admin@==6.2.0, google-cloud-firestore@==2.12.0, numpy@==1.26.3, requests@==2.31.0

### Recent commits (newest first)

- update readme
- deployment
- update analysis prompts
- firestore connection and analysis generation + revamp
- add backend
- first commit

## Key source files (fetched from GitHub, selected and truncated for size)

### backend/requirements.txt

```
# Core dependencies
firebase-admin==6.2.0  # Firebase Firestore SDK
google-cloud-firestore==2.12.0  # Firestore client
requests==2.31.0  # HTTP requests for Perplexity API

# Optional (for local testing)
numpy==1.26.3  # If needed for numerical operations
```

### backend/main.py

```python
from data_processing.fetch_stock_data import fetch_stock_data
from data_processing.decision_logic import make_decision
from data_processing.fetch_news import fetch_stock_news
from data_processing.generate_analysis import generate_analysis
from data_processing.store_analysis import store_analysis
from config.firebase_setup import db

def get_all_stock_symbols():
    """Retrieve all stock symbols from Firestore (document IDs in 'users' collection)."""
    users_ref = db.collection("users")
    stock_docs = users_ref.stream()  # Fetch all documents in "users" collection

    stock_symbols = [doc.id for doc in stock_docs]  # Extract document IDs (stock symbols)

    if not stock_symbols:
        print("⚠️ No stocks found in Firestore.")
    else:
        print(f"✅ Found {len(stock_symbols)} stocks in Firestore.")

    return stock_symbols

def main():
    """Run the full pipeline for all stocks in Firestore."""
    stock_symbols = get_all_stock_symbols()
    
    if not stock_symbols:
        print("No stocks found in Firestore.")
        return

    print(f"Processing {len(stock_symbols)} stocks...")

    for stock_symbol in stock_symbols:
        # Fetch stock data
        initial_value, final_value, last_price = fetch_stock_data(stock_symbol)

        if initial_value is None or final_value is None or last_price is None:
            print(f"Skipping {stock_symbol} due to missing data.")
            continue

        # Determine the decision
        decision = make_decision(initial_value, final_value, last_price)

        # Fetch stock news
        news_summary = fetch_stock_news(stock_symbol)

        # Generate analysis
        analysis = generate_analysis(stock_symbol, decision, initial_value, final_value, last_price, news_summary)

        # Store analysis in Firestore
        store_analysis(stock_symbol, decision, analysis)

        print(f"Completed processing for {stock_symbol}.")

if __name__ == "__main__":
    main()
```

### backend/api/app.py

```python
from flask import Flask, jsonify, request
from backend.temp import fetch_stock_data
from explanation import get_explanation
from flask_cors import CORS

app = Flask(__name__)
CORS(app)  # Enable CORS for frontend access

@app.route("/", methods=["GET"])
def home():
    return jsonify({"message": "Flask backend is running!"})

@app.route("/decision", methods=["GET"])
def get_decision():
    symbol = request.args.get("symbol", "AAPL")
    stock_data = fetch_stock_data(symbol)  # Fetch simulated stock data

    # Simulated decision-making logic (replace with actual C++ logic later)
    decision = "BUY" if symbol == "AAPL" else "HOLD"

    # Generate explanation using Perplexity AI
    explanation = get_explanation(decision, symbol, stock_data)

    return jsonify({"symbol": symbol, "decision": decision, "explanation": explanation})

if __name__ == "__main__":
    print("🚀 Running Flask backend on http://127.0.0.1:5001/")
    app.run(debug=True, host="0.0.0.0", port=5001)
```

### cpp/decision.cpp

```c++
// sample decision making model using simple moving average (SMA) strategy

#include <iostream>
#include <vector>
#include <string>
#include <nlohmann/json.hpp>

using json = nlohmann::json;

struct StockData {
    std::string date;
    double open;
    double close;
    double high;
    double low;
    double volume;
};

double calculateSMA(const std::vector<StockData>& data, int period) {
    if (data.size() < period) return -1;
    double sum = 0;
    for (int i = data.size() - period; i < data.size(); i++) {
        sum += data[i].close;
    }
    return sum / period;
}

std::string makeDecision(const std::vector<StockData>& data) {
    double sma_20 = calculateSMA(data, 20);
    double sma_50 = calculateSMA(data, 50);

    if (sma_20 == -1 || sma_50 == -1) return "Not enough data";
    return (sma_20 > sma_50) ? "BUY" : "SELL";
}

int main() {
    std::string jsonData = R"([{"date":"2024-02-12","open":150,"close":155,"high":157,"low":149,"volume":1000000},
                               {"date":"2024-02-13","open":156,"close":158,"high":160,"low":154,"volume":900000}])";

    std::vector<StockData> stockData;
    json parsedData = json::parse(jsonData);

    for (auto& item : parsedData) {
        stockData.push_back({item["date"], item["open"], item["close"], item["high"], item["low"], item["volume"]});
    }

    std::string decision = makeDecision(stockData);
    std::cout << decision << std::endl;
    return 0;
}

```

### backend/config/firebase_setup.py

```python
import firebase_admin
from firebase_admin import credentials, firestore

# Load Firebase credentials
cred = credentials.Certificate("config/credentials.json")
firebase_admin.initialize_app(cred)

# Initialize Firestore
db = firestore.client()

print("✅ Firebase Firestore connection successful!")
```

### backend/data_processing/decision_logic.py

```python
def make_decision(initial_value, final_value, last_price):
    """Determine buy/sell/hold decision based on stock price movement."""
    
    if final_value < last_price:
        decision = "HOLD"
    elif final_value > initial_value:
        decision = "BUY"
    else:
        decision = "SELL"

    return decision
```

### backend/data_processing/store_analysis.py

```python
from config.firebase_setup import db

def store_analysis(stock_symbol, decision, analysis):
    """Store stock decision and analysis in Firestore."""
    analysis_ref = db.collection("analysis").document(stock_symbol)  # Reference Firestore collection
    analysis_ref.set({
        "decision": decision,
        "analysis": analysis
    })
    print(f"✅ Stored analysis for {stock_symbol}.")
```

### backend/testing/test_firebase.py

```python
from config.firebase_setup import db

# Reference to Firestore collection
test_ref = db.collection("test_collection")

# Write sample data
test_ref.document("test_doc").set({"message": "Firebase is working!"})

# Read sample data
doc = test_ref.document("test_doc").get()

if doc.exists:
    print(f"✅ Firestore Test Passed: {doc.to_dict()}")
else:
    print("❌ Firestore Test Failed: Document not found")
```

### backend/testing/test_firestore.py

```python
from config.firebase_setup import db

def test_stock_retrieval():
    """Test Firestore stock retrieval."""
    users_ref = db.collection("users")
    stock_docs = users_ref.stream()

    stock_symbols = [doc.id for doc in stock_docs]
    
    if not stock_symbols:
        print("⚠️ No stocks found in Firestore.")
    else:
        print(f"✅ Found {len(stock_symbols)} stocks: {stock_symbols}")

test_stock_retrieval()
```

### backend/data_processing/generate_analysis.py

```python
def generate_analysis(stock_symbol, decision, initial_value, final_value, last_price, news_summary):
    """Generate an analysis based on stock data, decision, and news."""
    
    analysis = f"Stock: {stock_symbol}\n"
    analysis += f"Initial predicted price: {initial_value}, Final predicted price: {final_value}, Last known price: {last_price}\n"
    analysis += f"Decision: {decision}\n"
    
    if decision == "BUY":
        analysis += "The model suggests a BUY as the stock is projected to trend upwards.\n"
    elif decision == "HOLD":
        analysis += "The model suggests HOLD since the last known price is higher than the final projection.\n"
    else:
        analysis += "The model suggests SELL as the trend is not strongly positive.\n"

    analysis += f"News Context: {news_summary}\n"

    return analysis
```

[41 more indexed source files omitted to keep this export small. The full file list is in the Codebase structure section above.]