Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Updating Metaculus models #483

Merged
merged 3 commits into from
Oct 10, 2024
Merged

Updating Metaculus models #483

merged 3 commits into from
Oct 10, 2024

Conversation

kongzii
Copy link
Contributor

@kongzii kongzii commented Oct 9, 2024

Based on https://www.metaculus.com/notebooks/28595/updates-to-metaculus-api/ and my observations from their responses.

Copy link

coderabbitai bot commented Oct 9, 2024

Walkthrough

The changes in this pull request involve significant restructuring of the data_models.py file, including the modification of the QuestionType enum, the introduction of new classes (AggregationItem, Aggregation, Aggregations, and Question), and the removal of several existing classes (CommunityPrediction, Prediction, and UserPredictions). Additionally, the MetaculusQuestion class has been updated to reflect new attributes and property methods. The metaculus.py file also sees updates to the MetaculusAgentMarket class, particularly in the from_data_model method. Lastly, the test suite for AgentMarket has been adjusted for improved functionality.

Changes

File Path Change Summary
prediction_market_agent_tooling/markets/metaculus/data_models.py - Modified QuestionType enum to include only binary.
- Removed CommunityPrediction, Prediction, and UserPredictions classes.
- Added AggregationItem, Aggregation, and Aggregations classes.
- Introduced Question class with references to new classes.
- Updated MetaculusQuestion with new attributes and methods.
prediction_market_agent_tooling/markets/metaculus/metaculus.py - Updated MetaculusAgentMarket class to streamline attribute assignment from MetaculusQuestion.
- Altered logic in from_data_model method for attribute assignments.
tests/markets/test_markets.py - Increased limit in test_get_markets from 10 to 100.
- Corrected indentation in test_get_markets.

Possibly related PRs

  • Add partial Metaculus support #299: The changes in data_models.py related to the QuestionType enum and the introduction of new classes like AggregationItem, Aggregation, and Question are relevant to the modifications made in the same file in this PR, which also deals with data models for Metaculus questions and predictions.
  • Fix Metaculus get_questions api #304: This PR also modifies api.py and data_models.py for Metaculus, specifically updating the get_questions function and introducing a new class MetaculusQuestions, which relates to the overall structure and functionality of the Metaculus data models being altered in the main PR.

Thank you for using CodeRabbit. We offer it for free to the OSS community and would appreciate your support in helping us grow. If you find it useful, would you consider giving us a shout-out on your favorite social media?

❤️ Share
🪧 Tips

Chat

There are 3 ways to chat with CodeRabbit:

  • Review comments: Directly reply to a review comment made by CodeRabbit. Example:
    • I pushed a fix in commit <commit_id>, please review it.
    • Generate unit testing code for this file.
    • Open a follow-up GitHub issue for this discussion.
  • Files and specific lines of code (under the "Files changed" tab): Tag @coderabbitai in a new review comment at the desired location with your query. Examples:
    • @coderabbitai generate unit testing code for this file.
    • @coderabbitai modularize this function.
  • PR comments: Tag @coderabbitai in a new PR comment to ask questions about the PR branch. For the best results, please provide a very specific query, as very limited context is provided in this mode. Examples:
    • @coderabbitai gather interesting stats about this repository and render them as a table. Additionally, render a pie chart showing the language distribution in the codebase.
    • @coderabbitai read src/utils.ts and generate unit testing code.
    • @coderabbitai read the files in the src/scheduler package and generate a class diagram using mermaid and a README in the markdown format.
    • @coderabbitai help me debug CodeRabbit configuration file.

Note: Be mindful of the bot's finite context window. It's strongly recommended to break down tasks such as reading entire modules into smaller chunks. For a focused discussion, use review comments to chat about specific files and their changes, instead of using the PR comments.

CodeRabbit Commands (Invoked using PR comments)

  • @coderabbitai pause to pause the reviews on a PR.
  • @coderabbitai resume to resume the paused reviews.
  • @coderabbitai review to trigger an incremental review. This is useful when automatic reviews are disabled for the repository.
  • @coderabbitai full review to do a full review from scratch and review all the files again.
  • @coderabbitai summary to regenerate the summary of the PR.
  • @coderabbitai resolve resolve all the CodeRabbit review comments.
  • @coderabbitai configuration to show the current CodeRabbit configuration for the repository.
  • @coderabbitai help to get help.

