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

Volume Weighted Average Price Strategy added. #239

Merged
merged 1 commit into from
Oct 19, 2024

Conversation

cinar
Copy link
Owner

@cinar cinar commented Oct 19, 2024

Describe Request

Volume Weighted Average Price Strategy added.

Change Type

New strategy.

Summary by CodeRabbit

Release Notes

  • New Features

    • Introduced the VolumeWeightedAveragePriceStrategy, allowing users to make trading decisions based on the Volume Weighted Average Price (VWAP).
    • Enhanced documentation with updated installation and usage instructions, including dedicated test data in CSV format.
    • Added backtesting functionality for evaluating strategy performance against defined asset sets.
  • Bug Fixes

    • Corrected the link format for the Volume Weighted Average Price Strategy.
  • Documentation

    • Comprehensive updates to the README, reflecting version 2 enhancements and clarifying licensing information.
  • Tests

    • Implemented unit tests for the new VWAP strategy to ensure accuracy in computations and reporting.

Copy link

coderabbitai bot commented Oct 19, 2024

Walkthrough

The pull request introduces significant updates to the Indicator Go module, particularly in the README.md and the volume strategy implementations. The README now details version 2 features, including a complete codebase rewrite for improved test coverage, enhanced data handling via Go channels, and the introduction of a new VolumeWeightedAveragePriceStrategy. This strategy includes various methods for operation and reporting. Additionally, the backtesting functionality is emphasized, and licensing information is clarified. New unit tests for the volume strategy are also included to ensure functionality.

Changes

File Path Change Summary
README.md Updated to reflect version 2 features, including code coverage, data handling via channels, new TypeScript version, and backtesting functionality.
strategy/volume/README.md Introduced VolumeWeightedAveragePriceStrategy with associated methods documented, detailing configuration and behavior.
strategy/volume/volume.go Added NewVolumeWeightedAveragePriceStrategy() to AllStrategies, expanding available strategies.
strategy/volume/volume_weighted_average_price_strategy.go Introduced VolumeWeightedAveragePriceStrategy struct with methods for initialization, computation, and reporting.
strategy/volume/volume_weighted_average_price_strategy_test.go Added unit tests for VolumeWeightedAveragePriceStrategy, validating computation and report generation.

Possibly related PRs

🐰 In the garden of code, we hop and play,
With strategies new, we brighten the day.
Volume's weighted, actions clear,
In tests we trust, no room for fear.
So let’s celebrate with a joyful cheer,
For version two brings us all near! 🌼


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.

@codecov-commenter
Copy link

Codecov Report

Attention: Patch coverage is 97.33333% with 2 lines in your changes missing coverage. Please review.

Project coverage is 93.46%. Comparing base (0ea963f) to head (a9983c5).

Files with missing lines Patch % Lines
strategy/volume/volume.go 0.00% 1 Missing ⚠️
...y/volume/volume_weighted_average_price_strategy.go 98.64% 1 Missing ⚠️
Additional details and impacted files
@@            Coverage Diff             @@
##           master     #239      +/-   ##
==========================================
+ Coverage   93.41%   93.46%   +0.04%     
==========================================
  Files         170      171       +1     
  Lines        5922     5997      +75     
==========================================
+ Hits         5532     5605      +73     
- Misses        331      333       +2     
  Partials       59       59              

☔ View full report in Codecov by Sentry.
📢 Have feedback on the report? Share it here.

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 (5)
strategy/volume/volume_weighted_average_price_strategy_test.go (1)

17-37: LGTM with suggestion: Well-structured test for VolumeWeightedAveragePriceStrategy.

The test function is well-structured and follows good practices for Go unit tests. It properly handles errors and uses helper functions for reading CSV files and comparing results.

Suggestion for improvement:

Consider adding more specific error messages to the t.Fatal calls. This will make debugging easier if the test fails. For example:

if err != nil {
    t.Fatalf("Failed to read snapshots from CSV: %v", err)
}
README.md (1)

145-145: VWAP Strategy added successfully, minor formatting suggestion

The addition of the Volume Weighted Average Price Strategy aligns perfectly with the PR objectives. Great job on including this new strategy!

However, there's a minor formatting inconsistency:

Consider replacing the hard tab at the beginning of the line with spaces to maintain consistency with the rest of the file. This will improve readability and adhere to common Markdown formatting practices.

