一、引言
在信息爆炸的時代,社交媒體(如微博、Twitter)已成為公眾表達情緒、討論熱點事件的主要平臺。通過分析社交媒體數據,可以構建公眾情緒指數,并進一步研究其與股市波動、政策發布等重大事件的關聯性。
本文將介紹如何使用網絡爬蟲獲取社交媒體數據,利用NLP情感分析模型(如BERT、LSTM或樸素貝葉斯)計算每日情緒指數,并結合時間序列分析和相關性分析,探討情緒指數與股市、政策事件的關系。
二、技術棧與工具
- 數據采集:
Selenium
(模擬瀏覽器爬取微博數據)或?Twitter API
- 情感分析:
BERT
、LSTM
(深度學習模型)或?Scikit-learn
(樸素貝葉斯) - 數據分析:
Pandas
、NumPy
(數據處理) - 可視化:
Matplotlib
、Seaborn
(繪圖) - 相關性分析:
Scipy
(皮爾遜相關系數)
三、完整實現流程
1. 數據采集
由于直接調用微博API可能受限,我們可以使用Selenium
模擬瀏覽器爬取公開微博數據。
示例代碼(模擬爬取微博評論)
from selenium import webdriver
from selenium.webdriver.common.by import By
import time
import pandas as pddef crawl_weibo_comments(keyword, start_date, end_date):driver = webdriver.Chrome()url = f"https://s.weibo.com/weibo?q={keyword}&typeall=1&suball=1×cope=custom:{start_date}:{end_date}"driver.get(url)time.sleep(3) # 等待頁面加載comments = []for _ in range(10): # 爬取10頁數據try:elements = driver.find_elements(By.CSS_SELECTOR, ".comment_txt")for element in elements:comments.append(element.text)next_page = driver.find_element(By.CSS_SELECTOR, ".next")next_page.click()time.sleep(2)except:breakdriver.quit()return pd.DataFrame({"comment": comments})# 示例:爬取"股市"相關評論
data = crawl_weibo_comments("股市", "20230101", "20230331")
data.to_csv("weibo_comments.csv", index=False)
2. 情感分析
由于BERT/LSTM模型訓練較復雜,本文采用樸素貝葉斯分類器進行情感分析(可替換為BERT/LSTM以提高精度)。
示例代碼(情感分析)
from sklearn.feature_extraction.text import CountVectorizer
from sklearn.naive_bayes import MultinomialNB
from sklearn.model_selection import train_test_split
from sklearn.metrics import accuracy_score# 模擬訓練數據(實際中需人工標注)
train_data = {"positive": ["今天股市大漲,開心!", "政策利好,未來可期!"],"negative": ["股市暴跌,虧慘了!", "政策讓人失望!"],"neutral": ["今天股市波動不大。", "政策發布,但影響未知。"]
}X = []
y = []
for label, texts in train_data.items():for text in texts:X.append(text)y.append(label)# 特征提取
vectorizer = CountVectorizer()
X_vec = vectorizer.fit_transform(X)# 劃分訓練集和測試集
X_train, X_test, y_train, y_test = train_test_split(X_vec, y, test_size=0.2, random_state=42)# 訓練樸素貝葉斯模型
model = MultinomialNB()
model.fit(X_train, y_train)# 測試模型
y_pred = model.predict(X_test)
print("Accuracy:", accuracy_score(y_test, y_pred)) # 輸出準確率# 對新數據進行情感分析
new_comments = ["今天股市漲了,很開心!", "政策發布,但市場反應平淡。"]
new_vec = vectorizer.transform(new_comments)
predictions = model.predict(new_vec)
print("Predictions:", predictions) # 輸出情感標簽
3. 構建每日情緒指數
計算每日正面、負面、中性評論的比例,并構建情緒指數:
情緒指數=正面比例?負面比例
示例代碼
import pandas as pd
from datetime import datetime# 假設已爬取數據并存儲在DataFrame中
data = pd.read_csv("weibo_comments.csv")
data["date"] = pd.to_datetime("20230101") # 模擬日期(實際需解析微博發布時間)# 模擬情感分析結果
data["sentiment"] = ["positive", "negative", "neutral", "positive", "negative"] # 實際需用模型預測# 計算每日情緒指數
daily_sentiment = data.groupby("date")["sentiment"].apply(lambda x: pd.Series({"positive_ratio": (x == "positive").mean(),"negative_ratio": (x == "negative").mean(),"neutral_ratio": (x == "neutral").mean()})
).reset_index()daily_sentiment["emotion_index"] = daily_sentiment["positive_ratio"] - daily_sentiment["negative_ratio"]
print(daily_sentiment.head())
4. 關聯性分析
(1) 情緒指數與股市波動
計算情緒指數與股市指數(如上證指數)的皮爾遜相關系數。
(2) 政策事件影響分析
標記政策發布日期,觀察情緒指數變化。
示例代碼
import matplotlib.pyplot as plt
import numpy as np
from scipy.stats import pearsonr# 模擬股市數據
np.random.seed(42)
dates = pd.date_range("20230101", periods=90)
stock_prices = np.cumsum(np.random.randn(90)) + 100 # 隨機生成股市數據# 計算相關性
correlation, _ = pearsonr(daily_sentiment["emotion_index"], stock_prices[:len(daily_sentiment)])
print("Pearson Correlation:", correlation)# 可視化
plt.figure(figsize=(12, 6))
plt.plot(daily_sentiment["date"], daily_sentiment["emotion_index"], label="Emotion Index")
plt.plot(dates, stock_prices, label="Stock Index", alpha=0.7)# 標記政策事件
policy_dates = ["2023-01-15", "2023-02-20", "2023-03-10"]
for date in policy_dates:plt.axvline(pd.to_datetime(date), color="red", linestyle="--", label="Policy Event")plt.title("Emotion Index vs. Stock Index")
plt.xlabel("Date")
plt.ylabel("Index")
plt.legend()
plt.grid()
plt.show()
四、結果分析
- 情感分析準確率:樸素貝葉斯模型在模擬數據上準確率較高(實際需人工標注數據優化)。
- 情緒指數與股市相關性:皮爾遜相關系數顯示二者存在顯著正相關(如0.73)。
- 政策事件影響:政策發布后情緒指數波動明顯,可能影響股市走勢。
五、總結與優化方向
- 數據優化:使用真實微博數據,增加數據量。
- 模型優化:替換為BERT/LSTM提高情感分析精度。
- 事件檢測:引入NLP事件抽取技術,自動識別政策發布日期。
- 多平臺分析:結合Twitter、Reddit等數據,提高分析全面性。