Spaces:
Running
Running
title: Stock Trader | |
emoji: 📚 | |
colorFrom: yellow | |
colorTo: purple | |
sdk: streamlit | |
sdk_version: 1.42.2 | |
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. The application combines real-time market data, news sentiment analysis, and automated trading capabilities in an easy-to-use interface. | |
## Features | |
- **Real-time Stock Data**: Track current prices and market status | |
- **Manual Trading**: Buy and sell stocks with customizable quantities | |
- **Sentiment Analysis**: Analyze news sentiment for stocks using multiple sources | |
- **Automated Trading**: Background process trades stocks based on sentiment analysis | |
- **Portfolio Visualization**: View your holdings and portfolio value in real-time | |
- **Market Insights**: Monitor top volume stocks with interactive charts | |
## Prompt | |
I used a DeepSeek distilled Llama model with the following chat application to build the initial codebase: https://huggingface.co/spaces/Intel/intel-ai-enterprise-inference. | |
Here is the prompt I wrote: | |
```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. | |
``` | |
## Installation | |
### Prerequisites | |
- Python 3.8 or higher | |
- [UV](https://github.com/astral-sh/uv) package manager (for dependency management) | |
- API keys for: | |
- Alpaca Trading API | |
- News API | |
- Alpha Vantage API | |
### 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. | |
- **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 if you are deploying the application on Hugging Face. | |
6. Launch the application | |
```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. | |
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: | |
1. Analyzes sentiment for top 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 | |
## Troubleshooting | |
### Common Issues | |
- **API Rate Limits**: If charts or data fail to load, you may have exceeded API rate limits. Wait a few minutes and try again. | |
- **Invalid Stock Symbols**: Ensure you're entering valid ticker symbols when trading. | |
- **Market Hours**: Some features may behave differently when markets are closed. | |
### API Limitations | |
- **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 | |
## License | |
This project is licensed under the Apache 2.0 License. | |