🧰 Tools
🪛 Markdownlint

145-145: Column: 2
Hard tabs

(MD010, no-hard-tabs)

strategy/volume/README.md (1)

330-340: Minor improvement for consistency

The documentation for VolumeWeightedAveragePriceStrategy is well-written and follows the existing style. However, for consistency with other strategy descriptions, consider adding "It" at the beginning of the recommendation sentences.

Here's a suggested revision:

-VolumeWeightedAveragePriceStrategy represents the configuration parameters for calculating the Volume Weighted Average Price strategy. Recommends a Buy action when the closing crosses below the VWAP, recommends a Sell action when the closing crosses above the VWAP, and recommends a Hold action otherwise.
+VolumeWeightedAveragePriceStrategy represents the configuration parameters for calculating the Volume Weighted Average Price strategy. It recommends a Buy action when the closing crosses below the VWAP, recommends a Sell action when the closing crosses above the VWAP, and recommends a Hold action otherwise.
strategy/volume/volume_weighted_average_price_strategy.go (2)

16-18: Clarify the strategy description in the comments

Consider rephrasing the strategy description for better clarity. For example:

"VolumeWeightedAveragePriceStrategy represents the configuration parameters for calculating the Volume Weighted Average Price strategy. It recommends a Buy action when the closing price crosses below the VWAP, a Sell action when the closing price crosses above the VWAP, and a Hold action otherwise."


59-69: Handle equal values explicitly in action determination

Currently, when vwap equals closing, the strategy returns Hold by default. For clarity, consider handling this case explicitly in the code.

Apply this diff:

actions := helper.Operate(closingsSplice[0], vwaps, func(closing, vwap float64) strategy.Action {
    if vwap > closing {
        return strategy.Buy
    } else if vwap < closing {
        return strategy.Sell
+   } else {
+       return strategy.Hold
    }
-   }
-   return strategy.Hold
})
📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL

📥 Commits

Files that changed from the base of the PR and between 0ea963f and a9983c5.

