> built 2026-11-22 21:29 UTC from 7e8623c (main) · mood 0.0.19. Details: build_info.json

# index.html.md

<!-- generated by epythet -->

# mood

Investigations in financial sentiment analysis

To install:	`pip install mood`

Note: Requires an OpenAI API Token.
[How can to get one of those?](https://help.openai.com/en/articles/4936850-where-do-i-find-my-openai-api-key)

For more NLP work, see [idiom](https://github.com/thorwhalen/idiom/) and [lexis](https://github.com/thorwhalen/lexis/).

## Getting Started with Mood Models

The `mood` package provides a complete pipeline for training machine learning models to detect semantic attributes (or “moods”) in text. Here’s the typical workflow.
If you already have your training data, you can skip steps 1 and 2.

### 1. Define Your Semantic Attributes

Start by defining the semantic attributes you want to model. These are the “moods” or characteristics you want to detect in text:

```python
semantic_attributes = {
    "diplomatic_politeness": "Diplomatic Politeness (Degree of formality, civility, and ceremonial tone)",
    "military_intensity": "Military Reference Intensity (Mentions of soldiers, arms, tactics, or losses)",
    "sentiment_polarity": "Sentiment Polarity (Positive or negative affective tone)",
    # ... add more attributes as needed
}
```

### 2. Generate Training Data

Use the AI-powered dataset generation to create labeled training examples:

```python
from mood.dataset_makers import make_semantic_attributes_dataset

# Generate training data for your semantic attributes
make_semantic_attributes_dataset(
    semantic_attributes=semantic_attributes,
    store="path/to/save/datasets",  # or use a MutableMapping
    n_examples=1000,  # total examples per attribute
    batch_size=100,  # examples per API call
    verbose=2,  # show progress
)
```

This will create text segments with scores (0-5) for each semantic attribute, saved as text files with format:

```default
0 The meeting was dull and unproductive, leaving everyone feeling dissatisfied.
3 The negotiations showed moderate diplomatic courtesy between the parties.
5 Your Excellency, it is indeed our greatest honor to welcome you here today.
```

### 3. Parse and Prepare Data

Convert the raw text data into structured format and compute embeddings:

```python
from mood.dataset_makers import parsed_lines
import pandas as pd
from oa.batch_embeddings import compute_embeddings

# Parse the generated text files
dataset = pd.DataFrame(list(parsed_lines(dataset_content)))
# Results in: DataFrame with 'score' and 'segment' columns

# Compute embeddings for the text segments
embeddings = compute_embeddings(
    segments=dataset.segment.to_list(), batch_size=1000, verbosity=2
)

# Combine into final training dataset
training_data = pd.DataFrame(
    {"score": dataset.score, "segment": dataset.segment, "embedding": embeddings}
)
```

### 4. Train Mood Models

Use the `MoodModelingManager` to train and evaluate multiple types of models:

```python
from mood.mood_modeling import MoodModelingManager

# Create manager with your training data
manager = MoodModelingManager(
    df=training_data,
    embedding_col="embedding",
    score_col="score",
    verbose=2,  # Show detailed progress
)

# Train and evaluate models with single train/test split
results = manager.train_and_evaluate()

# For more stable metrics, run cross-validation
cv_results = manager.cross_validate_models(n_splits=10)

# Get performance summary
summary = manager.get_model_summary(use_cv=True)
print(summary)
```

### 5. Select and Deploy Best Model

```python
# Fit final models on all data
manager.fit_final_models()

# Get the best model based on performance metric
best_model_name, best_model = manager.get_best_model(
    metric="spearman",  # or 'accuracy', 'f1', etc.
    use_cv=True,
)

print(f"Best model: {best_model_name}")

# Use the model to predict mood scores for new text
new_embeddings = compute_embeddings(["Your new text here"])
mood_scores = manager.predict_mood(new_embeddings)
print(f"Mood scores: {mood_scores}")  # Values between 0 and 1
```

### Model Types Available

The system automatically trains several types of models:

- **Numerical Regression**: Ridge regression, SVR for continuous score prediction
- **Binary Classification**: Logistic regression, SVM for high/low classification
- **Ordinal Regression**: Specialized models for ordered categories (requires `mord` package)

Each model type handles the data differently:

- Numerical models predict continuous scores
- Binary models classify as high vs. low mood
- Ordinal models respect the ordered nature of the scores

### Output Interpretation

All final models output **mood scores between 0 and 1**, where:

- 0 = completely lacks the semantic attribute
- 1 = maximally expresses the semantic attribute
- Values are ordinally aligned with training scores

### Advanced Features

**Custom Model Configuration:**

```python
# Define custom models
custom_models = {
    "custom_ridge": {
        "data_type": "numerical",
        "model_class": Ridge,
        "model_params": {"alpha": 0.5},
        "max_dims": 200,
        "output_transform": "sigmoid",
    }
}

manager = MoodModelingManager(df=data, models=custom_models)
```

**Performance Analysis:**

```python
# Analyze model performance across different metrics
from mood.model_analysis import analyze_all

classifier_stats, regression_stats = compute_model_stats(model_stats)
report = analyze_all(classifier_stats, regression_stats)
```

## Quick Example: Current Headlines Sentiment

For a quick start, try analyzing current headlines:

```python
from mood import headlines_mood

# Get current headlines with sentiment scores
sentiment_scores = headlines_mood()
print(sentiment_scores)
```

This returns a dictionary mapping headlines to sentiment scores from -10 to +10.d

Investigations in financial sentiment analysis

To install:	`pip install mood`

Note: Requires an OpenAI API Token.
[How can to get one of those?](https://help.openai.com/en/articles/4936850-where-do-i-find-my-openai-api-key)

For more NLP work, see [idiom](https://github.com/thorwhalen/idiom/) and [lexis](https://github.com/thorwhalen/lexis/).

# Examples

## current headlines and their sentiment scores

```python

>>> from mood import headlines_mood
>>> headlines_mood()
{"Yaccarino shakes up X amid Musk's pressure on costs, FT says": -3,
 'Coup-hit Niger was betting on a China-backed oil pipeline as a lifeline. Then the troubles began': -7,
 'A Mexico City neighborhood keeps the iconic Volkswagen Beetle alive': 1,
 'Bitter political fight in Bolivia is paralyzing the government as unrest boils over economic crisis': -8,
 'Credit’s Strong Run Stumbles for First Time This Year': -4,
 'Former Stark Chairman in Thai Detention After Months on the Run': -5,
 '2 Millionaire-Maker Technology Stocks': 5,
 'Want to Earn More in the Stock Market With Less Effort? Try This Simple Strategy': 4,
 '3 Reasons to Buy Nvidia Stock Before June 26': 7,
 "Cathie Wood Says Software Is the Next Big AI Opportunity -- 2 Super Stocks You'll Wish You'd Bought Today if She's Right": 8,
 'Companies that give money to Democrats are beating Republican donors in the stock market': 2,
 'Is Buying Stocks When the S&P 500 Hits a New All-Time High a Smart Strategy? History Provides a Clear Answer.': 2,
 'Q1 Design Software Earnings: Unity (NYSE:U) Earns Top Marks': 4,
 'Social Networking Q1 Earnings: Snap (NYSE:SNAP) Simply the Best': 6,
 "A Look Back at Footwear Stocks' Q1 Earnings: Steven Madden (NASDAQ:SHOO) Vs The Rest Of The Pack": -1,
 "A Look Back at Heavy Machinery Stocks' Q1 Earnings: Oshkosh (NYSE:OSK) Vs The Rest Of The Pack": -1,
 'Unpacking Q1 Earnings: Keurig Dr Pepper (NASDAQ:KDP) In The Context Of Other Beverages and Alcohol Stocks': -2,
 'Q1 Earnings Outperformers: Agilysys (NASDAQ:AGYS) And The Rest Of The Vertical Software Stocks': 3,
 'What do homebuilders want? Immigration reform': 0,
 'Examining the steep rise in monthly auto loan payments': -2,
 'Cannes Lions 2024: What marketers are saying': 1,
 "Sports has to feed into a streamer's 'ecosystem': Kevin Mayer": 0,
 'Taylor Swift vs. Central Banks: One Swiftie calls ‘BS’': -2,
 "'There are bargains out there' as summer travel season heats up": 3,
 'This week in Bidenomics: Pile on the debt': -3,
 'Netflix flirts with all-time highs as investors cheer ad momentum, foray into live sports': 8,
 'Existing home sales decline in May as home prices reach record high': -4,
 "Regulators find weakness in 'living wills' from BofA, Citi, Goldman, and JPM": -6,
 'How to watch and listen to Yahoo Finance': 0,
 "Why Nvidia's 'gravy train' could come to 'screeching halt' after a volatile trading week": -7,
 'Trump’s campaign now has a cash advantage over Biden': 1,
 'The Anti-Altman’s Hail Mary Pitch to Investors': -3,
 "Tesla's Autonomous Strategy to be Key to EV Maker Reaching $1 Trillion-Plus Valuation, Wedbush Says": 7,
 'Alaska Airlines, Flight Attendants Union Reach Tentative Deal': 6,
 'China’s 618 online shopping event marks first-ever sales drop': -7,
 'Apple Throws Down the Gauntlet to European Regulators': -3,
 'Apple’s AI Features Won’t Be Offered in European Union Because of New Laws': -5,
 'Equity Markets Mostly Lower as Existing Home Sales Drop': -4,
 'Oil Rig Count Falls by Three This Week, Baker Hughes Says': -2,
 'Dubai Real Estate’s Resilience May Signal End of Boom-Bust Cycle': 5,
 'Montana aims to remind seniors about its ‘reverse annuity mortgage’': 0,
 'Desmarais-Backed Mortgage Firm Nesto Acquires Lender CMLS': 3,
 'Record high prices, rising mortgage rates depress US home sales': -8,
 'US home sales fall for the 3rd straight month in May amid rising mortgage rates, record-high prices': -8,
 "On wealthy Martha's Vineyard, costly housing is forcing workers out and threatening public safety": -7,
 "Mortgage rates decline for third consecutive week — 'bodes well for the housing market'": 4,
 'Congress should adopt mortgage interest tax credit: CHLA': 3,
 'Savings interest rates today, June 22, 2024 (best account provides 5.30% APY)': 4,
 'How to pay off your house faster with biweekly mortgage payments': 5,
 'The best credit cards for vacations for June 2024': 5,
 "Climate change makes India's monsoons erratic. Can farmers still find a way to prosper?": -2,
 'CDK Hackers Want Millions in Ransom to End Car Dealership Outage': -7,
 'S&P 500 Trading Volume Spikes at Wall Street Close: Markets Wrap': 0,
 'Bitcoin Could Hit $500,000 by October 2025, According to This Billionaire Investor': 7,
 'This Is Why Altcoin Investors Struggle Despite Bitcoin, Ether Sitting Near Yearly Highs': -3,
 'BitoGroup partners with Far Eastern International Bank to launch first crypto-friendly bank account': 2,
 'Cathie Wood sells $13 million of a struggling tech stock': -6,
 'Nvidia Stock Gets Hit With Bearish Reversal. If You Have Big Profits, This Is What You Should Do.': -5,
 "Single Mom With $1.3 Million From Divorce Can't Afford $8,000 Monthly Rent, Dave Ramsey Says It's Time To Move": -6,
 'Morningstar | A Weekly Summary of Stock Ideas and Developments in the Companies We Cover': 0,
 '5 Little-Known Perks of a Costco Membership': 4,
 'Billionaire David Tepper Goes Bargain Hunting: 6 Stocks He Just Bought': 5,
 'Palantir Inks Deal With Starlab. Is the Stock Ready to Head to the Stars?': 6,
 "Here's the Average Social Security Benefit at Age 62 -- and Why It's Not the Best News for Retirees": -5,
 'Analyst Report: Mitsubishi UFJ Financial Group, Inc.': 0,
 'Forget NextEra Energy. Buy This Magnificent Dividend King Instead': 6}
```

<p class="epythet-aggregates">This documentation as a single file: <a href="mood.md">mood.md</a> (Markdown, for agents).</p>


# _autosummary/mood.dataset_makers.html.md

# mood.dataset_makers

Tools to make datasets for training and testing models (for semantic attribute etc.)

### Functions

| [`default_save_key`](_autosummary/mood.dataset_makers.html.md#mood.dataset_makers.default_save_key)(name[, batch_idx, ...])     | Build the storage key for a dataset batch.                        |
|-----------------------------------------------------------------------------------------------|-------------------------------------------------------------------|
| [`make_semantic_attributes_dataset`](_autosummary/mood.dataset_makers.html.md#mood.dataset_makers.make_semantic_attributes_dataset)(...[, ...]) | Gather data for each semantic attribute and save it to the store. |
| `mk_concatenation_file`(dirpath, \*[, ...])                                                   |                                                                   |
| `parse_line`(line)                                                                            |                                                                   |
| `parsed_lines`(text_contents)                                                                 |                                                                   |
| [`text_lines`](_autosummary/mood.dataset_makers.html.md#mood.dataset_makers.text_lines)(text)                             | Yield the non-empty, stripped lines of `text`.                    |

### mood.dataset_makers.default_save_key(name, batch_idx=None, , include_subdir_prefix=True, counter_key_format='_{:02.0f}', extension='.txt')

Build the storage key for a dataset batch.

```pycon
>>> default_save_key("color", include_subdir_prefix=False)
'color.txt'
>>> default_save_key("color", 1, include_subdir_prefix=False)
'color_01.txt'
```

### mood.dataset_makers.make_semantic_attributes_dataset(semantic_attributes, store='/home/runner/.config/mood/semantic_attributes', \*, n_examples=1000, batch_size=100, start_batch_idx_at=0, save_key=<function default_save_key>, verbose=0, example_generator=None, \*\*dataset_maker_kwargs)

Gather data for each semantic attribute and save it to the store.

### Parameters

- semantic_attributes: Mapping of attribute names to their descriptions
- store: Storage location (string path or MutableMapping)
- n_examples: Total number of examples to gather per attribute
- batch_size: Number of examples per batch; if None, gather all examples in one batch
- start_batch_idx_at: Starting index for batch numbering
- save_key: Function to generate save keys
- verbose: Verbosity level (0=quiet, 1=attribute progress, 2=batch progress)
- example_generator: Injectable `(attribute, n_examples, ...) -> str` callable;
  when omitted it is built lazily on `aix` (so importing `mood` stays offline)
- dataset_maker_kwargs: Additional kwargs passed to the example generator

#### WARNING
Some models aren’t very good at generating the requested number of examples.
They may generate fewer or more than requested. This is a known issue with LLM
models.

```pycon
>>> store = {}
>>> attributes = {"color": "description of color"}
>>> # A deterministic generator keeps this example offline and reproducible;
>>> # omit ``example_generator`` to use the default aix-backed LLM generator.
>>> make_semantic_attributes_dataset(
...     attributes, store, n_examples=3, batch_size=2,
...     example_generator=lambda attribute, n_examples, **_: "0 a sample segment",
... )
>>> len(store)  # Two batches saved
2
>>> store
{
    'color/color_00.txt': '0 The meeting was dull and unproductive, leaving everyone feeling dissatisfied.'
                          '2 The car was old and rusty, with a paint job that had faded over time, hinting at its once vibrant color.'
                          '5 The sunset painted the sky in brilliant shades of orange, pink, and purple, creating a breathtaking display of color that captivated all who watched.'
                          '1 The room felt gloomy, with dark furniture casting shadows, though a hint of blue could be seen in the curtains.  ',
    'color/color_01.txt': '0 The meeting was dull and uneventful, lacking any excitement or engagement.'
                          '1 The car was just an ordinary vehicle, nothing special about its appearance. '
                          "2 The flowers were vibrant, but I couldn't quite tell what colors they were. "
                          '3 The sky turned a beautiful shade of orange as the sun began to set, casting a warm glow.'
                          "4 She wore a stunning red dress that caught everyone's attention at the party."
                          '5 The ocean sparkled in shades of deep blue and turquoise, a breathtaking view that left us speechless.  '
}
```

### mood.dataset_makers.text_lines(text)

Yield the non-empty, stripped lines of `text`.

```pycon
>>> list(text_lines("a\n\n  b  \nc"))
['a', 'b', 'c']
```


# _autosummary/mood.html.md

# mood

Sentiment analysis for stock market data.

```pycon
>>> from mood import headlines_mood
>>> headlines_mood()
{"Yaccarino shakes up X amid Musk's pressure on costs, FT says": -3,
 'Coup-hit Niger was betting on a China-backed oil pipeline as a lifeline. Then the troubles began': -7,
 'A Mexico City neighborhood keeps the iconic Volkswagen Beetle alive': 1,
 ...
 "Here's the Average Social Security Benefit at Age 62 -- and Why It's Not the Best News for Retirees": -5,
 'Analyst Report: Mitsubishi UFJ Financial Group, Inc.': 0,
 'Forget NextEra Energy. Buy This Magnificent Dividend King Instead': 6}
```

### Modules

| [`dataset_makers`](_autosummary/mood.dataset_makers.html.md#module-mood.dataset_makers)     | Tools to make datasets for training and testing models (for semantic attribute etc.)   |
|------------------------------------------------------------------------------------------------|----------------------------------------------------------------------------------------|
| [`learn_sentiments`](_autosummary/mood.learn_sentiments.html.md#module-mood.learn_sentiments) | Learning sentiments from data.                                                         |
| [`model_analysis`](_autosummary/mood.model_analysis.html.md#module-mood.model_analysis)     | Tools for model analysis                                                               |
| [`mood_modeling`](_autosummary/mood.mood_modeling.html.md#module-mood.mood_modeling)       | Mood Modeling Module                                                                   |
| [`scripts`](_autosummary/mood.scripts.html.md#module-mood.scripts)                   | Scripts for mood.                                                                      |
| [`sentiment`](_autosummary/mood.sentiment.html.md#module-mood.sentiment)               | Sentiment analysis tools                                                               |
| [`tools`](_autosummary/mood.tools.html.md#module-mood.tools)                       | Tools for sentiment analysis                                                           |
| [`util`](_autosummary/mood.util.html.md#module-mood.util)                         | Utils for mood                                                                         |


# _autosummary/mood.learn_sentiments.html.md

# mood.learn_sentiments

Learning sentiments from data.

### Functions

| [`fit_logistic_classifier`](_autosummary/mood.learn_sentiments.html.md#mood.learn_sentiments.fit_logistic_classifier)(X, y, \*[, ...])   | Fits a logistic regression model on embedding data for binary classification without feature scaling.   |
|---------------------------------------------------------------------------------------------|---------------------------------------------------------------------------------------------------------|
| [`get_binary_y`](_autosummary/mood.learn_sentiments.html.md#mood.learn_sentiments.get_binary_y)(y, target_y)                  | Convert a multi-class target array to a binary array for a specific target class.                       |
| [`predict_with_model`](_autosummary/mood.learn_sentiments.html.md#mood.learn_sentiments.predict_with_model)(model, X)               | Helper function to make predictions with a fitted model.                                                |

### Classes

| [`ModelStatistics`](_autosummary/mood.learn_sentiments.html.md#mood.learn_sentiments.ModelStatistics)([accuracy, precision, ...])   | Container for model performance statistics   |
|------------------------------------------------------------------------------------------------|----------------------------------------------|

### *class* mood.learn_sentiments.ModelStatistics(accuracy=None, precision=None, recall=None, f1=None, roc_auc=None, confusion_matrix=None, classification_report=None, train_test_performed=False, training_time=None, test_size=None, random_state=None)

Bases: [`object`](https://docs.python.org/3/builtins/functions.html#object)

Container for model performance statistics

### mood.learn_sentiments.fit_logistic_classifier(X, y, , test_size=0.2, random_state=42, c_value=1.0, max_iter=1000, solver='lbfgs', penalty='l2', class_weight=None, fit_intercept=True, skip_validation=False, verbose=True)

Fits a logistic regression model on embedding data for binary classification without feature scaling.

### Parameters

y
: Binary target values (0/1 or True/False).

test_size
: Proportion of the dataset to include in the test split.

random_state
: Controls the shuffling applied to the data before applying the split.

c_value
: Inverse of regularization strength; smaller values specify stronger regularization.

max_iter
: Maximum number of iterations taken for the solvers to converge.

solver
: Algorithm to use in the optimization problem (‘newton-cg’, ‘lbfgs’, ‘liblinear’, ‘sag’, ‘saga’).

penalty
: Specify the norm used in the penalization (‘l1’, ‘l2’, ‘elasticnet’, None).

class_weight
: Weights associated with classes. If ‘balanced’, uses class frequencies.

fit_intercept
: Whether to fit an intercept term in the model.

skip_validation
: If True, skips train/test validation and fits model on all data.

verbose
: If True, prints progress and results.

### Returns

stats
: Object containing performance statistics.

* **Return type:**
  [`tuple`](https://docs.python.org/3/builtins/stdtypes.html#tuple)[`LogisticRegression`, [`ModelStatistics`](_autosummary/mood.learn_sentiments.html.md#mood.learn_sentiments.ModelStatistics)]

### mood.learn_sentiments.get_binary_y(y, target_y)

Convert a multi-class target array to a binary array for a specific target class.

### mood.learn_sentiments.predict_with_model(model, X)

Helper function to make predictions with a fitted model.

### Parameters

X
: Feature vectors to predict on.

### Returns

y_prob
: Probability estimates for class 1.


# _autosummary/mood.model_analysis.html.md

# mood.model_analysis

Tools for model analysis

### Functions

| [`analyze_all`](_autosummary/mood.model_analysis.html.md#mood.model_analysis.analyze_all)(classifier_stats, regression_stats)   | Run all analyses and generate a complete report.                     |
|----------------------------------------------------------------------------------------------------|----------------------------------------------------------------------|
| [`analyze_by_data_type`](_autosummary/mood.model_analysis.html.md#mood.model_analysis.analyze_by_data_type)(classifier_stats, ...)       | Analyze performance by data type.                                    |
| [`analyze_classifiers`](_autosummary/mood.model_analysis.html.md#mood.model_analysis.analyze_classifiers)(classifier_stats)             | Example analysis of classifier models.                               |
| [`analyze_regression_models`](_autosummary/mood.model_analysis.html.md#mood.model_analysis.analyze_regression_models)(regression_stats)       | Example analysis of regression models.                               |
| [`analyze_specific_attribute`](_autosummary/mood.model_analysis.html.md#mood.model_analysis.analyze_specific_attribute)(classifier_stats, ...) | Focused analysis on a specific semantic attribute.                   |
| [`compare_datasets`](_autosummary/mood.model_analysis.html.md#mood.model_analysis.compare_datasets)(classifier_stats, ...)           | Compare model performance across classifier and regression datasets. |
| [`compare_models_across_datasets`](_autosummary/mood.model_analysis.html.md#mood.model_analysis.compare_models_across_datasets)(...[, ...])        | Compare model performance across classifier and regression datasets. |
| `compute_model_stats`(model_stats)                                                                 |                                                                      |

### Classes

| [`ModelPerformanceAnalyzer`](_autosummary/mood.model_analysis.html.md#mood.model_analysis.ModelPerformanceAnalyzer)(data[, ...])   | Analyze model performance metrics across different semantic attributes and model types.   |
|------------------------------------------------------------------------------------------|-------------------------------------------------------------------------------------------|

### *class* mood.model_analysis.ModelPerformanceAnalyzer(data, relevant_metrics=list(), model_type_column='model_name', attribute_column='semantic_attribute', data_type_column='data_type')

Bases: [`object`](https://docs.python.org/3/builtins/functions.html#object)

Analyze model performance metrics across different semantic attributes and model types.

This class provides methods to generate statistical summaries and visualizations
for comparing model performance across different metrics and semantic attributes.

```pycon
>>> import pandas as pd
>>> # Sample data
>>> data = pd.DataFrame({
...     'semantic_attribute': ['irony', 'irony', 'moral', 'moral'],
...     'model_name': ['svm', 'log_reg', 'svm', 'log_reg'],
...     'accuracy': [0.7, 0.6, 0.9, 0.8]
... })
>>> analyzer = ModelPerformanceAnalyzer(data)
>>> analyzer.get_metrics()
['accuracy']
```

#### filter_data(attributes=None, models=None, data_types=None)

Filter the dataframe based on specified attributes, models, and data types.

* **Parameters:**
  * **attributes** ([`list`](https://docs.python.org/3/builtins/stdtypes.html#list)[[`str`](https://docs.python.org/3/builtins/stdtypes.html#str)] | [`None`](https://docs.python.org/3/builtins/constants.html#None)) – List of semantic attributes to include
  * **models** ([`list`](https://docs.python.org/3/builtins/stdtypes.html#list)[[`str`](https://docs.python.org/3/builtins/stdtypes.html#str)] | [`None`](https://docs.python.org/3/builtins/constants.html#None)) – List of model names to include
  * **data_types** ([`list`](https://docs.python.org/3/builtins/stdtypes.html#list)[[`str`](https://docs.python.org/3/builtins/stdtypes.html#str)] | [`None`](https://docs.python.org/3/builtins/constants.html#None)) – List of data types to include
* **Returns:**
  Filtered dataframe
* **Return type:**
  `DataFrame`

#### generate_attribute_modelability_table(primary_metric, secondary_metrics=None, models=None, data_types=None)

Generate a table showing which semantic attributes are most modelable.

* **Parameters:**
  * **primary_metric** ([`str`](https://docs.python.org/3/builtins/stdtypes.html#str)) – The main metric to sort by (e.g., accuracy, r2)
  * **secondary_metrics** ([`list`](https://docs.python.org/3/builtins/stdtypes.html#list)[[`str`](https://docs.python.org/3/builtins/stdtypes.html#str)] | [`None`](https://docs.python.org/3/builtins/constants.html#None)) – Additional metrics to include in the table
  * **models** ([`list`](https://docs.python.org/3/builtins/stdtypes.html#list)[[`str`](https://docs.python.org/3/builtins/stdtypes.html#str)] | [`None`](https://docs.python.org/3/builtins/constants.html#None)) – List of model names to include (default: all)
  * **data_types** ([`list`](https://docs.python.org/3/builtins/stdtypes.html#list)[[`str`](https://docs.python.org/3/builtins/stdtypes.html#str)] | [`None`](https://docs.python.org/3/builtins/constants.html#None)) – List of data types to include (default: all)
* **Returns:**
  A table with attributes as rows and metrics as columns
* **Return type:**
  `DataFrame`

#### generate_model_comparison_table(metric, attributes=None, models=None, data_types=None)

Generate a comparison table of models across different semantic attributes for a given metric.

* **Parameters:**
  * **metric** ([`str`](https://docs.python.org/3/builtins/stdtypes.html#str)) – The metric to compare (e.g., accuracy, f1, r2)
  * **attributes** ([`list`](https://docs.python.org/3/builtins/stdtypes.html#list)[[`str`](https://docs.python.org/3/builtins/stdtypes.html#str)] | [`None`](https://docs.python.org/3/builtins/constants.html#None)) – List of semantic attributes to include (default: all)
  * **models** ([`list`](https://docs.python.org/3/builtins/stdtypes.html#list)[[`str`](https://docs.python.org/3/builtins/stdtypes.html#str)] | [`None`](https://docs.python.org/3/builtins/constants.html#None)) – List of model names to include (default: all)
  * **data_types** ([`list`](https://docs.python.org/3/builtins/stdtypes.html#list)[[`str`](https://docs.python.org/3/builtins/stdtypes.html#str)] | [`None`](https://docs.python.org/3/builtins/constants.html#None)) – List of data types to include (default: all)
* **Returns:**
  A table with attributes as rows and models as columns
* **Return type:**
  `DataFrame`

#### get_attributes()

Get the list of unique semantic attributes in the dataset.

* **Returns:**
  List of semantic attribute names
* **Return type:**
  [`list`](https://docs.python.org/3/builtins/stdtypes.html#list)[[`str`](https://docs.python.org/3/builtins/stdtypes.html#str)]

#### get_data_types()

Get the list of unique data types in the dataset.

* **Returns:**
  List of data types (e.g., binary, numerical, ordinal)
* **Return type:**
  [`list`](https://docs.python.org/3/builtins/stdtypes.html#list)[[`str`](https://docs.python.org/3/builtins/stdtypes.html#str)]

#### get_metrics()

Get the list of available metrics in the dataset.

* **Returns:**
  List of metric names
* **Return type:**
  [`list`](https://docs.python.org/3/builtins/stdtypes.html#list)[[`str`](https://docs.python.org/3/builtins/stdtypes.html#str)]

#### get_models()

Get the list of unique model names in the dataset.

* **Returns:**
  List of model names
* **Return type:**
  [`list`](https://docs.python.org/3/builtins/stdtypes.html#list)[[`str`](https://docs.python.org/3/builtins/stdtypes.html#str)]

#### visualize_attribute_modelability(metric, subset_idx=None, models=None, data_types=None, figsize=(10, 6), palette='viridis', tight_xlim=True)

Create a horizontal bar chart showing which attributes are most/least modelable.

* **Parameters:**
  * **metric** ([`str`](https://docs.python.org/3/builtins/stdtypes.html#str)) – The metric to visualize
  * **subset_idx** ([`int`](https://docs.python.org/3/builtins/functions.html#int) | [`None`](https://docs.python.org/3/builtins/constants.html#None)) – When positive, show first N attributes; when negative, show last N attributes
    (None = show all attributes)
  * **models** ([`list`](https://docs.python.org/3/builtins/stdtypes.html#list)[[`str`](https://docs.python.org/3/builtins/stdtypes.html#str)] | [`None`](https://docs.python.org/3/builtins/constants.html#None)) – List of model names to include (default: all)
  * **data_types** ([`list`](https://docs.python.org/3/builtins/stdtypes.html#list)[[`str`](https://docs.python.org/3/builtins/stdtypes.html#str)] | [`None`](https://docs.python.org/3/builtins/constants.html#None)) – List of data types to include (default: all)
  * **figsize** ([`tuple`](https://docs.python.org/3/builtins/stdtypes.html#tuple)[[`int`](https://docs.python.org/3/builtins/functions.html#int), [`int`](https://docs.python.org/3/builtins/functions.html#int)]) – Figure size (width, height)
  * **palette** ([`str`](https://docs.python.org/3/builtins/stdtypes.html#str)) – Color palette for the plot
  * **tight_xlim** ([`bool`](https://docs.python.org/3/builtins/functions.html#bool)) – Whether to use tight x-axis limits (default: True)
* **Returns:**
  The matplotlib figure object
* **Return type:**
  `Figure`

#### visualize_correlation_matrix(metrics=None, figsize=(10, 8))

Create a heatmap showing the correlation between different metrics.

* **Parameters:**
  * **metrics** ([`list`](https://docs.python.org/3/builtins/stdtypes.html#list)[[`str`](https://docs.python.org/3/builtins/stdtypes.html#str)] | [`None`](https://docs.python.org/3/builtins/constants.html#None)) – List of metrics to include in the correlation matrix (default: all)
  * **figsize** ([`tuple`](https://docs.python.org/3/builtins/stdtypes.html#tuple)[[`int`](https://docs.python.org/3/builtins/functions.html#int), [`int`](https://docs.python.org/3/builtins/functions.html#int)]) – Figure size (width, height)
* **Returns:**
  The matplotlib figure object
* **Return type:**
  `Figure`

#### visualize_metric_distributions(metrics, models=None, data_types=None, figsize=(12, 8))

Create box plots showing the distribution of metrics across semantic attributes.

* **Parameters:**
  * **metrics** ([`list`](https://docs.python.org/3/builtins/stdtypes.html#list)[[`str`](https://docs.python.org/3/builtins/stdtypes.html#str)]) – List of metrics to visualize
  * **models** ([`list`](https://docs.python.org/3/builtins/stdtypes.html#list)[[`str`](https://docs.python.org/3/builtins/stdtypes.html#str)] | [`None`](https://docs.python.org/3/builtins/constants.html#None)) – List of model names to include (default: all)
  * **data_types** ([`list`](https://docs.python.org/3/builtins/stdtypes.html#list)[[`str`](https://docs.python.org/3/builtins/stdtypes.html#str)] | [`None`](https://docs.python.org/3/builtins/constants.html#None)) – List of data types to include (default: all)
  * **figsize** ([`tuple`](https://docs.python.org/3/builtins/stdtypes.html#tuple)[[`int`](https://docs.python.org/3/builtins/functions.html#int), [`int`](https://docs.python.org/3/builtins/functions.html#int)]) – Figure size (width, height)
* **Returns:**
  The matplotlib figure object
* **Return type:**
  `Figure`

#### visualize_model_comparison(metric, attributes=None, models=None, data_types=None, figsize=(10, 6), palette='viridis', tight_ylim=True)

Create a grouped bar chart comparing model performance across semantic attributes.

* **Parameters:**
  * **metric** ([`str`](https://docs.python.org/3/builtins/stdtypes.html#str)) – The metric to visualize
  * **attributes** ([`list`](https://docs.python.org/3/builtins/stdtypes.html#list)[[`str`](https://docs.python.org/3/builtins/stdtypes.html#str)] | [`None`](https://docs.python.org/3/builtins/constants.html#None)) – List of semantic attributes to include (default: all)
  * **models** ([`list`](https://docs.python.org/3/builtins/stdtypes.html#list)[[`str`](https://docs.python.org/3/builtins/stdtypes.html#str)] | [`None`](https://docs.python.org/3/builtins/constants.html#None)) – List of model names to include (default: all)
  * **data_types** ([`list`](https://docs.python.org/3/builtins/stdtypes.html#list)[[`str`](https://docs.python.org/3/builtins/stdtypes.html#str)] | [`None`](https://docs.python.org/3/builtins/constants.html#None)) – List of data types to include (default: all)
  * **figsize** ([`tuple`](https://docs.python.org/3/builtins/stdtypes.html#tuple)[[`int`](https://docs.python.org/3/builtins/functions.html#int), [`int`](https://docs.python.org/3/builtins/functions.html#int)]) – Figure size (width, height)
  * **palette** ([`str`](https://docs.python.org/3/builtins/stdtypes.html#str)) – Color palette for the plot
  * **tight_ylim** ([`bool`](https://docs.python.org/3/builtins/functions.html#bool)) – Whether to use tight y-axis limits (default: True)
* **Returns:**
  The matplotlib figure object
* **Return type:**
  `Figure`

#### visualize_performance_radar(metrics, models, attribute, data_type=None, figsize=(10, 8))

Create a radar chart comparing models across multiple metrics for a specific attribute.

* **Parameters:**
  * **metrics** ([`list`](https://docs.python.org/3/builtins/stdtypes.html#list)[[`str`](https://docs.python.org/3/builtins/stdtypes.html#str)]) – List of metrics to include in the radar chart
  * **models** ([`list`](https://docs.python.org/3/builtins/stdtypes.html#list)[[`str`](https://docs.python.org/3/builtins/stdtypes.html#str)]) – List of model names to include
  * **attribute** ([`str`](https://docs.python.org/3/builtins/stdtypes.html#str)) – The semantic attribute to analyze
  * **data_type** ([`str`](https://docs.python.org/3/builtins/stdtypes.html#str) | [`None`](https://docs.python.org/3/builtins/constants.html#None)) – Data type to filter by (default: None)
  * **figsize** ([`tuple`](https://docs.python.org/3/builtins/stdtypes.html#tuple)[[`int`](https://docs.python.org/3/builtins/functions.html#int), [`int`](https://docs.python.org/3/builtins/functions.html#int)]) – Figure size (width, height)
* **Returns:**
  The matplotlib figure object
* **Return type:**
  `Figure`

### mood.model_analysis.analyze_all(classifier_stats, regression_stats, attribute='irony_humor')

Run all analyses and generate a complete report.

### mood.model_analysis.analyze_by_data_type(classifier_stats, regression_stats)

Analyze performance by data type.

### mood.model_analysis.analyze_classifiers(classifier_stats)

Example analysis of classifier models.

### mood.model_analysis.analyze_regression_models(regression_stats)

Example analysis of regression models.

### mood.model_analysis.analyze_specific_attribute(classifier_stats, regression_stats, attribute='irony_humor')

Focused analysis on a specific semantic attribute.

### mood.model_analysis.compare_datasets(classifier_stats, regression_stats)

Compare model performance across classifier and regression datasets.

### mood.model_analysis.compare_models_across_datasets(classifier_data, regression_data, common_models=None, common_attributes=None)

Compare model performance across classifier and regression datasets.

* **Parameters:**
  * **classifier_data** (`DataFrame`) – Dataframe with classifier metrics
  * **regression_data** (`DataFrame`) – Dataframe with regression metrics
  * **common_models** ([`list`](https://docs.python.org/3/builtins/stdtypes.html#list)[[`str`](https://docs.python.org/3/builtins/stdtypes.html#str)] | [`None`](https://docs.python.org/3/builtins/constants.html#None)) – List of model names to compare (must exist in both datasets)
  * **common_attributes** ([`list`](https://docs.python.org/3/builtins/stdtypes.html#list)[[`str`](https://docs.python.org/3/builtins/stdtypes.html#str)] | [`None`](https://docs.python.org/3/builtins/constants.html#None)) – List of attributes to compare (must exist in both datasets)
* **Returns:**
  Dictionary with comparison tables
* **Return type:**
  [`dict`](https://docs.python.org/3/builtins/stdtypes.html#dict)[[`str`](https://docs.python.org/3/builtins/stdtypes.html#str), `DataFrame`]


# _autosummary/mood.mood_modeling.html.md

# mood.mood_modeling

Mood Modeling Module

This module provides tools for modeling semantic attributes (or “moods”) based on text embeddings.
It allows for different modeling approaches: numerical regression, ordinal regression, and binary classification.

The main class, MoodModelingManager, handles the entire process:

- Preparing different (X, y) pairs from input dataframes
- Training and evaluating multiple modeling pipelines
- Gathering comprehensive validation statistics
- Providing a final model that outputs mood scores in the [0, 1] range

These mood scores are ordinally aligned with training scores, where higher values indicate
stronger presence of the target semantic attribute.

### Functions

| [`class_to_path`](_autosummary/mood.mood_modeling.html.md#mood.mood_modeling.class_to_path)(obj)                              | Convert an object to a string path.                                     |
|--------------------------------------------------------------------------------------------------|-------------------------------------------------------------------------|
| [`path_to_class`](_autosummary/mood.mood_modeling.html.md#mood.mood_modeling.path_to_class)(path)                             | Convert a string path to an object.                                     |
| [`x_and_y_with_boolean_y`](_autosummary/mood.mood_modeling.html.md#mood.mood_modeling.x_and_y_with_boolean_y)(data, x_col, y_col, ...) | Get the x and y values from a dataframe, converting y to binary values. |

### Classes

| [`DimensionReducer`](_autosummary/mood.mood_modeling.html.md#mood.mood_modeling.DimensionReducer)([max_dims])                  | Transformer to reduce dimensionality by selecting first n dimensions.                                                             |
|------------------------------------------------------------------------------------------------|-----------------------------------------------------------------------------------------------------------------------------------|
| [`MoodEstimator`](_autosummary/mood.mood_modeling.html.md#mood.mood_modeling.MoodEstimator)(model[, max_dims, ...])         | Custom estimator that wraps an underlying model and provides methods to transform predictions to mood scores in the [0, 1] range. |
| [`MoodModelingManager`](_autosummary/mood.mood_modeling.html.md#mood.mood_modeling.MoodModelingManager)(df[, embedding_col, ...]) | Manager class for building and evaluating mood models.                                                                            |
| [`OrdinalRandomForest`](_autosummary/mood.mood_modeling.html.md#mood.mood_modeling.OrdinalRandomForest)([ordinal_classes])        | Random Forest customized for ordinal regression.                                                                                  |

### *class* mood.mood_modeling.DimensionReducer(max_dims=None)

Bases: `BaseEstimator`, `TransformerMixin`

Transformer to reduce dimensionality by selecting first n dimensions.

This is useful for embedding vectors where the first dimensions typically
contain the most important information.

#### fit(X, y=None)

Fit method (no-op as this is a simple feature selector).

* **Parameters:**
  * **X** (`ndarray`) – Input features
  * **y** (`ndarray` | [`None`](https://docs.python.org/3/builtins/constants.html#None)) – Target values (not used)
* **Return type:**
  [`DimensionReducer`](_autosummary/mood.mood_modeling.html.md#mood.mood_modeling.DimensionReducer)
* **Returns:**
  Self

#### transform(X)

Transform X by selecting first max_dims dimensions.

* **Parameters:**
  **X** (`ndarray`) – Input features
* **Return type:**
  `ndarray`
* **Returns:**
  Reduced feature matrix

### *class* mood.mood_modeling.MoodEstimator(model, max_dims=None, output_transform='sigmoid', threshold=None, data_type='numerical')

Bases: `BaseEstimator`, `TransformerMixin`

Custom estimator that wraps an underlying model and provides methods to transform
predictions to mood scores in the [0, 1] range.

#### fit(X, y)

Fit the model to the data.

* **Parameters:**
  * **X** (`ndarray`) – Input features
  * **y** (`ndarray`) – Target values
* **Return type:**
  [`MoodEstimator`](_autosummary/mood.mood_modeling.html.md#mood.mood_modeling.MoodEstimator)
* **Returns:**
  Self

#### predict(X)

Make predictions using the underlying model.

* **Parameters:**
  **X** (`ndarray`) – Input features
* **Return type:**
  `ndarray`
* **Returns:**
  Raw model predictions

#### predict_proba(X)

Predict class probabilities if the underlying model supports it.

* **Parameters:**
  **X** (`ndarray`) – Input features
* **Return type:**
  `ndarray`
* **Returns:**
  Class probabilities if available, otherwise transformed predictions

#### transform(X)

Transform input features to mood scores in [0, 1] range.

* **Parameters:**
  **X** (`ndarray`) – Input features
* **Return type:**
  `ndarray`
* **Returns:**
  Mood scores in [0, 1] range

### *class* mood.mood_modeling.MoodModelingManager(df, embedding_col='embedding', score_col='score', test_size=0.2, random_state=42, models=None, verbose=1)

Bases: [`object`](https://docs.python.org/3/builtins/functions.html#object)

Manager class for building and evaluating mood models.

This class handles:

- Data preparation for different model types
- Training and evaluation of multiple modeling pipelines
- Collection of validation statistics
- Final model selection and fitting

#### cross_validate_models(n_splits=5, metrics=None)

Perform cross-validation on all models to get more stable performance metrics.

* **Parameters:**
  * **n_splits** ([`int`](https://docs.python.org/3/builtins/functions.html#int)) – Number of cross-validation folds
  * **metrics** ([`set`](https://docs.python.org/3/builtins/stdtypes.html#set)[[`str`](https://docs.python.org/3/builtins/stdtypes.html#str)] | [`None`](https://docs.python.org/3/builtins/constants.html#None)) – Set of metric names to compute (defaults to model-appropriate metrics)
* **Return type:**
  [`dict`](https://docs.python.org/3/builtins/stdtypes.html#dict)
* **Returns:**
  Dictionary of cross-validation results for all models

#### fit_final_models()

Fit final models on the entire dataset.

* **Return type:**
  [`dict`](https://docs.python.org/3/builtins/stdtypes.html#dict)
* **Returns:**
  Dictionary of fitted models

#### *classmethod* from_arrays(X, y, test_size=0.2, random_state=42, models=None, verbose=1)

Create a MoodModelingManager directly from numpy arrays.

* **Parameters:**
  * **X** (`ndarray`) – Array of embeddings, shape (n_samples, n_features)
  * **y** (`ndarray`) – Array of scores, shape (n_samples,)
  * **test_size** ([`float`](https://docs.python.org/3/builtins/functions.html#float)) – Proportion of data to use for testing
  * **random_state** ([`int`](https://docs.python.org/3/builtins/functions.html#int)) – Random seed for reproducibility
  * **models** ([`dict`](https://docs.python.org/3/builtins/stdtypes.html#dict) | [`None`](https://docs.python.org/3/builtins/constants.html#None)) – Dictionary of modeling pipelines (uses default_models if None)
  * **verbose** ([`int`](https://docs.python.org/3/builtins/functions.html#int)) – Level of verbosity
* **Return type:**
  [`MoodModelingManager`](_autosummary/mood.mood_modeling.html.md#mood.mood_modeling.MoodModelingManager)
* **Returns:**
  MoodModelingManager instance

### Example

```pycon
>>> manager = MoodModelingManager.from_arrays(X, y, verbose=2)
>>> results = manager.train_and_evaluate()
```

#### get_best_model(metric='spearman', data_type=None, use_cv=False)

Get the best model based on a specific metric.

* **Parameters:**
  * **metric** ([`str`](https://docs.python.org/3/builtins/stdtypes.html#str)) – Metric to use for comparison
  * **data_type** ([`str`](https://docs.python.org/3/builtins/stdtypes.html#str) | [`None`](https://docs.python.org/3/builtins/constants.html#None)) – Filter by data type (optional)
  * **use_cv** ([`bool`](https://docs.python.org/3/builtins/functions.html#bool)) – Whether to use cross-validation results for comparison (if available)
* **Return type:**
  [`tuple`](https://docs.python.org/3/builtins/stdtypes.html#tuple)[[`str`](https://docs.python.org/3/builtins/stdtypes.html#str), [`MoodEstimator`](_autosummary/mood.mood_modeling.html.md#mood.mood_modeling.MoodEstimator)]
* **Returns:**
  Tuple of (model_name, model)

#### get_model_summary(use_cv=False, \*, egress=<class 'pandas.DataFrame'>)

Get a summary of all models and their performance.

* **Parameters:**
  **use_cv** ([`bool`](https://docs.python.org/3/builtins/functions.html#bool)) – Whether to use cross-validation results (if available)
* **Returns:**
  DataFrame summarizing model performance

#### predict_mood(X, model_name=None)

Predict mood scores for new data.

* **Parameters:**
  * **X** (`ndarray`) – Input features
  * **model_name** ([`str`](https://docs.python.org/3/builtins/stdtypes.html#str) | [`None`](https://docs.python.org/3/builtins/constants.html#None)) – Name of model to use (uses best model if None)
* **Return type:**
  `ndarray`
* **Returns:**
  Array of mood scores in [0, 1] range

#### prepare_binary_data(threshold=None, positive_labels=None, negative_labels=None)

Prepare binary data from the dataframe.

* **Parameters:**
  * **threshold** ([`float`](https://docs.python.org/3/builtins/functions.html#float) | [`int`](https://docs.python.org/3/builtins/functions.html#int) | [`None`](https://docs.python.org/3/builtins/constants.html#None)) – Score threshold above which is considered positive
  * **positive_labels** ([`list`](https://docs.python.org/3/builtins/stdtypes.html#list) | [`None`](https://docs.python.org/3/builtins/constants.html#None)) – List of scores considered positive
  * **negative_labels** ([`list`](https://docs.python.org/3/builtins/stdtypes.html#list) | [`None`](https://docs.python.org/3/builtins/constants.html#None)) – List of scores considered negative
* **Return type:**
  [`tuple`](https://docs.python.org/3/builtins/stdtypes.html#tuple)[`ndarray`, `ndarray`]
* **Returns:**
  Tuple of (X, y) for binary classification

#### prepare_numerical_data(normalize=True)

Prepare numerical data from the dataframe.

* **Parameters:**
  **normalize** ([`bool`](https://docs.python.org/3/builtins/functions.html#bool)) – Whether to normalize scores to [0, 1]
* **Return type:**
  [`tuple`](https://docs.python.org/3/builtins/stdtypes.html#tuple)[`ndarray`, `ndarray`]
* **Returns:**
  Tuple of (X, y) for numerical regression

#### prepare_ordinal_data()

Prepare ordinal data from the dataframe.

* **Return type:**
  [`tuple`](https://docs.python.org/3/builtins/stdtypes.html#tuple)[`ndarray`, `ndarray`]
* **Returns:**
  Tuple of (X, y) for ordinal regression

#### train_and_evaluate()

Train and evaluate all models using a single train/test split, collecting performance metrics.

* **Return type:**
  [`dict`](https://docs.python.org/3/builtins/stdtypes.html#dict)
* **Returns:**
  Dictionary of results for all models

### *class* mood.mood_modeling.OrdinalRandomForest(ordinal_classes=None, \*\*kwargs)

Bases: `RandomForestRegressor`

Random Forest customized for ordinal regression.

Predicts continuous values first, then maps them to the closest ordinal class.

#### fit(X, y)

Build a forest of trees from the training set (X, y).

* **Parameters:**
  * **X** ( *{array-like* *,* *sparse matrix}* *of* *shape* *(**n_samples* *,* *n_features* *)*) – The training input samples. Internally, its dtype will be converted
    to `dtype=np.float32`. If a sparse matrix is provided, it will be
    converted into a sparse `csc_matrix`.
  * **y** (*array-like* *of* *shape* *(**n_samples* *,* *) or*  *(**n_samples* *,* *n_outputs* *)*) – The target values (class labels in classification, real numbers in
    regression).
  * **sample_weight** (*array-like* *of* *shape* *(**n_samples* *,* *)* *,* *default=None*) – Sample weights. If None, then samples are equally weighted. Splits
    that would create child nodes with net zero or negative weight are
    ignored while searching for a split in each node. In the case of
    classification, splits are also ignored if they would result in any
    single class carrying a negative weight in either child node.
* **Returns:**
  **self** – Fitted estimator.
* **Return type:**
  [*object*](https://docs.python.org/3/builtins/functions.html#object)

#### predict(X)

Predict regression target for X.

The predicted regression target of an input sample is computed as the
mean predicted regression targets of the trees in the forest.

* **Parameters:**
  **X** ( *{array-like* *,* *sparse matrix}* *of* *shape* *(**n_samples* *,* *n_features* *)*) – The input samples. Internally, its dtype will be converted to
  `dtype=np.float32`. If a sparse matrix is provided, it will be
  converted into a sparse `csr_matrix`.
* **Returns:**
  **y** – The predicted values.
* **Return type:**
  ndarray of shape (n_samples,) or (n_samples, n_outputs)

#### set_fit_request()

No-op.

Calling this method has no effect.

* **Returns:**
  **self** – The updated object.
* **Return type:**
  [`OrdinalRandomForest`](_autosummary/mood.mood_modeling.html.md#mood.mood_modeling.OrdinalRandomForest)

#### set_score_request(, sample_weight='$UNCHANGED$')

Configure whether metadata should be requested to be passed to the `score` method.

Note that this method is only relevant when this estimator is used as a
sub-estimator within a meta-estimator and metadata routing is enabled
with `enable_metadata_routing=True` (see `sklearn.set_config()`).
Please check the User Guide on how the routing
mechanism works.

The options for each parameter are:

- `True`: metadata is requested, and passed to `score` if provided. The request is ignored if metadata is not provided.
- `False`: metadata is not requested and the meta-estimator will not pass it to `score`.
- `None`: metadata is not requested, and the meta-estimator will raise an error if the user provides it.
- `str`: metadata should be passed to the meta-estimator with this given alias instead of the original name.

The default (`sklearn.utils.metadata_routing.UNCHANGED`) retains the
existing request. This allows you to change the request for some
parameters and not others.

#### Versionadded
Added in version 1.3.

* **Parameters:**
  **sample_weight** ([`Union`](https://docs.python.org/3/library/typing.html#typing.Union)[[`bool`](https://docs.python.org/3/builtins/functions.html#bool), [`None`](https://docs.python.org/3/builtins/constants.html#None), [`str`](https://docs.python.org/3/builtins/stdtypes.html#str)]) – Metadata routing for `sample_weight` parameter in `score`.
* **Returns:**
  **self** – The updated object.
* **Return type:**
  [`OrdinalRandomForest`](_autosummary/mood.mood_modeling.html.md#mood.mood_modeling.OrdinalRandomForest)

### mood.mood_modeling.class_to_path(obj)

Convert an object to a string path.
This is useful for serialization and deserialization of objects.

```pycon
>>> from sklearn.linear_model import LogisticRegression
>>> path = class_to_path(LogisticRegression)
>>> path
'sklearn.linear_model._logistic.LogisticRegression'
>>> path_to_class(path) == LogisticRegression
True
```

### mood.mood_modeling.path_to_class(path)

Convert a string path to an object.

### mood.mood_modeling.x_and_y_with_boolean_y(data, x_col, y_col, y_is_true_vals, y_is_false_vals=None)

Get the x and y values from a dataframe, converting y to binary values.
The output y elements will be 1 if and only if the y_col value is in y_is_true_vals.

* **Parameters:**
  * **data** (`DataFrame`) – The dataframe to get the x and y values from
  * **x_col** ([`str`](https://docs.python.org/3/builtins/stdtypes.html#str)) – The name of the column to use as x
  * **y_col** ([`str`](https://docs.python.org/3/builtins/stdtypes.html#str)) – The name of the column to use as y
  * **y_is_true_vals** ([`list`](https://docs.python.org/3/builtins/stdtypes.html#list) | [`str`](https://docs.python.org/3/builtins/stdtypes.html#str)) – The values in y_col that are considered 1
  * **y_is_false_vals** ([`list`](https://docs.python.org/3/builtins/stdtypes.html#list) | [`str`](https://docs.python.org/3/builtins/stdtypes.html#str) | [`None`](https://docs.python.org/3/builtins/constants.html#None)) – The values in y_col that are considered 0 (optional)
* **Return type:**
  [`tuple`](https://docs.python.org/3/builtins/stdtypes.html#tuple)[`ndarray`, `ndarray`]
* **Returns:**
  Tuple of (X, y) where X contains features and y contains binary labels


# _autosummary/mood.scripts.financial_news_searches.html.md

# mood.scripts.financial_news_searches

A script that searches for news and saves the results to a file.

Meant to be used in a cron on a server to periodically search for news.

### Functions

| [`main`](_autosummary/mood.scripts.financial_news_searches.html.md#mood.scripts.financial_news_searches.main)([argv])   | Parse `argv` (default: `sys.argv[1:]`) and run the search.   |
|-----------------------------------------------------------------|--------------------------------------------------------------|

### mood.scripts.financial_news_searches.main(argv=None)

Parse `argv` (default: `sys.argv[1:]`) and run the search.


# _autosummary/mood.scripts.html.md

# mood.scripts

Scripts for mood.

### Modules

| [`financial_news_searches`](_autosummary/mood.scripts.financial_news_searches.html.md#module-mood.scripts.financial_news_searches)   | A script that searches for news and saves the results to a file.   |
|------------------------------------------------------------------------------------------------------------------------|--------------------------------------------------------------------|


# _autosummary/mood.sentiment.html.md

# mood.sentiment

Sentiment analysis tools

### Functions

| [`flair_sentiment_score`](_autosummary/mood.sentiment.html.md#mood.sentiment.flair_sentiment_score)(text[, model])         | Analyzes the sentiment of the input text using Flair's pre-trained sentiment model.   |
|-----------------------------------------------------------------------------------------------|---------------------------------------------------------------------------------------|
| [`sentiment_analysis`](_autosummary/mood.sentiment.html.md#mood.sentiment.sentiment_analysis)(headlines, \*[, analyze]) | Score the sentiment of financial-news headlines.                                      |

### mood.sentiment.flair_sentiment_score(text, model='en-sentiment')

Analyzes the sentiment of the input text using Flair’s pre-trained sentiment model.

This function returns a sentiment score as a float:

> - Positive sentiment is returned as a positive value.
> - Negative sentiment is returned as a negative value.

### Example

Input: “I absolutely love this product!”
Output: 0.99 (approximately, for a strong positive sentiment)

* **Parameters:**
  **text** ([`str`](https://docs.python.org/3/builtins/stdtypes.html#str)) – The input string to analyze.
* **Return type:**
  [`float`](https://docs.python.org/3/builtins/functions.html#float)
* **Returns:**
  Sentiment score (positive for positive sentiment, negative for negative sentiment).

### mood.sentiment.sentiment_analysis(headlines, , analyze=None)

Score the sentiment of financial-news headlines.

`headlines` is a single string or an iterable of headline strings. Returns a
`{headline: score}` mapping where each score is an integer in `[-9, 9]`.

`analyze` is an injectable `headlines_str -> dict` callable; when omitted it
is built lazily on `aix` (so importing this module stays offline).


# _autosummary/mood.tools.html.md

# mood.tools

Tools for sentiment analysis

### Functions

| `current_time_str`([format])                   |    |
|------------------------------------------------|----|
| `get_key`(query[, prefix, suffix, day_folder]) |    |
| `mk_filename_safe`(string)                     |    |
| `search_and_save_news`([query, source, ...])   |    |


# _autosummary/mood.util.html.md

# mood.util

Utils for mood

### Functions

| [`add_egress`](_autosummary/mood.util.html.md#mood.util.add_egress)(post)   | Decorator to add an egress to the output of a function.   |
|---------------------------------------------------------------------|-----------------------------------------------------------|

### mood.util.add_egress(post)

Decorator to add an egress to the output of a function.

```pycon
>>> @add_egress(str)
... def foo(x: int) -> int:
...     return x + 1
>>> foo(3)
'4'
```

Note that if you need to access the underlying wrapped function, you can do so in
the python-standard way:

```pycon
>>> underlying_foo = foo.__wrapped__
>>> underlying_foo(3)
4
```


# about-this-build.html.md

<!-- generated by epythet -->

# About this build

This documentation was built on **2026-11-22 21:29 UTC** from commit <a href="https://github.com/thorwhalen/mood/commit/7e8623cfd486070ab7e10dfde42cfc615bd966b8"><code>7e8623c</code></a> on branch <code>main</code>, for **mood 0.0.19** (from <code>pyproject.toml</code>).

#### NOTE
Nothing suggests a mismatch: the tree was clean at the commit above, and the documented version is the one on PyPI.

## Source

|                     |                                                                                                                                                        |
|---------------------|--------------------------------------------------------------------------------------------------------------------------------------------------------|
| Commit              | <a href="https://github.com/thorwhalen/mood/commit/7e8623cfd486070ab7e10dfde42cfc615bd966b8"><code>7e8623cfd486070ab7e10dfde42cfc615bd966b8</code></a> |
| Branch              | <code>main</code>                                                                                                                                      |
| Tags at this commit | <code>0.0.19</code>                                                                                                                                    |
| Working tree        | clean                                                                                                                                                  |
| Remote              | <code>https://github.com/thorwhalen/mood</code>                                                                                                        |

## Continuous integration

|              |                                                                                            |
|--------------|--------------------------------------------------------------------------------------------|
| Repository   | <code>thorwhalen/mood</code>                                                               |
| Run          | <a href="https://github.com/thorwhalen/mood/actions/runs/45072048028">45072048028</a>      |
| Ref          | <code>refs/heads/main</code>                                                               |
| Event commit | <code>a76e215efb8459e5a41ea6de65ccde30b0d67de1</code> (in the history of the built commit) |

## Tools

|          |         |
|----------|---------|
| epythet  | 0.2.23  |
| Sphinx   | 9.1.1   |
| docutils | 0.22.4  |
| Python   | 3.12.16 |

## Configuration as resolved

|               |                                                                  |
|---------------|------------------------------------------------------------------|
| theme         | <code>auto</code> (Sphinx theme <code>furo</code>)               |
| accent        | <code>#923144</code>                                             |
| api_generator | <code>autosummary</code>                                         |
| ignore        | <code>tests/</code>, <code>scrap/</code>, <code>examples/</code> |
| agent_outputs | <code>true</code>                                                |
| aggregates    | <code>md</code>                                                  |
| ai_artifacts  | <code>true</code>                                                |

## Package on PyPI

Latest release: <a href="https://pypi.org/project/mood/0.0.19/">0.0.19</a>, the same as the documented version.

## Reproduce

```bash
git clone https://github.com/thorwhalen/mood && cd mood
git checkout 7e8623cfd486070ab7e10dfde42cfc615bd966b8
pip install "epythet==0.2.23"
epythet quickstart . --ignore tests/ scrap/ examples/
```

The same data, for machines: <a href="build_info.json"><code>build_info.json</code></a> (schema version 1).


# api.html.md

# API reference

| [`mood`](_autosummary/mood.html.md#module-mood)   | Sentiment analysis for stock market data.   |
|---------------------------------------------------------------------|---------------------------------------------|


