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

Add Fisher Transform indicator #49

Merged
merged 2 commits into from
Nov 8, 2024
Merged

Add Fisher Transform indicator #49

merged 2 commits into from
Nov 8, 2024

Conversation

mihakralj
Copy link
Owner

@mihakralj mihakralj commented Nov 8, 2024


For more details, open the Copilot Workspace session.

Summary by CodeRabbit

  • New Features
    • Introduced the Fisher Transform oscillator for financial analysis.
  • Tests
    • Added a new test method Fisher_Update to validate the functionality of the Fisher indicator.
  • Documentation
    • Updated the oscillator list to reflect the completion of the Fisher Transform, increasing the total count of completed oscillators to 22.

Copy link

coderabbitai bot commented Nov 8, 2024

Important

Review skipped

Auto reviews are disabled on base/target branches other than the default branch.

Please check the settings in the CodeRabbit UI or the .coderabbit.yaml file in this repository. To trigger a single review, invoke the @coderabbitai review command.

You can disable this status message by setting the reviews.review_status to false in the CodeRabbit configuration file.

Walkthrough

This pull request introduces a new Fisher class for calculating the Fisher Transform, a financial indicator, along with a corresponding test method Fisher_Update in the OscillatorsUpdateTests class. The Fisher class includes methods for managing state and performing calculations based on price data. Additionally, the oscillator list has been updated to reflect the completion of the Fisher Transform, increasing the total count of completed oscillators.

Changes

File Change Summary
lib/oscillators/Fisher.cs Added Fisher class with methods for calculation, state management, and price normalization.
Tests/test_updates_oscillators.cs Introduced Fisher_Update test method to validate the functionality of the Fisher indicator.
lib/oscillators/_list.md Updated the oscillator list to reflect the completion of the Fisher Transform.

Possibly related PRs

Poem

🐰 In the land of code where oscillators play,
A new Fisher joins, brightening the day.
With updates and tests, it dances with glee,
Calculating values, as smooth as can be.
Checkmarks abound, our list grows so fine,
Hooray for the Fisher, a true friend of mine! 🎉


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

📜 Review details

Configuration used: CodeRabbit UI
Review profile: ASSERTIVE

📥 Commits

Reviewing files that changed from the base of the PR and between a3c6133 and 708c11e.

📒 Files selected for processing (3)
  • Tests/test_updates_oscillators.cs (1 hunks)
  • lib/oscillators/Fisher.cs (1 hunks)
  • lib/oscillators/_list.md (2 hunks)
🧰 Additional context used
🪛 GitHub Check: CodeQL
lib/oscillators/Fisher.cs

[warning] 34-34:
The field 'Fisher._prevValue' is never used


[warning] 34-34:
The field 'Fisher._prevValue' is never used


[warning] 34-34:
The field 'Fisher._prevValue' is never used


[warning] 34-34:
The field 'Fisher._prevValue' is never used


[warning] 34-34:
The field 'Fisher._prevValue' is never used


[warning] 34-34:
The field 'Fisher._prevValue' is never used


[warning] 34-34:
The field 'Fisher._prevValue' is never used


[warning] 34-34:
The field 'Fisher._prevValue' is never used

🪛 GitHub Check: CodeFactor
lib/oscillators/Fisher.cs

[notice] 66-66: lib/oscillators/Fisher.cs#L66
Arithmetic expressions should declare precedence. (SA1407)

🪛 LanguageTool
lib/oscillators/_list.md

[grammar] ~2-~2: It appears that a hyphen is missing in the noun “To-do” (= task) or did you mean the verb “to do”?
Context: # Oscillators indicators Done: 22, Todo: 7 ✔️ AC - Acceleration Oscillator ✔️ ...

(TO_DO_HYPHEN)

🔇 Additional comments (2)
lib/oscillators/_list.md (1)

18-18: LGTM! Fisher Transform status correctly updated.

The checkmark for Fisher Transform has been added, maintaining alphabetical order in the list. This matches the PR objective of implementing the Fisher Transform indicator.

Let's verify the implementation matches this status update:

✅ Verification successful

Fisher Transform implementation is complete and properly tested

The implementation matches the status update in _list.md. The code includes:

  • A complete Fisher Transform implementation in lib/oscillators/Fisher.cs with proper documentation and formula
  • A corresponding test case in Tests/test_updates_oscillators.cs that verifies the indicator's behavior
  • The implementation follows the same pattern as other oscillators in the codebase
  • The test case validates both initial calculation and updates with random data
🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Description: Verify Fisher Transform implementation exists
# Expected: Find Fisher.cs implementation and corresponding test file