⛔ Files ignored due to path filters (1)
  • strategy/volume/testdata/volume_weighted_average_price_strategy.csv is excluded by !**/*.csv
📒 Files selected for processing (5)
  • README.md (1 hunks)
  • strategy/volume/README.md (2 hunks)
  • strategy/volume/volume.go (1 hunks)
  • strategy/volume/volume_weighted_average_price_strategy.go (1 hunks)
  • strategy/volume/volume_weighted_average_price_strategy_test.go (1 hunks)
🧰 Additional context used
🪛 Markdownlint
README.md

145-145: Column: 2
Hard tabs

(MD010, no-hard-tabs)

🔇 Additional comments (11)
strategy/volume/volume.go (1)

32-32: LGTM! New VWAP strategy successfully added.

The addition of NewVolumeWeightedAveragePriceStrategy() to the AllStrategies() function aligns well with the PR objectives of introducing a new Volume Weighted Average Price (VWAP) strategy. This change is consistent with the existing code structure and follows the pattern established for other volume strategies.

A few points to consider:

  1. Ensure that the NewVolumeWeightedAveragePriceStrategy() function is implemented in this package.
  2. Update any relevant documentation or README files to reflect this new strategy.
  3. Add unit tests for this new strategy if not already done.

To verify the implementation and documentation:

✅ Verification successful

Verification Successful

The implementation of NewVolumeWeightedAveragePriceStrategy() is present in the codebase. The README documentation has been updated accordingly, and relevant unit tests have been added to ensure the strategy functions as expected.

🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Verify the implementation of NewVolumeWeightedAveragePriceStrategy
ast-grep --lang go --pattern 'func NewVolumeWeightedAveragePriceStrategy() $_'

# Check for updates in README or documentation
rg -i "volume weighted average price|vwap" README.md

# Look for new test files or functions
fd -e go test_.*volume.*weighted.*average.*price
rg -t go "func Test.*VolumeWeightedAveragePrice"

Length of output: 1142

strategy/volume/volume_weighted_average_price_strategy_test.go (3)

1-5: LGTM: Proper file header and package declaration.

The file header includes appropriate copyright and license information. The package declaration follows Go conventions for test files.


7-15: LGTM: Appropriate import statements.

The import statements include all necessary packages for the tests, both from the standard library and the project's custom packages. The use of versioned imports (v2) is consistent with the project structure.


1-55: Overall assessment: Well-implemented test file with room for minor improvements.

This test file for the VolumeWeightedAveragePriceStrategy is well-structured and covers the main functionality of the strategy. It follows good Go testing practices and uses appropriate helper functions.

The suggested improvements, if implemented, would enhance error reporting, test coverage, and test isolation. These changes would make the tests more robust and easier to maintain in the long run.

Great job on implementing these tests! They will help ensure the reliability of the VolumeWeightedAveragePriceStrategy as the project evolves.

README.md (2)

Line range hint 1-290: Excellent documentation structure and content!

The README is well-organized and provides comprehensive information about the Indicator Go module. It effectively communicates the new features and improvements in version 2, aligning well with the PR objectives. The clear sections for indicators, strategies, repositories, backtesting, usage, contributing, and licensing make it easy for users to navigate and understand the module's capabilities.

🧰 Tools
🪛 Markdownlint

147-147: Expected: setext; Actual: atx
Heading style

(MD003, heading-style)


142-142: Column: 2
Hard tabs

(MD010, no-hard-tabs)


143-143: Column: 2
Hard tabs

(MD010, no-hard-tabs)


144-144: Column: 2
Hard tabs

(MD010, no-hard-tabs)


145-145: Column: 2
Hard tabs

(MD010, no-hard-tabs)


Line range hint 1-290: Excellent README update, minor formatting adjustment needed

The README has been comprehensively updated to reflect the new features and improvements in version 2 of the Indicator Go module. The addition of the Volume Weighted Average Price Strategy is well-documented and aligns perfectly with the PR objectives.

The overall structure and content of the README are excellent, providing clear and valuable information for users and potential contributors. The only improvement needed is a minor formatting adjustment on line 145 to replace the hard tab with spaces for consistency.

Great job on this update! Once the minor formatting issue is addressed, this README will serve as an excellent introduction and reference for the Indicator Go module.

🧰 Tools
🪛 Markdownlint

147-147: Expected: setext; Actual: atx
Heading style

(MD003, heading-style)


142-142: Column: 2
Hard tabs

(MD010, no-hard-tabs)


143-143: Column: 2
Hard tabs

(MD010, no-hard-tabs)


144-144: Column: 2
Hard tabs

(MD010, no-hard-tabs)


145-145: Column: 2
Hard tabs

(MD010, no-hard-tabs)

strategy/volume/README.md (3)

53-58: LGTM: VolumeWeightedAveragePriceStrategy added to index

The new VolumeWeightedAveragePriceStrategy has been correctly added to the index, following the existing pattern and providing appropriate links to its sections.


342-385: LGTM: Method documentation for VolumeWeightedAveragePriceStrategy

The method documentation for VolumeWeightedAveragePriceStrategy is well-written and consistent with the existing documentation style. It provides clear explanations for each method, including NewVolumeWeightedAveragePriceStrategy, NewVolumeWeightedAveragePriceStrategyWith, Compute, Name, and Report.


Line range hint 53-385: Summary: VolumeWeightedAveragePriceStrategy documentation

The addition of the VolumeWeightedAveragePriceStrategy to the README.md file is well-executed. The new strategy is properly indexed, and its documentation follows the established pattern for other strategies in the volume package. The explanations are clear and concise, providing users with a good understanding of the strategy's purpose and behavior.

A minor suggestion was made to improve consistency in the main description, but overall, the documentation is of high quality and integrates seamlessly with the existing content.

strategy/volume/volume_weighted_average_price_strategy.go (2)

24-30: Ensure the default period is appropriate

In the NewVolumeWeightedAveragePriceStrategy function, confirm that volume.DefaultVwapPeriod is the desired default period for this strategy. If a different default is more appropriate for your use case, consider updating it.


77-118: Confirm the synchronization of channels in the Report method

The Report method involves multiple channel duplications and skips. Ensure that all channels are properly synchronized to prevent any potential deadlocks or synchronization issues.

Comment on lines +39 to +55
func TestVolumeWeightedAveragePriceStrategyReport(t *testing.T) {
snapshots, err := helper.ReadFromCsvFile[asset.Snapshot]("testdata/brk-b.csv", true)
if err != nil {
t.Fatal(err)
}

vwaps := volume.NewVolumeWeightedAveragePriceStrategy()
report := vwaps.Report(snapshots)

fileName := "volume_weighted_average_price_strategy.html"
defer os.Remove(fileName)

err = report.WriteToFile(fileName)
if err != nil {
t.Fatal(err)
}
}
Copy link

Choose a reason for hiding this comment

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

🛠️ Refactor suggestion

LGTM with suggestions: Good test for VolumeWeightedAveragePriceStrategy report generation.

The test function is well-structured and follows good practices for Go unit tests. It properly handles errors and uses defer for file cleanup.

Suggestions for improvement:

  1. Consider adding more specific error messages to the t.Fatal calls, as suggested in the previous comment.

  2. The test currently only checks if the report can be written without errors. Consider adding some basic validation of the generated HTML file contents. For example:

content, err := os.ReadFile(fileName)
if err != nil {
    t.Fatalf("Failed to read generated report: %v", err)
}
if !strings.Contains(string(content), "Volume Weighted Average Price Strategy") {
    t.Error("Generated report does not contain expected content")
}
  1. To improve test isolation and avoid potential conflicts in parallel test execution, consider using t.TempDir() to create a temporary directory for the output file:
tempDir := t.TempDir()
fileName := filepath.Join(tempDir, "volume_weighted_average_price_strategy.html")

This approach eliminates the need for manual cleanup with defer os.Remove(fileName).

@@ -142,7 +142,7 @@ The following list of strategies are currently supported by this package:
- [Force Index Strategy](strategy/volume/README.md#type-forceindexstrategy)
- [Money Flow Index Strategy](strategy/volume/README.md#type-moneyflowindexstrategy)
- [Negative Volume Index Strategy](strategy/volume/README.md#type-negativevolumeindexstrategy)
- Volume Weighted Average Price Strategy
- [Volume Weighted Average Price Strategy](strategy/volume/README.md#type-volumeweightedaveragepricestrategy)
Copy link

Choose a reason for hiding this comment

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

⚠️ Potential issue

Replace hard tab with spaces (Markdownlint: MD010)

To address the Markdownlint warning and improve consistency:

Replace the hard tab at the beginning of line 145 with spaces. This will resolve the MD010 (no-hard-tabs) warning and ensure consistent formatting throughout the document.

🧰 Tools
🪛 Markdownlint

145-145: Column: 2
Hard tabs

(MD010, no-hard-tabs)

Comment on lines +34 to +38
func NewVolumeWeightedAveragePriceStrategyWith(period int) *VolumeWeightedAveragePriceStrategy {
return &VolumeWeightedAveragePriceStrategy{
VolumeWeightedAveragePrice: volume.NewVwapWithPeriod[float64](period),
}
}
Copy link

Choose a reason for hiding this comment

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

⚠️ Potential issue

Add validation for the period parameter

In the NewVolumeWeightedAveragePriceStrategyWith function, consider adding validation to ensure that the period parameter is a positive integer. This helps prevent potential runtime errors due to invalid input.

Apply this diff to add validation:

func NewVolumeWeightedAveragePriceStrategyWith(period int) *VolumeWeightedAveragePriceStrategy {
+   if period <= 0 {
+       panic("period must be a positive integer")
+   }
    return &VolumeWeightedAveragePriceStrategy{
        VolumeWeightedAveragePrice: volume.NewVwapWithPeriod[float64](period),
    }
}
📝 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
func NewVolumeWeightedAveragePriceStrategyWith(period int) *VolumeWeightedAveragePriceStrategy {
return &VolumeWeightedAveragePriceStrategy{
VolumeWeightedAveragePrice: volume.NewVwapWithPeriod[float64](period),
}
}
func NewVolumeWeightedAveragePriceStrategyWith(period int) *VolumeWeightedAveragePriceStrategy {
if period <= 0 {
panic("period must be a positive integer")
}
return &VolumeWeightedAveragePriceStrategy{
VolumeWeightedAveragePrice: volume.NewVwapWithPeriod[float64](period),
}
}

@cinar cinar merged commit 4e64211 into master Oct 19, 2024
6 checks passed
@cinar cinar deleted the volume-weighted-average-price-strategy branch October 19, 2024 20:50
@github-actions github-actions bot locked and limited conversation to collaborators Oct 19, 2024
Sign up for free to subscribe to this conversation on GitHub. Already have an account? Sign in.
Labels
None yet
Projects
None yet
Development

Successfully merging this pull request may close these issues.

2 participants