tosin2013 commited on
Commit
61a4161
·
1 Parent(s): e66a30a

updating backtest wording

Browse files
Files changed (1) hide show
  1. app.py +102 -94
app.py CHANGED
@@ -72,23 +72,27 @@ class TrendFollowingStrategy(bt.Strategy):
72
 
73
 
74
  def fetch_forex_intraday(api_key, from_symbol, to_symbol, interval, outputsize='compact'):
75
- url = f'https://www.alphavantage.co/query?function=FX_INTRADAY&from_symbol={from_symbol}&to_symbol={to_symbol}&interval={interval}&apikey={api_key}&outputsize={outputsize}'
76
- response = requests.get(url)
77
- data = response.json()
 
78
 
79
- # Extracting the time series data from the JSON object
80
- time_series_key = 'Time Series FX (' + str(interval) + ')'
81
- forex_data = pd.DataFrame(data[time_series_key]).T
82
- forex_data.columns = ['Open', 'High', 'Low', 'Close']
83
 
84
- # Convert index to datetime and sort data
85
- forex_data.index = pd.to_datetime(forex_data.index)
86
- forex_data.sort_index(inplace=True)
87
 
88
- # Convert columns to numeric
89
- forex_data = forex_data.apply(pd.to_numeric)
90
 
91
- return forex_data
 
 
 
92
 
93
  def analyze_sentiment(json_response, target_ticker):
94
  """
@@ -232,95 +236,99 @@ def run_backtest(api_key, from_symbol, to_symbol, interval):
232
  - html_message (str): An HTML message containing the calculated statistics, trade log, and trade decision information.
233
  """
234
  # Set up Cerebro engine
235
- cerebro = bt.Cerebro()
236
- cerebro.addstrategy(TrendFollowingStrategy)
237
-
238
- # Add data feed to Cerebro
239
- data = load_data(api_key, from_symbol, to_symbol, interval)
240
- cerebro.adddata(data)
241
-
242
- # Set initial cash (optional)
243
- cerebro.broker.set_cash(10000)
244
-
245
- # Run the backtest
246
- strategy_instance = cerebro.run()[0]
247
- api_endpoint = "https://www.alphavantage.co/query" # Replace with actual endpoint
248
-
249
- # Calculate win and loss percentages
250
- total_trades = strategy_instance.trade_count
251
- total_wins = strategy_instance.win_count
252
- total_losses = strategy_instance.loss_count
253
-
254
- win_percentage = (total_wins / total_trades) * 100
255
- loss_percentage = (total_losses / total_trades) * 100
256
-
257
- # Get trade log from the strategy
258
- trade_log = strategy_instance.get_trade_log()
259
-
260
- # Iterate through the trade log and count valid trades
261
- valid_buy_trades = 0
262
- valid_sell_trades = 0
263
-
264
- # Initialize a variable to store the last trade line
265
- last_trade_line = ""
266
-
267
- # Iterate through the trade log and count valid trades
268
- for trade in trade_log:
269
- if trade['trade_type'] == 'CALL':
270
- valid_buy_trades += 1
271
- elif trade['trade_type'] == 'PUT':
272
- valid_sell_trades += 1
273
-
274
- # Store the last trade line
275
- last_trade_line = f"Trade {trade['trade_num']}: {trade['trade_type']} - {trade['outcome']}"
276
-
277
- for trade in trade_log:
278
- if trade['trade_type'] == 'CALL':
279
- valid_buy_trades += 1
280
- elif trade['trade_type'] == 'PUT':
281
- valid_sell_trades += 1
282
-
283
- # Determine if the backtest agrees (valid Buy trades > valid Sell trades)
284
- if win_percentage > loss_percentage:
285
- signal = last_trade_line
286
- color = "green"
287
- else:
288
- signal = last_trade_line
289
- color = "red"
290
 
 
 
 
291
 
292
- # Get trade decision information
293
- trade_decision, trade_type, trade_timeframe, reason = should_trade(strategy_instance, api_endpoint, api_key, from_symbol, to_symbol)
294
 
295
 
296
- # Create an HTML message with the calculated statistics, trade log, and trade decision information
297
- html_message = f"""
298
- <p><strong>Strategy Performance Summary:</strong></p>
299
- <p>On the {interval} timeframe</p>
300
- <p>*****************************</p>
301
- <p>Total Trades: {total_trades}</p>
302
- <p>Total Wins: {total_wins} ({win_percentage:.2f}%)</p>
303
- <p>Total Losses: {total_losses} ({loss_percentage:.2f}%)</p>
304
- <p>Signal: <span style='color: {color}'>{signal}</span></p>
305
- <p><strong>Trade Log:</strong></p>
306
- <ul>
307
- """
308
-
309
- for trade in trade_log:
310
- html_message += f"<li>Trade {trade['trade_num']}: {trade['trade_type']} - {trade['outcome']}</li>"
311
 
 
 
 
 
312
 
313
- html_message += "</ul>"
 
314
 
315
- # Include trade decision information
316
- html_message += f"""
317
- <p><strong>Trade Decision:</strong></p>
318
- <p>Trade Type: {trade_type}</p>
319
- <p>Timeframe: {trade_timeframe}</p>
320
- <p>Reason: {reason}</p>
321
- """
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
322
 
323
- return html_message
 
 
324
 
325
 
326
  # Define a list of popular currency pairs for the dropdowns
 
