stocktrader / README.md
Benjamin Consolvo
syntax
30f4c63
---
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 a Streamlit front-end that allows you to monitor stock market data, execute trades using a paper trading account through Alpaca, automatically trade stocks based on sentiment, and visualize stock performance. It is hosted on Hugging Face Spaces [here](https://huggingface.co/spaces/Intel/stocktrader):
[![stocktrader](images/stocktrader.png)](https://huggingface.co/spaces/Intel/stocktrader)
## Prompt and LLM-Generated Code
To first build a draft of the codebase, the [deepseek-ai/DeepSeek-R1-Distill-Llama-70B](https://huggingface.co/deepseek-ai/DeepSeek-R1-Distill-Llama-70B) model was used with another LLM chat application on Hugging Face Spaces. The LLM chat app is [here](https://huggingface.co/spaces/Intel/intel-ai-enterprise-inference). It takes advantage of the inference endpoint [Intel® AI for Enterprise Inference](https://github.com/opea-project/Enterprise-Inference) with an OpenAI-compatible API key and model endpoint, leveraging the power of Intel® Gaudi® AI accelerators.
If you are interested in looking at which models are currently available, you can ping the endpoint with the instructions below. This is 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.
```bash
export OPENAI_API_KEY="your-api-key"
export BASE_URL="https://api.inference.denvrdata.com/v1/"
```
And the code to check the available models on your endpoint:
```python
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:
```bash
client model_names = ['deepseek-ai/DeepSeek-R1-Distill-Llama-8B', 'mistralai/Mixtral-8x7B-Instruct-v0.1', 'tiiuae/Falcon3-10B-Instruct', ... 'deepseek-ai/DeepSeek-R1-Distill-Llama-70B']
```
The initial prompt below was given to the [deepseek-ai/DeepSeek-R1-Distill-Llama-70B](https://hf.co/deepseek-ai/DeepSeek-R1-Distill-Llama-70B) model to generate the stock trading application.
```text
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.
```
The code was iteratively improved with the help of LLMs and some manual intervention. The final application can be found at [app.py](app.py).
## Installing the Application
### Setup Instructions
1. Clone the repository
```sh
git clone https://huggingface.co/spaces/Intel/stocktrader
cd stocktrader
```
2. Initialize the virtual environment
```bash
uv init
```
3. Install dependencies
```bash
uv add -r requirements.txt
```
4. Activate the virtual environment
```bash
source .venv/bin/activate
```
5. Configure your API keys in `.streamlit/secrets.toml`. For this application, you will need:
- **Alpaca Trading API**: Sign up at [Alpaca](https://alpaca.markets/) to get your API key and secret key. This app uses paper trading, so make sure to get paper trading credentials. You will likely need multifactor authentication to login to obtain the key and secret.
- **News API**: Register at [News API](https://newsapi.org/) to get a free API key for accessing news articles.
- **Alpha Vantage**: Get a free API key from [Alpha Vantage](https://www.alphavantage.co/support/#api-key) for stock market data.
The `.streamlit/secrets.toml` should have the following structure:
```toml
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 under "Variables and Secrets" if you are deploying the application on Hugging Face. If you want to host the application on Hugging Face, the easiest way is to duplicate the Hugging Face Space (per the screenshot below).
[![hf_dup](images/hf_dup.png)](https://huggingface.co/spaces/Intel/stocktrader)
6. To launch the application locally with Streamlit, you can run:
```bash
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. Also, the article titles and links will be displayed that were used to calculate sentiment for that stock. The sentiment should be in the range of [-1,1]. The following limits are used to rate the sentiment:
- [-1,-0.1): Negative
- (-0.1,0.1): Neutral
- (0.1,1]: Positive
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. How does it work?
1. Analyzes sentiment for top 10 volume stocks
2. Executes buy orders for stocks with positive sentiment, if there is sufficient buying power in the Alpaca account
3. Executes sell orders for stocks with negative sentiment, if a position is held in the stock
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 AI accelerators with just an endpoint and an OpenAI-compatible API key, using the inference endpoint [Intel® AI for Enterprise Inference](https://github.com/opea-project/Enterprise-Inference), powered by OPEA. At the time of writing, the endpoint is available on cloud provider [Denvr Dataworks](https://www.denvrdata.com/intel).
Chat with 6K+ fellow developers on the [Intel DevHub Discord](https://discord.gg/kfJ3NKEw5t).
Follow [Intel Software on LinkedIn](https://www.linkedin.com/showcase/intel-software/).
For more Intel AI developer resources, see [developer.intel.com/ai](https://developer.intel.com/ai).