Big Data Projects
300Hours Learn Lab Curriculum Reading | Topic: BIG DATA PROJECTS | Qualification: CFA LEVEL1
# Big Data Projects A financial data science or big data project involves extracting insights and predictive signals from vast, complex datasets containing both **structured data** (e.g., historical price feeds, accounting statements, trade logs) and **unstructured data** (e.g., SEC 10-K filings, earnings call audio transcripts, social media feeds, satellite imagery). Executing a successful big data project requires a disciplined, multi-step pipeline from problem conceptualization through data wrangling, feature engineering, and model evaluation. --- ## The Data Analysis Project Lifecycle Financial data analysis projects follow a structured five-step lifecycle: ```mermaid flowchart TD S1[1. Project Conceptualization Define problem & business objective] --> S2[2. Data Collection APIs, Scraping, DB Feeds] S2 --> S3[3. Data Preparation & Wrangling Cleansing, Preprocessing, Scaling] S3 --> S4[4. Data Exploration Feature Selection & Engineering] S4 --> S5[5. Model Training & Evaluation Hyperparameter Tuning & Metrics] ``` | Project Step | Primary Objectives | Key Tasks & Financial Examples | | :--- | :--- | :--- | | **1. Conceptualization** | Define output target and decision metric | Formulate investment hypothesis (e.g., predict corporate credit rating downgrades from 10-K text). | | **2. Data Collection** | Acquire raw structured & unstructured data | Query SQL databases, connect to exchange feeds via REST APIs, scrape news web pages. | | **3. Preparation & Wrangling** | Convert raw dirty data into clean structured tabular format | Handle missing values, filter outliers, parse HTML tags, tokenize text, scale numerical features. | | **4. Data Exploration** | Discover patterns and construct predictive signals | Compute summary stats, construct TF-IDF keyword matrices, evaluate feature correlations. | | **5. Model Training & Tuning** | Train ML algorithms and evaluate out-of-sample fit | Split data into train/val/test, tune hyperparameters via $K$-fold cross-validation, evaluate F1 score. | --- ## Data Preparation and Wrangling Raw financial data is rarely clean or ready for machine learning algorithms. Structured numerical data and unstructured text data require specialized preprocessing steps. ### Structuring and Normalizing Numerical Data When handling numerical datasets (e.g., financial ratios across thousands of firms), two critical tasks are handling missing values and feature scaling: 1. **Handling Missing Values:** - **Deletion:** Drop records with missing values (only suitable when missingness is small and completely random). - **Imputation:** Replace missing values with statistical measures (mean or median for symmetric/skewed data) or model-based predictions (KNN imputation). 2. **Feature Scaling:** Distance-based algorithms (KNN, SVM, K-Means) and gradient descent optimization require features to be on comparable scales: - **Min-Max Normalization:** Rescales values into a fixed $[0, 1]$ interval: $X_{\text{scaled}} = \frac{X - X_{\min}}{X_{\max} - X_{\min}}$ - **Standardization ($Z$-Score Normalization):** Transforms data to have zero mean ($\mu = 0$) and unit variance ($\sigma = 1$): $Z = \frac{X - \mu}{\sigma}$ Standardization ($Z$-score) is preferred over Min-Max scaling when datasets contain extreme outliers, because Min-Max scaling compresses normal data into a tiny range if $X_{\max}$ or $X_{\min}$ is an extreme outlier! Exam Tip: Outliers and Scaling --- ## Text Data Wrangling and Feature Engineering Unstructured text (e.g., annual reports, news articles) represents over 80\% of new financial data. To use text in machine learning models, it must undergo a multi-stage Natural Language Processing (NLP) pipeline: ```mermaid flowchart LR Raw[Raw Text Filing] --> Clean[1. Cleansing Remove HTML & Punctuation] Clean --> Tok[2. Tokenization Split into Tokens/N-Grams] Tok --> Stop[3. Stop Words Filter Common Filler Words] Stop --> Norm[4. Normalization Stemming vs. Lemmatization] Norm --> Vec[5. Vectorization BoW / TF-IDF Weights] ``` ### Text Preprocessing Steps 1. **Cleansing:** Removes unwanted noise such as HTML/XML markup tags, special symbols, numbers, and converts all characters to lowercase. 2. **Tokenization:** Splits character streams into individual words or multi-word phrases called **tokens**. - *Unigram:* Single word (e.g., "earnings"). - *Bigram:* Two-word sequence (e.g., "net income"). - *Trigram:* Three-word sequence (e.g., "cash flow statement"). 3. **Stop Words Removal:** Filters out high-frequency, non-informative words (e.g., "the", "is", "at", "which", "and") that carry no semantic sentiment. 4. **Normalization (Stemming vs. Lemmatization):** Converts tokens into their base or root forms: - **Stemming:** A fast, rule-based algorithmic approach that chops off word suffixes (e.g., "investing", "investor", "investments" all become "invest"). It can create non-dictionary words (e.g., "company" becomes "compani"). - **Lemmatization:** A dictionary-based morphological approach that uses vocabulary and grammatical analysis to reduce words to their true semantic root or **lemma** (e.g., "better" becomes "good", "saw" becomes "see"). It is computationally slower but preserves exact semantic meaning. Think of stemming as using a blunt hatchet to chop the ends off words, while lemmatization is using a dictionary to find the exact root word. In finance, where subtle word context matters (e.g., "defaulted" vs "defaulting"), lemmatization is far superior. Zee Explains: Stemming vs Lemmatization ### Text Feature Representation: TF-IDF After tokenization and normalization, text documents must be vectorized into numerical feature matrices. - **Bag-of-Words (BoW):** Creates a matrix where rows are documents and columns are unique vocabulary words. Each cell contains the raw word frequency count. *Limitation:* Ignores word importance across the broader collection of documents (corpus). - **Term Frequency-Inverse Document Frequency (TF-IDF):** Weighs a word's relative importance by evaluating how frequently it appears in a specific document relative to its rarity across the entire corpus of documents ($N$): $\text{TF-IDF}_{t,d} = \text{TF}_{t,d} \times \text{IDF}_t$ Where: - **Term Frequency ($\text{TF}_{t,d}$):** Proportion of term $t$ in document $d$: $\text{TF}_{t,d} = \frac{\text{Count of term } t \text{ in doc } d}{\text{Total word count in doc } d}$ - **Inverse Document Frequency ($\text{IDF}_t$):** Measure of term rarity across all $N$ documents in the corpus: $\text{IDF}_t = \ln\left(\frac{N}{\text{DF}_t}\right)$ Where $\text{DF}_t$ is the number of documents containing term $t$. If a term appears in every document ($\text{DF}_t = N$), $\text{IDF}_t = \ln(1) = 0$, giving the word a TF-IDF weight of zero. --- ## Evaluating Machine Learning Model Fit For classification models (e.g., predicting default vs. non-default, or buy vs. sell signals), evaluating performance solely by overall **Accuracy** is dangerous when dealing with imbalanced datasets. ### The Confusion Matrix A **Confusion Matrix** summarizes prediction results across actual vs. predicted class labels: | Actual \ Predicted | Predicted Positive ($Y = 1$) | Predicted Negative ($Y = 0$) | | :--- | :--- | :--- | | **Actual Positive ($Y = 1$)** | **True Positive (TP)** | **False Negative (FN)** *(Type II Error)* | | **Actual Negative ($Y = 0$)** | **False Positive (FP)** *(Type I Error)* | **True Negative (TN)** | ### Classification Performance Metrics $\text{Accuracy} = \frac{TP + TN}{TP + TN + FP + FN}$ $\text{Precision} = \frac{TP}{TP + FP}$ $\text{Recall (Sensitivity)} = \frac{TP}{TP + FN}$ $\text{F1 Score} = 2 \times \frac{\text{Precision} \times \text{Recall}}{\text{Precision} + \text{Recall}}$ - **Precision:** Measures the proportion of positive predictions that were correct. High precision is critical when the cost of a **False Positive (Type I Error)** is severe (e.g., executing an expensive quantitative trade based on a false buy signal). - **Recall (Sensitivity):** Measures the proportion of actual positive cases that the model successfully identified. High recall is critical when the cost of a **False Negative (Type II Error)** is severe (e.g., missing a corporate default or fraudulent transaction). - **F1 Score:** The **harmonic mean** of Precision and Recall. It provides a balanced metric when classes are highly imbalanced (e.g., 99\% non-defaults vs 1\% defaults). --- ## Text-Based Financial Forecasting Applying NLP to financial forecasting involves extracting numerical sentiment scores or latent topics from unstructured financial text sources. ### Financial Lexicons vs. Generic Dictionaries Generic NLP dictionaries (such as the Harvard IV-4 dictionary) classify words like "liability", "cost", "risk", or "yield" as negative. However, in corporate financial reporting, these are standard operational accounting terms! Quantitative financial models rely on domain-specific financial lexicons, most notably the **Loughran-McDonald (LM) Financial Dictionary**, which categorizes words specifically for financial SEC filings into six distinct sentiment categories: 1. Negative (e.g., *restructure, adverse, default, breach*) 2. Positive (e.g., *profitability, milestone, gain*) 3. Uncertainty (e.g., *approximate, contingent, unpredictable*) 4. Litigious (e.g., *claimant, legislation, petition*) 5. Strong Modal (e.g., *always, definitely, highest*) 6. Weak Modal (e.g., *could, might, possibly*) ### Sentiment Analysis and Topic Modeling - **Sentiment Score:** Calculated by computing the net proportion of positive vs. negative LM financial terms in a document: $\text{Sentiment Score} = \frac{\text{Count}_{\text{Positive}} - \text{Count}_{\text{Negative}}}{\text{Count}_{\text{Total Words}}}$ - **Topic Modeling (Latent Dirichlet Allocation - LDA):** An unsupervised learning technique that scans document corpora to discover clusters of co-occurring words that represent underlying thematic "topics" (e.g., regulatory compliance, supply chain disruption, M&A restructuring) without requiring predefined manual tags. --- - **5 Steps of a Big Data Project:** 1. Project Conceptualization, 2. Data Collection, 3. Data Preparation & Wrangling, 4. Data Exploration (Feature Engineering), and 5. Model Training & Evaluation. - **Data Scaling Methods:** Min-Max scaling rescales data into $[0, 1]$. Standardization ($Z$-score) rescales data to mean $\mu=0$ and standard deviation $\sigma=1$. Standardization is preferred when datasets contain extreme outliers. - **Text Wrangling Pipeline:** Cleansing (removing HTML/punctuation), Tokenization (splitting into tokens/N-grams), Stop-Words Removal (filtering common words like "the"), and Normalization. - **Stemming vs. Lemmatization:** Stemming uses crude algorithmic rules to chop off word suffixes (fast, creates non-words). Lemmatization uses dictionary analysis to resolve tokens to true semantic root words (lemmas, accurate, slower). - **TF-IDF Formula:** $\text{TF-IDF}_{t,d} = \text{TF}_{t,d} \times \text{IDF}_t$, where $\text{TF}_{t,d} = \frac{\text{Count of } t \text{ in } d}{\text{Total words in } d}$ and $\text{IDF}_t = \ln(N / \text{DF}_t)$. Assigns high weights to terms frequent in document $d$ but rare across corpus $N$. - **Confusion Matrix Metrics:** Precision = $TP / (TP + FP)$ (minimizes False Positives / Type I Errors). Recall = $TP / (TP + FN)$ (minimizes False Negatives / Type II Errors). F1 Score = $2 \times (\text{Precision} \times \text{Recall}) / (\text{Precision} + \text{Recall})$ (harmonic mean for imbalanced data). - **Financial Text Analysis:** Standard generic dictionaries misclassify normal accounting terms. Financial models use the **Loughran-McDonald (LM) dictionary** (categories: Negative, Positive, Uncertainty, Litigious, Strong/Weak Modal). Unsupervised **Topic Modeling (LDA)** discovers latent thematic topics in text corpora. What You Need to Know