Other keywords and placeholders

  • Add @coderabbitai ignore anywhere in the PR description to prevent this PR from being reviewed.
  • Add @coderabbitai summary to generate the high-level summary at a specific location in the PR description.
  • Add @coderabbitai anywhere in the PR title to generate the title automatically.

CodeRabbit Configuration File (.coderabbit.yaml)

  • You can programmatically configure CodeRabbit by adding a .coderabbit.yaml file to the root of your repository.
  • Please see the configuration documentation for more information.
  • If your editor has YAML language server enabled, you can add the path at the top of this file to enable auto-completion and validation: # yaml-language-server: $schema=https://coderabbit.ai/integrations/schema.v2.json

Documentation and Community

  • Visit our Documentation for detailed information on how to use CodeRabbit.
  • Join our Discord Community to get help, request features, and share feedback.
  • Follow us on X/Twitter for updates and announcements.

Copy link

@coderabbitai coderabbitai bot left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 5

🧹 Outside diff range and nitpick comments (2)
prediction_market_agent_tooling/markets/metaculus/data_models.py (2)

6-6: Organize imports according to PEP 8 guidelines

To enhance code readability and maintainability, organize the import statements following PEP 8 recommendations:

  1. Standard library imports
  2. Related third-party imports
  3. Local application/library-specific imports

Each group should be separated by a blank line.

Suggested reordering:

 from enum import Enum
+from typing import Any, Optional

 from pydantic import BaseModel
+from prediction_market_agent_tooling.tools.utils import DatetimeUTC
+from prediction_market_agent_tooling.gtypes import Probability

-from typing import Any
-from prediction_market_agent_tooling.gtypes import Probability
-from prediction_market_agent_tooling.tools.utils import DatetimeUTC

60-63: Add a docstring to the page_url property

Including a docstring for the page_url property enhances code clarity by explaining the purpose and return value of the method.

Suggested addition:

 @property
 def page_url(self) -> str:
+    """Return the URL of the Metaculus question page."""
     return f"https://www.metaculus.com/questions/{self.id}/"
📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL

📥 Commits

Files that changed from the base of the PR and between 2335bae and 7572fe3.

📒 Files selected for processing (3)
  • prediction_market_agent_tooling/markets/metaculus/data_models.py (1 hunks)
  • prediction_market_agent_tooling/markets/metaculus/metaculus.py (1 hunks)
  • tests/markets/test_markets.py (1 hunks)
🧰 Additional context used
🪛 Ruff
prediction_market_agent_tooling/markets/metaculus/data_models.py

67-67: f-string without any placeholders

Remove extraneous f prefix

(F541)

🔇 Additional comments (1)
tests/markets/test_markets.py (1)

81-81: Increased limit for market retrieval in test case.

The change from 10 to 100 for the limit variable allows for testing with a larger dataset. This can potentially uncover edge cases or issues that might not be apparent with a smaller sample size, which is beneficial for thorough testing.

However, consider the following:

  1. This change might increase the test execution time, especially when run for multiple market types. Ensure that this doesn't significantly impact the overall test suite performance.
  2. It might be worth adding a comment explaining the rationale behind choosing 100 as the new limit.

To ensure this change doesn't significantly impact test execution time, you can run the following script:

This will provide information about the execution time of the test_get_markets function, which you can compare with previous runs to assess the impact of the change.

Comment on lines +40 to +43
current_p_yes=model.p_yes,
created_time=model.created_at,
close_time=model.scheduled_close_time,
url=model.page_url,
Copy link

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

💡 Codebase verification

🛠️ Refactor suggestion

Inconsistent attribute usage with data_models.py

The from_data_model method references attributes (p_yes, scheduled_close_time, page_url, my_forecasts) that are not present in the MetaculusQuestion or Question classes within data_models.py. Please verify these attributes are correctly defined or update the method to align with the existing data models.

🔗 Analysis chain

