dayun0071 commited on
Commit
f18e56c
·
verified ·
1 Parent(s): 93f2e5a

Upload homework1_Analyze_the_news_headlines_dataset_colab.ipynb

Browse files
homework1_Analyze_the_news_headlines_dataset_colab.ipynb ADDED
@@ -0,0 +1,967 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "cells": [
3
+ {
4
+ "cell_type": "code",
5
+ "execution_count": 1,
6
+ "metadata": {
7
+ "id": "WW6kJjTQiQOX"
8
+ },
9
+ "outputs": [],
10
+ "source": [
11
+ "# Cell 1: install and import packages\n",
12
+ "!pip -q install nltk seaborn scikit-learn tqdm\n",
13
+ "\n",
14
+ "import os\n",
15
+ "import re\n",
16
+ "import warnings\n",
17
+ "\n",
18
+ "import matplotlib.pyplot as plt\n",
19
+ "import nltk\n",
20
+ "import numpy as np\n",
21
+ "import pandas as pd\n",
22
+ "import seaborn as sns\n",
23
+ "\n",
24
+ "from IPython.display import display\n",
25
+ "from nltk.sentiment.vader import SentimentIntensityAnalyzer\n",
26
+ "from sklearn.metrics import accuracy_score, classification_report, confusion_matrix\n",
27
+ "from tqdm.auto import tqdm\n",
28
+ "\n",
29
+ "warnings.filterwarnings(\"ignore\")\n",
30
+ "nltk.download(\"vader_lexicon\", quiet=True)\n",
31
+ "\n",
32
+ "tqdm.pandas()\n",
33
+ "pd.set_option(\"display.max_colwidth\", 180)\n",
34
+ "sns.set_theme(style=\"whitegrid\")"
35
+ ],
36
+ "id": "WW6kJjTQiQOX"
37
+ },
38
+ {
39
+ "cell_type": "code",
40
+ "execution_count": 2,
41
+ "metadata": {
42
+ "colab": {
43
+ "base_uri": "https://localhost:8080/"
44
+ },
45
+ "id": "CQnl5bndiQOZ",
46
+ "outputId": "db42c827-b972-4519-c835-9c4c67916aed"
47
+ },
48
+ "outputs": [
49
+ {
50
+ "output_type": "stream",
51
+ "name": "stdout",
52
+ "text": [
53
+ "Required files already found.\n",
54
+ "\n",
55
+ "Optional: upload labeled_data.csv too if you want accuracy and misclassification analysis.\n"
56
+ ]
57
+ }
58
+ ],
59
+ "source": [
60
+ "# Cell 2: upload files if they are not already in /content\n",
61
+ "from google.colab import files\n",
62
+ "\n",
63
+ "required_files = [\n",
64
+ " \"news_data.csv\",\n",
65
+ " \"Loughran-McDonald_MasterDictionary_1993-2024.csv\",\n",
66
+ "]\n",
67
+ "\n",
68
+ "missing_required = [\n",
69
+ " filename\n",
70
+ " for filename in required_files\n",
71
+ " if not os.path.exists(f\"/content/{filename}\") and not os.path.exists(filename)\n",
72
+ "]\n",
73
+ "\n",
74
+ "if missing_required:\n",
75
+ " print(\"Please upload these required files:\", missing_required)\n",
76
+ " uploaded = files.upload()\n",
77
+ "else:\n",
78
+ " print(\"Required files already found.\")\n",
79
+ "\n",
80
+ "print(\"\\nOptional: upload labeled_data.csv too if you want accuracy and misclassification analysis.\")"
81
+ ],
82
+ "id": "CQnl5bndiQOZ"
83
+ },
84
+ {
85
+ "cell_type": "code",
86
+ "execution_count": 3,
87
+ "metadata": {
88
+ "colab": {
89
+ "base_uri": "https://localhost:8080/"
90
+ },
91
+ "id": "MrDaboNQiQOa",
92
+ "outputId": "6c30ce9c-150b-4027-e4f9-b670279696e0"
93
+ },
94
+ "outputs": [
95
+ {
96
+ "output_type": "stream",
97
+ "name": "stdout",
98
+ "text": [
99
+ "news_data.csv: /content/news_data.csv\n",
100
+ "LM dictionary: /content/Loughran-McDonald_MasterDictionary_1993-2024.csv\n",
101
+ "optional labeled_data.csv: None\n"
102
+ ]
103
+ }
104
+ ],
105
+ "source": [
106
+ "# Cell 3: locate files\n",
107
+ "def find_file(filename):\n",
108
+ " candidates = [\n",
109
+ " f\"/content/{filename}\",\n",
110
+ " filename,\n",
111
+ " f\"/content/drive/MyDrive/{filename}\",\n",
112
+ " ]\n",
113
+ " for path in candidates:\n",
114
+ " if os.path.exists(path):\n",
115
+ " return path\n",
116
+ " return None\n",
117
+ "\n",
118
+ "news_path = find_file(\"news_data.csv\")\n",
119
+ "lm_path = find_file(\"Loughran-McDonald_MasterDictionary_1993-2024.csv\")\n",
120
+ "labeled_path = find_file(\"labeled_data.csv\")\n",
121
+ "\n",
122
+ "if news_path is None:\n",
123
+ " raise FileNotFoundError(\"news_data.csv was not found. Please upload it first.\")\n",
124
+ "if lm_path is None:\n",
125
+ " raise FileNotFoundError(\"Loughran-McDonald_MasterDictionary_1993-2024.csv was not found. Please upload it first.\")\n",
126
+ "\n",
127
+ "print(\"news_data.csv:\", news_path)\n",
128
+ "print(\"LM dictionary:\", lm_path)\n",
129
+ "print(\"optional labeled_data.csv:\", labeled_path)"
130
+ ],
131
+ "id": "MrDaboNQiQOa"
132
+ },
133
+ {
134
+ "cell_type": "code",
135
+ "execution_count": null,
136
+ "metadata": {
137
+ "id": "hLiughDAiQOb"
138
+ },
139
+ "outputs": [],
140
+ "source": [
141
+ "# Cell 4: read data\n",
142
+ "news = pd.read_csv(news_path, low_memory=False)\n",
143
+ "lm = pd.read_csv(lm_path, low_memory=False)\n",
144
+ "\n",
145
+ "print(\"News data shape:\", news.shape)\n",
146
+ "print(\"LM dictionary shape:\", lm.shape)\n",
147
+ "\n",
148
+ "print(\"\\nNews columns:\")\n",
149
+ "print(news.columns.tolist())\n",
150
+ "\n",
151
+ "display(news.head())"
152
+ ],
153
+ "id": "hLiughDAiQOb"
154
+ },
155
+ {
156
+ "cell_type": "code",
157
+ "execution_count": null,
158
+ "metadata": {
159
+ "id": "Ewt04Mj8iQOb"
160
+ },
161
+ "outputs": [],
162
+ "source": [
163
+ "# Cell 5: inspect missing values, duplicates, dates, tickers, and English filter\n",
164
+ "quality = pd.DataFrame({\n",
165
+ " \"dtype\": news.dtypes.astype(str),\n",
166
+ " \"missing_count\": news.isna().sum(),\n",
167
+ " \"missing_pct\": news.isna().mean().round(4),\n",
168
+ " \"unique_count\": news.nunique(dropna=True),\n",
169
+ "})\n",
170
+ "display(quality)\n",
171
+ "\n",
172
+ "print(\"Duplicate full rows:\", news.duplicated().sum())\n",
173
+ "\n",
174
+ "if {\"time\", \"ticker\", \"headline\"}.issubset(news.columns):\n",
175
+ " print(\"Duplicate time-ticker-headline rows:\", news.duplicated([\"time\", \"ticker\", \"headline\"]).sum())\n",
176
+ "\n",
177
+ "if \"headline\" in news.columns:\n",
178
+ " print(\"Duplicate headlines:\", news.duplicated([\"headline\"]).sum())\n",
179
+ "\n",
180
+ "if \"cleaned_text_nltk\" in news.columns:\n",
181
+ " print(\"Duplicate cleaned_text_nltk:\", news.duplicated([\"cleaned_text_nltk\"]).sum())\n",
182
+ "\n",
183
+ "news[\"time\"] = pd.to_datetime(news[\"time\"], errors=\"coerce\")\n",
184
+ "news[\"date\"] = news[\"time\"].dt.date.astype(str)\n",
185
+ "\n",
186
+ "print(\"\\nDate range:\")\n",
187
+ "print(news[\"time\"].min(), \"to\", news[\"time\"].max())\n",
188
+ "\n",
189
+ "print(\"\\nNumber of tickers:\", news[\"ticker\"].nunique())\n",
190
+ "\n",
191
+ "print(\"\\nTop 15 tickers by headline count:\")\n",
192
+ "display(news[\"ticker\"].value_counts().head(15))\n",
193
+ "\n",
194
+ "print(\"\\nEnglish flag distribution:\")\n",
195
+ "display(news[\"is_english\"].value_counts(dropna=False))\n",
196
+ "\n",
197
+ "print(\"\\nDoes news_data.csv have label/returns columns?\")\n",
198
+ "print(\"label\" in news.columns, \"returns\" in news.columns)"
199
+ ],
200
+ "id": "Ewt04Mj8iQOb"
201
+ },
202
+ {
203
+ "cell_type": "code",
204
+ "execution_count": null,
205
+ "metadata": {
206
+ "id": "IKZBFA4jiQOc"
207
+ },
208
+ "outputs": [],
209
+ "source": [
210
+ "# Cell 6: filter English headlines and clean text\n",
211
+ "df = news.copy()\n",
212
+ "\n",
213
+ "required_columns = [\"time\", \"date\", \"ticker\", \"headline\", \"is_english\"]\n",
214
+ "missing_columns = [c for c in required_columns if c not in df.columns]\n",
215
+ "if missing_columns:\n",
216
+ " raise ValueError(f\"Missing required columns: {missing_columns}\")\n",
217
+ "\n",
218
+ "df = df[df[\"is_english\"] == True].copy()\n",
219
+ "df = df.dropna(subset=[\"time\", \"ticker\", \"headline\"])\n",
220
+ "df = df.drop_duplicates(subset=[\"time\", \"ticker\", \"headline\"]).copy()\n",
221
+ "\n",
222
+ "def clean_text(text):\n",
223
+ " text = str(text).lower()\n",
224
+ " text = re.sub(r\"http\\S+|www\\S+\", \" \", text)\n",
225
+ " text = re.sub(r\"[^a-zA-Z\\s]\", \" \", text)\n",
226
+ " text = re.sub(r\"\\s+\", \" \", text).strip()\n",
227
+ " return text\n",
228
+ "\n",
229
+ "df[\"clean_text\"] = df[\"headline\"].apply(clean_text)\n",
230
+ "df = df[df[\"clean_text\"].str.len() > 0].copy()\n",
231
+ "\n",
232
+ "print(\"Prepared news data shape:\", df.shape)\n",
233
+ "display(df[[\"time\", \"ticker\", \"headline\", \"clean_text\"]].head())"
234
+ ],
235
+ "id": "IKZBFA4jiQOc"
236
+ },
237
+ {
238
+ "cell_type": "code",
239
+ "execution_count": null,
240
+ "metadata": {
241
+ "id": "vuCp3ZJwiQOd"
242
+ },
243
+ "outputs": [],
244
+ "source": [
245
+ "# Cell 7: optional speed setting\n",
246
+ "# Keep RUN_ON_SAMPLE = False for the final homework result.\n",
247
+ "# Set it to True only if you want a quick test run first.\n",
248
+ "\n",
249
+ "RUN_ON_SAMPLE = False\n",
250
+ "SAMPLE_N = 50000\n",
251
+ "\n",
252
+ "if RUN_ON_SAMPLE:\n",
253
+ " work_df = df.sample(n=min(SAMPLE_N, len(df)), random_state=42).copy()\n",
254
+ " print(\"Running on sample:\", work_df.shape)\n",
255
+ "else:\n",
256
+ " work_df = df.copy()\n",
257
+ " print(\"Running on full dataset:\", work_df.shape)"
258
+ ],
259
+ "id": "vuCp3ZJwiQOd"
260
+ },
261
+ {
262
+ "cell_type": "code",
263
+ "execution_count": null,
264
+ "metadata": {
265
+ "id": "6sYDy5UEiQOd"
266
+ },
267
+ "outputs": [],
268
+ "source": [
269
+ "# Cell 8: VADER baseline\n",
270
+ "sia = SentimentIntensityAnalyzer()\n",
271
+ "\n",
272
+ "def vader_score(text):\n",
273
+ " return sia.polarity_scores(str(text))[\"compound\"]\n",
274
+ "\n",
275
+ "def vader_label(score):\n",
276
+ " if score >= 0.05:\n",
277
+ " return \"Positive\"\n",
278
+ " if score <= -0.05:\n",
279
+ " return \"Negative\"\n",
280
+ " return \"Neutral\"\n",
281
+ "\n",
282
+ "# Use raw headline for VADER because VADER can use punctuation and capitalization.\n",
283
+ "work_df[\"vader_score\"] = work_df[\"headline\"].progress_apply(vader_score)\n",
284
+ "work_df[\"vader_sentiment\"] = work_df[\"vader_score\"].apply(vader_label)\n",
285
+ "\n",
286
+ "display(work_df[[\"headline\", \"vader_score\", \"vader_sentiment\"]].head())\n",
287
+ "display(work_df[\"vader_sentiment\"].value_counts(normalize=True).rename(\"share\"))"
288
+ ],
289
+ "id": "6sYDy5UEiQOd"
290
+ },
291
+ {
292
+ "cell_type": "code",
293
+ "execution_count": null,
294
+ "metadata": {
295
+ "id": "0JzpbFrAiQOe"
296
+ },
297
+ "outputs": [],
298
+ "source": [
299
+ "# Cell 9: inspect LM dictionary fields\n",
300
+ "sentiment_cols = [\n",
301
+ " \"Negative\",\n",
302
+ " \"Positive\",\n",
303
+ " \"Uncertainty\",\n",
304
+ " \"Litigious\",\n",
305
+ " \"Strong_Modal\",\n",
306
+ " \"Weak_Modal\",\n",
307
+ " \"Constraining\",\n",
308
+ " \"Complexity\",\n",
309
+ "]\n",
310
+ "\n",
311
+ "print(\"LM columns:\")\n",
312
+ "print(lm.columns.tolist())\n",
313
+ "\n",
314
+ "lm_summary = []\n",
315
+ "for col in sentiment_cols:\n",
316
+ " lm_summary.append({\n",
317
+ " \"field\": col,\n",
318
+ " \"nonzero_word_count\": int((lm[col] != 0).sum()),\n",
319
+ " \"examples\": \", \".join(lm.loc[lm[col] != 0, \"Word\"].dropna().astype(str).head(10)),\n",
320
+ " })\n",
321
+ "\n",
322
+ "display(pd.DataFrame(lm_summary))"
323
+ ],
324
+ "id": "0JzpbFrAiQOe"
325
+ },
326
+ {
327
+ "cell_type": "code",
328
+ "execution_count": null,
329
+ "metadata": {
330
+ "id": "evPOQo0wiQOe"
331
+ },
332
+ "outputs": [],
333
+ "source": [
334
+ "# Cell 10: Loughran-McDonald scoring\n",
335
+ "lm_clean = lm.dropna(subset=[\"Word\"]).copy()\n",
336
+ "lm_clean[\"Word\"] = lm_clean[\"Word\"].astype(str).str.upper()\n",
337
+ "\n",
338
+ "lm_positive = set(lm_clean.loc[lm_clean[\"Positive\"] != 0, \"Word\"])\n",
339
+ "lm_negative = set(lm_clean.loc[lm_clean[\"Negative\"] != 0, \"Word\"])\n",
340
+ "lm_uncertainty = set(lm_clean.loc[lm_clean[\"Uncertainty\"] != 0, \"Word\"])\n",
341
+ "lm_litigious = set(lm_clean.loc[lm_clean[\"Litigious\"] != 0, \"Word\"])\n",
342
+ "\n",
343
+ "def tokenize_upper(text):\n",
344
+ " return re.findall(r\"[A-Za-z]+\", str(text).upper())\n",
345
+ "\n",
346
+ "def lm_score_tuple(text):\n",
347
+ " tokens = tokenize_upper(text)\n",
348
+ " total = len(tokens)\n",
349
+ " if total == 0:\n",
350
+ " return (0.0, 0, 0, 0, 0, 0)\n",
351
+ "\n",
352
+ " pos_count = sum(t in lm_positive for t in tokens)\n",
353
+ " neg_count = sum(t in lm_negative for t in tokens)\n",
354
+ " uncertainty_count = sum(t in lm_uncertainty for t in tokens)\n",
355
+ " litigious_count = sum(t in lm_litigious for t in tokens)\n",
356
+ " score = (pos_count / total) - (neg_count / total)\n",
357
+ "\n",
358
+ " return (score, pos_count, neg_count, uncertainty_count, litigious_count, total)\n",
359
+ "\n",
360
+ "lm_values = work_df[\"clean_text\"].progress_apply(lm_score_tuple)\n",
361
+ "lm_values = pd.DataFrame(\n",
362
+ " lm_values.tolist(),\n",
363
+ " columns=[\n",
364
+ " \"lm_score\",\n",
365
+ " \"lm_pos_count\",\n",
366
+ " \"lm_neg_count\",\n",
367
+ " \"lm_uncertainty_count\",\n",
368
+ " \"lm_litigious_count\",\n",
369
+ " \"lm_token_count\",\n",
370
+ " ],\n",
371
+ " index=work_df.index,\n",
372
+ ")\n",
373
+ "\n",
374
+ "work_df = pd.concat([work_df, lm_values], axis=1)\n",
375
+ "\n",
376
+ "def lm_label(score):\n",
377
+ " if score > 0:\n",
378
+ " return \"Positive\"\n",
379
+ " if score < 0:\n",
380
+ " return \"Negative\"\n",
381
+ " return \"Neutral\"\n",
382
+ "\n",
383
+ "work_df[\"lm_sentiment\"] = work_df[\"lm_score\"].apply(lm_label)\n",
384
+ "\n",
385
+ "display(work_df[[\n",
386
+ " \"headline\",\n",
387
+ " \"lm_score\",\n",
388
+ " \"lm_pos_count\",\n",
389
+ " \"lm_neg_count\",\n",
390
+ " \"lm_uncertainty_count\",\n",
391
+ " \"lm_litigious_count\",\n",
392
+ " \"lm_sentiment\",\n",
393
+ "]].head())\n",
394
+ "\n",
395
+ "display(work_df[\"lm_sentiment\"].value_counts(normalize=True).rename(\"share\"))"
396
+ ],
397
+ "id": "evPOQo0wiQOe"
398
+ },
399
+ {
400
+ "cell_type": "code",
401
+ "execution_count": null,
402
+ "metadata": {
403
+ "id": "OB8MirpTiQOe"
404
+ },
405
+ "outputs": [],
406
+ "source": [
407
+ "# Cell 11: custom unigram/bigram lexicon\n",
408
+ "custom_unigram_weights = {\n",
409
+ " # positive / bullish terms\n",
410
+ " \"gain\": 1.2,\n",
411
+ " \"gains\": 1.2,\n",
412
+ " \"gained\": 1.1,\n",
413
+ " \"rise\": 1.2,\n",
414
+ " \"rises\": 1.2,\n",
415
+ " \"rose\": 1.2,\n",
416
+ " \"rising\": 1.1,\n",
417
+ " \"jump\": 1.5,\n",
418
+ " \"jumps\": 1.5,\n",
419
+ " \"jumped\": 1.5,\n",
420
+ " \"surge\": 1.8,\n",
421
+ " \"surges\": 1.8,\n",
422
+ " \"surged\": 1.8,\n",
423
+ " \"rally\": 1.6,\n",
424
+ " \"rallies\": 1.6,\n",
425
+ " \"rallied\": 1.6,\n",
426
+ " \"beat\": 1.5,\n",
427
+ " \"beats\": 1.5,\n",
428
+ " \"beating\": 1.4,\n",
429
+ " \"upgrade\": 1.6,\n",
430
+ " \"upgrades\": 1.6,\n",
431
+ " \"upgraded\": 1.6,\n",
432
+ " \"outperform\": 1.5,\n",
433
+ " \"buy\": 1.2,\n",
434
+ " \"bullish\": 1.8,\n",
435
+ " \"record\": 1.0,\n",
436
+ " \"strong\": 1.2,\n",
437
+ " \"growth\": 1.1,\n",
438
+ " \"profit\": 1.2,\n",
439
+ " \"profits\": 1.2,\n",
440
+ " \"approval\": 1.0,\n",
441
+ " \"approved\": 1.0,\n",
442
+ " \"accretive\": 1.3,\n",
443
+ " \"expands\": 1.0,\n",
444
+ " \"expand\": 1.0,\n",
445
+ " \"wins\": 1.1,\n",
446
+ " \"raises\": 1.5,\n",
447
+ " \"raised\": 1.5,\n",
448
+ "\n",
449
+ " # negative / bearish terms\n",
450
+ " \"loss\": -1.4,\n",
451
+ " \"losses\": -1.4,\n",
452
+ " \"decline\": -1.3,\n",
453
+ " \"declines\": -1.3,\n",
454
+ " \"declined\": -1.3,\n",
455
+ " \"drop\": -1.3,\n",
456
+ " \"drops\": -1.3,\n",
457
+ " \"dropped\": -1.3,\n",
458
+ " \"fall\": -1.2,\n",
459
+ " \"falls\": -1.2,\n",
460
+ " \"fell\": -1.2,\n",
461
+ " \"plunge\": -1.9,\n",
462
+ " \"plunges\": -1.9,\n",
463
+ " \"plunged\": -1.9,\n",
464
+ " \"slump\": -1.7,\n",
465
+ " \"slumps\": -1.7,\n",
466
+ " \"slumped\": -1.7,\n",
467
+ " \"miss\": -1.5,\n",
468
+ " \"misses\": -1.5,\n",
469
+ " \"missed\": -1.5,\n",
470
+ " \"downgrade\": -1.7,\n",
471
+ " \"downgrades\": -1.7,\n",
472
+ " \"downgraded\": -1.7,\n",
473
+ " \"underperform\": -1.5,\n",
474
+ " \"sell\": -1.2,\n",
475
+ " \"bearish\": -1.8,\n",
476
+ " \"lawsuit\": -1.4,\n",
477
+ " \"probe\": -1.2,\n",
478
+ " \"investigation\": -1.2,\n",
479
+ " \"bankruptcy\": -2.2,\n",
480
+ " \"default\": -2.0,\n",
481
+ " \"warning\": -1.4,\n",
482
+ " \"recall\": -1.3,\n",
483
+ " \"recession\": -1.9,\n",
484
+ " \"weak\": -1.2,\n",
485
+ " \"cuts\": -1.2,\n",
486
+ " \"cut\": -1.0,\n",
487
+ " \"lower\": -0.9,\n",
488
+ " \"lowers\": -1.2,\n",
489
+ "}\n",
490
+ "\n",
491
+ "custom_bigram_weights = {\n",
492
+ " # positive / bullish phrases\n",
493
+ " \"raises target\": 2.0,\n",
494
+ " \"raised target\": 2.0,\n",
495
+ " \"price target\": 0.0,\n",
496
+ " \"beats estimates\": 2.0,\n",
497
+ " \"beats expectations\": 2.0,\n",
498
+ " \"beat estimates\": 2.0,\n",
499
+ " \"strong earnings\": 1.8,\n",
500
+ " \"record high\": 1.7,\n",
501
+ " \"new high\": 1.3,\n",
502
+ " \"fda approval\": 1.4,\n",
503
+ " \"wins contract\": 1.4,\n",
504
+ " \"stock rises\": 1.4,\n",
505
+ " \"shares rise\": 1.4,\n",
506
+ " \"shares jump\": 1.7,\n",
507
+ " \"shares surge\": 1.9,\n",
508
+ " \"buy rating\": 1.3,\n",
509
+ " \"upgraded to\": 1.4,\n",
510
+ "\n",
511
+ " # negative / bearish phrases\n",
512
+ " \"cuts target\": -2.0,\n",
513
+ " \"cut target\": -2.0,\n",
514
+ " \"lowers target\": -2.0,\n",
515
+ " \"lowered target\": -2.0,\n",
516
+ " \"misses estimates\": -2.0,\n",
517
+ " \"misses expectations\": -2.0,\n",
518
+ " \"weak earnings\": -1.8,\n",
519
+ " \"profit warning\": -1.8,\n",
520
+ " \"stock falls\": -1.4,\n",
521
+ " \"shares fall\": -1.4,\n",
522
+ " \"shares drop\": -1.5,\n",
523
+ " \"shares plunge\": -2.0,\n",
524
+ " \"sell rating\": -1.3,\n",
525
+ " \"downgraded to\": -1.4,\n",
526
+ " \"files bankruptcy\": -2.2,\n",
527
+ " \"sec probe\": -1.6,\n",
528
+ "}\n",
529
+ "\n",
530
+ "neutral_unigrams = {\n",
531
+ " \"dow\",\n",
532
+ " \"jones\",\n",
533
+ " \"selected\",\n",
534
+ " \"stock\",\n",
535
+ " \"stocks\",\n",
536
+ " \"nyse\",\n",
537
+ " \"nasdaq\",\n",
538
+ " \"reg\",\n",
539
+ " \"plc\",\n",
540
+ " \"inc\",\n",
541
+ " \"corp\",\n",
542
+ " \"company\",\n",
543
+ " \"companies\",\n",
544
+ " \"net\",\n",
545
+ " \"asset\",\n",
546
+ " \"value\",\n",
547
+ " \"shares\",\n",
548
+ " \"share\",\n",
549
+ " \"market\",\n",
550
+ " \"markets\",\n",
551
+ " \"update\",\n",
552
+ " \"brief\",\n",
553
+ " \"rpt\",\n",
554
+ "}\n",
555
+ "\n",
556
+ "def tokenize_lower(text):\n",
557
+ " return re.findall(r\"[a-z]+\", str(text).lower())\n",
558
+ "\n",
559
+ "def custom_score_tuple(text):\n",
560
+ " tokens = [t for t in tokenize_lower(text) if t not in neutral_unigrams]\n",
561
+ " if not tokens:\n",
562
+ " return (0.0, 0, 0, 0)\n",
563
+ "\n",
564
+ " bigrams = [f\"{tokens[i]} {tokens[i + 1]}\" for i in range(len(tokens) - 1)]\n",
565
+ "\n",
566
+ " raw_score = 0.0\n",
567
+ " unigram_hits = 0\n",
568
+ " bigram_hits = 0\n",
569
+ "\n",
570
+ " for token in tokens:\n",
571
+ " weight = custom_unigram_weights.get(token, 0.0)\n",
572
+ " if weight != 0:\n",
573
+ " raw_score += weight\n",
574
+ " unigram_hits += 1\n",
575
+ "\n",
576
+ " for bigram in bigrams:\n",
577
+ " weight = custom_bigram_weights.get(bigram, 0.0)\n",
578
+ " if weight != 0:\n",
579
+ " raw_score += weight\n",
580
+ " bigram_hits += 1\n",
581
+ "\n",
582
+ " normalized_score = raw_score / np.sqrt(len(tokens))\n",
583
+ " return (normalized_score, raw_score, unigram_hits, bigram_hits)\n",
584
+ "\n",
585
+ "custom_values = work_df[\"clean_text\"].progress_apply(custom_score_tuple)\n",
586
+ "custom_values = pd.DataFrame(\n",
587
+ " custom_values.tolist(),\n",
588
+ " columns=[\"custom_score\", \"custom_raw_score\", \"custom_unigram_hits\", \"custom_bigram_hits\"],\n",
589
+ " index=work_df.index,\n",
590
+ ")\n",
591
+ "\n",
592
+ "work_df = pd.concat([work_df, custom_values], axis=1)\n",
593
+ "\n",
594
+ "def custom_label(score):\n",
595
+ " if score >= 0.05:\n",
596
+ " return \"Positive\"\n",
597
+ " if score <= -0.05:\n",
598
+ " return \"Negative\"\n",
599
+ " return \"Neutral\"\n",
600
+ "\n",
601
+ "work_df[\"custom_sentiment\"] = work_df[\"custom_score\"].apply(custom_label)\n",
602
+ "\n",
603
+ "display(work_df[[\n",
604
+ " \"headline\",\n",
605
+ " \"custom_score\",\n",
606
+ " \"custom_raw_score\",\n",
607
+ " \"custom_unigram_hits\",\n",
608
+ " \"custom_bigram_hits\",\n",
609
+ " \"custom_sentiment\",\n",
610
+ "]].head())\n",
611
+ "\n",
612
+ "display(work_df[\"custom_sentiment\"].value_counts(normalize=True).rename(\"share\"))"
613
+ ],
614
+ "id": "OB8MirpTiQOe"
615
+ },
616
+ {
617
+ "cell_type": "code",
618
+ "execution_count": null,
619
+ "metadata": {
620
+ "id": "hPq4-qZHiQOf"
621
+ },
622
+ "outputs": [],
623
+ "source": [
624
+ "# Cell 12: compare sentiment distributions\n",
625
+ "sentiment_columns = [\"vader_sentiment\", \"lm_sentiment\", \"custom_sentiment\"]\n",
626
+ "\n",
627
+ "distribution_tables = []\n",
628
+ "for col in sentiment_columns:\n",
629
+ " temp = work_df[col].value_counts(normalize=True).rename(\"share\").reset_index()\n",
630
+ " temp.columns = [\"sentiment\", \"share\"]\n",
631
+ " temp[\"model\"] = col.replace(\"_sentiment\", \"\")\n",
632
+ " distribution_tables.append(temp)\n",
633
+ "\n",
634
+ "sentiment_distribution = pd.concat(distribution_tables, ignore_index=True)\n",
635
+ "display(sentiment_distribution)\n",
636
+ "\n",
637
+ "plt.figure(figsize=(10, 5))\n",
638
+ "ax = sns.barplot(data=sentiment_distribution, x=\"model\", y=\"share\", hue=\"sentiment\")\n",
639
+ "ax.set_title(\"Sentiment Distribution by Lexicon Model\")\n",
640
+ "ax.set_xlabel(\"Model\")\n",
641
+ "ax.set_ylabel(\"Share of Headlines\")\n",
642
+ "ax.set_ylim(0, 1)\n",
643
+ "plt.show()"
644
+ ],
645
+ "id": "hPq4-qZHiQOf"
646
+ },
647
+ {
648
+ "cell_type": "code",
649
+ "execution_count": null,
650
+ "metadata": {
651
+ "id": "sE1s_vLTiQOf"
652
+ },
653
+ "outputs": [],
654
+ "source": [
655
+ "# Cell 13: compare average sentiment by ticker\n",
656
+ "ticker_summary = (\n",
657
+ " work_df.groupby(\"ticker\")\n",
658
+ " .agg(\n",
659
+ " headline_count=(\"headline\", \"size\"),\n",
660
+ " vader_mean=(\"vader_score\", \"mean\"),\n",
661
+ " lm_mean=(\"lm_score\", \"mean\"),\n",
662
+ " custom_mean=(\"custom_score\", \"mean\"),\n",
663
+ " )\n",
664
+ " .sort_values(\"headline_count\", ascending=False)\n",
665
+ ")\n",
666
+ "\n",
667
+ "print(\"Most covered tickers:\")\n",
668
+ "display(ticker_summary.head(20))\n",
669
+ "\n",
670
+ "print(\"Most positive tickers by custom score, minimum 100 headlines:\")\n",
671
+ "display(ticker_summary[ticker_summary[\"headline_count\"] >= 100].sort_values(\"custom_mean\", ascending=False).head(20))\n",
672
+ "\n",
673
+ "print(\"Most negative tickers by custom score, minimum 100 headlines:\")\n",
674
+ "display(ticker_summary[ticker_summary[\"headline_count\"] >= 100].sort_values(\"custom_mean\", ascending=True).head(20))"
675
+ ],
676
+ "id": "sE1s_vLTiQOf"
677
+ },
678
+ {
679
+ "cell_type": "code",
680
+ "execution_count": null,
681
+ "metadata": {
682
+ "id": "zAkNKh0yiQOf"
683
+ },
684
+ "outputs": [],
685
+ "source": [
686
+ "# Cell 14: compare average sentiment over time\n",
687
+ "daily_summary = (\n",
688
+ " work_df.groupby(\"date\")\n",
689
+ " .agg(\n",
690
+ " headline_count=(\"headline\", \"size\"),\n",
691
+ " vader_mean=(\"vader_score\", \"mean\"),\n",
692
+ " lm_mean=(\"lm_score\", \"mean\"),\n",
693
+ " custom_mean=(\"custom_score\", \"mean\"),\n",
694
+ " )\n",
695
+ " .reset_index()\n",
696
+ ")\n",
697
+ "\n",
698
+ "daily_summary[\"date\"] = pd.to_datetime(daily_summary[\"date\"])\n",
699
+ "\n",
700
+ "plt.figure(figsize=(12, 5))\n",
701
+ "plt.plot(daily_summary[\"date\"], daily_summary[\"vader_mean\"], label=\"VADER\")\n",
702
+ "plt.plot(daily_summary[\"date\"], daily_summary[\"lm_mean\"], label=\"Loughran-McDonald\")\n",
703
+ "plt.plot(daily_summary[\"date\"], daily_summary[\"custom_mean\"], label=\"Custom\")\n",
704
+ "plt.axhline(0, color=\"black\", linewidth=1)\n",
705
+ "plt.title(\"Average Daily Sentiment\")\n",
706
+ "plt.xlabel(\"Date\")\n",
707
+ "plt.ylabel(\"Average Sentiment Score\")\n",
708
+ "plt.legend()\n",
709
+ "plt.show()"
710
+ ],
711
+ "id": "zAkNKh0yiQOf"
712
+ },
713
+ {
714
+ "cell_type": "code",
715
+ "execution_count": null,
716
+ "metadata": {
717
+ "id": "lQ4wrZhLiQOf"
718
+ },
719
+ "outputs": [],
720
+ "source": [
721
+ "# Cell 15: review strongest positive/negative examples\n",
722
+ "print(\"Most positive by custom lexicon:\")\n",
723
+ "display(work_df.sort_values(\"custom_score\", ascending=False)[[\n",
724
+ " \"time\", \"ticker\", \"headline\", \"vader_score\", \"lm_score\", \"custom_score\",\n",
725
+ " \"vader_sentiment\", \"lm_sentiment\", \"custom_sentiment\"\n",
726
+ "]].head(20))\n",
727
+ "\n",
728
+ "print(\"Most negative by custom lexicon:\")\n",
729
+ "display(work_df.sort_values(\"custom_score\", ascending=True)[[\n",
730
+ " \"time\", \"ticker\", \"headline\", \"vader_score\", \"lm_score\", \"custom_score\",\n",
731
+ " \"vader_sentiment\", \"lm_sentiment\", \"custom_sentiment\"\n",
732
+ "]].head(20))"
733
+ ],
734
+ "id": "lQ4wrZhLiQOf"
735
+ },
736
+ {
737
+ "cell_type": "code",
738
+ "execution_count": null,
739
+ "metadata": {
740
+ "id": "AILWhbsBiQOg"
741
+ },
742
+ "outputs": [],
743
+ "source": [
744
+ "# Cell 16: review model disagreement examples\n",
745
+ "disagreement = work_df[\n",
746
+ " (work_df[\"vader_sentiment\"] != work_df[\"lm_sentiment\"])\n",
747
+ " | (work_df[\"vader_sentiment\"] != work_df[\"custom_sentiment\"])\n",
748
+ " | (work_df[\"lm_sentiment\"] != work_df[\"custom_sentiment\"])\n",
749
+ "].copy()\n",
750
+ "\n",
751
+ "disagreement[\"score_spread\"] = disagreement[[\"vader_score\", \"lm_score\", \"custom_score\"]].max(axis=1) - disagreement[[\n",
752
+ " \"vader_score\", \"lm_score\", \"custom_score\"\n",
753
+ "]].min(axis=1)\n",
754
+ "\n",
755
+ "print(\"Number of disagreement rows:\", len(disagreement))\n",
756
+ "display(disagreement.sort_values(\"score_spread\", ascending=False)[[\n",
757
+ " \"time\", \"ticker\", \"headline\",\n",
758
+ " \"vader_score\", \"lm_score\", \"custom_score\",\n",
759
+ " \"vader_sentiment\", \"lm_sentiment\", \"custom_sentiment\",\n",
760
+ "]].head(30))"
761
+ ],
762
+ "id": "AILWhbsBiQOg"
763
+ },
764
+ {
765
+ "cell_type": "code",
766
+ "execution_count": null,
767
+ "metadata": {
768
+ "id": "yNuexF8giQOg"
769
+ },
770
+ "outputs": [],
771
+ "source": [
772
+ "# Cell 17: explain custom lexicon score for one headline\n",
773
+ "def explain_custom_prediction(text):\n",
774
+ " tokens = [t for t in tokenize_lower(text) if t not in neutral_unigrams]\n",
775
+ " bigrams = [f\"{tokens[i]} {tokens[i + 1]}\" for i in range(len(tokens) - 1)]\n",
776
+ "\n",
777
+ " rows = []\n",
778
+ " for token in tokens:\n",
779
+ " weight = custom_unigram_weights.get(token, 0.0)\n",
780
+ " if weight != 0:\n",
781
+ " rows.append({\"term\": token, \"type\": \"unigram\", \"weight\": weight})\n",
782
+ "\n",
783
+ " for bigram in bigrams:\n",
784
+ " weight = custom_bigram_weights.get(bigram, 0.0)\n",
785
+ " if weight != 0:\n",
786
+ " rows.append({\"term\": bigram, \"type\": \"bigram\", \"weight\": weight})\n",
787
+ "\n",
788
+ " return pd.DataFrame(rows).sort_values(\"weight\", ascending=False)\n",
789
+ "\n",
790
+ "example_row = work_df.sort_values(\"custom_score\", ascending=False).iloc[0]\n",
791
+ "print(\"Example headline:\")\n",
792
+ "print(example_row[\"headline\"])\n",
793
+ "display(explain_custom_prediction(example_row[\"headline\"]))"
794
+ ],
795
+ "id": "yNuexF8giQOg"
796
+ },
797
+ {
798
+ "cell_type": "code",
799
+ "execution_count": null,
800
+ "metadata": {
801
+ "id": "kRt--hVQiQOg"
802
+ },
803
+ "outputs": [],
804
+ "source": [
805
+ "# Cell 18: optional merge with labeled_data.csv for accuracy evaluation\n",
806
+ "if labeled_path is None:\n",
807
+ " print(\"labeled_data.csv not found. Skipping accuracy evaluation.\")\n",
808
+ " eval_df = None\n",
809
+ "else:\n",
810
+ " labeled = pd.read_csv(labeled_path, low_memory=False)\n",
811
+ " labeled[\"date\"] = pd.to_datetime(labeled[\"time\"], errors=\"coerce\").dt.date.astype(str)\n",
812
+ " labeled[\"label_int\"] = labeled[\"label\"].astype(int)\n",
813
+ "\n",
814
+ " daily_by_ticker = (\n",
815
+ " work_df.groupby([\"ticker\", \"date\"])\n",
816
+ " .agg(\n",
817
+ " headline_count=(\"headline\", \"size\"),\n",
818
+ " vader_score=(\"vader_score\", \"mean\"),\n",
819
+ " lm_score=(\"lm_score\", \"mean\"),\n",
820
+ " custom_score=(\"custom_score\", \"mean\"),\n",
821
+ " combined_headlines=(\"headline\", lambda x: \" | \".join(x.astype(str).head(5))),\n",
822
+ " )\n",
823
+ " .reset_index()\n",
824
+ " )\n",
825
+ "\n",
826
+ " eval_df = labeled.merge(\n",
827
+ " daily_by_ticker,\n",
828
+ " on=[\"ticker\", \"date\"],\n",
829
+ " how=\"inner\",\n",
830
+ " suffixes=(\"_labeled\", \"_news\"),\n",
831
+ " )\n",
832
+ "\n",
833
+ " print(\"Merged evaluation shape:\", eval_df.shape)\n",
834
+ " display(eval_df.head())"
835
+ ],
836
+ "id": "kRt--hVQiQOg"
837
+ },
838
+ {
839
+ "cell_type": "code",
840
+ "execution_count": null,
841
+ "metadata": {
842
+ "id": "R_5cto-iiQOg"
843
+ },
844
+ "outputs": [],
845
+ "source": [
846
+ "# Cell 19: optional accuracy metrics\n",
847
+ "if eval_df is None or len(eval_df) == 0:\n",
848
+ " print(\"No evaluation data available.\")\n",
849
+ " evaluation_results = None\n",
850
+ "else:\n",
851
+ " def score_to_binary_label(score):\n",
852
+ " return np.where(score >= 0, 1, -1)\n",
853
+ "\n",
854
+ " eval_df[\"vader_pred\"] = score_to_binary_label(eval_df[\"vader_score\"])\n",
855
+ " eval_df[\"lm_pred\"] = score_to_binary_label(eval_df[\"lm_score\"])\n",
856
+ " eval_df[\"custom_pred\"] = score_to_binary_label(eval_df[\"custom_score\"])\n",
857
+ "\n",
858
+ " evaluation_results = []\n",
859
+ "\n",
860
+ " def evaluate_binary_model(name, pred_col):\n",
861
+ " y_true = eval_df[\"label_int\"]\n",
862
+ " y_pred = eval_df[pred_col]\n",
863
+ " acc = accuracy_score(y_true, y_pred)\n",
864
+ " evaluation_results.append({\"model\": name, \"accuracy\": acc})\n",
865
+ "\n",
866
+ " print(\"=\" * 70)\n",
867
+ " print(name)\n",
868
+ " print(f\"Accuracy: {acc:.4f}\")\n",
869
+ " print(\"Confusion matrix, rows=true labels, columns=predicted labels:\")\n",
870
+ " print(confusion_matrix(y_true, y_pred, labels=[-1, 1]))\n",
871
+ " print(classification_report(y_true, y_pred, labels=[-1, 1], target_names=[\"SELL/-1\", \"BUY/1\"]))\n",
872
+ "\n",
873
+ " evaluate_binary_model(\"VADER daily average\", \"vader_pred\")\n",
874
+ " evaluate_binary_model(\"Loughran-McDonald daily average\", \"lm_pred\")\n",
875
+ " evaluate_binary_model(\"Custom daily average\", \"custom_pred\")\n",
876
+ "\n",
877
+ " evaluation_results = pd.DataFrame(evaluation_results).sort_values(\"accuracy\", ascending=False)\n",
878
+ " display(evaluation_results)"
879
+ ],
880
+ "id": "R_5cto-iiQOg"
881
+ },
882
+ {
883
+ "cell_type": "code",
884
+ "execution_count": null,
885
+ "metadata": {
886
+ "id": "fhRmDyCXiQOg"
887
+ },
888
+ "outputs": [],
889
+ "source": [
890
+ "# Cell 20: optional misclassification analysis\n",
891
+ "if eval_df is None or len(eval_df) == 0 or evaluation_results is None:\n",
892
+ " print(\"No misclassification analysis available without labeled_data.csv.\")\n",
893
+ "else:\n",
894
+ " best_eval_model = evaluation_results.iloc[0][\"model\"]\n",
895
+ " pred_col_map = {\n",
896
+ " \"VADER daily average\": \"vader_pred\",\n",
897
+ " \"Loughran-McDonald daily average\": \"lm_pred\",\n",
898
+ " \"Custom daily average\": \"custom_pred\",\n",
899
+ " }\n",
900
+ " best_pred_col = pred_col_map[best_eval_model]\n",
901
+ "\n",
902
+ " eval_df[\"best_pred\"] = eval_df[best_pred_col]\n",
903
+ " eval_df[\"is_misclassified\"] = eval_df[\"label_int\"] != eval_df[\"best_pred\"]\n",
904
+ "\n",
905
+ " misclassified = eval_df[eval_df[\"is_misclassified\"]].copy()\n",
906
+ "\n",
907
+ " print(\"Best evaluation model:\", best_eval_model)\n",
908
+ " print(\"Misclassified rows:\", len(misclassified))\n",
909
+ " print(\"Misclassification rate:\", len(misclassified) / len(eval_df))\n",
910
+ "\n",
911
+ " display(misclassified[[\n",
912
+ " \"ticker\", \"date\", \"combined_headlines\", \"returns\", \"label_int\",\n",
913
+ " \"best_pred\", \"vader_score\", \"lm_score\", \"custom_score\", \"headline_count\"\n",
914
+ " ]].head(30))"
915
+ ],
916
+ "id": "fhRmDyCXiQOg"
917
+ },
918
+ {
919
+ "cell_type": "code",
920
+ "execution_count": null,
921
+ "metadata": {
922
+ "id": "-ljc7GJciQOh"
923
+ },
924
+ "outputs": [],
925
+ "source": [
926
+ "# Cell 21: save output files\n",
927
+ "work_df.to_csv(\"/content/news_data_scored_sentiment.csv\", index=False)\n",
928
+ "sentiment_distribution.to_csv(\"/content/sentiment_distribution.csv\", index=False)\n",
929
+ "ticker_summary.to_csv(\"/content/ticker_sentiment_summary.csv\")\n",
930
+ "daily_summary.to_csv(\"/content/daily_sentiment_summary.csv\", index=False)\n",
931
+ "\n",
932
+ "print(\"Saved:\")\n",
933
+ "print(\"/content/news_data_scored_sentiment.csv\")\n",
934
+ "print(\"/content/sentiment_distribution.csv\")\n",
935
+ "print(\"/content/ticker_sentiment_summary.csv\")\n",
936
+ "print(\"/content/daily_sentiment_summary.csv\")\n",
937
+ "\n",
938
+ "if labeled_path is not None and eval_df is not None and len(eval_df) > 0:\n",
939
+ " eval_df.to_csv(\"/content/news_data_daily_evaluation.csv\", index=False)\n",
940
+ " print(\"/content/news_data_daily_evaluation.csv\")\n",
941
+ "\n",
942
+ " if evaluation_results is not None:\n",
943
+ " evaluation_results.to_csv(\"/content/evaluation_results.csv\", index=False)\n",
944
+ " print(\"/content/evaluation_results.csv\")\n",
945
+ "\n",
946
+ " if \"misclassified\" in globals():\n",
947
+ " misclassified.to_csv(\"/content/misclassified_daily_examples.csv\", index=False)\n",
948
+ " print(\"/content/misclassified_daily_examples.csv\")"
949
+ ],
950
+ "id": "-ljc7GJciQOh"
951
+ }
952
+ ],
953
+ "metadata": {
954
+ "colab": {
955
+ "provenance": []
956
+ },
957
+ "kernelspec": {
958
+ "display_name": "Python 3",
959
+ "name": "python3"
960
+ },
961
+ "language_info": {
962
+ "name": "python"
963
+ }
964
+ },
965
+ "nbformat": 4,
966
+ "nbformat_minor": 5
967
+ }