Spaces:
Running
Running
Benjamin Consolvo
commited on
Commit
·
c084b1e
1
Parent(s):
1aa276e
stock trader readme
Browse files
README.md
CHANGED
@@ -14,19 +14,20 @@ short_description: 'Stock trading application'
|
|
14 |
# Stock Trader Application
|
15 |
|
16 |
## Overview
|
17 |
-
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,
|
18 |
|
|
|
19 |
|
20 |
## Prompt and LLM-Generated Code
|
21 |
-
|
22 |
|
23 |
-
If you are interested in looking at which models are currently available, you can ping the endpoint with the instructions below. This is
|
24 |
```bash
|
25 |
export OPENAI_API_KEY="your-api-key"
|
26 |
export BASE_URL="https://api.inference.denvrdata.com/v1/"
|
27 |
```
|
28 |
|
29 |
-
|
30 |
```python
|
31 |
from openai import OpenAI
|
32 |
import os
|
@@ -41,31 +42,11 @@ print(f'client model_names = {model_names}')
|
|
41 |
|
42 |
You should get back something like:
|
43 |
|
44 |
-
|
45 |
```bash
|
46 |
-
client model_names = ['deepseek-ai/DeepSeek-R1-Distill-Llama-8B', 'mistralai/Mixtral-8x7B-Instruct-v0.1', 'tiiuae/Falcon3-10B-Instruct',
|
47 |
```
|
48 |
-
|
49 |
-
|
50 |
-
| Model |
|
51 |
-
|------------|
|
52 |
-
| [ALLaM-AI/ALLaM-7B-Instruct-preview](https://huggingface.co/ALLaM-AI/ALLaM-7B-Instruct-preview) |
|
53 |
-
| [BAAI/bge-base-en-v1.5](https://huggingface.co/BAAI/bge-base-en-v1.5) |
|
54 |
-
| [deepseek-ai/DeepSeek-R1-Distill-Llama-70B](https://huggingface.co/deepseek-ai/DeepSeek-R1-Distill-Llama-70B) |
|
55 |
-
| [deepseek-ai/DeepSeek-R1-Distill-Llama-8B](https://huggingface.co/deepseek-ai/DeepSeek-R1-Distill-Llama-8B) |
|
56 |
-
| [inceptionai/jais-adapted-70b-chat](https://huggingface.co/inceptionai/jais-adapted-70b-chat) |
|
57 |
-
| [meta-llama/Llama-3.1-70B-Instruct](https://huggingface.co/meta-llama/Llama-3.1-70B-Instruct) |
|
58 |
-
| [meta-llama/Llama-3.2-1B-Instruct](https://huggingface.co/meta-llama/Llama-3.2-1B-Instruct) |
|
59 |
-
| [meta-llama/Llama-3.2-3B-Instruct](https://huggingface.co/meta-llama/Llama-3.2-3B-Instruct) |
|
60 |
-
| [meta-llama/Llama-3.3-70B-Instruct](https://huggingface.co/meta-llama/Llama-3.3-70B-Instruct) |
|
61 |
-
| [meta-llama/Meta-Llama-3.1-8B-Instruct](https://huggingface.co/meta-llama/Meta-Llama-3.1-8B-Instruct) |
|
62 |
-
| [mistralai/Mistral-7B-Instruct-v0.1](https://huggingface.co/mistralai/Mistral-7B-Instruct-v0.1) |
|
63 |
-
| [mistralai/Mistral-7B-Instruct-v0.2](https://huggingface.co/mistralai/Mistral-7B-Instruct-v0.2) |
|
64 |
-
| [mistralai/Mixtral-8x7B-Instruct-v0.1](https://huggingface.co/mistralai/Mixtral-8x7B-Instruct-v0.1) |
|
65 |
-
| [tiiuae/Falcon3-10B-Instruct](https://huggingface.co/tiiuae/Falcon3-10B-Instruct) |
|
66 |
-
| [tiiuae/Falcon3-7B-Instruct](https://huggingface.co/tiiuae/Falcon3-7B-Instruct) |
|
67 |
-
|
68 |
-
Here is the initial prompt I gave to the DeepSeek model to generate the stock trading application:
|
69 |
|
70 |
```text
|
71 |
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:
|
@@ -84,16 +65,9 @@ You are an expert Python software engineer and financial technology developer. G
|
|
84 |
12. Use only free frameworks and APIs. Don’t use any paid ones.
|
85 |
```
|
86 |
|
87 |
-
|
88 |
|
89 |
## Installing the Application
|
90 |
-
### Prerequisites
|
91 |
-
- Python 3.8 or higher
|
92 |
-
- [UV](https://github.com/astral-sh/uv) package manager (for dependency management)
|
93 |
-
- API keys for:
|
94 |
-
- Alpaca Trading API
|
95 |
-
- News API
|
96 |
-
- Alpha Vantage API
|
97 |
|
98 |
### Setup Instructions
|
99 |
1. Clone the repository
|
@@ -119,7 +93,7 @@ source .venv/bin/activate
|
|
119 |
```
|
120 |
|
121 |
5. Configure your API keys in `.streamlit/secrets.toml`. For this application, you will need:
|
122 |
-
- **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.
|
123 |
|
124 |
- **News API**: Register at [News API](https://newsapi.org/) to get a free API key for accessing news articles.
|
125 |
|
@@ -134,9 +108,12 @@ NEWS_API_KEY = "your_news_api_key"
|
|
134 |
ALPHA_VANTAGE_API_KEY = "your_alpha_vantage_api_key"
|
135 |
```
|
136 |
|
137 |
-
Or you can add your secrets directly to the Hugging Face Space Settings if you are deploying the application on Hugging Face.
|
|
|
|
|
138 |
|
139 |
-
|
|
|
140 |
```bash
|
141 |
streamlit run app.py
|
142 |
```
|
@@ -145,13 +122,16 @@ streamlit run app.py
|
|
145 |
### Manual Trading
|
146 |
1. **Enter a Stock Symbol**: Type a valid stock ticker symbol (e.g., AAPL, MSFT) in the sidebar.
|
147 |
|
148 |
-
2. **Check Sentiment**: Click the "Check Sentiment" button to analyze current news sentiment for the selected stock.
|
|
|
|
|
|
|
149 |
|
150 |
3. **Trade Execution**:
|
151 |
-
|
152 |
-
|
153 |
-
|
154 |
-
|
155 |
|
156 |
4. **Portfolio Information**: View your current cash balance, buying power, equity, and portfolio value in the sidebar.
|
157 |
|
@@ -162,11 +142,11 @@ The main area displays charts for top volume stocks, showing historical price mo
|
|
162 |
- Hover over data points for precise values
|
163 |
|
164 |
### Automated Trading
|
165 |
-
The application includes an automated trading feature that runs in the background in a loop. You can open up the
|
166 |
|
167 |
1. Analyzes sentiment for top 10 volume stocks
|
168 |
-
2. Executes buy orders for stocks with positive sentiment
|
169 |
-
3. Executes sell orders for stocks with negative sentiment
|
170 |
4. Holds positions for stocks with neutral sentiment
|
171 |
|
172 |
### Common Issues
|
@@ -176,10 +156,13 @@ The application includes an automated trading feature that runs in the backgroun
|
|
176 |
- **Invalid Stock Symbols**: Ensure you're entering valid ticker symbols when trading.
|
177 |
- **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.
|
178 |
|
179 |
-
|
|
|
|
|
|
|
|
|
180 |
|
181 |
-
|
182 |
|
183 |
-
|
184 |
|
185 |
-
Connect with me on LinkedIn: https://linkedin.com/in/bconsolvo
|
|
|
14 |
# Stock Trader Application
|
15 |
|
16 |
## Overview
|
17 |
+
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):
|
18 |
|
19 |
+
[](https://huggingface.co/spaces/Intel/stocktrader)
|
20 |
|
21 |
## Prompt and LLM-Generated Code
|
22 |
+
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.
|
23 |
|
24 |
+
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.
|
25 |
```bash
|
26 |
export OPENAI_API_KEY="your-api-key"
|
27 |
export BASE_URL="https://api.inference.denvrdata.com/v1/"
|
28 |
```
|
29 |
|
30 |
+
And the code to check the available models on your endpoint:
|
31 |
```python
|
32 |
from openai import OpenAI
|
33 |
import os
|
|
|
42 |
|
43 |
You should get back something like:
|
44 |
|
|
|
45 |
```bash
|
46 |
+
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']
|
47 |
```
|
48 |
+
|
49 |
+
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.
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
50 |
|
51 |
```text
|
52 |
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:
|
|
|
65 |
12. Use only free frameworks and APIs. Don’t use any paid ones.
|
66 |
```
|
67 |
|
68 |
+
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).
|
69 |
|
70 |
## Installing the Application
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
71 |
|
72 |
### Setup Instructions
|
73 |
1. Clone the repository
|
|
|
93 |
```
|
94 |
|
95 |
5. Configure your API keys in `.streamlit/secrets.toml`. For this application, you will need:
|
96 |
+
- **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.
|
97 |
|
98 |
- **News API**: Register at [News API](https://newsapi.org/) to get a free API key for accessing news articles.
|
99 |
|
|
|
108 |
ALPHA_VANTAGE_API_KEY = "your_alpha_vantage_api_key"
|
109 |
```
|
110 |
|
111 |
+
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).
|
112 |
+
|
113 |
+
[](https://huggingface.co/spaces/Intel/stocktrader)
|
114 |
|
115 |
+
|
116 |
+
6. To launch the application locally with Streamlit, you can run:
|
117 |
```bash
|
118 |
streamlit run app.py
|
119 |
```
|
|
|
122 |
### Manual Trading
|
123 |
1. **Enter a Stock Symbol**: Type a valid stock ticker symbol (e.g., AAPL, MSFT) in the sidebar.
|
124 |
|
125 |
+
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:
|
126 |
+
- [-1,0.1): Negative
|
127 |
+
- (-0.1,0.1): Neutral
|
128 |
+
- (0.1,1]: Positive
|
129 |
|
130 |
3. **Trade Execution**:
|
131 |
+
- Choose between "Enter Quantity" or "Enter Amount"
|
132 |
+
- Specify the quantity of shares or dollar amount
|
133 |
+
- Select "Buy" or "Sell" action
|
134 |
+
- Click "Execute" to place your order. If you submit outside of market hours, it will only execute when the market next opens.
|
135 |
|
136 |
4. **Portfolio Information**: View your current cash balance, buying power, equity, and portfolio value in the sidebar.
|
137 |
|
|
|
142 |
- Hover over data points for precise values
|
143 |
|
144 |
### Automated Trading
|
145 |
+
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?
|
146 |
|
147 |
1. Analyzes sentiment for top 10 volume stocks
|
148 |
+
2. Executes buy orders for stocks with positive sentiment, if there is sufficient buying power in the Alpaca account
|
149 |
+
3. Executes sell orders for stocks with negative sentiment, if a position is held in the stock
|
150 |
4. Holds positions for stocks with neutral sentiment
|
151 |
|
152 |
### Common Issues
|
|
|
156 |
- **Invalid Stock Symbols**: Ensure you're entering valid ticker symbols when trading.
|
157 |
- **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.
|
158 |
|
159 |
+
## Follow Up
|
160 |
+
|
161 |
+
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).
|
162 |
+
|
163 |
+
Chat with 6K+ fellow developers on the [Intel DevHub Discord](https://discord.gg/kfJ3NKEw5t).
|
164 |
|
165 |
+
Follow [Intel Software on LinkedIn](https://www.linkedin.com/showcase/intel-software/).
|
166 |
|
167 |
+
For more Intel AI developer resources, see [developer.intel.com/ai](https://developer.intel.com/ai).
|
168 |
|
|
app.py
CHANGED
@@ -505,9 +505,9 @@ class TradingApp:
|
|
505 |
logger.error(f"Error fetching URLs for headlines: {e}")
|
506 |
headlines_with_links = [(headline, None) for headline in article_headlines]
|
507 |
|
508 |
-
# Always use
|
509 |
for idx, (headline, url) in enumerate(headlines_with_links, 1):
|
510 |
-
color = "#
|
511 |
if url:
|
512 |
st.markdown(
|
513 |
f"<div style='font-size:0.75em; margin-bottom:0.15em; color:{color};'>"
|
@@ -695,8 +695,8 @@ def get_market_times(alpaca_api):
|
|
695 |
return None, None, None, None
|
696 |
|
697 |
def main():
|
698 |
-
st.title("
|
699 |
-
st.markdown("This is a fun stock trading application that uses a combination of key frameworks like Alpaca API, yfinance, News API, and Alpha Vantage for stock information and trading. Come and trade
|
700 |
|
701 |
if not st.secrets['ALPACA_API_KEY'] or not st.secrets['NEWS_API_KEY']:
|
702 |
st.error("Please configure your ALPACA_API_KEY and NEWS_API_KEY")
|
|
|
505 |
logger.error(f"Error fetching URLs for headlines: {e}")
|
506 |
headlines_with_links = [(headline, None) for headline in article_headlines]
|
507 |
|
508 |
+
# Always use teal for headline text/links for better visibility
|
509 |
for idx, (headline, url) in enumerate(headlines_with_links, 1):
|
510 |
+
color = "#008080" # teal
|
511 |
if url:
|
512 |
st.markdown(
|
513 |
f"<div style='font-size:0.75em; margin-bottom:0.15em; color:{color};'>"
|
|
|
695 |
return None, None, None, None
|
696 |
|
697 |
def main():
|
698 |
+
st.title("Stock Trading Application")
|
699 |
+
st.markdown("This is a fun stock trading application that uses a combination of key frameworks like Alpaca API, yfinance, News API, and Alpha Vantage for stock information and trading. Come and trade money! Well, it's a paper account, so it's not real money. But still, have fun!")
|
700 |
|
701 |
if not st.secrets['ALPACA_API_KEY'] or not st.secrets['NEWS_API_KEY']:
|
702 |
st.error("Please configure your ALPACA_API_KEY and NEWS_API_KEY")
|