-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathdata_oracles_strategy.py
More file actions
2755 lines (1981 loc) · 79 KB
/
Copy pathdata_oracles_strategy.py
File metadata and controls
2755 lines (1981 loc) · 79 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
#!/usr/bin/env python
# coding: utf-8
# ---
# title: "Vortex–Sentiment Adaptive Volatility (VSAV) Strategy"
# author:
# - name: Group Data Oracles
# affiliations:
# - name: Boston University
# city: Boston
# state: MA
# format:
# html:
# toc: true
# css: styles.css
# html-math-method: katex
# embed-resources: false
# code-fold: true
# jupyter: python3
# execute:
# eval: true
# ---
#
# ## Importing Necessary Libraries for Analysis
# In[1816]:
import yfinance as yf # For downloading financial data
import numpy as np # For numerical operations
import pandas as pd # For data manipulation
import requests # For downloading the API data
import numpy as np
import plotly.graph_objects as go
import plotly.express as px # Import the Plotly Express module for interactive visualization
import json
import vectorbt as vbt
from plotly.subplots import make_subplots
import streamlit as st
# ## Data Collection
# ### Fetch daily OHLCV data
# In[1817]:
# Data for the TSLA, XLY, and SPY tickers is retrieved from the Yahoo Finance library, covering the period from January 1, 2019,
# to March 5, 2025.
tsla = yf.download('TSLA', start='2019-01-01', end='2025-03-05')
xly = yf.download('XLY', start='2019-01-01', end='2025-03-05')
spy = yf.download('SPY', start='2019-01-01', end='2025-03-05')
# In[1818]:
# Displays a summary of the TSLA DataFrame, including column names, data types, non-null counts, and memory usage.
tsla.info()
# In[1819]:
# Displays a summary of the XLY DataFrame, including column names, data types, non-null counts, and memory usage.
xly.info()
# In[1820]:
# Displays a summary of the SPY DataFrame, including column names, data types, non-null counts, and memory usage.
spy.info()
# ### Fetch sentiment scores from the API
# In[1821]:
# Defines the API endpoint URL for retrieving news sentiment data related to Tesla (TSLA)
# from the Alpha Vantage service. The query specifies the function type, date range, result limit,
# targeted ticker symbol, and a valid API key.
###url = 'https://www.alphavantage.co/query?function=NEWS_SENTIMENT&time_from=20250101T0130&time_to=20250301T0130&limit=1000&tickers=TSLA&apikey=PNM5EHRALIOT1CKJ'
# Sends a GET request to the specified URL to initiate the API call.
###response = requests.get(url)
# Evaluates whether the API call was successful based on the HTTP response status code.
###if response.status_code == 200:
# Parses the JSON response and extracts the 'feed' section containing sentiment data.
###sentiment_data = response.json()
# Converts the extracted sentiment feed into a DataFrame for further analysis or visualization.
### sentiment_df = pd.DataFrame(sentiment_data['feed'])
# Displays the first five rows of the sentiment DataFrame to provide an overview of the retrieved content.
###print(sentiment_df.head())
###else:
# Prints an error message if the API request was unsuccessful.
###print("API call failed:", response.status_code)
# Independently parses the full JSON response and prints its contents for inspection or debugging purposes.
###sentiment_json = response.json()
###print(sentiment_json)
# ## Indicator Calculation
# ### Compute VI+ and VI-
# In[1822]:
# Defines a function to calculate the Vortex Indicator (VI) for a given DataFrame and ticker symbol.
# The calculation uses a default lookback period of 14 days unless specified otherwise.
def calculate_vortex(df, value, n=14):
# Extracts the high, low, and close price series for the specified ticker.
high = df[("High", value)]
low = df[("Low", value)]
close = df[("Close", value)]
# Calculates the Vortex Movement values:
# VM+ = absolute difference between today's high and yesterday's low
# VM− = absolute difference between today's low and yesterday's high
vm_plus = abs(high - low.shift(1)) # |Today's High – Yesterday’s Low|
vm_minus = abs(low - high.shift(1)) # |Today's Low – Yesterday’s High|
# Computes the True Range (TR) as the maximum of:
# - High - Low
# - Absolute difference between High and Previous Close
# - Absolute difference between Low and Previous Close
tr = pd.concat([
high - low,
abs(high - close.shift(1)),
abs(low - close.shift(1))
], axis=1).max(axis=1)
# Applies a rolling window to compute the n-period sum of VM+ and VM− values
# and the corresponding True Range values.
sum_vm_plus = vm_plus.rolling(window=n).sum()
sum_vm_minus = vm_minus.rolling(window=n).sum()
sum_tr = tr.rolling(window=n).sum()
# Calculates the Vortex Indicator components:
# VI+ = sum of VM+ over n periods divided by sum of TR over n periods
# VI− = sum of VM− over n periods divided by sum of TR over n periods
vi_plus = sum_vm_plus / sum_tr
vi_minus = sum_vm_minus / sum_tr
# Returns the VI+ and VI− series as output.
return vi_plus, vi_minus
# In[1823]:
# Calculates the Vortex Indicator values for TSLA and stores the results as new columns in the DataFrame.
tsla['VI+'], tsla['VI-'] = calculate_vortex(tsla, 'TSLA')
# Calculates the Vortex Indicator values for XLY and stores the results as new columns in the DataFrame.
xly['VI+'], xly['VI-'] = calculate_vortex(xly, 'XLY')
# Calculates the Vortex Indicator values for SPY and stores the results as new columns in the DataFrame.
spy['VI+'], spy['VI-'] = calculate_vortex(spy, 'SPY')
# In[1824]:
# Displays the first 20 rows of the TSLA DataFrame to provide an initial overview of its structure and content with the new function applied.
tsla.head(20)
# ### Calculate Volume-Weighted Sentiment
# In[1825]:
# Load the sentiment JSON file from local storage
with open("TSLA_sentiment.json", "r") as f:
sentiment_json = json.load(f)
# Extract the "feed" list from the top-level JSON dictionary.
# This section contains the array of sentiment articles or entries.
sentiment_feed = sentiment_json.get("feed", [])
# Initialize an empty list to hold cleaned and structured sentiment data
sentiment_data = []
# Iterate through each item in the sentiment feed to extract relevant fields
for item in sentiment_feed:
try:
sentiment_data.append({
# Convert the timestamp to pandas datetime for proper indexing
"time_published": pd.to_datetime(item["time_published"]),
# Convert the sentiment score string to float
"sentiment_score": float(item["overall_sentiment_score"]),
# Store the sentiment label (e.g., Positive, Neutral, Negative)
"sentiment_label": item["overall_sentiment_label"],
})
except (KeyError, ValueError, TypeError):
# Skip malformed or incomplete entries that raise an error
continue
# Convert the structured list of dictionaries into a pandas DataFrame
sentiment_df = pd.DataFrame(sentiment_data)
# Set the 'time_published' column as the DataFrame index to enable time-series operations
sentiment_df.set_index("time_published", inplace=True)
# Display the first few rows of the DataFrame to verify content and structure
print(sentiment_df.head())
# Output a summary of the DataFrame structure, including column types and memory usage
print(sentiment_df.info())
# In[1826]:
# Initialize an empty list to store processed sentiment records
sentiment_data = []
# Iterate through each news item in the 'feed' section of the JSON object
for news_item in sentiment_json.get("feed", []):
# Append a dictionary with selected and transformed fields to the sentiment list
sentiment_data.append({
# Convert the time of publication to datetime format
"time_published": pd.to_datetime(news_item["time_published"]),
# Extract the sentiment score (as-is; conversion to float may be handled separately if needed)
"sentiment_score": news_item["overall_sentiment_score"],
# Extract the sentiment label (e.g., Positive, Neutral, Negative)
"sentiment_label": news_item["overall_sentiment_label"],
})
# Convert the list of dictionaries into a pandas DataFrame
sentiment_data = pd.DataFrame(sentiment_data)
# In[1827]:
# Sort the DataFrame by publication time in ascending order for chronological analysis
sentiment_data['time_published'].sort_values(ascending=True)
# In[1828]:
# Convert the 'time_published' column to only retain the date portion (drop time-of-day)
sentiment_data['time_published'] = sentiment_data['time_published'].dt.date
# In[1829]:
# Filter sentiment data to retain only those records that match dates present in the TSLA index
sentiment_scores_filtered = sentiment_data[
pd.to_datetime(sentiment_data['time_published']).isin(tsla.index)
]
# Group the filtered data by publication date and calculate the average sentiment score per day
sentiment_scores_filtered = sentiment_scores_filtered.groupby('time_published')['sentiment_score'].mean().reset_index()
# In[1830]:
# Fix the multi-level column issue by selecting the 'Volume' column and resetting its name
tsla_volume = tsla[('Volume', 'TSLA')].rename('Volume')
# Ensure the index of tsla_volume is a column and convert it to match the type of time_published
tsla_volume = tsla_volume.reset_index()
tsla_volume['Date'] = pd.to_datetime(tsla_volume['Date'])
# In[1831]:
# Convert 'time_published' in the sentiment data to datetime to match volume data type
sentiment_scores_filtered['time_published'] = pd.to_datetime(sentiment_scores_filtered['time_published'])
# Perform an inner merge between sentiment scores and volume data based on matching dates
merged_data = pd.merge(
tsla_volume,
sentiment_scores_filtered,
left_on='Date',
right_on='time_published',
how='inner'
)
# In[1832]:
# Compute the weighted sentiment by multiplying raw sentiment by trading volume
merged_data['Weighted_Sentiment'] = merged_data['Volume'] * merged_data['sentiment_score']
# Calculate a 5-day rolling average of the weighted sentiment to smooth short-term noise
merged_data['5_day_avg_sentiment'] = merged_data['Weighted_Sentiment'].rolling(window=5).mean()
# Define a binary condition for when the average sentiment is positive
merged_data['Buy_Condition'] = merged_data['5_day_avg_sentiment'] > 0
# Normalize the rolling sentiment score by average volume to allow comparability across scales
merged_data['5_day_avg_sentiment_norm'] = (
merged_data['5_day_avg_sentiment'] / merged_data['Volume'].mean()
)
# In[1833]:
merged_data
# ### Derive ATR (10) for Volatility Adjustments
# In[1834]:
# Flatten MultiIndex columns if present to simplify DataFrame operations
tsla.columns = [
'_'.join(col).strip() if isinstance(col, tuple) else col
for col in tsla.columns
]
# Calculate the previous closing price to support True Range computation
tsla["prev_close"] = tsla["Close_TSLA"].shift(1)
# Compute three True Range variations used in ATR calculation
tsla["tr1"] = tsla["High_TSLA"] - tsla["Low_TSLA"]
tsla["tr2"] = abs(tsla["High_TSLA"] - tsla["prev_close"])
tsla["tr3"] = abs(tsla["Low_TSLA"] - tsla["prev_close"])
# Derive the True Range (TR) as the maximum of the three variants
tsla["true_range"] = tsla[["tr1", "tr2", "tr3"]].max(axis=1)
# Compute the 10-day Average True Range (ATR) to measure market volatility
tsla["ATR_10"] = tsla["true_range"].rolling(window=10).mean()
# Calculate ATR as a percentage of the current closing price to normalize volatility
tsla["atr_pct"] = tsla["ATR_10"] / tsla["Close_TSLA"]
# Define a function to assign position size based on volatility levels
def position_size(row):
if row["atr_pct"] < 0.03:
return 0.01 # Allocate 1% of capital for low-volatility conditions
else:
return 0.005 # Allocate 0.5% of capital for high-volatility conditions
# Apply the position size function across all rows
tsla["position_size"] = tsla.apply(position_size, axis=1)
# Display the latest 10 rows with selected indicators for inspection
print(tsla[["Close_TSLA", "ATR_10", "atr_pct", "position_size"]].tail(10))
# In[1835]:
# Create a line chart to visualize the ATR% (Average True Range as a percentage of price) over time
fig = px.line(
tsla,
x=tsla.index,
y="atr_pct",
title="ATR% Over Time" # Title of the chart
)
# Add a horizontal reference line at 3% to represent the low-volatility cutoff threshold
fig.add_hline(
y=0.03,
line_dash="dot",
line_color="green",
annotation_text="Low Volatility Cutoff"
)
# Display the chart
fig.show()
# In[1836]:
from IPython.display import IFrame
IFrame(src='figures/atr%_5y.html', width='100%', height='600px')
# The chart illustrates the historical volatility of TSLA, measured by the Average True Range (ATR) as a percentage of the closing price. Periods where the ATR% falls below the dotted green line at 3% indicate low volatility, which is typically associated with more stable market conditions. In contrast, noticeable spikes—such as those seen in 2020 and 2021—reflect periods of heightened volatility. More recently, ATR% values appear to remain closer to or slightly above the low-volatility threshold, suggesting relatively calmer market behavior compared to earlier years.
# In[1837]:
# Filter the TSLA DataFrame to include only records from the year 2025
tsla_2025 = tsla[tsla.index.year == 2025]
# Create a line chart to visualize ATR% for TSLA during 2025
fig = px.line(
tsla_2025,
x=tsla_2025.index,
y="atr_pct",
title="ATR% Over Time (2025 Only)"
)
# Add a horizontal line at the 3% threshold to denote the low-volatility cutoff
fig.add_hline(
y=0.03,
line_dash="dot",
line_color="green",
annotation_text="Low Volatility Cutoff"
)
# Display the chart
fig.show()
# The chart displays ATR% for TSLA during 2025, reflecting how the stock's volatility has evolved since the start of the year. While ATR% began above the 7% mark in early January, it gradually declined and remained mostly between 4% and 6% throughout February. Although volatility did not breach the low-volatility threshold of 3%, the dip toward that level suggests a period of relative calm. Toward early March, ATR% showed a clear upward trend, indicating a potential resurgence in market volatility.
# In[1838]:
# Create Buy Signal
tsla['Buy_Signal'] = tsla['VI+_'] > tsla['VI-_'] # Vortex crossover
# Create Sell Signal (basic)
tsla['Sell_Signal'] = tsla['VI-_'] > tsla['VI+_']
# Initialize the position tracking column with 0 (no active position)
tsla['Position'] = 0
# Initialize a variable to store the peak price during a position for trailing stop logic
peak_price = 0
# Iterate through the dataset starting from index 1 to access previous values
for i in range(1, len(tsla)):
# Entry condition: enter a position if a buy signal is present
if tsla['Buy_Signal'].iloc[i]:
tsla.at[tsla.index[i], 'Position'] = 1 # Mark entry into a position
peak_price = tsla['Close_TSLA'].iloc[i] # Record the entry price as initial peak
# If already in position, check for exit condition using trailing stop
elif tsla['Position'].iloc[i - 1] == 1:
current_price = tsla['Close_TSLA'].iloc[i] # Current closing price
peak_price = max(peak_price, current_price) # Update peak price if current exceeds previous
drawdown = (peak_price - current_price) / peak_price # Compute drawdown from peak
# Exit condition: drawdown exceeds 3%
if drawdown >= 0.03:
tsla.at[tsla.index[i], 'Sell_Signal'] = True # Trigger a sell signal
tsla.at[tsla.index[i], 'Position'] = 0 # Exit position
else:
tsla.at[tsla.index[i], 'Position'] = 1 # Maintain position
# Display the total number of buy and sell signals generated across the dataset
print("Buy signals:", tsla['Buy_Signal'].sum())
print("Sell signals:", tsla['Sell_Signal'].sum())
# In[1839]:
# Create an empty figure object
fig = go.Figure()
# Plot the TSLA closing price as a continuous line
fig.add_trace(go.Scatter(
x=tsla.index,
y=tsla['Close_TSLA'],
mode='lines',
name='TSLA Price'
))
# Add markers to indicate Buy Signals using upward-pointing green triangles
fig.add_trace(go.Scatter(
x=tsla[tsla['Buy_Signal']].index,
y=tsla[tsla['Buy_Signal']]['Close_TSLA'],
mode='markers',
marker=dict(symbol='triangle-up', size=10, color='green'),
name='Buy Signal'
))
# Add markers to indicate Sell Signals using downward-pointing red triangles
fig.add_trace(go.Scatter(
x=tsla[tsla['Sell_Signal']].index,
y=tsla[tsla['Sell_Signal']]['Close_TSLA'],
mode='markers',
marker=dict(symbol='triangle-down', size=10, color='red'),
name='Sell Signal'
))
# Update layout settings including title and visual style
fig.update_layout(
title='TSLA Buy & Sell Signals',
template='plotly_white'
)
# Render the interactive plot
fig.show()
# The chart illustrates the closing price of Tesla stock over time, with overlaid trading signals generated by the strategy. Green upward triangles represent buy signals, while red downward triangles mark sell signals. These signals are distributed throughout periods of both rising and falling prices, reflecting how the algorithm dynamically enters and exits positions based on market conditions. Clusters of signals during high-volatility periods—such as 2020, 2021, and early 2025—indicate frequent entries and exits, whereas more stable phases show fewer trades.
# In[1840]:
# Calculate ATR as a percentage of the closing price to normalize volatility
tsla['atr_pct'] = tsla['ATR_10'] / tsla['Close_TSLA']
# Define Vortex Indicator crossover signals:
# - VI_Cross_Up: Identifies when VI+ crosses above VI− (potential bullish signal)
# - VI_Cross_Down: Identifies when VI− crosses above VI+ (potential bearish signal)
tsla['VI_Cross_Up'] = (tsla['VI+_'] > tsla['VI-_']) & (tsla['VI+_'].shift(1) <= tsla['VI-_'].shift(1))
tsla['VI_Cross_Down'] = (tsla['VI-_'] > tsla['VI+_']) & (tsla['VI-_'].shift(1) <= tsla['VI+_'].shift(1))
# Initialize signal and state columns
tsla['Buy_Signal'] = False # Flag for buy signal
tsla['Sell_Signal'] = False # Flag for sell signal
tsla['Position'] = 0 # Position state: 1 = in position, 0 = no position
tsla['Entry_Type'] = None # Strategy classification: 'aggressive' or 'conservative'
# Initialize control variables for trailing stop and price tracking
in_position = False # Boolean flag for current position state
peak_price = 0 # Highest price observed during an open position
# Iterate through the DataFrame to simulate trading logic based on Vortex signals and volatility
for i in range(1, len(tsla)):
row = tsla.iloc[i]
idx = tsla.index[i]
# Buy condition: Enter a new position if VI_Cross_Up occurs and no current position is held
if not in_position and row['VI_Cross_Up']:
tsla.at[idx, 'Buy_Signal'] = True
tsla.at[idx, 'Position'] = 1
in_position = True
peak_price = row['Close_TSLA']
# Classify entry type based on volatility threshold
if row['atr_pct'] < 0.03:
tsla.at[idx, 'Entry_Type'] = 'aggressive'
else:
tsla.at[idx, 'Entry_Type'] = 'conservative'
# While in position, evaluate for trailing stop or VI_Cross_Down exit condition
elif in_position:
current_price = row['Close_TSLA']
peak_price = max(peak_price, current_price)
drawdown = (peak_price - current_price) / peak_price
# Sell condition: Exit if drawdown exceeds 3% or VI_Cross_Down occurs
if drawdown >= 0.03 or row['VI_Cross_Down']:
tsla.at[idx, 'Sell_Signal'] = True
tsla.at[idx, 'Position'] = 0
in_position = False
else:
tsla.at[idx, 'Position'] = 1 # Maintain position
# Output the total count of each type of signal and entry classification
print("Buy signals:", tsla['Buy_Signal'].sum())
print("Sell signals:", tsla['Sell_Signal'].sum())
print("Aggressive entries:", (tsla['Entry_Type'] == 'aggressive').sum())
print("Conservative entries:", (tsla['Entry_Type'] == 'conservative').sum())
# In[1841]:
# Create an empty figure to hold all plot layers
fig = go.Figure()
# Plot the TSLA closing price as a continuous blue line
fig.add_trace(go.Scatter(
x=tsla.index,
y=tsla['Close_TSLA'],
mode='lines',
name='TSLA Price',
line=dict(color='blue')
))
# Add markers for aggressive buy signals (Entry_Type = 'aggressive')
fig.add_trace(go.Scatter(
x=tsla[(tsla['Buy_Signal']) & (tsla['Entry_Type'] == 'aggressive')].index,
y=tsla[(tsla['Buy_Signal']) & (tsla['Entry_Type'] == 'aggressive')]['Close_TSLA'],
mode='markers',
name='Buy (Aggressive)',
marker=dict(symbol='triangle-up', color='limegreen', size=10)
))
# Add markers for conservative buy signals (Entry_Type = 'conservative')
fig.add_trace(go.Scatter(
x=tsla[(tsla['Buy_Signal']) & (tsla['Entry_Type'] == 'conservative')].index,
y=tsla[(tsla['Buy_Signal']) & (tsla['Entry_Type'] == 'conservative')]['Close_TSLA'],
mode='markers',
name='Buy (Conservative)',
marker=dict(symbol='triangle-up', color='green', size=10)
))
# Add markers for sell signals using red downward-pointing triangles
fig.add_trace(go.Scatter(
x=tsla[tsla['Sell_Signal']].index,
y=tsla[tsla['Sell_Signal']]['Close_TSLA'],
mode='markers',
name='Sell Signal',
marker=dict(symbol='triangle-down', color='red', size=10)
))
# Configure chart layout with appropriate title, axis labels, and style
fig.update_layout(
title='TSLA Buy/Sell Signals Over Time',
xaxis_title='Date',
yaxis_title='Price (USD)',
template='plotly_white',
height=600
)
# Render the figure
fig.show()
# The chart displays the historical closing price of Tesla (TSLA) stock alongside algorithmically generated buy and sell signals. The blue line represents TSLA's closing price, while the green upward-pointing triangles indicate buy entries—distinguished by lime green for aggressive entries (lower volatility) and dark green for conservative entries (higher volatility). Red downward-pointing triangles represent sell signals.
#
# The buy signals are generally aligned with upward momentum, and sell signals frequently follow periods of short-term retracement or heightened volatility. The system shows particularly dense activity around highly volatile phases, such as mid-2020 to early 2022, capturing many entries and exits. In contrast, during more stable periods, the signals are more spaced out. Overall, the plot provides a clear visual assessment of how the strategy adapts dynamically to changing market conditions by modulating its entries based on volatility and exiting with protective trailing logic.
# ## Tesla Analysis Results
# In[1842]:
tsla_signals = tsla.reset_index()[['Date', 'VI_Cross_Up', 'VI_Cross_Down', 'atr_pct', 'Close_TSLA']]
# In[1843]:
merged_data = pd.merge(merged_data, tsla, on='Date', how='left')
# In[1844]:
# Calculate ATR percentage
merged_data['atr_pct'] = merged_data['ATR_10'] / merged_data['Close_TSLA']
# Vortex crossover logic
merged_data['VI_Cross_Up'] = (merged_data['VI+_'] > merged_data['VI-_']) & (merged_data['VI+_'].shift(1) <= merged_data['VI-_'].shift(1))
merged_data['VI_Cross_Down'] = (merged_data['VI-_'] > merged_data['VI+_']) & (merged_data['VI-_'].shift(1) <= merged_data['VI+_'].shift(1))
# Initialize signal & state columns
merged_data['Buy_Signal'] = False
merged_data['Sell_Signal'] = False
merged_data['Position'] = 0
merged_data['Entry_Type'] = None # aggressive/conservative
# Trailing stop logic variables
in_position = False
peak_price = 0
for i in range(1, len(merged_data)):
row = merged_data.iloc[i]
idx = merged_data.index[i]
# Buy condition
if not in_position or row['VI_Cross_Up'] or row['5_day_avg_sentiment_norm']>0:
merged_data.at[idx, 'Buy_Signal'] = True
merged_data.at[idx, 'Position'] = 1
in_position = True
peak_price = row['Close_TSLA']
# Entry Type: aggressive if ATR < 3%, else conservative
if row['atr_pct'] < 0.03:
merged_data.at[idx, 'Entry_Type'] = 'aggressive'
else:
merged_data.at[idx, 'Entry_Type'] = 'conservative'
# While in position, check for trailing stop or VI cross down
elif in_position:
current_price = row['Close_TSLA']
peak_price = max(peak_price, current_price)
drawdown = (peak_price - current_price) / peak_price
if drawdown >= 0.03 or row['VI_Cross_Down']:
merged_data.at[idx, 'Sell_Signal'] = True
merged_data.at[idx, 'Position'] = 0
in_position = False
else:
merged_data.at[idx, 'Position'] = 1
# Show result counts
print("Buy signals:", merged_data['Buy_Signal'].sum())
print("Sell signals:", merged_data['Sell_Signal'].sum())
print("Aggressive entries:", (merged_data['Entry_Type'] == 'aggressive').sum())
print("Conservative entries:", (merged_data['Entry_Type'] == 'conservative').sum())
# In[1845]:
# Ensure 'Date' is datetime and set as index if needed
merged_data['Date'] = pd.to_datetime(merged_data['Date'])
fig = go.Figure()
# Plot 5-day Avg Sentiment
fig.add_trace(go.Scatter(
x=merged_data['Date'],
y=merged_data['5_day_avg_sentiment_norm'],
mode='lines+markers',
name='5-Day Avg Sentiment',
line=dict(color='blue')
))
# Plot ATR %
fig.add_trace(go.Scatter(
x=merged_data['Date'],
y=merged_data['atr_pct'],
mode='lines+markers',
name='ATR %',
yaxis='y2',
line=dict(color='orange')
))
# Optional: Highlight Buy Signal Dates (even though there are none now)
fig.add_trace(go.Scatter(
x=merged_data.loc[merged_data['Buy_Signal'], 'Date'],
y=merged_data.loc[merged_data['Buy_Signal'], '5_day_avg_sentiment_norm'],
mode='markers',
marker=dict(color='green', size=10, symbol='star'),
name='Buy Signal'
))
# Add dual axis layout
fig.update_layout(
title="5-Day Sentiment vs ATR % (with Buy Signals)",
xaxis_title='Date',
yaxis=dict(title='5-Day Avg Sentiment'),
yaxis2=dict(title='ATR %', overlaying='y', side='right'),
legend=dict(x=0.01, y=0.99),
height=500
)
fig.show()
# In[1846]:
# Initialize portfolio variables
capital = 100000 # Starting capital for the simulation
in_position = False # Flag indicating whether a position is currently held
entry_price = 0 # Entry price of the current position
position_value = 0 # Dollar value allocated to the position
cash = capital # Available cash (initially equal to capital)
returns = [] # List to store profit/loss for each trade
# Iterate over the dataset to simulate trading
for i in range(len(merged_data)):
row = merged_data.iloc[i]
# ==== Buy Logic ====
if row['Buy_Signal'] and not in_position:
position_size = row['position_size'] # Fraction of capital to allocate
position_value = cash * position_size # Calculate how much capital to invest
entry_price = row['Close_TSLA'] # Record entry price
shares_bought = position_value / entry_price # Calculate number of shares to buy
cash -= position_value # Deduct invested capital from cash
in_position = True # Update position flag
# ==== Sell Logic ====
elif row['Sell_Signal'] and in_position:
exit_price = row['Close_TSLA'] # Get the exit price
proceeds = shares_bought * exit_price # Calculate proceeds from sale
profit = proceeds - position_value # Profit = proceeds - initial investment
cash += proceeds # Add proceeds back to cash
returns.append(profit) # Record trade return
in_position = False # Reset position state
position_value = 0 # Clear position value
entry_price = 0 # Reset entry price
# ==== Final Capital Calculation ====
# If still holding a position, add unrealized value to cash
final_value = cash + (shares_bought * row['Close_TSLA'] if in_position else 0)
total_return = final_value - capital # Net profit/loss from strategy
# ==== Print Performance Metrics ====
print(f"Final Capital: ${final_value:,.2f}")
print(f"Total Return: ${total_return:.2f}")
print(f"Total Trades: {len(returns)}")
print(f"Average Profit per Trade: ${np.mean(returns):.2f}")
# In[1847]:
# Make sure index is datetime and 'Close_TSLA' exists
price = tsla['Close_TSLA']
# Generate entries and exits from your signals
entries = tsla['Buy_Signal']
exits = tsla['Sell_Signal']
# Create portfolio
portfolio = vbt.Portfolio.from_signals(
close=price,
entries=entries,
exits=exits,
size=np.nan, # Let it auto-calculate position size if fixed capital
init_cash=100_000,
fees=0.001, # 0.1% per trade
slippage=0.0005 # Optional
)
# In[1848]:
# Summary stats
print(portfolio.stats())
# Equity curve
portfolio.plot().show()
# In[1849]:
print(tsla['Buy_Signal'].sum()) # Should be > 0
print(tsla['Sell_Signal'].sum()) # Should also be > 0
# In[1850]:
tsla = tsla.dropna(subset=['Close_TSLA'])
entries = tsla['Buy_Signal'].astype(bool)
exits = tsla['Sell_Signal'].astype(bool)
# In[1851]:
price = tsla['Close_TSLA']
portfolio = vbt.Portfolio.from_signals(
close=price,
entries=entries,
exits=exits,
init_cash=100_000,
fees=0.001
)
print(portfolio.stats())
portfolio.plot().show()
# The backtest results show that while the strategy achieved a total return of approximately 62.76%, it significantly underperformed compared to a simple buy-and-hold strategy on TSLA, which yielded a 1215.81% return. The strategy executed 80 trades with a low win rate of 32.5%, indicating that most trades were unprofitable. Although it had a few strong winners, the average profit per trade was marginal, with a profit factor of 1.19. Additionally, the portfolio experienced a substantial maximum drawdown of 55.35% and a prolonged recovery period lasting two years, signaling high risk. Visuals further confirm that many trades resulted in small losses or gains, with only a few notable profitable exits. Overall, while the strategy demonstrates some profitability, its risk-return profile is weak and may require optimization in entry/exit logic, volatility filtering, or sentiment integration to compete with the benchmark performance.
# ## XLY Analysis Results
# In[1852]:
#url = 'https://www.alphavantage.co/query?function=NEWS_SENTIMENT&time_from=20250101T0130&time_to=20250301T0130&limit=1000&tickers=XLY&apikey=PNM5EHRALIOT1CKJ'
#response = requests.get(url)
#if response.status_code == 200:
# sentiment_data = response.json()
# sentiment_df = pd.DataFrame(sentiment_data['feed'])
# print(sentiment_df.head())
#else:
# print("API call failed:", response.status_code)
#sentiment_json = response.json()
#print(sentiment_json)
# In[1853]:
sentiment_data = []
for news_item in sentiment_json.get("feed", []):
sentiment_data.append({
"time_published": pd.to_datetime(news_item["time_published"]),
"sentiment_score": news_item["overall_sentiment_score"],
"sentiment_label": news_item["overall_sentiment_label"],
})
sentiment_data = pd.DataFrame(sentiment_data)
# In[1854]:
sentiment_data['time_published'] = sentiment_data['time_published'].dt.date
sentiment_scores_filtered = sentiment_data[pd.to_datetime(sentiment_data['time_published']).isin(tsla.index)]
sentiment_scores_filtered = sentiment_scores_filtered.groupby('time_published')['sentiment_score'].mean().reset_index()
# In[1855]:
# Fix the multi-level column issue by selecting the 'Volume' column and resetting its name
xly_volume = xly[('Volume', 'XLY')].rename('Volume')
# Ensure the index of tsla_volume is a column and convert it to match the type of time_published
xly_volume = xly_volume.reset_index()
xly_volume['Date'] = pd.to_datetime(xly_volume['Date'])
# Convert time_published to datetime
sentiment_scores_filtered['time_published'] = pd.to_datetime(sentiment_scores_filtered['time_published'])
# Merge the dataframes
merged_data = pd.merge(xly_volume, sentiment_scores_filtered, left_on='Date', right_on='time_published', how='inner')
merged_data['Weighted_Sentiment'] = merged_data['Volume'] * merged_data['sentiment_score']
merged_data['5_day_avg_sentiment'] = merged_data['Weighted_Sentiment'].rolling(window=5).mean()
merged_data['Buy_Condition'] = merged_data['5_day_avg_sentiment'] > 0
merged_data['5_day_avg_sentiment_norm'] = merged_data['5_day_avg_sentiment']/merged_data['Volume'].mean()
# In[1856]:
# Flatten MultiIndex columns
xly.columns = [
'_'.join(col).strip() if isinstance(col, tuple) else col
for col in xly.columns
]
# Calculate True Range
xly["prev_close"] = xly["Close_XLY"].shift(1)
xly["tr1"] = xly["High_XLY"] - xly["Low_XLY"]
xly["tr2"] = abs(xly["High_XLY"] - xly["prev_close"])
xly["tr3"] = abs(xly["Low_XLY"] - xly["prev_close"])
xly["true_range"] = xly[["tr1", "tr2", "tr3"]].max(axis=1)
# 10-day ATR
xly["ATR_10"] = xly["true_range"].rolling(window=10).mean()
# ---- STEP 4: Calculate ATR as a percentage of closing price ----
xly["atr_pct"] = xly["ATR_10"] / xly["Close_XLY"]
# allocating the capital
def position_size(row):
if row["atr_pct"] < 0.03: # < 3% volatility → low risk
return 0.01 # allocate 1% of capital
else: # ≥ 3% volatility → high risk
return 0.005 # allocate 0.5% of capital
xly["position_size"] = xly.apply(position_size, axis=1)
# ---- STEP 6: Optional - Capital allocation per trade ----
#capital = 100000 # Example: $100K total portfolio
#xly["allocation_dollars"] = xly["position_size"] * capital
# ---- Preview ----
print(xly[["Close_XLY", "ATR_10", "atr_pct", "position_size"]].tail(10))
# In[1857]:
import plotly.express as px
fig = px.line(xly, x=xly.index, y="atr_pct", title="ATR% Over Time")
fig.add_hline(y=0.03, line_dash="dot", line_color="green", annotation_text="Low Volatility Cutoff")
fig.show()
# In[1858]:
import plotly.express as px
# Filter only 2025 data
xly_2025 = xly[xly.index.year == 2025]
# Plot
fig = px.line(xly_2025, x=xly_2025.index, y="atr_pct", title="ATR% Over Time (2025 Only)")
fig.add_hline(y=0.03, line_dash="dot", line_color="green", annotation_text="Low Volatility Cutoff")
fig.show()
# In[1859]:
merged_data = pd.merge(merged_data, xly, on='Date', how='left')
# In[1860]:
# Calculate ATR percentage
merged_data['atr_pct'] = merged_data['ATR_10'] / merged_data['Close_XLY']
# Vortex crossover logic
merged_data['VI_Cross_Up'] = (merged_data['VI+_'] > merged_data['VI-_']) & (merged_data['VI+_'].shift(1) <= merged_data['VI-_'].shift(1))
merged_data['VI_Cross_Down'] = (merged_data['VI-_'] > merged_data['VI+_']) & (merged_data['VI-_'].shift(1) <= merged_data['VI+_'].shift(1))
# Initialize signal & state columns