quantitative 0.1.0

Sign up to get free protection for your applications and to get access to all the features.
checksums.yaml ADDED
@@ -0,0 +1,7 @@
1
+ ---
2
+ SHA256:
3
+ metadata.gz: 81321ddd563920c047db7eef1c0eaa922a582a5fc17f0c52ea49b4a629aa9010
4
+ data.tar.gz: d7e00ef24cf0dcf1aaf2cb015591058e37fbbf2d0771f8d950f6d7e38da662cc
5
+ SHA512:
6
+ metadata.gz: f79190f22f241256fe8a34c35ad8289c09253642a3f534ac8ee4b1fc3fc4cf5f092bbc6c263adb0bf9087067fb5772ad74ff8430f623b467e76973a7a0e95b16
7
+ data.tar.gz: fa39ccd339097b6d7f18b0e5e9707643be4c224d52b5a27b0adea8b292f626f48ee4c7058771ca4316674196506920fd202b671c40446235e9d121bd9b2ea22e
data/.rspec ADDED
@@ -0,0 +1,3 @@
1
+ --format documentation
2
+ --color
3
+ --require spec_helper
data/.rubocop.yml ADDED
@@ -0,0 +1,25 @@
1
+ inherit_gem:
2
+ relaxed-rubocop: .rubocop.yml
3
+
4
+ AllCops:
5
+ TargetRubyVersion: 3.0
6
+
7
+ Style/AccessorGrouping:
8
+ Enabled: false
9
+
10
+ Style/StringLiterals:
11
+ Enabled: true
12
+ EnforcedStyle: double_quotes
13
+
14
+ Style/StringLiteralsInInterpolation:
15
+ Enabled: true
16
+ EnforcedStyle: double_quotes
17
+
18
+ Layout/LineLength:
19
+ Max: 120
20
+
21
+ Lint/AmbiguousBlockAssociation:
22
+ AllowedMethods:
23
+ - change
24
+ - not_change
25
+
@@ -0,0 +1,84 @@
1
+ # Contributor Covenant Code of Conduct
2
+
3
+ ## Our Pledge
4
+
5
+ We as members, contributors, and leaders pledge to make participation in our community a harassment-free experience for everyone, regardless of age, body size, visible or invisible disability, ethnicity, sex characteristics, gender identity and expression, level of experience, education, socio-economic status, nationality, personal appearance, race, religion, or sexual identity and orientation.
6
+
7
+ We pledge to act and interact in ways that contribute to an open, welcoming, diverse, inclusive, and healthy community.
8
+
9
+ ## Our Standards
10
+
11
+ Examples of behavior that contributes to a positive environment for our community include:
12
+
13
+ * Demonstrating empathy and kindness toward other people
14
+ * Being respectful of differing opinions, viewpoints, and experiences
15
+ * Giving and gracefully accepting constructive feedback
16
+ * Accepting responsibility and apologizing to those affected by our mistakes, and learning from the experience
17
+ * Focusing on what is best not just for us as individuals, but for the overall community
18
+
19
+ Examples of unacceptable behavior include:
20
+
21
+ * The use of sexualized language or imagery, and sexual attention or
22
+ advances of any kind
23
+ * Trolling, insulting or derogatory comments, and personal or political attacks
24
+ * Public or private harassment
25
+ * Publishing others' private information, such as a physical or email
26
+ address, without their explicit permission
27
+ * Other conduct which could reasonably be considered inappropriate in a
28
+ professional setting
29
+
30
+ ## Enforcement Responsibilities
31
+
32
+ Community leaders are responsible for clarifying and enforcing our standards of acceptable behavior and will take appropriate and fair corrective action in response to any behavior that they deem inappropriate, threatening, offensive, or harmful.
33
+
34
+ Community leaders have the right and responsibility to remove, edit, or reject comments, commits, code, wiki edits, issues, and other contributions that are not aligned to this Code of Conduct, and will communicate reasons for moderation decisions when appropriate.
35
+
36
+ ## Scope
37
+
38
+ This Code of Conduct applies within all community spaces, and also applies when an individual is officially representing the community in public spaces. Examples of representing our community include using an official e-mail address, posting via an official social media account, or acting as an appointed representative at an online or offline event.
39
+
40
+ ## Enforcement
41
+
42
+ Instances of abusive, harassing, or otherwise unacceptable behavior may be reported to the community leaders responsible for enforcement at mwlang@cybrains.net. All complaints will be reviewed and investigated promptly and fairly.
43
+
44
+ All community leaders are obligated to respect the privacy and security of the reporter of any incident.
45
+
46
+ ## Enforcement Guidelines
47
+
48
+ Community leaders will follow these Community Impact Guidelines in determining the consequences for any action they deem in violation of this Code of Conduct:
49
+
50
+ ### 1. Correction
51
+
52
+ **Community Impact**: Use of inappropriate language or other behavior deemed unprofessional or unwelcome in the community.
53
+
54
+ **Consequence**: A private, written warning from community leaders, providing clarity around the nature of the violation and an explanation of why the behavior was inappropriate. A public apology may be requested.
55
+
56
+ ### 2. Warning
57
+
58
+ **Community Impact**: A violation through a single incident or series of actions.
59
+
60
+ **Consequence**: A warning with consequences for continued behavior. No interaction with the people involved, including unsolicited interaction with those enforcing the Code of Conduct, for a specified period of time. This includes avoiding interactions in community spaces as well as external channels like social media. Violating these terms may lead to a temporary or permanent ban.
61
+
62
+ ### 3. Temporary Ban
63
+
64
+ **Community Impact**: A serious violation of community standards, including sustained inappropriate behavior.
65
+
66
+ **Consequence**: A temporary ban from any sort of interaction or public communication with the community for a specified period of time. No public or private interaction with the people involved, including unsolicited interaction with those enforcing the Code of Conduct, is allowed during this period. Violating these terms may lead to a permanent ban.
67
+
68
+ ### 4. Permanent Ban
69
+
70
+ **Community Impact**: Demonstrating a pattern of violation of community standards, including sustained inappropriate behavior, harassment of an individual, or aggression toward or disparagement of classes of individuals.
71
+
72
+ **Consequence**: A permanent ban from any sort of public interaction within the community.
73
+
74
+ ## Attribution
75
+
76
+ This Code of Conduct is adapted from the [Contributor Covenant][homepage], version 2.0,
77
+ available at https://www.contributor-covenant.org/version/2/0/code_of_conduct.html.
78
+
79
+ Community Impact Guidelines were inspired by [Mozilla's code of conduct enforcement ladder](https://github.com/mozilla/diversity).
80
+
81
+ [homepage]: https://www.contributor-covenant.org
82
+
83
+ For answers to common questions about this code of conduct, see the FAQ at
84
+ https://www.contributor-covenant.org/faq. Translations are available at https://www.contributor-covenant.org/translations.
data/DISCLAIMER.txt ADDED
@@ -0,0 +1,14 @@
1
+ ## DISCLAIMER
2
+
3
+ This library is intended for educational and informational purposes only. It is
4
+ not intended to provide trading or investment advice. Trading cryptocurrency,
5
+ stocks and forex involves substantial risk of loss and is not suitable for everyone.
6
+
7
+ The information provided by this library should not be construed as an endorsement,
8
+ recommendation, or solicitation to buy or sell any security or financial instrument.
9
+ Users of this library are solely responsible for their own trading decisions and
10
+ should seek independent financial advice if they have any questions or concerns.
11
+
12
+ Past performance is not necessarily indicative of future results. By using this
13
+ library, you agree that the developers and contributors will not be liable for any
14
+ losses or damages arising from your use of the library. Use at your own risk.
data/Gemfile ADDED
@@ -0,0 +1,14 @@
1
+ # frozen_string_literal: true
2
+
3
+ source "https://rubygems.org"
4
+
5
+ # Specify your gem's dependencies in quantitative.gemspec
6
+ gemspec
7
+
8
+ gem "rake", "~> 13.0"
9
+
10
+ gem "rspec", "~> 3.0"
11
+
12
+ gem "rubocop", "~> 1.21"
13
+ gem "rubocop-rspec"
14
+ gem "relaxed-rubocop"
data/Gemfile.lock ADDED
@@ -0,0 +1,126 @@
1
+ PATH
2
+ remote: .
3
+ specs:
4
+ quantitative (0.1.0)
5
+ oj (~> 3.10)
6
+
7
+ GEM
8
+ remote: https://rubygems.org/
9
+ specs:
10
+ ast (2.4.2)
11
+ coderay (1.1.3)
12
+ debug (1.8.0)
13
+ irb (>= 1.5.0)
14
+ reline (>= 0.3.1)
15
+ diff-lcs (1.5.0)
16
+ ffi (1.16.3)
17
+ formatador (1.1.0)
18
+ guard (2.18.1)
19
+ formatador (>= 0.2.4)
20
+ listen (>= 2.7, < 4.0)
21
+ lumberjack (>= 1.0.12, < 2.0)
22
+ nenv (~> 0.1)
23
+ notiffany (~> 0.0)
24
+ pry (>= 0.13.0)
25
+ shellany (~> 0.0)
26
+ thor (>= 0.18.1)
27
+ guard-compat (1.2.1)
28
+ guard-rspec (4.7.3)
29
+ guard (~> 2.1)
30
+ guard-compat (~> 1.1)
31
+ rspec (>= 2.99.0, < 4.0)
32
+ io-console (0.6.0)
33
+ irb (1.9.1)
34
+ rdoc
35
+ reline (>= 0.3.8)
36
+ json (2.7.1)
37
+ language_server-protocol (3.17.0.3)
38
+ listen (3.8.0)
39
+ rb-fsevent (~> 0.10, >= 0.10.3)
40
+ rb-inotify (~> 0.9, >= 0.9.10)
41
+ lumberjack (1.2.9)
42
+ method_source (1.0.0)
43
+ nenv (0.3.0)
44
+ notiffany (0.1.3)
45
+ nenv (~> 0.1)
46
+ shellany (~> 0.0)
47
+ oj (3.16.1)
48
+ parallel (1.24.0)
49
+ parser (3.3.0.4)
50
+ ast (~> 2.4.1)
51
+ racc
52
+ pry (0.14.2)
53
+ coderay (~> 1.1)
54
+ method_source (~> 1.0)
55
+ psych (5.1.2)
56
+ stringio
57
+ racc (1.7.3)
58
+ rainbow (3.1.1)
59
+ rake (13.1.0)
60
+ rb-fsevent (0.11.2)
61
+ rb-inotify (0.10.1)
62
+ ffi (~> 1.0)
63
+ rdoc (6.6.2)
64
+ psych (>= 4.0.0)
65
+ regexp_parser (2.9.0)
66
+ relaxed-rubocop (2.5)
67
+ reline (0.4.1)
68
+ io-console (~> 0.5)
69
+ rexml (3.2.6)
70
+ rspec (3.12.0)
71
+ rspec-core (~> 3.12.0)
72
+ rspec-expectations (~> 3.12.0)
73
+ rspec-mocks (~> 3.12.0)
74
+ rspec-core (3.12.2)
75
+ rspec-support (~> 3.12.0)
76
+ rspec-expectations (3.12.3)
77
+ diff-lcs (>= 1.2.0, < 2.0)
78
+ rspec-support (~> 3.12.0)
79
+ rspec-mocks (3.12.6)
80
+ diff-lcs (>= 1.2.0, < 2.0)
81
+ rspec-support (~> 3.12.0)
82
+ rspec-support (3.12.1)
83
+ rubocop (1.60.1)
84
+ json (~> 2.3)
85
+ language_server-protocol (>= 3.17.0)
86
+ parallel (~> 1.10)
87
+ parser (>= 3.3.0.2)
88
+ rainbow (>= 2.2.2, < 4.0)
89
+ regexp_parser (>= 1.8, < 3.0)
90
+ rexml (>= 3.2.5, < 4.0)
91
+ rubocop-ast (>= 1.30.0, < 2.0)
92
+ ruby-progressbar (~> 1.7)
93
+ unicode-display_width (>= 2.4.0, < 3.0)
94
+ rubocop-ast (1.30.0)
95
+ parser (>= 3.2.1.0)
96
+ rubocop-capybara (2.20.0)
97
+ rubocop (~> 1.41)
98
+ rubocop-factory_bot (2.25.1)
99
+ rubocop (~> 1.41)
100
+ rubocop-rspec (2.26.1)
101
+ rubocop (~> 1.40)
102
+ rubocop-capybara (~> 2.17)
103
+ rubocop-factory_bot (~> 2.22)
104
+ ruby-progressbar (1.13.0)
105
+ shellany (0.0.1)
106
+ stringio (3.1.0)
107
+ thor (1.3.0)
108
+ unicode-display_width (2.5.0)
109
+ yard (0.9.34)
110
+
111
+ PLATFORMS
112
+ arm64-darwin-22
113
+
114
+ DEPENDENCIES
115
+ debug
116
+ guard-rspec (~> 4.7)
117
+ quantitative!
118
+ rake (~> 13.0)
119
+ relaxed-rubocop
120
+ rspec (~> 3.0)
121
+ rubocop (~> 1.21)
122
+ rubocop-rspec
123
+ yard (~> 0.9)
124
+
125
+ BUNDLED WITH
126
+ 2.3.13
data/Guardfile ADDED
@@ -0,0 +1,6 @@
1
+ guard :rspec, cmd: "rspec" do
2
+ watch(%r{^spec/.+_spec\.rb$})
3
+ watch(%r{^spec/lib/**/.+_spec\.rb$})
4
+ watch(%r{^lib/(.+)\.rb$}) { |m| "spec/lib/#{m[1]}_spec.rb" }
5
+ watch("spec/spec_helper.rb") { "spec" }
6
+ end
data/LICENSE.txt ADDED
@@ -0,0 +1,21 @@
1
+ The MIT License (MIT)
2
+
3
+ Copyright (c) 2024 mwlang
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in
13
+ all copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
21
+ THE SOFTWARE.
data/README.md ADDED
@@ -0,0 +1,53 @@
1
+ # Quantitative
2
+
3
+ STATUS: ALPHA - very early stages! The framework is very much a work in progress and I am rapidly introducing new things and changing existing things around.
4
+
5
+ Quantitative is a statistical and quantitative library for Ruby 3.x for trading stocks, cryptocurrency, and forex. It provides a number of classes and modules for working with time-series data, financial data, and other quantitative data. It is designed to be fast, efficient, and easy to use.
6
+
7
+ It has been highly optimized for fairly high-frequency trading purely in Ruby (no external numerical/statistical native extensions). The one exception is that I opted to depend on `Oj` which is a high-performant JSON parser that greatly speeds up serializing data between disk and memory. In practice, Quantitative is performant enough to trade one minute tickers on down to 30 second ticks for around 100 or so ticker symbols. Trading anything lower depends on the amount of analysis you're doing and your mileage may vary. It is possible, but you will find yourself with tradeoffs between the amount of data you can crunch and how fast you can react to live trading situations.
8
+
9
+ If you're looking to perform high-frequency quantitative trading intervals less than 30 seconds, or 1,000's of tickers concurrently, this library is probably not performant enough for such tasks due solely to Ruby's speed, not to mention that below 5 seconds, you're competing against other automated systems that are responding in the 4 to 10 milliseconds range.
10
+
11
+ This library is an extraction from an automated trading framework that I use to automate trading on cryptocurrency and stock exchanges. It does not provide API endpoint functionality for hooking into such. It is however, a very rich modeling of the space, thus allowing you to easily get started by building a few bridges to turn the payloads the API returns into something you can begin analyzing and generating signals to trade. Quantitative provides the foundational building blocks to let you easily model ticks, series, intervals, and provides various indicators such as RSI, dominant cycles, band-pass, moving averages, bollinger, donchian, and many more. Most of the indicators are designed around the concept of a dominant cycle to control the look back periods vs. relying on, say, setting the RSI to 14.
12
+
13
+ I have ported the majority of this library from Crystal-language, but have not released an open source version for Crystal. As a strongly-typed language, Crystal can be challenging to work out new designs and refactor rapidly and that led me to port this library to Ruby. I used the opportunity to rethink many pain-points that I wanted to solve for in the Ruby version with an eye towards eventually rewriting the Crystal version to match. If you're interested in a Crystal port, let me know.
14
+
15
+ ## Disclaimer
16
+
17
+ This library is intended for educational and informational purposes only. It is not intended to provide trading or investment advice. Trading cryptocurrency, stocks and forex involves substantial risk of loss and is not suitable for everyone.
18
+
19
+ The information provided by this library should not be construed as an endorsement, recommendation, or solicitation to buy or sell any security or financial instrument. Users of this library are solely responsible for their own trading decisions and should seek independent financial advice if they have any questions or concerns.
20
+
21
+ Past performance is not necessarily indicative of future results. By using this library, you agree that the developers and contributors will not be liable for any losses or damages arising from your use of the library. Use at your own risk.
22
+
23
+ ## Installation
24
+
25
+ Install the gem and add to the application's Gemfile by executing:
26
+
27
+ $ bundle add quantitative
28
+
29
+ If bundler is not being used to manage dependencies, install the gem by executing:
30
+
31
+ $ gem install quantitative
32
+
33
+ ## Usage
34
+
35
+ TODO: Write usage instructions here
36
+
37
+ ## Development
38
+
39
+ After checking out the repo, run `bin/setup` to install dependencies. Then, run `rake spec` to run the tests. You can also run `bin/console` for an interactive prompt that will allow you to experiment.
40
+
41
+ To install this gem onto your local machine, run `bundle exec rake install`. To release a new version, update the version number in `version.rb`, and then run `bundle exec rake release`, which will create a git tag for the version, push git commits and the created tag, and push the `.gem` file to [rubygems.org](https://rubygems.org).
42
+
43
+ ## Contributing
44
+
45
+ Bug reports and pull requests are welcome on GitHub at https://github.com/mwlang/quantitative. This project is intended to be a safe, welcoming space for collaboration, and contributors are expected to adhere to the [code of conduct](https://github.com/mwlang/quantitative/blob/main/CODE_OF_CONDUCT.md).
46
+
47
+ ## License
48
+
49
+ The gem is available as open source under the terms of the [MIT License](https://opensource.org/licenses/MIT).
50
+
51
+ ## Code of Conduct
52
+
53
+ Everyone interacting in the Quantitative project's codebases, issue trackers, chat rooms and mailing lists is expected to follow the [code of conduct](https://github.com/mwlang/quantitative/blob/main/CODE_OF_CONDUCT.md).
data/Rakefile ADDED
@@ -0,0 +1,12 @@
1
+ # frozen_string_literal: true
2
+
3
+ require "bundler/gem_tasks"
4
+ require "rspec/core/rake_task"
5
+
6
+ RSpec::Core::RakeTask.new(:spec)
7
+
8
+ require "rubocop/rake_task"
9
+
10
+ RuboCop::RakeTask.new
11
+
12
+ task default: %i[spec rubocop]
@@ -0,0 +1,7 @@
1
+ # frozen_string_literal: true
2
+
3
+ module Quant
4
+ class Error < StandardError; end
5
+ class InvalidInterval < Error; end
6
+ class InvalidResolution < Error; end
7
+ end
@@ -0,0 +1,226 @@
1
+ # frozen_string_literal: true
2
+
3
+ # rubocop:disable Layout/HashAlignment
4
+
5
+ # Quantitative is a statistical and quantitative library for Ruby 3.x. It provides a number of classes and modules for working with
6
+ # time-series data, financial data, and other quantitative data. It is designed to be fast, efficient, and easy to use.
7
+ #
8
+ # == Installation
9
+ #
10
+ # Add this line to your application's Gemfile:
11
+ #
12
+ # gem 'quantitative'
13
+ #
14
+ # And then execute:
15
+ #
16
+ # $ bundle install
17
+ #
18
+ # Or install it yourself as:
19
+ #
20
+ # $ gem install quantitative
21
+ #
22
+ # == Usage
23
+ #
24
+ # Quantitative provides a number of classes and modules for working with time-series data, financial data, and other quantitative data.
25
+ # It is designed to be fast, efficient, and easy to use.
26
+ #
27
+ # Here's a simple example of how to use Quantitative:
28
+ #
29
+ # require "quantitative"
30
+ #
31
+ # # Create a new series
32
+ # series = Quant::Series.new
33
+ #
34
+ # # Add some data to the series
35
+ # ticks = [25.0, 26.0, 23.5, 24.5, 25.5, 26.5, 27.5, 28.5, 29.5, 30.5]
36
+ # ticks.each { |tick| series << tick }
37
+ #
38
+ # # Print the series
39
+ # pp series
40
+ #
41
+ module Quant
42
+ # +Quant::Interval+ abstracts away the concept of ticks (candles, bars, etc.) and their duration and offers some basic utilities for
43
+ # working with multiple timeframes. Intervals are used in +Tick+ and +Series+ classes to define the duration of the ticks.
44
+ #
45
+ # When the +Interval+ is unknown, it is set to +'na'+ (not available) and the duration is set to 0. The shorthand for this is
46
+ # +Interval.na+. and +Interval[:na]+. and +Interval[nil]+.
47
+ #
48
+ # +Interval+ are instantiated in multple ways to support a wide variety of use-cases. Here's an example:
49
+ # Quant::Interval.new("1d") # => #<Quant::Interval @interval="1d"> (daily interval)
50
+ # Quant::Interval.new(:daily) # => #<Quant::Interval @interval="1d">
51
+ # Quant::Interval[:daily] # => #<Quant::Interval @interval="1d">
52
+ # Quant::Interval.from_resolution(60) # => #<Quant::Interval @interval="1h">
53
+ # Quant::Interval.from_resolution("1D") # => #<Quant::Interval @interval="1d">
54
+ # Quant::Interval.from_resolution("D") # => #<Quant::Interval @interval="1d">
55
+ #
56
+ # Intervals have a number of useful methods:
57
+ # interval = Quant::Interval.new("1d") # => #<Quant::Interval @interval="1d"> (daily interval)
58
+ # interval.nil? # => false
59
+ # interval.duration # => 86400
60
+ # interval.ticks_per_minute # => 0.0006944444444444445
61
+ # interval.half_life # => 43200.0
62
+ # interval.next_interval # => #<Quant::Interval @interval="1w"> (weekly interval)
63
+ #
64
+ # When you don't wish to specify an interval or it is unknown, you can use the +na+ interval:
65
+ # interval = Quant::Interval.na # => #<Quant::Interval @interval="na">
66
+ # interval.nil? # => true
67
+ # interval.duration # => 0
68
+ #
69
+ class Interval
70
+ MAPPINGS = {
71
+ na: { interval: "na", distance: 0 },
72
+ second: { interval: "1s", distance: 1 },
73
+ two_seconds: { interval: "2s", distance: 2 },
74
+ three_seconds: { interval: "3s", distance: 3 },
75
+ five_seconds: { interval: "5s", distance: 5 },
76
+ ten_seconds: { interval: "10s", distance: 10 },
77
+ fifteen_seconds: { interval: "15s", distance: 15 },
78
+ thirty_seconds: { interval: "30s", distance: 30 },
79
+ minute: { interval: "1m", distance: 60 },
80
+ one_minute: { interval: "1m", distance: 60 },
81
+ three_minutes: { interval: "3m", distance: 60 * 3 },
82
+ five_minutes: { interval: "5m", distance: 60 * 5 },
83
+ fifteen_minutes: { interval: "15", distance: 60 * 15 },
84
+ thirty_minutes: { interval: "30", distance: 60 * 30 },
85
+ hour: { interval: "1h", distance: 60 * 60 },
86
+ two_hours: { interval: "2h", distance: 60 * 60 * 2 },
87
+ four_hours: { interval: "4h", distance: 60 * 60 * 4 },
88
+ eight_hours: { interval: "8h", distance: 60 * 60 * 8 },
89
+ twelve_hours: { interval: "12h", distance: 60 * 60 * 12 },
90
+ daily: { interval: "1d", distance: 60 * 60 * 24 },
91
+ weekly: { interval: "1w", distance: 60 * 60 * 24 * 7 },
92
+ monthly: { interval: "1M", distance: 60 * 60 * 24 * 30 },
93
+ }.freeze
94
+
95
+ INTERVAL_DISTANCE = MAPPINGS.values.map { |v| [v[:interval], v[:distance]] }.to_h.freeze
96
+
97
+ MAPPINGS.each_pair do |name, values|
98
+ define_singleton_method(name) do
99
+ Interval.new(values[:interval])
100
+ end
101
+
102
+ define_method("#{name}?") do
103
+ interval == values[:interval]
104
+ end
105
+ end
106
+
107
+ RESOLUTIONS = {
108
+ "1" => :one_minute,
109
+ "3" => :three_minutes,
110
+ "5" => :five_minutes,
111
+ "15" => :fifteen_minutes,
112
+ "30" => :thirty_minutes,
113
+ "60" => :hour,
114
+ "240" => :four_hours,
115
+ "D" => :daily,
116
+ "1D" => :daily,
117
+ }.freeze
118
+
119
+ def self.all_resolutions
120
+ RESOLUTIONS.keys
121
+ end
122
+
123
+ # Instantiates an Interval from a resolution. For example, TradingView uses resolutions
124
+ # like "1", "3", "5", "15", "30", "60", "240", "D", "1D" to represent the duration of a
125
+ # candlestick. +from_resolution+ translates resolutions to the appropriate +Interval+.
126
+ def self.from_resolution(resolution)
127
+ ensure_valid_resolution!(resolution)
128
+
129
+ Interval.new(MAPPINGS[RESOLUTIONS[resolution]][:interval])
130
+ end
131
+
132
+ # Instantiates an Interval from a string or symbol. If the value is already
133
+ # an +Interval+, it is returned as-is.
134
+ def self.[](value)
135
+ return value if value.is_a? Interval
136
+
137
+ from_mappings(value) || Interval.new(value)
138
+ end
139
+
140
+ # Looks up the given mapping (i.e. :daily) and returns the Interval for that mapping.
141
+ def self.from_mappings(value)
142
+ mapping = MAPPINGS[value&.to_sym]
143
+ return unless mapping
144
+
145
+ Interval.new(mapping[:interval])
146
+ end
147
+
148
+ attr_reader :interval
149
+
150
+ def initialize(interval)
151
+ ensure_valid_interval!(interval)
152
+
153
+ @interval = (interval || "na").to_s
154
+ end
155
+
156
+ def nil?
157
+ interval == "na"
158
+ end
159
+
160
+ def to_s
161
+ interval
162
+ end
163
+
164
+ def duration
165
+ INTERVAL_DISTANCE[interval]
166
+ end
167
+ alias seconds duration
168
+
169
+ def ==(other)
170
+ interval == other&.interval
171
+ end
172
+
173
+ def ticks_per_minute
174
+ 60.0 / seconds
175
+ end
176
+
177
+ def half_life
178
+ raise "bad interval #{interval}" if duration.nil?
179
+
180
+ duration / 2.0
181
+ end
182
+
183
+ # Returns the Interval for the next higher timeframe.
184
+ # For example, hourly -> daily -> weekly -> monthly
185
+ def next_interval
186
+ intervals = INTERVAL_DISTANCE.keys
187
+ Interval.new intervals[intervals.index(interval) + 1] || intervals[-1]
188
+ end
189
+
190
+ def self.valid_intervals
191
+ INTERVAL_DISTANCE.keys
192
+ end
193
+
194
+ # NOTE: if timestamp doesn't cover a full interval, it will be rounded up to 1
195
+ def ticks_to(timestamp)
196
+ ((timestamp - Quant.current_time) / duration).round(2).ceil
197
+ end
198
+
199
+ def timestamp_for(ticks:, timestamp: Quant.current_time)
200
+ timestamp + (ticks * duration)
201
+ end
202
+
203
+ def self.ensure_valid_resolution!(resolution)
204
+ return if RESOLUTIONS.keys.include? resolution
205
+
206
+ raise InvalidResolution, "resolution (#{resolution}) not a valid resolution. Should be one of: (#{RESOLUTIONS.keys.join(", ")})"
207
+ end
208
+
209
+ private
210
+
211
+ def valid_intervals
212
+ self.class.valid_intervals
213
+ end
214
+
215
+ def ensure_valid_interval!(interval)
216
+ return if interval.nil? || valid_intervals.include?(interval.to_s)
217
+
218
+ raise InvalidInterval, "interval (#{interval.inspect}) not a valid interval. Should be one of: (#{valid_intervals.join(", ")})"
219
+ end
220
+
221
+ def ensure_valid_resolution!(resolution)
222
+ self.class.ensure_valid_resolution!(resolution)
223
+ end
224
+ end
225
+ end
226
+ # rubocop:enable Layout/HashAlignment
@@ -0,0 +1,45 @@
1
+ # frozen_string_literal: true
2
+
3
+ module Quant
4
+ module Mixins
5
+ module Direction
6
+ def direction(average, current)
7
+ if average < current
8
+ :up
9
+ elsif average > current
10
+ :down
11
+ else
12
+ :flat
13
+ end
14
+ end
15
+
16
+ def dir_label(average, current)
17
+ { up: "UP", flat: "--", down: "DN" }[direction(average, current)]
18
+ end
19
+
20
+ def up?
21
+ direction == :up
22
+ end
23
+
24
+ def flat?
25
+ direction == :flat
26
+ end
27
+
28
+ def down?
29
+ direction == :down
30
+ end
31
+
32
+ def up_or_flat?
33
+ up? || flat?
34
+ end
35
+
36
+ def down_or_flat?
37
+ down? || flat?
38
+ end
39
+
40
+ def dir_label(colorize)
41
+ dir_label(average, psn, colorize)
42
+ end
43
+ end
44
+ end
45
+ end