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

Derive the %Diff reference price from a less noisy metric #168

Merged

Conversation

karashiiro
Copy link
Member

@karashiiro karashiiro commented Dec 7, 2024

Changes the %Diff reference price to use the median unit price of the last 7 days of sales. This will make it based on the actual selling price and less vulnerable to high-priced listings shifting the value to an unrealistic amount.

This aims to make the %Diff more useful for sellers and purchasers by communicating something about what the useful selling prices are, rather than whatever the current arbitrary listing prices are.

Fixes Universalis-FFXIV/Universalis#1394.

Summary by CodeRabbit

Release Notes

  • New Features

    • Enhanced average price calculations using a new utility function for improved pricing accuracy.
    • Introduced a Quality enum for better categorization of market data.
    • Added new properties to the market data structure for detailed pricing and histogram information.
  • Bug Fixes

    • Streamlined code in various components for better performance and maintainability.
  • Documentation

    • Added comments to clarify the purpose of average total values in the MarketAverages component.

Copy link

coderabbitai bot commented Dec 7, 2024

Warning

There were issues while running some tools. Please review the errors and either fix the tool’s configuration or disable the tool if it’s a critical failure.

🔧 eslint

If the error stems from missing dependencies, add them to the package.json file. For unrecoverable errors (e.g., due to private dependencies), disable the tool in the CodeRabbit configuration.

error next-auth@4.18.7: The engine "node" is incompatible with this module. Expected version "^12.19.0 || ^14.15.0 || ^16.13.0 || ^18.12.0". Got "22.9.0"
error Found incompatible module.

Walkthrough

The changes in this pull request involve updates to several components within the market module, enhancing type safety and simplifying code structure. Key modifications include the introduction of a utility function, calculateReferencePrice, for calculating average prices based on the MarketV2 type. The properties in various interfaces have been updated to reflect more specific types, and new properties have been added to the MarketV2 interface. Additionally, comments have been added to clarify the purpose of certain sections of the code.

Changes

File Path Change Summary
components/Market/MarketAverages/MarketAverages.tsx Added a comment in the MarketAverages component regarding the usefulness of average total values.
components/Market/MarketDataCenter/MarketDataCenter.tsx Updated market property type to MarketV2, refactored average price calculations to use calculateReferencePrice, and removed explicit type annotations.
components/Market/MarketRegion/MarketRegion.tsx Changed dcMarkets property type to Record<string, MarketV2>, updated average price calculations to use calculateReferencePrice, and removed explicit type annotations.
components/Market/MarketWorld/MarketWorld.tsx Updated market property type to MarketV2, introduced nqReferencePrice and hqReferencePrice constants, and modified average price handling.
components/Market/utils.ts Introduced Quality enum and calculateReferencePrice function with overloads, along with additional utility functions for sales data processing.
types/universalis/MarketV2.ts Added new properties to the MarketV2 interface for enhanced pricing and histogram information.

Assessment against linked issues