Verify attribute assignments and update documentation

The changes in the from_data_model method reflect updates to the MetaculusQuestion model structure. Please ensure these modifications maintain the intended functionality:

  1. Confirm that model.p_yes is the correct attribute and doesn't require the Probability wrapper.
  2. Verify that created_at, scheduled_close_time, and page_url are the correct attribute names in the updated MetaculusQuestion model.
  3. Check if the new logic for have_predicted using model.question.my_forecasts.latest is accurate.

Consider adding type hints to improve code clarity:

@staticmethod
def from_data_model(model: MetaculusQuestion) -> "MetaculusAgentMarket":
    return MetaculusAgentMarket(
        id=str(model.id),
        question=model.title,
        outcomes=[],
        resolution=None,
        current_p_yes=model.p_yes,  # type: Probability
        created_time=model.created_at,  # type: DatetimeUTC
        close_time=model.scheduled_close_time,  # type: DatetimeUTC
        url=model.page_url,  # type: str
        volume=None,
        have_predicted=model.question.my_forecasts.latest is not None,  # type: bool
        outcome_token_pool=None,
    )

Update the method's docstring to reflect these changes and explain the new attribute mappings.

To ensure consistency with the data_models.py file, run the following script:

Also applies to: 45-45

🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Description: Verify the attribute names in the MetaculusQuestion model

# Test: Check for the presence of new attribute names
rg --type python 'class MetaculusQuestion.*?:.*?(p_yes|created_at|scheduled_close_time|page_url)' prediction_market_agent_tooling/markets/metaculus/data_models.py

# Test: Check for the presence of my_forecasts attribute
rg --type python 'class Question.*?:.*?my_forecasts' prediction_market_agent_tooling/markets/metaculus/data_models.py

Length of output: 346


Script:

#!/bin/bash
# Description: Verify the attribute names in the MetaculusQuestion model

# Test: Check for the presence of new attribute names in MetaculusQuestion
rg -g "*.py" 'class\s+MetaculusQuestion.*?\n(?:.*\n)*?.*\b(p_yes|created_at|scheduled_close_time|page_url)\b' prediction_market_agent_tooling/markets/metaculus/data_models.py

# Test: Check for the presence of my_forecasts attribute in Question class
rg -g "*.py" 'class\s+Question.*?\n(?:.*\n)*?.*\bmy_forecasts\b' prediction_market_agent_tooling/markets/metaculus/data_models.py

Length of output: 692


Script:

#!/bin/bash
# Description: Verify the attribute names in the MetaculusQuestion model with multiline support

# Test: Check for the presence of new attribute names in MetaculusQuestion
rg -U -g "*.py" 'class\s+MetaculusQuestion.*?\n(?:.*\n)*?.*\b(p_yes|created_at|scheduled_close_time|page_url)\b' prediction_market_agent_tooling/markets/metaculus/data_models.py

# Test: Check for the presence of my_forecasts attribute in Question class
rg -U -g "*.py" 'class\s+Question.*?\n(?:.*\n)*?.*\bmy_forecasts\b' prediction_market_agent_tooling/markets/metaculus/data_models.py

Length of output: 1245

@property
def p_yes(self) -> Probability:
if self.question.type != QuestionType.binary:
raise ValueError(f"Only binary markets can have p_yes.")
Copy link

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

⚠️ Potential issue

Remove unnecessary f prefix in exception message

At line 67, the ValueError is using an f-string without any placeholders. The f prefix is unnecessary and can be removed to clean up the code.

Apply this change:

-                raise ValueError(f"Only binary markets can have p_yes.")
+                raise ValueError("Only binary markets can have p_yes.")
📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
raise ValueError(f"Only binary markets can have p_yes.")
raise ValueError("Only binary markets can have p_yes.")
🧰 Tools
🪛 Ruff

67-67: f-string without any placeholders

Remove extraneous f prefix

(F541)

group = "group"
conditional_group = "conditional_group"
multiple_choice = "multiple_choice"
binary = "binary"
Copy link

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🛠️ Refactor suggestion

Consider simplifying QuestionType Enum with only one member

