stocktrader / README.md
Benjamin Consolvo
readme
5cd769d
metadata
title: Stock Trader
emoji: 📚
colorFrom: yellow
colorTo: purple
sdk: streamlit
sdk_version: 1.45.1
app_file: app.py
pinned: false
license: apache-2.0
short_description: Stock trading application

Stock Trader Application

Overview

Stock Trader is an interactive web application built with Streamlit that allows you to monitor stock market data, execute trades using a paper trading account through Alpaca, analyze market sentiment, and visualize stock performance. It is hosted on Hugging Face

Prompt and LLM-Generated Code

I used the deepseek-ai/DeepSeek-R1-Distill-Llama-70B model with another LLM chat application I also built on Hugging Face Spaces to generate the initial codebase. The LLM chat app is here: https://huggingface.co/spaces/Intel/intel-ai-enterprise-inference. It takes advantage of the Intel® AI for Enterprise Inference with an OpenAI-compatible API key and model endpoint, hosted on cloud provider Denvr Dataworks.

If you are interested in looking at which models are currently available, you can ping the endpoint with the instructions below. This is standard boilerplate OpenAI code to check on your models that you can use with any OpenAI-compatible API key and model endpoint. First, make sure to save your API key and model endpoint in your environment variables first.

export OPENAI_API_KEY="your-api-key"
export BASE_URL="https://api.inference.denvrdata.com/v1/"

Here is the Python code to check on the models available on your endpoint:

from openai import OpenAI
import os

api_key = os.environ["OPENAI_API_KEY"]
base_url = os.environ["BASE_URL"]
client = OpenAI(api_key=api_key, base_url=base_url)
models= client.models.list()
model_names = [model.id for model in models] 
print(f'client model_names = {model_names}')

You should get back something like:

client model_names = ['deepseek-ai/DeepSeek-R1-Distill-Llama-8B', 'mistralai/Mixtral-8x7B-Instruct-v0.1', 'tiiuae/Falcon3-10B-Instruct', 'BAAI/bge-base-en-v1.5', 'mistralai/Mistral-7B-Instruct-v0.1', 'inceptionai/jais-adapted-70b-chat', 'mistralai/Mistral-7B-Instruct-v0.2', 'tiiuae/Falcon3-7B-Instruct', 'meta-llama/Llama-3.2-1B-Instruct', 'meta-llama/Meta-Llama-3.1-8B-Instruct', 'meta-llama/Llama-3.3-70B-Instruct', 'ALLaM-AI/ALLaM-7B-Instruct-preview', 'meta-llama/Llama-3.2-3B-Instruct', 'meta-llama/Llama-3.1-70B-Instruct', 'deepseek-ai/DeepSeek-R1-Distill-Llama-70B']

The models supported on Denvr at the time of writing are highlighted below. New models are always being added.

Here is the initial prompt I gave to the DeepSeek model to generate the stock trading application:

You are an expert Python software engineer and financial technology developer. Generate a fully functional Python stock trading application that uses the `yfinance` and `alpaca` packages to fetch stock data and automatically buys and sells stocks (a day-trader) based on sentiment analysis of news headlines. The app should:

1. Fetch historical stock data for the top 10 stocks, by volume traded.
2. Fetch the top news headlines for these top 10 stocks and then rate them as “Negative, Neutral, or Positive” from a sentiment analysis model. If negative, sell the stock. If neutral, hold it. If positive, buy the stock. You will have to make sure that we first have a position in the stock before selling it!
3. Keep track of when the stock trading day is open or closed to make sure that trades are only being executed while the trading day is open.
4. Continuously check for updated news and stock prices throughout the trading day.
5. Display key indicators like moving averages and price charts.
6. In addition to automatically buying and selling stocks based on news sentiment, allow the user to buy or sell stocks manually. 
7. Maintain a portfolio state (cash balance, current holdings, transaction history).
8. Log transactions and update the portfolio after each command.
9. Be modular, clean, and readable. Put all of the code in one block, but split into classes and functions as necessary.
10. Create a simple web UI for the program. I prefer streamlit.
11. Include comments, a short README describing how to run the app, and a requirements.txt file for what packages are required.
12. Use only free frameworks and APIs. Don’t use any paid ones.