# Check for Fisher implementation
fd -e cs Fisher lib/oscillators

# Check for Fisher tests
fd -e cs test.*oscillators Tests

Length of output: 130


Script:

#!/bin/bash
# Let's verify the actual implementation of Fisher Transform
cat lib/oscillators/Fisher.cs

# And check the test file content
cat Tests/test_updates_oscillators.cs

Length of output: 14033

Tests/test_updates_oscillators.cs (1)

328-329: Verify input type and period value for Fisher Transform.

The test uses TValue input type and period=10. Let's verify these choices:

✅ Verification successful

Fisher Transform implementation and test parameters are appropriate

The verification confirms that:

  • The Fisher Transform implementation accepts a default period of 10, which matches the test's usage
  • The indicator properly works with TValue input type as it inherits from AbstractBase
  • The period=10 choice aligns with common practice for this indicator, as mentioned in the implementation's documentation
🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Check Fisher Transform implementation details
echo "Checking Fisher Transform implementation and common usage..."

# Look for Fisher class definition and constructor
ast-grep --pattern 'class Fisher {
  $$$
  Fisher($period) {
    $$$
  }
  $$$
}'

# Search for documentation about recommended period values
rg -i "fisher.*period|period.*fisher" --type md

Length of output: 264


Script:

#!/bin/bash
# Let's try a broader search for Fisher class implementation
ast-grep --pattern 'class Fisher'

# Search for Fisher class files
fd -e cs -e fs Fisher

# Look for Fisher usage in tests
rg "new Fisher\(" -A 2

Length of output: 17450


Script:

#!/bin/bash
# Let's examine the Fisher class implementation
cat lib/oscillators/Fisher.cs

# Look for other Fisher indicator tests
rg "Fisher" Tests/ -A 5

Length of output: 3570

@@ -1,5 +1,5 @@
# Oscillators indicators
Done: 21, Todo: 8
Done: 22, Todo: 7
Copy link

Choose a reason for hiding this comment

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

🧹 Nitpick (assertive)

Fix formatting in the count summary.

The counts are correctly updated to reflect the Fisher Transform completion. However, there's a minor formatting issue.

-Done: 22, Todo: 7
+Done: 22, To-do: 7
📝 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
Done: 22, Todo: 7
Done: 22, To-do: 7
🧰 Tools
🪛 LanguageTool

[grammar] ~2-~2: It appears that a hyphen is missing in the noun “To-do” (= task) or did you mean the verb “to do”?
Context: # Oscillators indicators Done: 22, Todo: 7 ✔️ AC - Acceleration Oscillator ✔️ ...

(TO_DO_HYPHEN)

Comment on lines +326 to +338
public void Fisher_Update()
{
var indicator = new Fisher(period: 10);
double initialValue = indicator.Calc(new TValue(DateTime.Now, ReferenceValue, IsNew: true));

for (int i = 0; i < RandomUpdates; i++)
{
indicator.Calc(new TValue(DateTime.Now, GetRandomDouble(), IsNew: false));
}
double finalValue = indicator.Calc(new TValue(DateTime.Now, ReferenceValue, IsNew: false));

Assert.Equal(initialValue, finalValue, precision);
}
Copy link

Choose a reason for hiding this comment

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

🧹 Nitpick (assertive)

Add documentation for the Fisher Transform test.

Consider adding a brief XML documentation comment explaining:

  • The purpose of the Fisher Transform indicator
  • Why period=10 was chosen as the test value
  • Expected behavior with the reference value

Example:

/// <summary>
/// Verifies that the Fisher Transform indicator maintains consistency
/// when receiving repeated reference values after random updates.
/// Period of 10 is used as it's the commonly recommended value for this indicator.
/// </summary>
[Fact]
public void Fisher_Update()

Comment on lines +331 to +334
for (int i = 0; i < RandomUpdates; i++)
{
indicator.Calc(new TValue(DateTime.Now, GetRandomDouble(), IsNew: false));
}
Copy link

Choose a reason for hiding this comment

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

🧹 Nitpick (assertive)

Consider adding edge case tests.

While the random update testing is good, consider adding specific test cases for:

  • Extreme values (very high/low)
  • Rapid value changes
  • Constant values

Example addition:

// Test extreme values
indicator.Calc(new TValue(DateTime.Now, double.MaxValue * 0.1, IsNew: false));
indicator.Calc(new TValue(DateTime.Now, -double.MaxValue * 0.1, IsNew: false));

// Test constant values
for (int i = 0; i < 10; i++)
{
    indicator.Calc(new TValue(DateTime.Now, 100.0, IsNew: false));
}

