{ "cells": [ { "cell_type": "markdown", "metadata": {}, "source": [ "# Cybersecurity news\n", "Interactive exploratory notebook for trend analysis and marketing-ready visuals.\n" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "import os\n", "import pandas as pd\n", "import numpy as np\n", "import plotly.express as px\n", "import plotly.graph_objects as go\n", "articles = pd.read_csv('cybersecurity-news-en-title-3000.csv')\n", "weekly_path = 'weekly_counts.csv'\n", "peaks_path = 'weekly_peak_headlines.csv'\n", "weekly = pd.read_csv(weekly_path) if os.path.exists(weekly_path) else pd.DataFrame()\n", "peaks = pd.read_csv(peaks_path) if os.path.exists(peaks_path) else pd.DataFrame()\n", "articles.head()\n" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "articles['pub_date'] = pd.to_datetime(articles['pub_date'], errors='coerce', utc=True)\n", "articles = articles.dropna(subset=['pub_date']).copy()\n", "articles['week'] = articles['pub_date'].dt.to_period('W').dt.start_time\n", "articles.shape\n" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "keyword_columns = [\"mentions_ransomware\", \"mentions_ddos\", \"mentions_data_breach\", \"mentions_vulnerability\", \"mentions_hacking\", \"mentions_cyber_attack\"]\n", "if not weekly.empty and keyword_columns:\n", " weekly['week'] = pd.to_datetime(weekly['week'])\n", " long_df = weekly.melt(\n", " id_vars=['week'],\n", " value_vars=keyword_columns,\n", " var_name='mention_flag',\n", " value_name='count'\n", " )\n", " long_df['count'] = pd.to_numeric(long_df['count'], errors='coerce').fillna(0).astype(int)\n", "\n", " long_df['week_total'] = long_df.groupby('week')['count'].transform('sum')\n", " long_df['share_pct'] = np.where(long_df['week_total'] > 0, (long_df['count'] / long_df['week_total']) * 100, 0.0)\n", " long_df = long_df.sort_values(['mention_flag', 'week']).reset_index(drop=True)\n", " long_df['wow_pct'] = (\n", " long_df.groupby('mention_flag')['count']\n", " .pct_change()\n", " .replace([np.inf, -np.inf], np.nan)\n", " .fillna(0.0) * 100\n", " )\n", "\n", " weekly_rep_parts = []\n", " for flag in keyword_columns:\n", " if flag not in articles.columns:\n", " continue\n", " rep = (\n", " articles[articles[flag].astype(str).str.lower().isin(['true', '1'])]\n", " .sort_values('pub_date')\n", " .groupby('week', as_index=False)\n", " .first()[['week', 'title', 'source_title']]\n", " )\n", " rep['mention_flag'] = flag\n", " weekly_rep_parts.append(rep)\n", "\n", " if weekly_rep_parts:\n", " weekly_rep = pd.concat(weekly_rep_parts, ignore_index=True)\n", " long_df = long_df.merge(weekly_rep, on=['week', 'mention_flag'], how='left')\n", " else:\n", " long_df['title'] = ''\n", " long_df['source_title'] = ''\n", "\n", " long_df['title'] = long_df['title'].fillna('')\n", " long_df['source_title'] = long_df['source_title'].fillna('')\n", " long_df['headline_short'] = np.where(\n", " long_df['title'].str.len() > 110,\n", " long_df['title'].str.slice(0, 107) + '...',\n", " long_df['title']\n", " )\n", "\n", " fig = px.line(\n", " long_df,\n", " x='week',\n", " y='count',\n", " color='mention_flag',\n", " markers=True,\n", " custom_data=[\n", " 'share_pct',\n", " 'wow_pct',\n", " 'headline_short',\n", " 'source_title',\n", " ],\n", " title='Weekly Mention Counts (Interactive)'\n", " )\n", "\n", " fig.update_traces(\n", " hovertemplate=(\n", " 'Mention: %{fullData.name}
'\n", " 'Week: %{x|%Y-%m-%d}
'\n", " 'Count: %{y:,}
'\n", " 'Share: %{customdata[0]:.1f}%
'\n", " 'Week-over-week change: %{customdata[1]:+.1f}%
'\n", " 'Example headline: %{customdata[2]}
'\n", " 'Source: %{customdata[3]}'\n", " ''\n", " ),\n", " line={'width': 2.6},\n", " marker={'size': 6},\n", " )\n", "\n", " if not peaks.empty:\n", " peaks['peak_week'] = pd.to_datetime(peaks['peak_week'])\n", " peaks['headline_short'] = np.where(\n", " peaks['representative_headline'].fillna('').str.len() > 110,\n", " peaks['representative_headline'].fillna('').str.slice(0, 107) + '...',\n", " peaks['representative_headline'].fillna('')\n", " )\n", " custom = peaks[['headline_short', 'source_title']].fillna('').to_numpy()\n", " fig.add_trace(go.Scatter(\n", " x=peaks['peak_week'],\n", " y=peaks['peak_count'],\n", " mode='markers',\n", " marker=dict(size=10, symbol='diamond', line=dict(width=1)),\n", " name='Peak week',\n", " customdata=custom,\n", " text=peaks['mention_flag'],\n", " hovertemplate=(\n", " 'Mention: %{text}
'\n", " 'Week: %{x|%Y-%m-%d}
'\n", " 'Count: %{y}
'\n", " 'Example headline: %{customdata[0]}
'\n", " 'Source: %{customdata[1]}'\n", " ''\n", " )\n", " ))\n", "\n", " fig.update_layout(\n", " template='plotly_white',\n", " hovermode='closest',\n", " legend_title_text='',\n", " xaxis_title='Week',\n", " yaxis_title='Article count',\n", " font=dict(size=13),\n", " margin=dict(l=30, r=30, t=70, b=30),\n", " hoverlabel=dict(bgcolor='white', font_size=12),\n", " )\n", " fig.update_xaxes(showgrid=True, gridcolor='#EFEFEF')\n", " fig.update_yaxes(showgrid=True, gridcolor='#EFEFEF')\n", " fig.show()\n", "else:\n", " print('No weekly data available for interactive mention chart.')\n" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "top_sources = (\n", " articles['source_title']\n", " .value_counts()\n", " .head(20)\n", " .rename_axis('source_title')\n", " .reset_index(name='articles')\n", ")\n", "fig = px.bar(\n", " top_sources,\n", " x='articles',\n", " y='source_title',\n", " orientation='h',\n", " title='Top 20 Sources by Article Count (Interactive)',\n", " color='articles',\n", " color_continuous_scale='Blues'\n", ")\n", "fig.update_layout(\n", " template='plotly_white',\n", " yaxis={'categoryorder': 'total ascending'},\n", " coloraxis_showscale=False,\n", " margin=dict(l=30, r=20, t=60, b=20),\n", ")\n", "fig.show()\n" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "if not peaks.empty:\n", " peaks[['mention_flag', 'peak_week', 'peak_count', 'representative_headline', 'source_title', 'article_link']]\n", "else:\n", " print('No peak headline rows generated for this dataset.')\n" ] } ], "metadata": { "kernelspec": { "display_name": "Python 3", "language": "python", "name": "python3" }, "language_info": { "name": "python", "version": "3" } }, "nbformat": 4, "nbformat_minor": 5 }