After generating the initial code, I took that and modified it to my needs to arrive at what you would find in app.py.

Installing the Application

Prerequisites

  • Python 3.8 or higher
  • UV package manager (for dependency management)
  • API keys for:
    • Alpaca Trading API
    • News API
    • Alpha Vantage API

Setup Instructions

  1. Clone the repository
git clone https://huggingface.co/spaces/Intel/stocktrader
cd stocktrader
  1. Initialize the virtual environment
uv init
  1. Install dependencies
uv add -r requirements.txt
  1. Activate the virtual environment
source .venv/bin/activate
  1. Configure your API keys in .streamlit/secrets.toml. For this application, you will need:
  • Alpaca Trading API: Sign up at Alpaca to get your API key and secret key. This app uses paper trading, so make sure to get paper trading credentials.

  • News API: Register at News API to get a free API key for accessing news articles.

  • Alpha Vantage: Get a free API key from Alpha Vantage for stock market data.

The .streamlit/secrets.toml should have the following structure:

ALPACA_API_KEY = "your_alpaca_api_key"
ALPACA_SECRET_KEY = "your_alpaca_secret_key"
NEWS_API_KEY = "your_news_api_key"
ALPHA_VANTAGE_API_KEY = "your_alpha_vantage_api_key"

Or you can add your secrets directly to the Hugging Face Space Settings if you are deploying the application on Hugging Face.

  1. To launch the application locally with streamlit, you can run:
streamlit run app.py

Using the Application

Manual Trading

  1. Enter a Stock Symbol: Type a valid stock ticker symbol (e.g., AAPL, MSFT) in the sidebar.

  2. Check Sentiment: Click the "Check Sentiment" button to analyze current news sentiment for the selected stock.

  3. Trade Execution:

    • Choose between "Enter Quantity" or "Enter Amount"
    • Specify the quantity of shares or dollar amount
    • Select "Buy" or "Sell" action
    • Click "Execute" to place your order. If you submit outside of market hours, it will only execute when the market next opens.
  4. Portfolio Information: View your current cash balance, buying power, equity, and portfolio value in the sidebar.

Stock Charts

The main area displays charts for top volume stocks, showing historical price movements since 2023. You can:

  • Zoom in/out of charts
  • Pan across time periods
  • Hover over data points for precise values

Automated Trading

The application includes an automated trading feature that runs in the background in a loop. You can open up the Logs on the Hugging Face Spaces app if you have deployed it there, or look at the terminal output if you deployed it locally.

  1. Analyzes sentiment for top 10 volume stocks
  2. Executes buy orders for stocks with positive sentiment (if there is sufficient buying power)
  3. Executes sell orders for stocks with negative sentiment (if a position is held)
  4. Holds positions for stocks with neutral sentiment

Common Issues

  • API Rate Limits: If charts or data fail to load, you may have exceeded API rate limits.
    • News API: Limited to 100 requests per day on the free tier
    • Alpha Vantage: Limited to 5 API requests per minute and 500 requests per day on the free tier
  • Invalid Stock Symbols: Ensure you're entering valid ticker symbols when trading.
  • Market Hours: Some features may behave differently when markets are closed, though you should be able to still buy and sell stocks. The actual execution of the trade will only occur once the market opens again.

Follow Up

Connect to LLMs on Intel® Gaudi® accelerators with just an endpoint and an OpenAI-compatible API key, courtesy of cloud-provider Denvr Dataworks: https://www.denvrdata.com/intel

Chat with 6K+ fellow developers on the Intel DevHub Discord: https://discord.gg/kfJ3NKEw5t

Connect with me on LinkedIn: https://linkedin.com/in/bconsolvo