private readonly int _period;
private readonly double[] _prices;
private double _prevFisher;
private double _prevValue;
Copy link

Choose a reason for hiding this comment

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

🧹 Nitpick (assertive)

Remove unused field '_prevValue'

The field _prevValue is declared but never used in the class. Removing it will clean up the code and eliminate unnecessary clutter.

Apply this diff to remove the unused field:

 private readonly int _period;
 private readonly double[] _prices;
-private double _prevValue;
 private double _prevFisher;
📝 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
private double _prevValue;
private readonly int _period;
private readonly double[] _prices;
private double _prevFisher;
🧰 Tools
🪛 GitHub Check: CodeQL

[warning] 34-34:
The field 'Fisher._prevValue' is never used


[warning] 34-34:
The field 'Fisher._prevValue' is never used


[warning] 34-34:
The field 'Fisher._prevValue' is never used


[warning] 34-34:
The field 'Fisher._prevValue' is never used


[warning] 34-34:
The field 'Fisher._prevValue' is never used


[warning] 34-34:
The field 'Fisher._prevValue' is never used


[warning] 34-34:
The field 'Fisher._prevValue' is never used


[warning] 34-34:
The field 'Fisher._prevValue' is never used

[MethodImpl(MethodImplOptions.AggressiveInlining)]
private double NormalizePrice(double price, double min, double max)
{
return 2 * ((price - min) / (max - min) - 0.5);
Copy link

Choose a reason for hiding this comment

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

🧹 Nitpick (assertive)

Clarify arithmetic precedence with additional parentheses

Adding parentheses can make the arithmetic operations clearer and enhance code readability, even if the current expression is technically correct.

Apply this diff to add parentheses for clarity:

 return 2 * ((price - min) / (max - min) - 0.5);
+return 2 * (((price - min) / (max - min)) - 0.5);

Committable suggestion skipped: line range outside the PR's diff.

🧰 Tools
🪛 GitHub Check: CodeFactor

[notice] 66-66: lib/oscillators/Fisher.cs#L66
Arithmetic expressions should declare precedence. (SA1407)


⚠️ Potential issue

Handle potential division by zero when 'max' equals 'min' in 'NormalizePrice'

In the NormalizePrice method, if max equals min, the denominator (max - min) becomes zero, leading to a division by zero error. This situation can occur when all prices in the period are the same.

Apply this diff to handle the scenario where max equals min:

 private double NormalizePrice(double price, double min, double max)
 {
+    var range = max - min;
+    if (range == 0)
+        return 0;
+    else
+        return 2 * ((price - min) / range - 0.5);
-    return 2 * ((price - min) / (max - min) - 0.5);
 }
📝 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
return 2 * ((price - min) / (max - min) - 0.5);
private double NormalizePrice(double price, double min, double max)
{
var range = max - min;
if (range == 0)
return 0;
else
return 2 * ((price - min) / range - 0.5);
}
🧰 Tools
🪛 GitHub Check: CodeFactor

[notice] 66-66: lib/oscillators/Fisher.cs#L66
Arithmetic expressions should declare precedence. (SA1407)

[MethodImpl(MethodImplOptions.AggressiveInlining)]
private double FisherTransform(double value)
{
return 0.5 * System.Math.Log((1 + value) / (1 - value));
Copy link

Choose a reason for hiding this comment

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

⚠️ Potential issue

Prevent division by zero or invalid logarithm in 'FisherTransform'

In the FisherTransform method, if value equals 1 or -1, the denominator (1 - value) becomes zero, and the logarithm function receives an undefined or infinite input. To prevent exceptions, clamp value to be within the open interval (-0.999, 0.999).

Apply this diff to clamp value within a safe range:

 private double FisherTransform(double value)
 {
+    const double limit = 0.999;
+    if (value >= limit) value = limit;
+    if (value <= -limit) value = -limit;
     return 0.5 * System.Math.Log((1 + value) / (1 - value));
 }
📝 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
return 0.5 * System.Math.Log((1 + value) / (1 - value));
const double limit = 0.999;
if (value >= limit) value = limit;
if (value <= -limit) value = -limit;
return 0.5 * System.Math.Log((1 + value) / (1 - value));

@mihakralj mihakralj changed the base branch from main to dev November 8, 2024 03:01
Copy link

sonarqubecloud bot commented Nov 8, 2024

@mihakralj mihakralj merged commit 43380f1 into dev Nov 8, 2024
11 checks passed
@mihakralj mihakralj deleted the add-fisher-transform branch November 8, 2024 03:29
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.

1 participant