Dhahlan2000 commited on
Commit
494b1fb
·
1 Parent(s): 18e88fc

Enhance sentiment analysis in trading strategy within app.py

Browse files

- Updated get_sentiment method to calculate positive and negative sentiment percentages from news headlines.
- Added handling for cases with no news available, returning None for sentiment data.
- Modified on_trading_iteration to log sentiment data and adjust trading decisions based on new sentiment thresholds.
- Improved trading logic to utilize sentiment percentages instead of binary sentiment classification.

This update refines the trading strategy by incorporating a more nuanced sentiment analysis approach, allowing for better-informed trading decisions.

Files changed (1) hide show
  1. app.py +40 -14
app.py CHANGED
@@ -132,21 +132,46 @@ def execute_alpaca_trading():
132
  three_days_prior = today - Timedelta(days=3)
133
  return today.strftime('%Y-%m-%d'), three_days_prior.strftime('%Y-%m-%d')
134
 
135
- def get_sentiment(self):
136
  today, three_days_prior = self.get_dates()
137
- news = self.api.get_news(symbol=self.symbol,
138
- start=three_days_prior,
139
- end=today)
140
- news = [ev.__dict__["_raw"]["headline"] for ev in news]
141
- probability, sentiment = estimate_sentiment(news)
142
- return probability, sentiment
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
143
 
144
  def on_trading_iteration(self):
145
- cash, last_price, quantity = self.position_sizing()
146
- probability, sentiment = self.get_sentiment()
 
 
 
 
 
 
147
 
148
  if cash > last_price:
149
- if sentiment == "positive" and probability > .999:
150
  if self.last_trade == "sell":
151
  self.sell_all()
152
  order = self.create_order(
@@ -155,11 +180,11 @@ def execute_alpaca_trading():
155
  "buy",
156
  type="bracket",
157
  take_profit_price=last_price * 1.20,
158
- stop_loss_price=last_price * .95
159
  )
160
  self.submit_order(order)
161
  self.last_trade = "buy"
162
- elif sentiment == "negative" and probability > .999:
163
  if self.last_trade == "buy":
164
  self.sell_all()
165
  order = self.create_order(
@@ -167,12 +192,13 @@ def execute_alpaca_trading():
167
  quantity,
168
  "sell",
169
  type="bracket",
170
- take_profit_price=last_price * .8,
171
- stop_loss_price=last_price * 1.05
172
  )
173
  self.submit_order(order)
174
  self.last_trade = "sell"
175
 
 
176
  start_date = datetime(2021, 1, 1)
177
  end_date = datetime(2024, 10, 1)
178
  broker = Alpaca(ALPACA_CREDS)
 
132
  three_days_prior = today - Timedelta(days=3)
133
  return today.strftime('%Y-%m-%d'), three_days_prior.strftime('%Y-%m-%d')
134
 
135
+ def get_sentiment(self):
136
  today, three_days_prior = self.get_dates()
137
+ news = self.api.get_news(symbol=self.symbol, start=three_days_prior, end=today)
138
+
139
+ if not news:
140
+ return None, None # No news available
141
+
142
+ # Extract headlines
143
+ news_headlines = [ev.__dict__["_raw"]["headline"] for ev in news]
144
+
145
+ # Calculate sentiment for each headline
146
+ positive_count = 0
147
+ negative_count = 0
148
+
149
+ for headline in news_headlines:
150
+ probability, sentiment = estimate_sentiment([headline])
151
+ if sentiment == "positive":
152
+ positive_count += 1
153
+ elif sentiment == "negative":
154
+ negative_count += 1
155
+
156
+ total_articles = len(news_headlines)
157
+ positive_percentage = (positive_count / total_articles) * 100 if total_articles else 0
158
+ negative_percentage = (negative_count / total_articles) * 100 if total_articles else 0
159
+
160
+ return positive_percentage, negative_percentage
161
+
162
 
163
  def on_trading_iteration(self):
164
+ cash, last_price, quantity = self.position_sizing()
165
+ positive_percentage, negative_percentage = self.get_sentiment()
166
+
167
+ if positive_percentage is None or negative_percentage is None:
168
+ self.log("No sentiment data available, skipping this iteration.")
169
+ return
170
+
171
+ self.log(f"Positive Sentiment: {positive_percentage:.2f}%, Negative Sentiment: {negative_percentage:.2f}%")
172
 
173
  if cash > last_price:
174
+ if positive_percentage > 60 and negative_percentage < 30: # Example threshold
175
  if self.last_trade == "sell":
176
  self.sell_all()
177
  order = self.create_order(
 
180
  "buy",
181
  type="bracket",
182
  take_profit_price=last_price * 1.20,
183
+ stop_loss_price=last_price * 0.95,
184
  )
185
  self.submit_order(order)
186
  self.last_trade = "buy"
187
+ elif negative_percentage > 60 and positive_percentage < 30: # Example threshold
188
  if self.last_trade == "buy":
189
  self.sell_all()
190
  order = self.create_order(
 
192
  quantity,
193
  "sell",
194
  type="bracket",
195
+ take_profit_price=last_price * 0.8,
196
+ stop_loss_price=last_price * 1.05,
197
  )
198
  self.submit_order(order)
199
  self.last_trade = "sell"
200
 
201
+
202
  start_date = datetime(2021, 1, 1)
203
  end_date = datetime(2024, 10, 1)
204
  broker = Alpaca(ALPACA_CREDS)