Objective Addressed Explanation
Change %diff column to use median prices or remove it (#1394)

🐰 In the market where prices sway,
A new function has come to play!
With types so neat and prices clear,
We hop along without a fear.
Average values now hold true,
Thanks to the changes, fresh and new! 🥕


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: 3

🧹 Outside diff range and nitpick comments (3)
components/Market/utils.ts (1)

60-62: Remove the unused 'isDistinctMedianIndex' function

After correcting the median calculation, the isDistinctMedianIndex function is no longer needed.

Apply this diff to remove the unused function:

-function isDistinctMedianIndex(idx: number): boolean {
-  return Math.trunc(idx) === idx;
-}
components/Market/MarketDataCenter/MarketDataCenter.tsx (1)

38-70: Consider refactoring duplicate average calculations

The code for calculating averages of listings and sales is repetitive. Extracting this logic into a helper function can improve maintainability.

Example:

function calculateAverage(values: number[]): number {
  return Math.ceil(values.reduce((sum, val) => sum + val, 0) / values.length) || 0;
}

// Usage:
const hqListingsAveragePpu = calculateAverage(hqListings.map((listing) => listing.pricePerUnit));
components/Market/MarketRegion/MarketRegion.tsx (1)

57-89: Refactor repetitive average calculations

The average calculations for listings and sales are duplicated. Consider creating a utility function to reduce redundancy.

Example:

function calculateAverage(values: number[]): number {
  return Math.ceil(values.reduce((sum, val) => sum + val, 0) / values.length) || 0;
}
📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL

📥 Commits

Reviewing files that changed from the base of the PR and between d9958a7 and 8d1b9f6.

📒 Files selected for processing (6)
  • components/Market/MarketAverages/MarketAverages.tsx (1 hunks)
  • components/Market/MarketDataCenter/MarketDataCenter.tsx (6 hunks)
  • components/Market/MarketRegion/MarketRegion.tsx (6 hunks)
  • components/Market/MarketWorld/MarketWorld.tsx (4 hunks)
  • components/Market/utils.ts (1 hunks)
  • types/universalis/MarketV2.ts (1 hunks)
✅ Files skipped from review due to trivial changes (1)
  • components/Market/MarketAverages/MarketAverages.tsx
🧰 Additional context used
🪛 Biome (1.9.4)
components/Market/utils.ts

[error] 3-6: The enum declaration should not be const

Const enums are not supported by bundlers and are incompatible with the 'isolatedModules' mode. Their use can lead to import inexistent values.
See TypeScript Docs for more details.
Safe fix: Turn the const enum into a regular enum.

(lint/suspicious/noConstEnum)

🔇 Additional comments (12)
types/universalis/MarketV2.ts (1)

35-41: New properties in 'MarketV2' interface are appropriate

The additional properties enhance the data structure with detailed pricing and histogram information. The types are correctly defined.

components/Market/MarketWorld/MarketWorld.tsx (3)

14-15: Type updates and imports improve type safety

Updating the market property to type MarketV2 and importing calculateReferencePrice and Quality enhances type safety and consistency across the codebase.

Also applies to: 20-20


38-39: Correct implementation of reference price calculations

Calculating nqReferencePrice and hqReferencePrice using calculateReferencePrice ensures consistent pricing logic.


55-56: Passing reference prices to tables is appropriate

Using the calculated reference prices in ListingsTable and SalesTable maintains consistency in displaying pricing information.

Also applies to: 70-71

components/Market/MarketDataCenter/MarketDataCenter.tsx (4)

15-16: Updated types and imports enhance code quality

Changing the market type to MarketV2 and importing calculateReferencePrice and Quality improves type safety and aligns with the overall architecture.

Also applies to: 21-21


31-34: Filtering listings and sales logically

The filtering of listings and sales into HQ and NQ categories is clear and efficient.


73-75: Proper use of reference price calculations

Calculating nqReferencePrice and hqReferencePrice enhances the pricing logic with recent sales data.


94-95: Consistent usage of reference prices in tables

Passing the reference prices to ListingsTable and SalesTable ensures accurate %Diff calculations.

Also applies to: 108-109, 126-127, 139-140

components/Market/MarketRegion/MarketRegion.tsx (4)

15-16: Type enhancements improve robustness

Updating dcMarkets to type Record<string, MarketV2> and importing necessary utilities strengthens type safety.

Also applies to: 22-22


50-53: Effective filtering of listings and sales

Separating HQ and NQ listings and sales is efficiently handled.


92-94: Correct implementation of reference price calculations

Using calculateReferencePrice for nqReferencePrice and hqReferencePrice correctly integrates the new pricing logic.


113-114: Consistent application of reference prices

Passing the calculated reference prices to the tables ensures accurate and consistent data display across the application.

Also applies to: 129-130, 149-150, 164-165

components/Market/utils.ts Outdated Show resolved Hide resolved
components/Market/utils.ts Show resolved Hide resolved
components/Market/utils.ts Outdated Show resolved Hide resolved
Changes the %Diff reference price to use the median unit price of the last 7 days
of sales. This will make it based on the actual selling price and less vulnerable to
high-priced listings shifting the value to an unrealistic amount.

This aims to make the %Diff more useful for sellers and purchasers by communicating
something about what the useful selling prices are, rather than whatever the current
arbitrary listing prices are.
@karashiiro karashiiro force-pushed the feat/new-reference-prices branch from 8d1b9f6 to 88efd73 Compare December 7, 2024 02:43
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: 0

🧹 Outside diff range and nitpick comments (2)
components/Market/utils.ts (1)

67-73: Consider adding a constant for milliseconds conversion

While the implementation is correct, readability could be improved by extracting the milliseconds conversion factor.

 const SECONDS_PER_DAY = 86400;
+const MILLISECONDS_PER_SECOND = 1000;
 
 function withinDays(days: number) {
   const maxTimeDiff = days * SECONDS_PER_DAY;
-  const now = Date.now() / 1000;
+  const now = Date.now() / MILLISECONDS_PER_SECOND;
   return function (sale: Sale): boolean {
     return now - sale.timestamp <= maxTimeDiff;
   };
 }
components/Market/MarketRegion/MarketRegion.tsx (1)

92-93: Consider consolidating average price calculations

The component now has two sets of average calculations:

  1. Reference prices using the new median-based calculation
  2. Arithmetic means for listings and sales

Consider using the reference prices consistently throughout the component to reduce complexity and potential confusion.

Also applies to: 113-114, 129-130, 149-150, 164-165

📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL

📥 Commits

Reviewing files that changed from the base of the PR and between 8d1b9f6 and 88efd73.

📒 Files selected for processing (6)
  • components/Market/MarketAverages/MarketAverages.tsx (1 hunks)
  • components/Market/MarketDataCenter/MarketDataCenter.tsx (6 hunks)
  • components/Market/MarketRegion/MarketRegion.tsx (6 hunks)
  • components/Market/MarketWorld/MarketWorld.tsx (4 hunks)
  • components/Market/utils.ts (1 hunks)
  • types/universalis/MarketV2.ts (1 hunks)
🚧 Files skipped from review as they are similar to previous changes (3)
  • components/Market/MarketAverages/MarketAverages.tsx
  • types/universalis/MarketV2.ts
  • components/Market/MarketDataCenter/MarketDataCenter.tsx
🧰 Additional context used
🪛 Biome (1.9.4)
components/Market/utils.ts

[error] 3-6: The enum declaration should not be const

Const enums are not supported by bundlers and are incompatible with the 'isolatedModules' mode. Their use can lead to import inexistent values.
See TypeScript Docs for more details.
Safe fix: Turn the const enum into a regular enum.

(lint/suspicious/noConstEnum)

🔇 Additional comments (7)
components/Market/utils.ts (5)

8-28: LGTM! Well-structured implementation of the new reference price calculation

The function effectively:

  • Uses median of last 7 days of sales as requested in issue #1394
  • Handles both single market and multiple markets through overloads
  • Properly handles empty sales case

30-47: LGTM! Type-safe implementation of sales concatenation

The function effectively handles both single and multiple markets with proper type narrowing and null safety.


49-59: LGTM! Correct implementation of median calculation

The function correctly handles both odd and even-length arrays while maintaining immutability.


75-83: LGTM! Clean implementation of quality filter

The function follows functional programming patterns and has clear, simple logic.


3-6: ⚠️ Potential issue

Convert const enum to regular enum for better compatibility

Using const enum can cause issues with bundlers and is incompatible with the 'isolatedModules' mode.

Apply this diff to fix the issue:

-export const enum Quality {
+export enum Quality {
  NormalQuality,
  HighQuality,
}

Likely invalid or redundant comment.

🧰 Tools
🪛 Biome (1.9.4)

[error] 3-6: The enum declaration should not be const

Const enums are not supported by bundlers and are incompatible with the 'isolatedModules' mode. Their use can lead to import inexistent values.
See TypeScript Docs for more details.
Safe fix: Turn the const enum into a regular enum.

(lint/suspicious/noConstEnum)

components/Market/MarketWorld/MarketWorld.tsx (1)

14-15: LGTM! Proper integration of new reference price calculation

The changes correctly:

  • Improve type safety by using MarketV2 type
  • Calculate reference prices for both quality types
  • Update table components with the new reference prices

Also applies to: 20-20, 38-39, 55-56, 70-71

components/Market/MarketRegion/MarketRegion.tsx (1)

15-16: LGTM! Improved type safety with MarketV2

The changes properly type the market data structures.

Also applies to: 22-22

@karashiiro karashiiro merged commit 09594bb into Universalis-FFXIV:main Dec 7, 2024
2 checks passed
@karashiiro karashiiro deleted the feat/new-reference-prices branch December 7, 2024 04:07
@coderabbitai coderabbitai bot mentioned this pull request Dec 9, 2024
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.

%diff column is virtually useless
1 participant