The QuestionType enum now contains only a single member binary. Enums are typically used to define a set of constant values. If no other question types are expected, it might be more appropriate to replace the enum with a simple constant or a type alias to reduce unnecessary complexity.

Suggested change:

-from enum import Enum
+from typing import Literal

-class QuestionType(str, Enum):
-    binary = "binary"
+QuestionType = Literal["binary"]
📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
binary = "binary"
from typing import Literal
QuestionType = Literal["binary"]

Comment on lines +14 to +23
class AggregationItem(BaseModel):
start_time: DatetimeUTC
end_time: DatetimeUTC | None
forecast_values: list[float] | None
forecaster_count: int
interval_lower_bounds: list[float] | None
centers: list[float] | None
interval_upper_bounds: list[float] | None
means: list[float] | None
histogram: list[float] | None
Copy link

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🛠️ Refactor suggestion

Use Optional from typing for optional type hints

In the AggregationItem class, several fields are annotated with the union syntax | None to indicate that they can be None. For better compatibility with earlier Python versions (prior to 3.10) and to improve readability, consider importing Optional from the typing module.

Apply the following changes:

-from typing import Any
+from typing import Any, Optional

 class AggregationItem(BaseModel):
     start_time: DatetimeUTC
-    end_time: DatetimeUTC | None
-    forecast_values: list[float] | None
+    end_time: Optional[DatetimeUTC]
+    forecast_values: Optional[list[float]]
     forecaster_count: int
-    interval_lower_bounds: list[float] | None
-    centers: list[float] | None
-    interval_upper_bounds: list[float] | None
-    means: list[float] | None
-    histogram: list[float] | None
+    interval_lower_bounds: Optional[list[float]]
+    centers: Optional[list[float]]
+    interval_upper_bounds: Optional[list[float]]
+    means: Optional[list[float]]
+    histogram: Optional[list[float]]
📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
class AggregationItem(BaseModel):
start_time: DatetimeUTC
end_time: DatetimeUTC | None
forecast_values: list[float] | None
forecaster_count: int
interval_lower_bounds: list[float] | None
centers: list[float] | None
interval_upper_bounds: list[float] | None
means: list[float] | None
histogram: list[float] | None
from typing import Any, Optional
class AggregationItem(BaseModel):
start_time: DatetimeUTC
end_time: Optional[DatetimeUTC]
forecast_values: Optional[list[float]]
forecaster_count: int
interval_lower_bounds: Optional[list[float]]
centers: Optional[list[float]]
interval_upper_bounds: Optional[list[float]]
means: Optional[list[float]]
histogram: Optional[list[float]]

Comment on lines +65 to +83
def p_yes(self) -> Probability:
if self.question.type != QuestionType.binary:
raise ValueError(f"Only binary markets can have p_yes.")
if (
self.question.aggregations.recency_weighted is None
or self.question.aggregations.recency_weighted.latest is None
or self.question.aggregations.recency_weighted.latest.forecast_values
is None
):
# If no value is provided (i.e. the question is new and has not been answered yet), we default to 0.5.
return Probability(0.5)
if len(self.question.aggregations.recency_weighted.latest.forecast_values) != 2:
raise ValueError(
f"Invalid logic, assumed that binary markets will have two forecasts, got: {self.question.aggregations.recency_weighted.latest.forecast_values}"
)
# Experimentally figured out that they store "Yes" at index 1.
return Probability(
self.question.aggregations.recency_weighted.latest.forecast_values[1]
)
Copy link

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🛠️ Refactor suggestion

Handle non-binary question types gracefully in p_yes property

Currently, the p_yes property raises a ValueError if the question type is not binary. To make the property safer and more user-friendly, consider returning None or a default value when the question type is not binary. This avoids exceptions and allows calling code to handle non-binary questions appropriately.

Suggested refactor:

 def p_yes(self) -> Probability | None:
-    if self.question.type != QuestionType.binary:
-        raise ValueError("Only binary markets can have p_yes.")
+    if self.question.type != QuestionType.binary:
+        return None
     if (
         self.question.aggregations.recency_weighted is None

Additionally, update the return type annotation to reflect that None can be returned:

-    def p_yes(self) -> Probability:
+    def p_yes(self) -> Probability | None:
📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
def p_yes(self) -> Probability:
if self.question.type != QuestionType.binary:
raise ValueError(f"Only binary markets can have p_yes.")
if (
self.question.aggregations.recency_weighted is None
or self.question.aggregations.recency_weighted.latest is None
or self.question.aggregations.recency_weighted.latest.forecast_values
is None
):
# If no value is provided (i.e. the question is new and has not been answered yet), we default to 0.5.
return Probability(0.5)
if len(self.question.aggregations.recency_weighted.latest.forecast_values) != 2:
raise ValueError(
f"Invalid logic, assumed that binary markets will have two forecasts, got: {self.question.aggregations.recency_weighted.latest.forecast_values}"
)
# Experimentally figured out that they store "Yes" at index 1.
return Probability(
self.question.aggregations.recency_weighted.latest.forecast_values[1]
)
def p_yes(self) -> Probability | None:
if self.question.type != QuestionType.binary:
return None
if (
self.question.aggregations.recency_weighted is None
or self.question.aggregations.recency_weighted.latest is None
or self.question.aggregations.recency_weighted.latest.forecast_values
is None
):
# If no value is provided (i.e. the question is new and has not been answered yet), we default to 0.5.
return Probability(0.5)
if len(self.question.aggregations.recency_weighted.latest.forecast_values) != 2:
raise ValueError(
f"Invalid logic, assumed that binary markets will have two forecasts, got: {self.question.aggregations.recency_weighted.latest.forecast_values}"
)
# Experimentally figured out that they store "Yes" at index 1.
return Probability(
self.question.aggregations.recency_weighted.latest.forecast_values[1]
)
🧰 Tools
🪛 Ruff

67-67: f-string without any placeholders

Remove extraneous f prefix

(F541)

Copy link

@coderabbitai coderabbitai bot left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 1

📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL

📥 Commits

Files that changed from the base of the PR and between 7572fe3 and 436c9f0.

📒 Files selected for processing (1)
  • prediction_market_agent_tooling/markets/metaculus/data_models.py (1 hunks)
🧰 Additional context used
🪛 Ruff
prediction_market_agent_tooling/markets/metaculus/data_models.py

82-82: f-string without any placeholders

Remove extraneous f prefix

(F541)

Comment on lines +81 to +98
if self.question.type != QuestionType.binary:
raise ValueError(f"Only binary markets can have p_yes.")
if (
self.question.aggregations.recency_weighted is None
or self.question.aggregations.recency_weighted.latest is None
or self.question.aggregations.recency_weighted.latest.forecast_values
is None
):
# If no value is provided (i.e. the question is new and has not been answered yet), we default to 0.5.
return Probability(0.5)
if len(self.question.aggregations.recency_weighted.latest.forecast_values) != 2:
raise ValueError(
f"Invalid logic, assumed that binary markets will have two forecasts, got: {self.question.aggregations.recency_weighted.latest.forecast_values}"
)
# Experimentally figured out that they store "Yes" at index 1.
return Probability(
self.question.aggregations.recency_weighted.latest.forecast_values[1]
)
Copy link

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🛠️ Refactor suggestion

Consider making the p_yes property more robust to data format changes

In the p_yes property, the index 1 is hardcoded with the assumption that "Yes" is stored at that position in forecast_values. This reliance on a specific index may lead to errors if Metaculus changes their data format in the future. To improve robustness, consider identifying the correct index dynamically or using a key-value mapping if available.

🧰 Tools
🪛 Ruff

82-82: f-string without any placeholders

Remove extraneous f prefix

(F541)

raise ValueError(
f"Invalid logic, assumed that binary markets will have two forecasts, got: {self.question.aggregations.recency_weighted.latest.forecast_values}"
)
# Experimentally figured out that they store "Yes" at index 1.
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

😱 why so complicated metaculuuuuuus!!

@kongzii kongzii merged commit 245826f into main Oct 10, 2024
14 checks passed
@kongzii kongzii deleted the peter/metaculus branch October 10, 2024 08:16
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

Successfully merging this pull request may close these issues.

2 participants