72
 
73
 
74
  def fetch_forex_intraday(api_key, from_symbol, to_symbol, interval, outputsize='compact'):
75
+ try:
76
+ url = f'https://www.alphavantage.co/query?function=FX_INTRADAY&from_symbol={from_symbol}&to_symbol={to_symbol}&interval={interval}&apikey={api_key}&outputsize={outputsize}'
77
+ response = requests.get(url)
78
+ data = response.json()
79
 
80
+ # Extracting the time series data from the JSON object
81
+ time_series_key = 'Time Series FX (' + str(interval) + ')'
82
+ forex_data = pd.DataFrame(data[time_series_key]).T
83
+ forex_data.columns = ['Open', 'High', 'Low', 'Close']
84
 
85
+ # Convert index to datetime and sort data
86
+ forex_data.index = pd.to_datetime(forex_data.index)
87
+ forex_data.sort_index(inplace=True)
88
 
89
+ # Convert columns to numeric
90
+ forex_data = forex_data.apply(pd.to_numeric)
91
 
92
+ return forex_data
93
+ except Exception as e:
94
+ print(f"An error occurred: {str(e)}")
95
+ return None
96
 
97
  def analyze_sentiment(json_response, target_ticker):
98
  """
 
236
  - html_message (str): An HTML message containing the calculated statistics, trade log, and trade decision information.
237
  """
238
  # Set up Cerebro engine
239
+ try:
240
+ cerebro = bt.Cerebro()
241
+ cerebro.addstrategy(TrendFollowingStrategy)
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
242
 
243
+ # Add data feed to Cerebro
244
+ data = load_data(api_key, from_symbol, to_symbol, interval)
245
+ cerebro.adddata(data)
246
 
247
+ # Set initial cash (optional)
248
+ cerebro.broker.set_cash(10000)
249
 
250
 
251
+ # Run the backtest
252
+ strategy_instance = cerebro.run()[0]
253
+ api_endpoint = "https://www.alphavantage.co/query" # Replace with actual endpoint
 
 
 
 
 
 
 
 
 
 
 
 
254
 
255
+ # Calculate win and loss percentages
256
+ total_trades = strategy_instance.trade_count
257
+ total_wins = strategy_instance.win_count
258
+ total_losses = strategy_instance.loss_count
259
 
260
+ win_percentage = (total_wins / total_trades) * 100
261
+ loss_percentage = (total_losses / total_trades) * 100
262
 
263
+ # Get trade log from the strategy
264
+ trade_log = strategy_instance.get_trade_log()
265
+
266
+ # Iterate through the trade log and count valid trades
267
+ valid_buy_trades = 0
268
+ valid_sell_trades = 0
269
+
270
+ # Initialize a variable to store the last trade line
271
+ last_trade_line = ""
272
+
273
+ # Iterate through the trade log and count valid trades
274
+ for trade in trade_log:
275
+ if trade['trade_type'] == 'CALL':
276
+ valid_buy_trades += 1
277
+ elif trade['trade_type'] == 'PUT':
278
+ valid_sell_trades += 1
279
+
280
+ # Store the last trade line
281
+ last_trade_line = f"Trade {trade['trade_num']}: {trade['trade_type']} - {trade['outcome']}"
282
+
283
+ for trade in trade_log:
284
+ if trade['trade_type'] == 'CALL':
285
+ valid_buy_trades += 1
286
+ elif trade['trade_type'] == 'PUT':
287
+ valid_sell_trades += 1
288
+
289
+ # Determine if the backtest agrees (valid Buy trades > valid Sell trades)
290
+ if win_percentage > loss_percentage:
291
+ signal = last_trade_line
292
+ color = "green"
293
+ else:
294
+ signal = last_trade_line
295
+ color = "red"
296
+
297
+
298
+ # Get trade decision information
299
+ trade_decision, trade_type, trade_timeframe, reason = should_trade(strategy_instance, api_endpoint, api_key, from_symbol, to_symbol)
300
+
301
+
302
+ # Create an HTML message with the calculated statistics, trade log, and trade decision information
303
+ html_message = f"""
304
+ <p><strong>Strategy Performance Summary:</strong></p>
305
+ <p>On the {interval} timeframe</p>
306
+ <p>*****************************</p>
307
+ <p>Total Trades: {total_trades}</p>
308
+ <p>Total Wins: {total_wins} ({win_percentage:.2f}%)</p>
309
+ <p>Total Losses: {total_losses} ({loss_percentage:.2f}%)</p>
310
+ <p>Signal: <span style='color: {color}'>{signal}</span></p>
311
+ <p><strong>Trade Log:</strong></p>
312
+ <ul>
313
+ """
314
+
315
+ for trade in trade_log:
316
+ html_message += f"<li>Trade {trade['trade_num']}: {trade['trade_type']} - {trade['outcome']}</li>"
317
+
318
+
319
+ html_message += "</ul>"
320
+
321
+ # Include trade decision information
322
+ html_message += f"""
323
+ <p><strong>Trade Decision:</strong></p>
324
+ <p>Trade Type: {trade_type}</p>
325
+ <p>Timeframe: {trade_timeframe}</p>
326
+ <p>Reason: {reason}</p>
327
+ """
328
 
329
+ return html_message
330
+ except Exception as e:
331
+ return f"Waiting for data"
332
 
333
 
334
  # Define a list of popular currency pairs for the dropdowns