In this tutorial, we'll walk you through the process of building a trader bot that uses sentiment analysis of live news events to make trading decisions. By leveraging tools like Alpaca for trading and Transformers for sentiment analysis, we'll create a powerful bot capable of reacting to market sentiment in real-time.
GitHub Repository
Prerequisites
Before we begin, make sure you have the following set up:
- Python 3.10 installed on your system.
- An Alpaca account with API key and secret.
- Installation of necessary dependencies including lumibot, timedelta, and alpaca-trade-api.
- Installation of transformers for sentiment analysis.
Step 1: Setting Up Environment
Start by creating a virtual environment and installing the required dependencies:
conda create -n trader python=3.10
conda activate trader
pip install lumibot timedelta alpaca-trade-api==3.1.1
pip install torch torchvision torchaudio transformers
Step 2: Configuring Alpaca API
Update the API_KEY and API_SECRET in your tradingbot.py file with the values from your Alpaca account.
Step 3: Implementing Sentiment Analysis
Create a script for sentiment analysis using Transformers. You can use the finbert_utils.py script provided in the tutorial.
from transformers import AutoTokenizer, AutoModelForSequenceClassification
import torch
from typing import Tuple
device = "cuda:0" if torch.cuda.is_available() else "cpu"
tokenizer = AutoTokenizer.from_pretrained("ProsusAI/finbert")
model = AutoModelForSequenceClassification.from_pretrained("ProsusAI/finbert").to(device)
labels = ["positive", "negative", "neutral"]
def estimate_sentiment(news):
if news:
tokens = tokenizer(news, return_tensors="pt", padding=True).to(device)
result = model(tokens["input_ids"], attention_mask=tokens["attention_mask"])[
"logits"
]
result = torch.nn.functional.softmax(torch.sum(result, 0), dim=-1)
probability = result[torch.argmax(result)]
sentiment = labels[torch.argmax(result)]
return probability, sentiment
else:
return 0, labels[-1]
if __name__ == "__main__":
tensor, sentiment = estimate_sentiment(['markets responded negatively to the news!','traders were displeased!'])
print(tensor, sentiment)
print(torch.cuda.is_available())
Step 4: Building the Trader Bot
Now, let's create the trader bot script tradingbot.py using the Lumibot framework. We'll define a strategy (MLTrader) that utilizes sentiment analysis to make trading decisions based on live news events.
from lumibot.brokers import Alpaca
from lumibot.backtesting import YahooDataBacktesting
from lumibot.strategies.strategy import Strategy
from lumibot.traders import Trader
from datetime import datetime
from alpaca_trade_api import REST
from timedelta import Timedelta
from finbert_utils import estimate_sentiment
API_KEY = "YOUR API KEY"
API_SECRET = "YOUR API SECRET"
BASE_URL = "https://paper-api.alpaca.markets"
ALPACA_CREDS = {
"API_KEY":API_KEY,
"API_SECRET": API_SECRET,
"PAPER": True
}
class MLTrader(Strategy):
def initialize(self, symbol:str="SPY", cash_at_risk:float=.5):
self.symbol = symbol
self.sleeptime = "24H"
self.last_trade = None
self.cash_at_risk = cash_at_risk
self.api = REST(base_url=BASE_URL, key_id=API_KEY, secret_key=API_SECRET)
def position_sizing(self):
cash = self.get_cash()
last_price = self.get_last_price(self.symbol)
quantity = round(cash * self.cash_at_risk / last_price,0)
return cash, last_price, quantity
def get_dates(self):
today = self.get_datetime()
three_days_prior = today - Timedelta(days=3)
return today.strftime('%Y-%m-%d'), three_days_prior.strftime('%Y-%m-%d')
def get_sentiment(self):
today, three_days_prior = self.get_dates()
news = self.api.get_news(symbol=self.symbol,
start=three_days_prior,
end=today)
news = [ev.__dict__["_raw"]["headline"] for ev in news]
probability, sentiment = estimate_sentiment(news)
return probability, sentiment
def on_trading_iteration(self):
cash, last_price, quantity = self.position_sizing()
probability, sentiment = self.get_sentiment()
if cash > last_price:
if sentiment == "positive" and probability > .999:
if self.last_trade == "sell":
self.sell_all()
order = self.create_order(
self.symbol,
quantity,
"buy",
type="bracket",
take_profit_price=last_price*1.20,
stop_loss_price=last_price*.95
)
self.submit_order(order)
self.last_trade = "buy"
elif sentiment == "negative" and probability > .999:
if self.last_trade == "buy":
self.sell_all()
order = self.create_order(
self.symbol,
quantity,
"sell",
type="bracket",
take_profit_price=last_price*.8,
stop_loss_price=last_price*1.05
)
self.submit_order(order)
self.last_trade = "sell"
start_date = datetime(2020,1,1)
end_date = datetime(2023,12,31)
broker = Alpaca(ALPACA_CREDS)
strategy = MLTrader(name='mlstrat', broker=broker,
parameters={"symbol":"SPY",
"cash_at_risk":.5})
strategy.backtest(
YahooDataBacktesting,
start_date,
end_date,
parameters={"symbol":"SPY", "cash_at_risk":.5}
)
# trader = Trader()
# trader.add_strategy(strategy)
# trader.run_all()
Step 5: Running the Bot
Once everything is set up, you can run the bot using the following command:
python tradingbot.py
Troubleshooting
SSL Errors: If you encounter SSL errors when communicating with the Alpaca API, make sure to install the required SSL certificates.
By following these steps, you'll have a fully functional trader bot capable of analyzing market sentiment and making informed trading decisions. Happy trading!
Note: Don't forget to make the necessary adjustments and customizations based on your specific requirements and preferences. GitHub Repository
Top comments (0)