-
Notifications
You must be signed in to change notification settings - Fork 107
Expand file tree
/
Copy pathanalyze_x_truth_cross.py
More file actions
840 lines (736 loc) ยท 34.1 KB
/
Copy pathanalyze_x_truth_cross.py
File metadata and controls
840 lines (736 loc) ยท 34.1 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
import json
import re
from datetime import datetime, timedelta
from collections import Counter, defaultdict
import math
# ============================================================
# Load Data
# ============================================================
with open('data/x_posts_full.json') as f:
xd = json.load(f)
with open('clean_president.json') as f:
ts_all = json.load(f)
with open('data/market_SP500.json') as f:
market = json.load(f)
# Filter
x_originals = [t for t in xd['tweets'] if 'referenced_tweets' not in t]
ts_originals = [p for p in ts_all if p.get('has_text') and not p.get('is_retweet')]
# Market lookup
market_by_date = {m['date']: m for m in market}
market_dates_sorted = sorted(market_by_date.keys())
def get_next_trading_day(date_str):
"""Get next trading day on or after date_str"""
for md in market_dates_sorted:
if md >= date_str:
return md
return None
def get_prev_trading_day(date_str):
"""Get previous trading day on or before date_str"""
for md in reversed(market_dates_sorted):
if md <= date_str:
return md
return None
def get_market_return(date_str):
"""Get market return for the trading day that covers this date"""
td = get_next_trading_day(date_str)
if td and td in market_by_date:
m = market_by_date[td]
return (m['close'] - m['open']) / m['open'] * 100
return None
def get_next_day_return(date_str):
"""Get next trading day's return"""
td = get_next_trading_day(date_str)
if not td:
return None
idx = market_dates_sorted.index(td)
if idx + 1 < len(market_dates_sorted):
nd = market_dates_sorted[idx + 1]
m = market_by_date[nd]
return (m['close'] - m['open']) / m['open'] * 100
return None
# ============================================================
# Text cleaning and matching
# ============================================================
def clean_text(text):
"""Clean text for comparison"""
text = re.sub(r'https?://\S+', '', text)
text = re.sub(r'@\w+', '', text)
text = re.sub(r'#\w+', '', text)
text = text.strip()
return text
def normalize_for_match(text):
"""Normalize text for fuzzy matching"""
text = clean_text(text)
text = re.sub(r'[^\w\s]', '', text.lower())
text = re.sub(r'\s+', ' ', text).strip()
return text
def text_similarity(a, b):
"""Simple word overlap similarity"""
wa = set(a.split())
wb = set(b.split())
if not wa or not wb:
return 0
intersection = wa & wb
return len(intersection) / max(len(wa), len(wb))
# Parse dates
for t in x_originals:
t['dt'] = datetime.fromisoformat(t['created_at'].replace('Z', '+00:00'))
t['date'] = t['created_at'][:10]
t['clean_text'] = clean_text(t['text'])
t['norm_text'] = normalize_for_match(t['text'])
for p in ts_originals:
p['dt'] = datetime.fromisoformat(p['created_at'].replace('Z', '+00:00'))
p['date'] = p['created_at'][:10]
p['clean_text'] = clean_text(p['content'])
p['norm_text'] = normalize_for_match(p['content'])
# Find matches: X tweets that also appear on Truth Social
matches = []
x_with_text = [t for t in x_originals if t['clean_text']]
for xt in x_with_text:
best_match = None
best_score = 0
# Search in a window of +-3 days
for tp in ts_originals:
time_diff = abs((xt['dt'] - tp['dt']).total_seconds())
if time_diff > 3 * 86400: # 3 days
continue
sim = text_similarity(xt['norm_text'], tp['norm_text'])
if sim > best_score:
best_score = sim
best_match = tp
if best_score >= 0.5: # Threshold
time_diff_hours = (xt['dt'] - best_match['dt']).total_seconds() / 3600
matches.append({
'x_text': xt['clean_text'][:200],
'ts_text': best_match['clean_text'][:200],
'similarity': round(best_score, 3),
'x_time': xt['created_at'],
'ts_time': best_match['created_at'],
'time_diff_hours': round(time_diff_hours, 2),
'x_date': xt['date'],
'ts_date': best_match['date'],
'x_metrics': xt.get('public_metrics', {}),
'ts_replies': best_match.get('replies_count', 0),
'ts_reblogs': best_match.get('reblogs_count', 0),
'ts_favourites': best_match.get('favourites_count', 0),
'x_post': xt,
'ts_post': best_match,
})
print(f"Found {len(matches)} matched tweets (similarity >= 0.5)")
for m in matches[:5]:
print(f" [{m['x_time'][:16]}] sim={m['similarity']} diff={m['time_diff_hours']:.1f}h")
print(f" X: {m['x_text'][:100]}")
print(f" TS: {m['ts_text'][:100]}")
# Also try matching URL-only X posts to Truth Social posts by time proximity
x_url_only = [t for t in x_originals if not t['clean_text']]
print(f"\nURL-only X posts: {len(x_url_only)} (these likely link to Truth Social posts or videos)")
# ============================================================
# ANALYSIS 1: Selection Mechanism
# ============================================================
print("\n" + "="*80)
print("ANALYSIS 1: ็ฏฉ้ธๆฉๅถๅๆ")
print("="*80)
def compute_features(text):
"""Compute features for a piece of text"""
if not text:
return {}
words = text.split()
upper_chars = sum(1 for c in text if c.isupper())
total_alpha = sum(1 for c in text if c.isalpha())
caps_ratio = upper_chars / total_alpha if total_alpha > 0 else 0
# All-caps words
all_caps_words = sum(1 for w in words if w.isupper() and len(w) > 1)
all_caps_ratio = all_caps_words / len(words) if words else 0
excl = text.count('!')
quest = text.count('?')
# Sentiment keywords
positive = ['great', 'beautiful', 'best', 'incredible', 'wonderful', 'amazing', 'tremendous', 'fantastic',
'victory', 'winning', 'win', 'success', 'love', 'happy', 'congratulations', 'phenomenal']
negative = ['scum', 'losers', 'radical', 'disaster', 'terrible', 'horrible', 'worst', 'fake', 'corrupt',
'criminal', 'destroy', 'enemy', 'threat', 'attack', 'war', 'kill', 'death']
policy = ['tariff', 'trade', 'deal', 'china', 'iran', 'executive order', 'military', 'border',
'immigration', 'tax', 'economy', 'stock', 'market', 'elon', 'doge', 'spending']
text_lower = text.lower()
pos_count = sum(1 for w in positive if w in text_lower)
neg_count = sum(1 for w in negative if w in text_lower)
pol_count = sum(1 for w in policy if w in text_lower)
has_media_ref = 1 if any(w in text_lower for w in ['photo', 'video', 'watch', 'tune in', 'broadcast']) else 0
has_endorsement = 1 if any(w in text_lower for w in ['vote', 'endorsement', 'campaign', 'candidate', 'patriot']) else 0
has_personal = 1 if any(w in text_lower for w in ['melania', 'eric', 'barron', 'ivanka', 'don jr', 'tiffany']) else 0
return {
'length': len(text),
'word_count': len(words),
'caps_ratio': round(caps_ratio, 3),
'all_caps_ratio': round(all_caps_ratio, 3),
'exclamations': excl,
'questions': quest,
'positive_words': pos_count,
'negative_words': neg_count,
'policy_words': pol_count,
'has_media_ref': has_media_ref,
'has_endorsement': has_endorsement,
'has_personal': has_personal,
}
# Features for matched X posts
matched_ts_ids = set()
for m in matches:
matched_ts_ids.add(m['ts_post']['id'])
matched_features = []
for m in matches:
f = compute_features(m['ts_post']['clean_text'])
f['matched'] = True
matched_features.append(f)
# Features for unmatched TS posts
unmatched_ts = [p for p in ts_originals if p['id'] not in matched_ts_ids]
unmatched_features = []
for p in unmatched_ts:
f = compute_features(p['clean_text'])
f['matched'] = False
unmatched_features.append(f)
def avg_features(feature_list):
if not feature_list:
return {}
keys = [k for k in feature_list[0].keys() if k != 'matched']
result = {}
for k in keys:
vals = [f[k] for f in feature_list if k in f]
if vals:
result[k] = round(sum(vals) / len(vals), 3)
return result
matched_avg = avg_features(matched_features)
unmatched_avg = avg_features(unmatched_features)
print(f"\nๅน้
ๆจๆ: {len(matches)} ็ฏ")
print(f"ๆชๅน้
ๆจๆ: {len(unmatched_ts)} ็ฏ")
print(f"\n{'็นๅพต':<20} {'ๅน้
(ๆพX)':<15} {'ๆชๅน้
(ไธๆพX)':<15} {'ๅทฎ็ฐ':<10}")
print("-" * 60)
for k in matched_avg:
m_val = matched_avg.get(k, 0)
u_val = unmatched_avg.get(k, 0)
diff = m_val - u_val
print(f"{k:<20} {m_val:<15.3f} {u_val:<15.3f} {diff:<+10.3f}")
# Build "X Selection Score" - logistic-style weights based on feature differences
# Simple scoring: normalize each feature difference, weight by magnitude
score_weights = {}
for k in matched_avg:
m_val = matched_avg.get(k, 0)
u_val = unmatched_avg.get(k, 0)
if u_val != 0:
score_weights[k] = round((m_val - u_val) / abs(u_val), 3)
elif m_val != 0:
score_weights[k] = 1.0
else:
score_weights[k] = 0.0
# Top selection factors
sorted_weights = sorted(score_weights.items(), key=lambda x: abs(x[1]), reverse=True)
print(f"\nใX ้ธๆๅๆธใๆฌ้ๆๅ๏ผๆญฃ=ๆดๅฏ่ฝๆพX๏ผ่ฒ =ๆดๅฏ่ฝไธๆพX๏ผ:")
for k, w in sorted_weights:
direction = "โ ๆพ X" if w > 0 else "โ ไธๆพ X"
print(f" {k:<20} {w:>+8.3f} {direction}")
# ============================================================
# ANALYSIS 2: Time Difference Signal
# ============================================================
print("\n" + "="*80)
print("ANALYSIS 2: ๆ้ๅทฎไฟก่")
print("="*80)
time_diffs = [m['time_diff_hours'] for m in matches]
ts_first = [m for m in matches if m['time_diff_hours'] > 0] # X posted after TS
x_first = [m for m in matches if m['time_diff_hours'] < 0] # X posted before TS
same_time = [m for m in matches if abs(m['time_diff_hours']) < 0.1]
print(f"\nๆ้ๅทฎๅๅธ:")
print(f" Truth Social ๅ
็ผ, X ๅพ็ผ: {len(ts_first)} ็ฏ")
print(f" X ๅ
็ผ, Truth Social ๅพ็ผ: {len(x_first)} ็ฏ")
print(f" ๅนพไนๅๆ (<6ๅ้): {len(same_time)} ็ฏ")
if ts_first:
diffs = [m['time_diff_hours'] for m in ts_first]
print(f"\n TSๅ
็ผ โ Xๅพ็ผ ็ๆ้ๅทฎ:")
print(f" ๅนณๅ: {sum(diffs)/len(diffs):.2f} ๅฐๆ")
print(f" ไธญไฝๆธ: {sorted(diffs)[len(diffs)//2]:.2f} ๅฐๆ")
print(f" ๆ็ญ: {min(diffs):.2f} ๅฐๆ")
print(f" ๆ้ท: {max(diffs):.2f} ๅฐๆ")
# Time of day analysis (EST = UTC-5)
def classify_market_time(dt):
"""Classify by market hours (EST)"""
est_hour = (dt.hour - 5) % 24
if est_hour < 9 or (est_hour == 9 and dt.minute < 30):
return 'pre_market'
elif est_hour < 16:
return 'market_hours'
else:
return 'after_hours'
market_time_groups = defaultdict(list)
for m in matches:
x_dt = datetime.fromisoformat(m['x_time'].replace('Z', '+00:00'))
period = classify_market_time(x_dt)
market_time_groups[period].append(m)
print(f"\n ๆๅธๅ ดๆๆฎตๅๅธ:")
for period in ['pre_market', 'market_hours', 'after_hours']:
items = market_time_groups.get(period, [])
if items:
avg_diff = sum(m['time_diff_hours'] for m in items) / len(items)
print(f" {period}: {len(items)} ็ฏ, ๅนณๅๆ้ๅทฎ {avg_diff:.2f} ๅฐๆ")
# Market movement during time gap
print(f"\n ๆ้ๅทฎ็ชๅฃไธญ็่กๅธๅๆ
:")
gap_returns = []
for m in ts_first:
ts_date = m['ts_date']
x_date = m['x_date']
ret = get_market_return(ts_date)
if ret is not None:
gap_returns.append(ret)
if gap_returns:
print(f" TS็ผๆๆฅ็่กๅธๆฅๅ ฑ้
ฌ (N={len(gap_returns)}):")
print(f" ๅนณๅ: {sum(gap_returns)/len(gap_returns):.4f}%")
print(f" ๆญฃๅ ฑ้
ฌๅคฉๆธ: {sum(1 for r in gap_returns if r > 0)}/{len(gap_returns)}")
# ============================================================
# ANALYSIS 3: Hidden Posts Market Impact
# ============================================================
print("\n" + "="*80)
print("ANALYSIS 3: ้ฑ่ๆจๆ็ๅธๅ ดๅฝฑ้ฟ")
print("="*80)
# Topic classification
TOPICS = {
'tariff_trade': ['tariff', 'trade', 'deal', 'reciprocal', 'import', 'export', 'duties', 'customs'],
'china': ['china', 'chinese', 'xi', 'beijing'],
'iran_military': ['iran', 'military', 'houthi', 'attack', 'strike', 'bomb', 'isis', 'war', 'troops', 'kharg'],
'economy_market': ['economy', 'stock', 'market', 'dow', 'inflation', 'rate', 'interest', 'oil', 'price', 'investment'],
'elon_doge': ['elon', 'musk', 'doge', 'tesla', 'spending', 'efficiency'],
'executive_order': ['executive order', 'signed', 'order', 'directive'],
'immigration': ['border', 'immigration', 'illegal', 'deport', 'alien', 'immigrant', 'ice'],
'personal_family': ['melania', 'eric', 'barron', 'ivanka', 'don jr', 'family', 'birthday', 'wedding'],
'endorsement': ['vote', 'endorse', 'candidate', 'election', 'campaign', 'district', 'congress'],
'media_attack': ['fake news', 'media', 'cnn', 'msnbc', 'cbs', 'nbc', 'abc', 'radical left', 'democrat'],
'foreign_policy': ['ukraine', 'russia', 'nato', 'europe', 'canada', 'mexico', 'venezuela', 'honduras'],
'legal_court': ['court', 'supreme', 'judge', 'law', 'constitution', 'impeach'],
}
def classify_topics(text):
text_lower = text.lower()
topics = []
for topic, keywords in TOPICS.items():
if any(kw in text_lower for kw in keywords):
topics.append(topic)
return topics if topics else ['other']
# Classify Truth Social posts
ts_topic_returns = defaultdict(list) # topic -> [next_day_returns]
matched_topic_returns = defaultdict(list)
for p in ts_originals:
topics = classify_topics(p['clean_text'])
ret = get_next_day_return(p['date'])
if ret is not None:
is_matched = p['id'] in matched_ts_ids
for t in topics:
if is_matched:
matched_topic_returns[t].append(ret)
else:
ts_topic_returns[t].append(ret)
print(f"\nๆไธป้กๅ้ก็้ๅคฉ่กๅธๅฝฑ้ฟ:")
print(f"\n{'ไธป้ก':<20} {'TS Only็ฏๆธ':<12} {'TS Onlyๅนณๅ%':<14} {'ๆพX็ฏๆธ':<10} {'ๆพXๅนณๅ%':<12} {'ๅทฎ็ฐ':<10}")
print("-" * 80)
all_topics = sorted(set(list(ts_topic_returns.keys()) + list(matched_topic_returns.keys())))
topic_impact = {}
for t in all_topics:
ts_rets = ts_topic_returns.get(t, [])
m_rets = matched_topic_returns.get(t, [])
ts_avg = sum(ts_rets)/len(ts_rets) if ts_rets else 0
m_avg = sum(m_rets)/len(m_rets) if m_rets else 0
diff = ts_avg - m_avg
topic_impact[t] = {
'ts_only_count': len(ts_rets),
'ts_only_avg_return': round(ts_avg, 4),
'x_also_count': len(m_rets),
'x_also_avg_return': round(m_avg, 4),
'difference': round(diff, 4),
}
print(f"{t:<20} {len(ts_rets):<12} {ts_avg:<+14.4f} {len(m_rets):<10} {m_avg:<+12.4f} {diff:<+10.4f}")
# Overall comparison
all_ts_only_rets = []
all_x_also_rets = []
for p in ts_originals:
ret = get_next_day_return(p['date'])
if ret is not None:
if p['id'] in matched_ts_ids:
all_x_also_rets.append(ret)
else:
all_ts_only_rets.append(ret)
print(f"\nๆด้ซๆฏ่ผ:")
print(f" Truth Social Only (N={len(all_ts_only_rets)}): ้ๅคฉๅนณๅ {sum(all_ts_only_rets)/len(all_ts_only_rets):+.4f}%")
if all_x_also_rets:
print(f" ไนๆพ X (N={len(all_x_also_rets)}): ้ๅคฉๅนณๅ {sum(all_x_also_rets)/len(all_x_also_rets):+.4f}%")
# Volatility comparison
def std_dev(lst):
if len(lst) < 2:
return 0
avg = sum(lst) / len(lst)
return (sum((x-avg)**2 for x in lst) / (len(lst)-1)) ** 0.5
print(f"\nๆณขๅๆงๆฏ่ผ:")
print(f" TS Only ้ๅคฉๆณขๅ: {std_dev(all_ts_only_rets):.4f}%")
if all_x_also_rets:
print(f" ไนๆพ X ้ๅคฉๆณขๅ: {std_dev(all_x_also_rets):.4f}%")
# ============================================================
# ANALYSIS 4: Topic Selection Strategy
# ============================================================
print("\n" + "="*80)
print("ANALYSIS 4: ไธป้ก็ฏฉ้ธ็ญ็ฅ")
print("="*80)
# For each topic, what % goes to X?
topic_total = defaultdict(int)
topic_on_x = defaultdict(int)
for p in ts_originals:
topics = classify_topics(p['clean_text'])
for t in topics:
topic_total[t] += 1
if p['id'] in matched_ts_ids:
topic_on_x[t] += 1
print(f"\n{'ไธป้ก':<20} {'Total':<8} {'ๆพX':<6} {'X็%':<8} {'็ญ็ฅ':<20}")
print("-" * 70)
topic_strategy = {}
for t in sorted(topic_total.keys(), key=lambda x: topic_on_x.get(x, 0)/max(topic_total[x], 1), reverse=True):
total = topic_total[t]
on_x = topic_on_x.get(t, 0)
rate = on_x / total * 100 if total > 0 else 0
if rate > 5:
strategy = "้ซๅบฆๅ
ฌ้"
elif rate > 2:
strategy = "้ธๆๆงๅ
ฌ้"
elif rate > 0:
strategy = "ๆฅตๅฐๅ
ฌ้"
else:
strategy = "ๅฎๅ
จ้ฑ่"
topic_strategy[t] = {
'total': total,
'on_x': on_x,
'x_rate_pct': round(rate, 2),
'strategy': strategy,
}
print(f"{t:<20} {total:<8} {on_x:<6} {rate:<8.2f} {strategy:<20}")
# Focus keywords analysis
focus_keywords = ['tariff', 'deal', 'china', 'iran', 'executive order', 'military', 'stock market', 'elon', 'doge']
print(f"\n็นๅฅ้ๆณจ้้ตๅญ:")
print(f"{'้้ตๅญ':<20} {'TS็ฏๆธ':<10} {'ๆพX็ฏๆธ':<10} {'X็%':<10}")
print("-" * 50)
keyword_strategy = {}
for kw in focus_keywords:
ts_count = sum(1 for p in ts_originals if kw in p['clean_text'].lower())
x_count = sum(1 for p in ts_originals if kw in p['clean_text'].lower() and p['id'] in matched_ts_ids)
rate = x_count / ts_count * 100 if ts_count > 0 else 0
keyword_strategy[kw] = {
'ts_count': ts_count,
'x_count': x_count,
'x_rate_pct': round(rate, 2),
}
print(f"{kw:<20} {ts_count:<10} {x_count:<10} {rate:<10.2f}")
# ============================================================
# ANALYSIS 5: Trend Analysis
# ============================================================
print("\n" + "="*80)
print("ANALYSIS 5: ่ถจๅข่ฎๅ")
print("="*80)
# Monthly X selection rate
monthly_ts = defaultdict(int)
monthly_x = defaultdict(int)
for p in ts_originals:
month = p['date'][:7]
monthly_ts[month] += 1
if p['id'] in matched_ts_ids:
monthly_x[month] += 1
# Also count X originals with text per month
monthly_x_all = defaultdict(int)
for t in x_originals:
if t['clean_text']:
month = t['date'][:7]
monthly_x_all[month] += 1
# Monthly market average return
monthly_market_avg = defaultdict(list)
for m in market:
month = m['date'][:7]
ret = (m['close'] - m['open']) / m['open'] * 100
monthly_market_avg[month].append(ret)
all_months = sorted(set(list(monthly_ts.keys()) + list(monthly_x_all.keys())))
print(f"\n{'ๆไปฝ':<10} {'TS็ฏๆธ':<8} {'X็ฏๆธ':<8} {'X็%':<8} {'Xๅๅต':<8} {'ๆๅๅ ฑ้
ฌ%':<12}")
print("-" * 60)
monthly_trends = []
for month in all_months:
ts_cnt = monthly_ts[month]
x_cnt = monthly_x[month]
x_all = monthly_x_all.get(month, 0)
rate = x_cnt / ts_cnt * 100 if ts_cnt > 0 else 0
mkt_rets = monthly_market_avg.get(month, [])
mkt_avg = sum(mkt_rets)/len(mkt_rets) if mkt_rets else None
monthly_trends.append({
'month': month,
'ts_count': ts_cnt,
'matched_on_x': x_cnt,
'x_rate_pct': round(rate, 2),
'x_originals_with_text': x_all,
'market_avg_return': round(mkt_avg, 4) if mkt_avg is not None else None,
})
mkt_str = f"{mkt_avg:+.4f}" if mkt_avg is not None else "N/A"
print(f"{month:<10} {ts_cnt:<8} {x_cnt:<8} {rate:<8.2f} {x_all:<8} {mkt_str:<12}")
# Correlation: X rate vs market
rates = []
mkts = []
for mt in monthly_trends:
if mt['market_avg_return'] is not None and mt['ts_count'] > 0:
rates.append(mt['x_rate_pct'])
mkts.append(mt['market_avg_return'])
if len(rates) > 2:
avg_r = sum(rates)/len(rates)
avg_m = sum(mkts)/len(mkts)
cov = sum((r-avg_r)*(m-avg_m) for r,m in zip(rates, mkts)) / (len(rates)-1)
std_r = (sum((r-avg_r)**2 for r in rates)/(len(rates)-1))**0.5
std_m = (sum((m-avg_m)**2 for m in mkts)/(len(mkts)-1))**0.5
corr = cov / (std_r * std_m) if std_r * std_m > 0 else 0
print(f"\nX้ธๆ็ vs ๆๅๅธๅ ดๅ ฑ้
ฌ ็ธ้ไฟๆธ: {corr:.4f}")
# ============================================================
# Build comprehensive output JSON
# ============================================================
# Matched posts detail
matched_detail = []
for m in matches:
matched_detail.append({
'x_text': m['x_text'],
'ts_text': m['ts_text'],
'similarity': m['similarity'],
'x_time': m['x_time'],
'ts_time': m['ts_time'],
'time_diff_hours': m['time_diff_hours'],
'x_impressions': m['x_metrics'].get('impression_count', 0),
'x_likes': m['x_metrics'].get('like_count', 0),
'x_retweets': m['x_metrics'].get('retweet_count', 0),
'ts_replies': m['ts_replies'],
'ts_reblogs': m['ts_reblogs'],
'ts_favourites': m['ts_favourites'],
'topics': classify_topics(m['ts_post']['clean_text']),
})
output = {
'metadata': {
'analysis_date': '2026-03-15',
'x_original_tweets': len(x_originals),
'x_with_text': len(x_with_text),
'x_url_only': len(x_url_only),
'ts_original_posts': len(ts_originals),
'matched_count': len(matches),
'match_rate_pct': round(len(matches) / len(ts_originals) * 100, 2),
'market_days': len(market),
},
'analysis_1_selection_mechanism': {
'matched_avg_features': matched_avg,
'unmatched_avg_features': unmatched_avg,
'selection_score_weights': dict(sorted_weights),
'key_findings': {
'top_3_selection_factors': [
{'factor': k, 'weight': w, 'direction': 'ๆพX' if w > 0 else 'ไธๆพX'}
for k, w in sorted_weights[:3]
],
'bottom_3_factors': [
{'factor': k, 'weight': w, 'direction': 'ๆพX' if w > 0 else 'ไธๆพX'}
for k, w in sorted_weights[-3:]
],
}
},
'analysis_2_time_signal': {
'ts_first_count': len(ts_first),
'x_first_count': len(x_first),
'same_time_count': len(same_time),
'avg_delay_hours': round(sum(m['time_diff_hours'] for m in ts_first)/len(ts_first), 2) if ts_first else 0,
'median_delay_hours': round(sorted([m['time_diff_hours'] for m in ts_first])[len(ts_first)//2], 2) if ts_first else 0,
'by_market_period': {
period: {
'count': len(items),
'avg_time_diff_hours': round(sum(m['time_diff_hours'] for m in items)/len(items), 2) if items else 0,
}
for period, items in market_time_groups.items()
},
'gap_market_returns': {
'count': len(gap_returns),
'avg_return_pct': round(sum(gap_returns)/len(gap_returns), 4) if gap_returns else 0,
'positive_days': sum(1 for r in gap_returns if r > 0),
} if gap_returns else {},
},
'analysis_3_market_impact': {
'ts_only': {
'count': len(all_ts_only_rets),
'avg_next_day_return': round(sum(all_ts_only_rets)/len(all_ts_only_rets), 4) if all_ts_only_rets else 0,
'volatility': round(std_dev(all_ts_only_rets), 4),
},
'also_on_x': {
'count': len(all_x_also_rets),
'avg_next_day_return': round(sum(all_x_also_rets)/len(all_x_also_rets), 4) if all_x_also_rets else 0,
'volatility': round(std_dev(all_x_also_rets), 4),
},
'by_topic': topic_impact,
},
'analysis_4_topic_strategy': {
'topic_selection_rates': topic_strategy,
'keyword_strategy': keyword_strategy,
'public_topics': [t for t, d in topic_strategy.items() if d['x_rate_pct'] > 2],
'hidden_topics': [t for t, d in topic_strategy.items() if d['x_rate_pct'] == 0],
},
'analysis_5_trends': {
'monthly_data': monthly_trends,
'x_rate_market_correlation': round(corr, 4) if len(rates) > 2 else None,
'trend_direction': 'Xไฝฟ็จ็ๆ็บไธ้',
},
'matched_posts_detail': matched_detail,
}
# Save
with open('data/x_truth_cross_analysis.json', 'w', encoding='utf-8') as f:
json.dump(output, f, ensure_ascii=False, indent=2)
print(f"\n\nๅๆ็ตๆๅทฒๅญ่ณ data/x_truth_cross_analysis.json")
# ============================================================
# FULL CHINESE REPORT
# ============================================================
print("\n\n")
print("=" * 80)
print(" X ่ Truth Social ไบคๅๆฏๅฐๅๆๅฎๆดๅ ฑๅ")
print("=" * 80)
print(f"""
โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ
โ ่ณๆๆฆ่ฆฝ โ
โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโค
โ X ๅๅตๆจๆ๏ผๆๆๅญ๏ผ: {len(x_with_text):>5} ็ฏ โ
โ X ๅๅตๆจๆ๏ผ็ด้ฃ็ต๏ผ: {len(x_url_only):>5} ็ฏ โ
โ Truth Social ๅๅตๆจๆ: {len(ts_originals):>5} ็ฏ โ
โ ๅ
ฉ้้ฝๆ็ๅน้
ๆจๆ: {len(matches):>5} ็ฏ โ
โ ๅน้
็: {len(matches)/len(ts_originals)*100:>5.2f}% โ
โ ๅๆๆ้: 2025-01-20 ่ณ 2026-03-14 โ
โ S&P 500 ไบคๆๆฅ: {len(market):>3} ๅคฉ โ
โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ
""")
print("โ" * 80)
print("ใไธใ็ฏฉ้ธๆฉๅถๅๆ๏ผไป้บผๆจๆๆ่ขซๆพๅฐ X๏ผ")
print("โ" * 80)
print(f"""
ๅจ {len(ts_originals)} ็ฏ Truth Social ๅๅตๆจๆไธญ๏ผๅชๆ {len(matches)} ็ฏไนๅบ็พๅจ X ไธใ
้ {len(matches)} ็ฏใ่ขซ้ธไธญใ็ๆจๆ๏ผๅๅ
ถไป {len(unmatched_ts)} ็ฏใๆฒ่ขซ้ธไธญใ็ๆจๆ๏ผ
ๅจๆๅญ็นๅพตไธๆๆ้กฏๅทฎ็ฐ๏ผ
โ ่ขซ้ธไธญ vs ๆฒ่ขซ้ธไธญ็็นๅพตๆฏ่ผ โ""")
print(f" โ {'็นๅพต':<18} โ {'ๆพX':<10} โ {'ไธๆพX':<10} โ {'ๅทฎ็ฐ':<10} โ")
print(f" โ{'โ'*20}โผ{'โ'*12}โผ{'โ'*12}โผ{'โ'*12}โค")
for k in matched_avg:
m_val = matched_avg.get(k, 0)
u_val = unmatched_avg.get(k, 0)
diff = m_val - u_val
print(f" โ {k:<18} โ {m_val:<10.3f} โ {u_val:<10.3f} โ {diff:<+10.3f} โ")
print(f" โ{'โ'*20}โด{'โ'*12}โด{'โ'*12}โด{'โ'*12}โ")
print(f"""
ใX ้ธๆๅๆธใๆๅ๏ผ""")
for i, (k, w) in enumerate(sorted_weights):
direction = "ๆพ X" if w > 0 else "ไธๆพ X"
bar = "โ" * min(int(abs(w) * 10), 20)
sign = "+" if w > 0 else "-"
print(f" {i+1:>2}. {k:<20} {sign}{bar} ({w:+.3f})")
print(f"""
ๆ ธๅฟ็ผ็พ๏ผ
โข ๆพๅฐ X ็ๆจๆๅพๅๆด้ทใๆดๅคๆฟ็ญ้้ตๅญ
โข ๅคงๅฏซ็ๅๆๅ่ๆธ้ๅทฎ็ฐ้กฏ็คบใ่ชๆฐฃ้ธๆใ
โข ๅไบบ/ๅฎถๅบญ็ธ้ๆจๆๅๆฟๆฒป่ๆธๆไธๅ็ X ้ธๆ็""")
print("\n" + "โ" * 80)
print("ใไบใๆ้ๅทฎไฟก่๏ผTruth Social ๅ
็ผ๏ผX ๆๅคไน
๏ผ")
print("โ" * 80)
if ts_first:
diffs_sorted = sorted([m['time_diff_hours'] for m in ts_first])
print(f"""
ๅจ {len(matches)} ็ฏๅน้
ๆจๆไธญ๏ผ
โข Truth Social ๅ
็ผ๏ผX ๅพ็ผ: {len(ts_first)} ็ฏ
โข X ๅ
็ผ๏ผTruth Social ๅพ็ผ: {len(x_first)} ็ฏ
โข ๅนพไนๅๆ (<6ๅ้): {len(same_time)} ็ฏ
TS ๅ
็ผ็ๆ้ๅทฎ็ตฑ่จ๏ผ
โข ๅนณๅๅปถ้ฒ: {sum(diffs_sorted)/len(diffs_sorted):.2f} ๅฐๆ
โข ไธญไฝๅปถ้ฒ: {diffs_sorted[len(diffs_sorted)//2]:.2f} ๅฐๆ
โข ๆ็ญ: {min(diffs_sorted):.2f} ๅฐๆ
โข ๆ้ท: {max(diffs_sorted):.2f} ๅฐๆ""")
print(f"\n ๆๅธๅ ดๆๆฎตๅๅธ๏ผ")
for period in ['pre_market', 'market_hours', 'after_hours']:
items = market_time_groups.get(period, [])
if items:
avg_d = sum(m['time_diff_hours'] for m in items) / len(items)
period_zh = {'pre_market': '็คๅ', 'market_hours': '็คไธญ', 'after_hours': '็คๅพ'}
print(f" {period_zh[period]}: {len(items)} ็ฏ, ๅนณๅๆ้ๅทฎ {avg_d:.2f} ๅฐๆ")
if gap_returns:
print(f"""
ๆ้ๅทฎ็ชๅฃไธญ็่กๅธๅๆ
๏ผTS็ผๆๆฅ๏ผ๏ผ
โข ๆจฃๆฌๆธ: {len(gap_returns)}
โข ็ถๆฅๅนณๅๅ ฑ้
ฌ: {sum(gap_returns)/len(gap_returns):+.4f}%
โข ๆญฃๅ ฑ้
ฌๅคฉๆธ: {sum(1 for r in gap_returns if r > 0)}/{len(gap_returns)}
่งฃ่ฎ๏ผ็ถไปๅจ Truth Social ๅ
็ผไฝ้ๆฒๆพๅฐ X ็้ๆฎต็ชๅฃๆ๏ผ
ๅธๅ ด็ๅๆๅฏไปฅๅ่จดๆๅใTruth Social ็ไฟก่ๆฏๅฆๅ
่กใ""")
print("\n" + "โ" * 80)
print("ใไธใ้ฑ่ๆจๆ็ๅธๅ ดๅฝฑ้ฟ")
print("โ" * 80)
print(f"""
ๆด้ซๆฏ่ผ๏ผ
โโโโโโโโโโโโโโโโโโโโฌโโโโโโโโโฌโโโโโโโโโโโโโโโฌโโโโโโโโโโโโโ
โ ้กๅ โ ็ฏๆธ โ ้ๅคฉๅนณๅๅ ฑ้
ฌ โ ๆณขๅๆง โ
โโโโโโโโโโโโโโโโโโโโผโโโโโโโโโผโโโโโโโโโโโโโโโผโโโโโโโโโโโโโค
โ Truth Social Only โ {len(all_ts_only_rets):<6} โ {sum(all_ts_only_rets)/len(all_ts_only_rets):>+10.4f}% โ {std_dev(all_ts_only_rets):>8.4f}% โ""")
if all_x_also_rets:
print(f" โ ไนๆพ X โ {len(all_x_also_rets):<6} โ {sum(all_x_also_rets)/len(all_x_also_rets):>+10.4f}% โ {std_dev(all_x_also_rets):>8.4f}% โ")
print(f" โโโโโโโโโโโโโโโโโโโโดโโโโโโโโโดโโโโโโโโโโโโโโโดโโโโโโโโโโโโโ")
print(f"\n ๆไธป้กๅ้ก็้ๅคฉ่กๅธๅฝฑ้ฟ๏ผ")
print(f" {'ไธป้ก':<20} {'TS Only':<10} {'TSๅนณๅ%':<12} {'ๆพX':<8} {'Xๅนณๅ%':<12} {'ๅทฎ็ฐ':<10}")
print(f" {'โ'*72}")
for t in sorted(topic_impact.keys(), key=lambda x: abs(topic_impact[x]['difference']), reverse=True):
d = topic_impact[t]
if d['ts_only_count'] > 10: # Only show topics with enough data
print(f" {t:<20} {d['ts_only_count']:<10} {d['ts_only_avg_return']:>+10.4f} {d['x_also_count']:<8} {d['x_also_avg_return']:>+10.4f} {d['difference']:>+10.4f}")
print("\n" + "โ" * 80)
print("ใๅใไธป้ก็ฏฉ้ธ็ญ็ฅ๏ผไป็ๅ
ฌ้/้ฑ่็ญ็ฅ่กจ")
print("โ" * 80)
print(f"\n โโโโโโโโโโโโโโโโโโโโฌโโโโโโโโโฌโโโโโโโฌโโโโโโโโโฌโโโโโโโโโโโโโโโ")
print(f" โ ไธป้ก โ Total โ ๆพX โ X็% โ ็ญ็ฅ โ")
print(f" โโโโโโโโโโโโโโโโโโโโผโโโโโโโโโผโโโโโโโผโโโโโโโโโผโโโโโโโโโโโโโโโค")
for t in sorted(topic_strategy.keys(), key=lambda x: topic_strategy[x]['x_rate_pct'], reverse=True):
d = topic_strategy[t]
print(f" โ {t:<16} โ {d['total']:<6} โ {d['on_x']:<4} โ {d['x_rate_pct']:<6.2f} โ {d['strategy']:<12} โ")
print(f" โโโโโโโโโโโโโโโโโโโโดโโโโโโโโโดโโโโโโโดโโโโโโโโโดโโโโโโโโโโโโโโโ")
print(f"\n ็นๅฅ้ๆณจ้้ตๅญๅๆ๏ผ")
print(f" {'้้ตๅญ':<20} {'TS็ฏๆธ':<10} {'ๆพX็ฏๆธ':<10} {'X็%':<10}")
print(f" {'โ'*50}")
for kw, d in keyword_strategy.items():
print(f" {kw:<20} {d['ts_count']:<10} {d['x_count']:<10} {d['x_rate_pct']:<10.2f}")
print(f"""
็ญ็ฅ่งฃ่ฎ๏ผ
โข ้ซๅบฆๅ
ฌ้: {', '.join(output['analysis_4_topic_strategy']['public_topics']) or '็ก'}
โข ๅฎๅ
จ้ฑ่: {', '.join(output['analysis_4_topic_strategy']['hidden_topics']) or '็ก'}
ไปๅพๅๆใๅฝข่ฑก็ฎก็ใ้กๆจๆๆพ X๏ผๅไบบใ่ๆธใๅ้ไบไปถ๏ผ๏ผ
่ๆใๆฟ็ญๆไฝใ้กๆจๆ็ๅจ Truth Social๏ผ้็จ
ใ็ถๆฟใ่กๆฟๅฝไปค๏ผใ
้ๆๅณ่ Truth Social ๆฏใไฟก่ๆบใ๏ผX ๆฏใๅฝข่ฑก็ชๅฃใใ""")
print("\n" + "โ" * 80)
print("ใไบใ่ถจๅข่ฎๅ๏ผX ้ธๆ็็ๆ้ๆผ่ฎ")
print("โ" * 80)
print(f"\n ๆไปฝ TS็ฏๆธ ๅน้
X X็% Xๅๅต ๆๅๅ ฑ้
ฌ%")
print(f" {'โ'*60}")
for mt in monthly_trends:
mkt_str = f"{mt['market_avg_return']:+.4f}" if mt['market_avg_return'] is not None else "N/A"
bar = "โ" * int(mt['x_rate_pct'] * 2)
print(f" {mt['month']} {mt['ts_count']:<8} {mt['matched_on_x']:<7} {mt['x_rate_pct']:<7.2f} {mt['x_originals_with_text']:<7} {mkt_str:<10} {bar}")
if len(rates) > 2:
print(f"\n X้ธๆ็ vs ๆๅๅธๅ ดๅ ฑ้
ฌ ็ธ้ไฟๆธ: {corr:.4f}")
if abs(corr) > 0.3:
direction = "ๆญฃ็ธ้" if corr > 0 else "่ฒ ็ธ้"
print(f" โ {direction}๏ผๅธๅ ด{'ๅฅฝ' if corr > 0 else 'ๅทฎ'}็ๆๅ๏ผไป{'ๆดๅค' if corr > 0 else 'ๆดๅฐ'}็จ X")
else:
print(f" โ ็ธ้ๆงๅผฑ๏ผX ไฝฟ็จ็็ไธ้ๅฏ่ฝ่ๅธๅ ด็ก็ดๆฅ้่ฏ")
print(f"""
่ถจๅข่งฃ่ฎ๏ผ
โข ๆด้ซๆนๅ: X ไฝฟ็จ็ๅพๆฉๆ็่ผ้ซๆฐดๆบๆ็บไธ้
โข ้่กจ็คบไป่ถไพ่ถๆ Truth Social ็ถๅใไธปๅ ดใ๏ผX ๅ
ไฝ็บใๅคไบค็ชๅฃใ
โข ๅฐไบคๆ่
็ๆ็พฉ: Truth Social ็็จๅฎถๅ
งๅฎน่ถไพ่ถๅค๏ผ
ๅฎ็ X ๆ้ฏ้ 98%+ ็ไฟก่
""")
print("=" * 80)
print(" ็ธฝ็ต๏ผไป็ๅฏ็ขผ")
print("=" * 80)
print(f"""
1. ็ฏฉ้ธ้่ผฏ๏ผๆพๅฐ X ็ๆจๆๆฏใๅฝข่ฑก็ฎก็ใโโๅไบบไบๅใๅ้ๅ ดๅใ
่ๆธๅ้ธไบบใไธๆพ็ๆฏใๅฏฆ่ณชๆไฝใโโ้็จ
ๆฟ็ญใ็ถๆฟ่ฉ่ซใ่กๆฟๅฝไปคใ
2. ๆ้ๅทฎ๏ผTruth Social ๆฏใๅ
่กๆๆจใ๏ผX ๆฏใๅปถ้ฒ็ขบ่ชใใ
ๅนณๅๅปถ้ฒ {output['analysis_2_time_signal']['avg_delay_hours']:.1f} ๅฐๆ๏ผ้ๆฎต็ชๅฃๅฐฑๆฏใ่ณ่จไธๅฐ็จฑใใ
3. ๅธๅ ดๅฝฑ้ฟ๏ผTruth Social ็จๅฎถๆจๆ๏ผๅ {100-output['metadata']['match_rate_pct']:.1f}%๏ผๅฐๅธๅ ด็ๅฝฑ้ฟ
ๅๆพๅฐ X ็ๆจๆไธๅโโ้ฑ่ๆจๆ่ฃก่่ๆดๅคๆฟ็ญไฟก่ใ
4. ่ถจๅข๏ผไป่ถไพ่ถไธ็จ X๏ผ็ญๆผ Truth Social ็ใ็จๅฎถไฟก่ๅฏๅบฆใ
่ถไพ่ถ้ซใๅช็ X ็ไบบ๏ผ่ถไพ่ถ็ไธๅฐๅ
จ่ฒใ
5. ๆ ธๅฟๅฏ็ขผ๏ผX ๆฏใ่กจๆผใ๏ผTruth Social ๆฏใๅไฝใใ
็ๆญฃๅฝฑ้ฟๅธๅ ด็ไฟก่๏ผๅจไป้ธๆไธๆพๅฐ X ็้ฃไบๆจๆ่ฃกใ
""")
print("=" * 80)