sqa 0.0.32 → 0.0.38

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (110) hide show
  1. checksums.yaml +4 -4
  2. data/CHANGELOG.md +154 -1
  3. data/README.md +4 -0
  4. data/Rakefile +52 -10
  5. data/docs/advanced/index.md +1 -13
  6. data/docs/api/index.md +547 -61
  7. data/docs/api-reference/alphavantageapi.md +1057 -0
  8. data/docs/api-reference/apierror.md +31 -0
  9. data/docs/api-reference/index.md +221 -0
  10. data/docs/api-reference/notimplemented.md +27 -0
  11. data/docs/api-reference/sqa.md +267 -0
  12. data/docs/api-reference/sqa_backtest.md +171 -0
  13. data/docs/api-reference/sqa_backtest_results.md +530 -0
  14. data/docs/api-reference/sqa_badparametererror.md +13 -0
  15. data/docs/api-reference/sqa_config.md +538 -0
  16. data/docs/api-reference/sqa_configurationerror.md +13 -0
  17. data/docs/api-reference/sqa_datafetcherror.md +56 -0
  18. data/docs/api-reference/sqa_dataframe.md +779 -0
  19. data/docs/api-reference/sqa_dataframe_alphavantage.md +30 -0
  20. data/docs/api-reference/sqa_dataframe_data.md +325 -0
  21. data/docs/api-reference/sqa_dataframe_yahoofinance.md +25 -0
  22. data/docs/api-reference/sqa_ensemble.md +413 -0
  23. data/docs/api-reference/sqa_fpop.md +211 -0
  24. data/docs/api-reference/sqa_geneticprogram.md +325 -0
  25. data/docs/api-reference/sqa_geneticprogram_individual.md +114 -0
  26. data/docs/api-reference/sqa_marketregime.md +212 -0
  27. data/docs/api-reference/sqa_multitimeframe.md +227 -0
  28. data/docs/api-reference/sqa_patternmatcher.md +195 -0
  29. data/docs/api-reference/sqa_pluginmanager.md +55 -0
  30. data/docs/api-reference/sqa_portfolio.md +512 -0
  31. data/docs/api-reference/sqa_portfolio_position.md +220 -0
  32. data/docs/api-reference/sqa_portfolio_trade.md +332 -0
  33. data/docs/api-reference/sqa_portfoliooptimizer.md +248 -0
  34. data/docs/api-reference/sqa_riskmanager.md +388 -0
  35. data/docs/api-reference/sqa_seasonalanalyzer.md +121 -0
  36. data/docs/api-reference/sqa_sectoranalyzer.md +163 -0
  37. data/docs/api-reference/sqa_stock.md +661 -0
  38. data/docs/api-reference/sqa_strategy.md +178 -0
  39. data/docs/api-reference/sqa_strategy_bollingerbands.md +26 -0
  40. data/docs/api-reference/sqa_strategy_common.md +29 -0
  41. data/docs/api-reference/sqa_strategy_consensus.md +129 -0
  42. data/docs/api-reference/sqa_strategy_ema.md +41 -0
  43. data/docs/api-reference/sqa_strategy_kbs.md +154 -0
  44. data/docs/api-reference/sqa_strategy_macd.md +26 -0
  45. data/docs/api-reference/sqa_strategy_mp.md +41 -0
  46. data/docs/api-reference/sqa_strategy_mr.md +41 -0
  47. data/docs/api-reference/sqa_strategy_random.md +41 -0
  48. data/docs/api-reference/sqa_strategy_rsi.md +41 -0
  49. data/docs/api-reference/sqa_strategy_sma.md +41 -0
  50. data/docs/api-reference/sqa_strategy_stochastic.md +26 -0
  51. data/docs/api-reference/sqa_strategy_volumebreakout.md +26 -0
  52. data/docs/api-reference/sqa_strategygenerator.md +298 -0
  53. data/docs/api-reference/sqa_strategygenerator_pattern.md +264 -0
  54. data/docs/api-reference/sqa_strategygenerator_patterncontext.md +326 -0
  55. data/docs/api-reference/sqa_strategygenerator_profitablepoint.md +424 -0
  56. data/docs/api-reference/sqa_stream.md +256 -0
  57. data/docs/api-reference/sqa_ticker.md +175 -0
  58. data/docs/api-reference/string.md +135 -0
  59. data/docs/assets/images/advanced-workflow.svg +89 -0
  60. data/docs/assets/images/architecture.svg +107 -0
  61. data/docs/assets/images/data-flow.svg +138 -0
  62. data/docs/assets/images/getting-started-workflow.svg +88 -0
  63. data/docs/assets/images/strategy-flow.svg +78 -0
  64. data/docs/assets/images/system-architecture.svg +150 -0
  65. data/docs/concepts/index.md +292 -19
  66. data/docs/file_formats.md +250 -0
  67. data/docs/getting-started/index.md +1 -14
  68. data/docs/index.md +26 -23
  69. data/docs/llms.txt +109 -0
  70. data/docs/strategies/kbs.md +15 -14
  71. data/docs/strategy.md +381 -3
  72. data/docs/terms_of_use.md +1 -1
  73. data/examples/README.md +10 -0
  74. data/lib/api/alpha_vantage_api.rb +3 -7
  75. data/lib/sqa/backtest.rb +32 -0
  76. data/lib/sqa/config.rb +109 -28
  77. data/lib/sqa/data_frame/data.rb +13 -1
  78. data/lib/sqa/data_frame.rb +193 -26
  79. data/lib/sqa/errors.rb +79 -17
  80. data/lib/sqa/init.rb +70 -15
  81. data/lib/sqa/pattern_matcher.rb +4 -4
  82. data/lib/sqa/portfolio.rb +55 -1
  83. data/lib/sqa/sector_analyzer.rb +3 -11
  84. data/lib/sqa/stock.rb +180 -15
  85. data/lib/sqa/strategy.rb +62 -4
  86. data/lib/sqa/ticker.rb +106 -48
  87. data/lib/sqa/version.rb +1 -1
  88. data/lib/sqa.rb +4 -4
  89. data/mkdocs.yml +69 -81
  90. metadata +89 -21
  91. data/docs/README.md +0 -43
  92. data/examples/sinatra_app/Gemfile +0 -42
  93. data/examples/sinatra_app/Gemfile.lock +0 -268
  94. data/examples/sinatra_app/QUICKSTART.md +0 -169
  95. data/examples/sinatra_app/README.md +0 -471
  96. data/examples/sinatra_app/RUNNING_WITHOUT_TALIB.md +0 -90
  97. data/examples/sinatra_app/TROUBLESHOOTING.md +0 -95
  98. data/examples/sinatra_app/app.rb +0 -404
  99. data/examples/sinatra_app/config.ru +0 -5
  100. data/examples/sinatra_app/public/css/style.css +0 -723
  101. data/examples/sinatra_app/public/debug_macd.html +0 -82
  102. data/examples/sinatra_app/public/js/app.js +0 -107
  103. data/examples/sinatra_app/start.sh +0 -53
  104. data/examples/sinatra_app/views/analyze.erb +0 -306
  105. data/examples/sinatra_app/views/backtest.erb +0 -325
  106. data/examples/sinatra_app/views/dashboard.erb +0 -831
  107. data/examples/sinatra_app/views/error.erb +0 -58
  108. data/examples/sinatra_app/views/index.erb +0 -118
  109. data/examples/sinatra_app/views/layout.erb +0 -61
  110. data/examples/sinatra_app/views/portfolio.erb +0 -43
@@ -0,0 +1,250 @@
1
+ # File Formats
2
+
3
+ This document describes the CSV file formats used by SQA for data import and export.
4
+
5
+ ## Portfolio CSV Formats
6
+
7
+ The `SQA::Portfolio` class supports two CSV file formats for different purposes: positions (holdings) and trade history.
8
+
9
+ ### Portfolio Positions CSV
10
+
11
+ This format is used to save and load current portfolio holdings.
12
+
13
+ **Methods:**
14
+ - `portfolio.save_to_csv(filename)` - Save positions
15
+ - `SQA::Portfolio.load_from_csv(filename)` - Load positions
16
+
17
+ **Schema:**
18
+
19
+ | Column | Type | Description |
20
+ |--------|------|-------------|
21
+ | `ticker` | String | Stock ticker symbol (e.g., 'AAPL', 'MSFT') |
22
+ | `shares` | Integer | Number of shares currently held |
23
+ | `avg_cost` | Float | Average cost per share (cost basis) |
24
+ | `total_cost` | Float | Total cost basis for the entire position |
25
+
26
+ **Example File (`portfolio.csv`):**
27
+
28
+ ```csv
29
+ ticker,shares,avg_cost,total_cost
30
+ AAPL,100,150.0,15000.0
31
+ MSFT,50,300.0,15000.0
32
+ GOOG,25,120.0,3000.0
33
+ ```
34
+
35
+ **Usage:**
36
+
37
+ ```ruby
38
+ # Save current positions to CSV
39
+ portfolio = SQA::Portfolio.new(initial_cash: 100_000)
40
+ portfolio.buy('AAPL', shares: 100, price: 150.0)
41
+ portfolio.buy('MSFT', shares: 50, price: 300.0)
42
+ portfolio.save_to_csv('my_portfolio.csv')
43
+
44
+ # Load positions from CSV
45
+ loaded_portfolio = SQA::Portfolio.load_from_csv('my_portfolio.csv')
46
+ loaded_portfolio.position('AAPL').shares # => 100
47
+ ```
48
+
49
+ **Notes:**
50
+ - The CSV includes only current positions (open holdings)
51
+ - Cash balance is NOT saved in the CSV (set via `initial_cash` parameter when loading)
52
+ - Use this format for portfolio snapshots and position tracking
53
+
54
+ ---
55
+
56
+ ### Trade History CSV
57
+
58
+ This format is used to export the complete log of all buy and sell transactions.
59
+
60
+ **Methods:**
61
+ - `portfolio.save_trades_to_csv(filename)` - Export trade history
62
+
63
+ **Schema:**
64
+
65
+ | Column | Type | Description |
66
+ |--------|------|-------------|
67
+ | `date` | Date | Trade execution date (YYYY-MM-DD format) |
68
+ | `ticker` | String | Stock ticker symbol |
69
+ | `action` | Symbol | Trade type: `buy` or `sell` |
70
+ | `shares` | Integer | Number of shares traded |
71
+ | `price` | Float | Price per share at execution |
72
+ | `total` | Float | Total transaction value (shares × price) |
73
+ | `commission` | Float | Commission paid for the trade |
74
+
75
+ **Example File (`trades.csv`):**
76
+
77
+ ```csv
78
+ date,ticker,action,shares,price,total,commission
79
+ 2024-01-15,AAPL,buy,100,150.0,15000.0,1.0
80
+ 2024-01-20,MSFT,buy,50,300.0,15000.0,1.0
81
+ 2024-02-05,AAPL,sell,50,160.0,8000.0,1.0
82
+ 2024-02-15,GOOG,buy,25,120.0,3000.0,1.0
83
+ 2024-03-01,MSFT,sell,25,310.0,7750.0,1.0
84
+ ```
85
+
86
+ **Usage:**
87
+
88
+ ```ruby
89
+ # Execute some trades
90
+ portfolio = SQA::Portfolio.new(initial_cash: 100_000, commission: 1.0)
91
+ portfolio.buy('AAPL', shares: 100, price: 150.0, date: Date.parse('2024-01-15'))
92
+ portfolio.buy('MSFT', shares: 50, price: 300.0, date: Date.parse('2024-01-20'))
93
+ portfolio.sell('AAPL', shares: 50, price: 160.0, date: Date.parse('2024-02-05'))
94
+
95
+ # Export complete trade history
96
+ portfolio.save_trades_to_csv('trade_history.csv')
97
+ ```
98
+
99
+ **Notes:**
100
+ - This format is write-only (no corresponding `load_trades_from_csv()` method)
101
+ - Use for audit trails, tax reporting, and performance analysis
102
+ - Each row represents a single executed trade
103
+ - The `total` column does NOT include commission (commission is tracked separately)
104
+
105
+ ---
106
+
107
+ ## Stock Data CSV Format
108
+
109
+ Stock price and volume data is stored in CSV format with the following schema:
110
+
111
+ **Schema:**
112
+
113
+ | Column | Type | Description |
114
+ |--------|------|-------------|
115
+ | `timestamp` | String | Date in YYYY-MM-DD format |
116
+ | `open_price` | Float | Opening price |
117
+ | `high_price` | Float | Highest price during the period |
118
+ | `low_price` | Float | Lowest price during the period |
119
+ | `close_price` | Float | Closing price |
120
+ | `adj_close_price` | Float | Adjusted closing price (accounts for splits/dividends) |
121
+ | `volume` | Integer | Trading volume |
122
+
123
+ **Example File (`aapl.csv`):**
124
+
125
+ ```csv
126
+ timestamp,open_price,high_price,low_price,close_price,adj_close_price,volume
127
+ 2023-01-03,130.28,130.90,124.17,125.07,124.38,112117500
128
+ 2023-01-04,126.89,128.66,125.08,126.36,125.66,89113600
129
+ 2023-01-05,127.13,127.77,124.76,125.02,124.33,80962700
130
+ ```
131
+
132
+ **Location:**
133
+ - Stock CSV files are stored in `~/sqa_data/` by default (configurable via `SQA::Config`)
134
+ - File naming convention: `{ticker}.csv` (e.g., `aapl.csv`, `msft.csv`)
135
+
136
+ **Data Ordering:**
137
+ - **CRITICAL:** Data MUST be in ascending chronological order (oldest first, newest last)
138
+ - This ordering is required for TA-Lib compatibility
139
+ - Index [0] = oldest data point, Index [last] = newest data point
140
+
141
+ **Usage:**
142
+
143
+ ```ruby
144
+ # Stock data is automatically loaded/saved
145
+ stock = SQA::Stock.new(ticker: 'AAPL')
146
+ stock.df.to_csv('aapl_export.csv') # Export to custom location
147
+
148
+ # Load from custom CSV
149
+ df = SQA::DataFrame.load(source: 'path/to/custom.csv')
150
+ ```
151
+
152
+ **Notes:**
153
+ - Data is automatically fetched from Alpha Vantage or Yahoo Finance on first load
154
+ - Updates are appended and deduplicated using `concat_and_deduplicate!`
155
+ - Use `adj_close_price` for calculations that need to account for corporate actions
156
+
157
+ ---
158
+
159
+ ## Stock Metadata JSON Format
160
+
161
+ Stock metadata (company information) is stored in JSON format alongside CSV files.
162
+
163
+ **Location:** `~/sqa_data/{ticker}.json`
164
+
165
+ **Example File (`aapl.json`):**
166
+
167
+ ```json
168
+ {
169
+ "ticker": "aapl",
170
+ "name": "Apple Inc.",
171
+ "exchange": "NASDAQ",
172
+ "source": "alpha_vantage",
173
+ "indicators": {},
174
+ "overview": {
175
+ "symbol": "AAPL",
176
+ "asset_type": "Common Stock",
177
+ "name": "Apple Inc.",
178
+ "exchange": "NASDAQ",
179
+ "currency": "USD",
180
+ "country": "USA",
181
+ "sector": "TECHNOLOGY",
182
+ "industry": "ELECTRONIC COMPUTERS",
183
+ "market_capitalization": 2500000000000,
184
+ "pe_ratio": 28.5,
185
+ "eps": 6.05,
186
+ "dividend_per_share": 0.92,
187
+ "dividend_yield": 0.0055
188
+ }
189
+ }
190
+ ```
191
+
192
+ **Usage:**
193
+
194
+ ```ruby
195
+ stock = SQA::Stock.new(ticker: 'AAPL')
196
+ stock.data.overview['market_capitalization'] # => 2500000000000
197
+ stock.data.overview['pe_ratio'] # => 28.5
198
+ ```
199
+
200
+ ---
201
+
202
+ ## Configuration File Format
203
+
204
+ SQA supports YAML and TOML configuration files.
205
+
206
+ **Location:** `~/.sqa.yml` or `~/.sqa.toml`
207
+
208
+ **Example YAML (`~/.sqa.yml`):**
209
+
210
+ ```yaml
211
+ data_dir: ~/sqa_data
212
+ lazy_update: false
213
+ log_level: info
214
+ plotting_library: gnuplot
215
+ ```
216
+
217
+ **Example TOML (`~/.sqa.toml`):**
218
+
219
+ ```toml
220
+ data_dir = "~/sqa_data"
221
+ lazy_update = false
222
+ log_level = "info"
223
+ plotting_library = "gnuplot"
224
+ ```
225
+
226
+ **Available Configuration Options:**
227
+
228
+ | Option | Type | Default | Description |
229
+ |--------|------|---------|-------------|
230
+ | `data_dir` | String | `~/sqa_data` | Directory for storing stock data files |
231
+ | `lazy_update` | Boolean | `false` | If true, skip automatic data updates |
232
+ | `log_level` | Symbol | `:info` | Logging level (`:debug`, `:info`, `:warn`, `:error`) |
233
+ | `plotting_library` | Symbol | `:gnuplot` | Plotting library to use |
234
+
235
+ **Usage:**
236
+
237
+ ```ruby
238
+ # Load custom configuration
239
+ config = SQA::Config.new(data_dir: '/path/to/data', lazy_update: true)
240
+ SQA.init(config)
241
+ ```
242
+
243
+ ---
244
+
245
+ ## See Also
246
+
247
+ - [API Reference - Portfolio](api-reference/sqa_portfolio.md)
248
+ - [API Reference - Stock](api-reference/sqa_stock.md)
249
+ - [API Reference - DataFrame](api-reference/sqa_dataframe.md)
250
+ - [Data Frame Documentation](data_frame.md)
@@ -46,20 +46,7 @@ Before you begin, make sure you have:
46
46
 
47
47
  Here's the typical workflow when using SQA:
48
48
 
49
- ```mermaid
50
- graph LR
51
- A[Install SQA] --> B[Configure API Keys]
52
- B --> C[Load Stock Data]
53
- C --> D[Calculate Indicators]
54
- D --> E[Apply Strategies]
55
- E --> F{Analysis Type}
56
- F -->|Backtest| G[Run Backtest]
57
- F -->|Live| H[Stream Real-Time]
58
- F -->|Research| I[Explore in Console]
59
- G --> J[Review Results]
60
- H --> J
61
- I --> J
62
- ```
49
+ ![Getting Started Workflow](../assets/images/getting-started-workflow.svg)
63
50
 
64
51
  ## What's Next?
65
52
 
data/docs/index.md CHANGED
@@ -1,8 +1,25 @@
1
1
  # SQA - Simple Qualitative Analysis
2
2
 
3
- <p align="center">
4
- <strong>A Powerful Ruby Library for Stock Market Technical Analysis</strong>
5
- </p>
3
+ <div style="display: flex; align-items: flex-start; gap: 2rem; margin-bottom: 2rem;">
4
+ <div style="flex: 0 0 400px;">
5
+ <img src="assets/images/sqa.jpg" alt="SQA - Simple Qualitative Analysis" style="width: 100%; border-radius: 8px; box-shadow: 0 4px 6px rgba(0,0,0,0.1);">
6
+ </div>
7
+ <div style="flex: 1;">
8
+ <h2 style="margin-top: 0;">Key Features</h2>
9
+ <ul>
10
+ <li><strong>High Performance</strong> - Rust-backed Polars DataFrames (30x faster)</li>
11
+ <li><strong>150+ Technical Indicators</strong> - TA-Lib integration via sqa-tai</li>
12
+ <li><strong>13+ Trading Strategies</strong> - RSI, MACD, Bollinger Bands, and more</li>
13
+ <li><strong>Portfolio Management</strong> - Track positions, P&L, commissions</li>
14
+ <li><strong>Backtesting Framework</strong> - Comprehensive performance metrics</li>
15
+ <li><strong>Real-Time Streaming</strong> - Live price data with callbacks</li>
16
+ <li><strong>Strategy Generation</strong> - Discover patterns from profitable trades</li>
17
+ <li><strong>Genetic Programming</strong> - Evolve optimal parameters</li>
18
+ <li><strong>Risk Management</strong> - VaR, CVaR, position sizing</li>
19
+ <li><strong>Pattern Matching</strong> - Find similar historical patterns</li>
20
+ </ul>
21
+ </div>
22
+ </div>
6
23
 
7
24
  ---
8
25
 
@@ -97,26 +114,7 @@ puts "Max Drawdown: #{results.max_drawdown}%"
97
114
 
98
115
  ## Architecture
99
116
 
100
- ```mermaid
101
- graph TD
102
- A[Stock Data] --> B[SQA::DataFrame]
103
- B --> C[Technical Indicators]
104
- C --> D[Trading Strategies]
105
- D --> E{Strategy Type}
106
- E -->|Simple| F[SMA/EMA/RSI]
107
- E -->|Advanced| G[MACD/Bollinger]
108
- E -->|Rule-Based| H[KBS Strategy]
109
- D --> I[Portfolio Management]
110
- I --> J[Backtesting]
111
- J --> K[Performance Metrics]
112
-
113
- L[Real-Time Data] --> M[SQA::Stream]
114
- M --> D
115
-
116
- N[Pattern Discovery] --> O[StrategyGenerator]
117
- O --> P[Generated Strategies]
118
- P --> D
119
- ```
117
+ ![SQA Architecture](assets/images/architecture.svg)
120
118
 
121
119
  ## Getting Started
122
120
 
@@ -143,10 +141,15 @@ Ready to dive in? Check out our guides:
143
141
  - [Data Sources](data-sources/index.md) - Working with data
144
142
  - [Terms of Use](terms_of_use.md) - Important legal information
145
143
 
144
+ ## Demo Application
145
+
146
+ Want to see SQA in action? Check out the **[sqa_demo-sinatra](https://github.com/MadBomber/sqa_demo-sinatra)** gem - a web-based demonstration application that provides a visual interface for exploring stock analysis, technical indicators, and trading strategies.
147
+
146
148
  ## Community & Support
147
149
 
148
150
  - **GitHub**: [github.com/madbomber/sqa](https://github.com/madbomber/sqa)
149
151
  - **RubyGems**: [rubygems.org/gems/sqa](https://rubygems.org/gems/sqa)
152
+ - **Demo App**: [sqa_demo-sinatra](https://github.com/MadBomber/sqa_demo-sinatra) - Web-based SQA demonstration
150
153
  - **Issues**: Report bugs or request features on [GitHub Issues](https://github.com/madbomber/sqa/issues)
151
154
 
152
155
  ## License
data/docs/llms.txt ADDED
@@ -0,0 +1,109 @@
1
+ # SQA - Simple Qualitative Analysis
2
+
3
+ > A powerful Ruby library for stock market technical analysis and trading strategy development
4
+
5
+ SQA (Simple Qualitative Analysis) is an educational Ruby library designed for stock market technical analysis and trading strategy development. Built with high-performance data structures and seamlessly integrated with TA-Lib, SQA provides a comprehensive toolkit for analyzing historical stock data, implementing trading strategies, and backtesting your ideas.
6
+
7
+ SQA is designed for educational purposes only. It should not be used for actual trading without extensive testing and professional financial advice. Trading stocks involves substantial risk of loss.
8
+
9
+ - Polars DataFrames: Rust-backed data structures providing 30x faster operations than pure Ruby - TA-Lib Integration: Access to 150+ battle-tested technical indicators via the sqa-tai gem - Efficient Algorithms: Optimized for large historical datasets
10
+
11
+ ## Getting Started
12
+
13
+ - [Index](https://madbomber.github.io/sqa/getting-started/index): Welcome to SQA! This guide will help you get up and running with stock market technical analysis in just a few minutes.
14
+ - [Installation](https://madbomber.github.io/sqa/getting-started/installation): This guide walks you through installing SQA and all its dependencies.
15
+ - [Quick Start](https://madbomber.github.io/sqa/getting-started/quick-start): Get up and running with SQA in just a few minutes!
16
+
17
+ ## Core Concepts
18
+
19
+ - [Index](https://madbomber.github.io/sqa/concepts/index): Understanding the fundamental building blocks of SQA.
20
+ - [Dataframes](https://madbomber.github.io/sqa/data_frame): The SQA::DataFrame class is a high-performance wrapper around the Polars DataFrame library, specifically designed for time series financial data...
21
+ - [Technical Indicators](https://madbomber.github.io/sqa/indicators/index): SQA provides access to 150+ technical indicators via the sqa-tai gem, which wraps the industry-standard TA-Lib library.
22
+ - [Trading Strategies](https://madbomber.github.io/sqa/strategy): A strategy is a recipe that cooks all the indicators together to make a decision on a potential trade. The SQA::Strategy class provides the...
23
+
24
+ ## Technical Indicators
25
+
26
+ - [Index](https://madbomber.github.io/sqa/indicators/index): SQA provides access to 150+ technical indicators via the sqa-tai gem, which wraps the industry-standard TA-Lib library.
27
+ - [Overview](https://madbomber.github.io/sqa/indicators): ## The Philosophy of Indicators
28
+
29
+
30
+
31
+ ## Trading Strategies
32
+
33
+ - [Index](https://madbomber.github.io/sqa/strategies/index): Explore SQA's comprehensive suite of trading strategies.
34
+
35
+ ### Built-in Strategies
36
+
37
+ - [Bollinger Bands Strategy](https://madbomber.github.io/sqa/strategies/bollinger-bands): The Bollinger Bands strategy uses volatility bands to identify oversold and overbought conditions. The strategy generates buy signals when price...
38
+ - [Rsi Strategy](https://madbomber.github.io/sqa/strategies/rsi): The Relative Strength Index (RSI) strategy identifies overbought and oversold conditions using momentum oscillators. It generates signals when RSI...
39
+ - [Macd Strategy](https://madbomber.github.io/sqa/strategies/macd): Moving Average Convergence Divergence (MACD) is a trend-following momentum indicator that shows the relationship between two moving averages.
40
+ - [Sma Strategy](https://madbomber.github.io/sqa/strategies/sma): The SMA strategy uses crossovers of short-term and long-term simple moving averages to identify trend changes and generate trading signals.
41
+ - [Ema Strategy](https://madbomber.github.io/sqa/strategies/ema): Similar to SMA but gives more weight to recent prices, making it more responsive to price changes.
42
+ - [Stochastic Strategy](https://madbomber.github.io/sqa/strategies/stochastic): Compares closing price to the price range over a period to identify overbought/oversold conditions and momentum changes.
43
+ - [Volume Breakout](https://madbomber.github.io/sqa/strategies/volume-breakout): Identifies price breakouts confirmed by high trading volume for stronger signal reliability.
44
+ - [Mean Reversion](https://madbomber.github.io/sqa/strategies/mean-reversion): Based on the theory that prices tend to return to their average over time. Buys when price is below average and sells when above.
45
+ - [Market Profile](https://madbomber.github.io/sqa/strategies/market-profile): Uses market profile analysis to identify support and resistance levels, generating signals when price reaches these key levels.
46
+ - [Consensus Strategy](https://madbomber.github.io/sqa/strategies/consensus): Aggregates signals from multiple strategies and makes trading decisions based on majority vote. Reduces risk of acting on single false signals.
47
+
48
+ ### Advanced Strategies
49
+
50
+ - [Knowledge Based Strategy (kbs)](https://madbomber.github.io/sqa/strategies/kbs): Advanced rule-based trading system using RETE forward-chaining inference engine. Combines multiple indicators with custom logic rules.
51
+ - [Custom Strategies](https://madbomber.github.io/sqa/strategies/custom): Learn how to create your own trading strategies in the SQA framework.
52
+
53
+ ## Advanced Features
54
+
55
+ - [Index](https://madbomber.github.io/sqa/advanced/index): Explore SQA's advanced capabilities for professional-grade analysis.
56
+ - [Portfolio Management](https://madbomber.github.io/sqa/advanced/portfolio): The Portfolio class tracks positions, calculates P&L, manages commissions, and monitors portfolio performance over time.
57
+ - [Backtesting](https://madbomber.github.io/sqa/advanced/backtesting): Simulate trading strategies on historical data to evaluate performance before risking real capital.
58
+ - [Strategy Generator](https://madbomber.github.io/sqa/advanced/strategy-generator): Reverse-engineer profitable trades to discover patterns and automatically generate executable trading strategies.
59
+ - [Genetic Programming](https://madbomber.github.io/sqa/genetic_programming): ### Overview of Genetic Programming (GP)
60
+ - [Real Time Streaming](https://madbomber.github.io/sqa/advanced/streaming): Process live price data with event callbacks and parallel strategy execution for real-time trading signals.
61
+ - [Fpop Analysis](https://madbomber.github.io/sqa/advanced/fpop): Calculate future returns, risk metrics, and direction classification to evaluate trading opportunities.
62
+ - [Risk Management](https://madbomber.github.io/sqa/advanced/risk-management): Comprehensive risk management tools including VaR, position sizing, and risk metrics.
63
+ - [Portfolio Optimizer](https://madbomber.github.io/sqa/advanced/portfolio-optimizer): Multi-objective portfolio optimization for optimal asset allocation and rebalancing.
64
+ - [Ensemble Strategies](https://madbomber.github.io/sqa/advanced/ensemble): Combine multiple strategies with voting and meta-learning.
65
+ - [Multi Timeframe Analysis](https://madbomber.github.io/sqa/advanced/multi-timeframe): Analyze multiple timeframes simultaneously for better trade timing.
66
+ - [Pattern Matcher](https://madbomber.github.io/sqa/advanced/pattern-matcher): Pattern recognition and similarity search for forecasting.
67
+
68
+ ## AI & Machine Learning
69
+
70
+ - [Ai And Ml](https://madbomber.github.io/sqa/ai_and_ml): ## AI and ML in Trading -- Advancing Decision-Making
71
+ - [Mean Reversion](https://madbomber.github.io/sqa/mean_reversion): Determines if a stock exhibits mean reversion behavior based on a given price series.
72
+ - [Predict Next Value](https://madbomber.github.io/sqa/predict_next_value): As a stock quantitative analyst, having a predict next value method on a timeseries array of closing day stock price data would be extremely helpful....
73
+ - [Identify Wave Condition](https://madbomber.github.io/sqa/identify_wave_condition): The Elliott Wave Theory is a popular method used in stock technical analysis to predict future price movements in financial markets. It is based on...
74
+ - [Libsvm Format](https://madbomber.github.io/sqa/libsvm_file_format): This file format is used by rumale.
75
+
76
+ ## API Reference
77
+
78
+ - [Index](https://madbomber.github.io/sqa/api/index): Complete API documentation for SQA classes and modules.
79
+ - [Dataframe Class](https://madbomber.github.io/sqa/api/dataframe): SQA::DataFrame is a high-performance wrapper around the Polars DataFrame library, specifically optimized for time series financial data manipulation....
80
+
81
+ ## Data Sources
82
+
83
+ - [Index](https://madbomber.github.io/sqa/data-sources/index): SQA supports multiple data sources for historical stock price data.
84
+
85
+ ## Resources
86
+
87
+ - [Tags](https://madbomber.github.io/sqa/tags): Browse documentation by topic.
88
+ - [Requirements](https://madbomber.github.io/sqa/requirements): ... otherwise know as what I want to do. Some people would call it a roadmap; but, where I'm going "we don't need no stinking roads!"
89
+ - [Terms Of Use](https://madbomber.github.io/sqa/terms_of_use): Some sections of these Terms of Use are aspirational. If found to be so, they shall not invalidate any other section which shall remain in full...
90
+ - [Trading Ideas](https://madbomber.github.io/sqa/i_gotta_an_idea): ... based upon my prior work with sports outcome predictions and sensor net architecture.
91
+ - [Factor Analysis](https://madbomber.github.io/sqa/factors_that_impact_price): ## Factors that Impact Price
92
+
93
+ ### External Tools
94
+
95
+ - [Finviz](https://madbomber.github.io/sqa/finviz): The original finviz unofficial gem has been untouched for 3 years. I just forked it in the hope that I can bring it forward to current versions of...
96
+ - [Fx Pro Bit](https://madbomber.github.io/sqa/fx_pro_bit): FXProBot is a new trading software by Avenix Fzco, a major fintech firm located in Dubai that specializes in automated trading. This advanced robot...
97
+ - [Options Trading](https://madbomber.github.io/sqa/options): https://www.youtube.com/watch?v=A5w-dEgIU1M
98
+
99
+ ## Contributing
100
+
101
+ - [Index](https://madbomber.github.io/sqa/contributing/index): Thank you for your interest in contributing to SQA!
102
+
103
+ ## Optional
104
+
105
+ These resources provide supplementary information that may be skipped for shorter context:
106
+
107
+ - [Tags](https://madbomber.github.io/sqa/tags): Browse documentation by topic.
108
+ - [Requirements](https://madbomber.github.io/sqa/requirements): ... otherwise know as what I want to do. Some people would call it a roadmap; but, where I'm going "we don't need no stinking roads!"
109
+ - [Terms of Use](https://madbomber.github.io/sqa/terms_of_use): Some sections of these Terms of Use are aspirational. If found to be so, they shall not invalidate any other section which shall remain in full...
@@ -2,7 +2,7 @@
2
2
 
3
3
  ## Overview
4
4
 
5
- Advanced rule-based trading system using RETE forward-chaining inference engine. Combines multiple indicators with custom logic rules.
5
+ Advanced rule-based trading system using RETE forward-chaining inference engine. Combines multiple indicators with custom logic rules using the `kbs` (knowledge-based system) ruby gem. A complete [documentation website for the `kbs` ruby gem is available.](https://madbomber.github.io/kbs)
6
6
 
7
7
  ## How It Works
8
8
 
@@ -29,6 +29,7 @@ end
29
29
  ## Default Rules
30
30
 
31
31
  The KBS strategy includes 10 default rules:
32
+
32
33
  1. Buy on RSI oversold in uptrend
33
34
  2. Sell on RSI overbought in downtrend
34
35
  3. Buy on bullish MACD crossover
@@ -71,10 +72,10 @@ strategy.add_rule :strong_buy do
71
72
  without :position # Don't buy if already holding
72
73
 
73
74
  perform do
74
- kb.assert(:signal, {
75
- action: :buy,
75
+ kb.assert(:signal, {
76
+ action: :buy,
76
77
  confidence: :high,
77
- reason: :triple_confirmation
78
+ reason: :triple_confirmation
78
79
  })
79
80
  end
80
81
  end
@@ -100,18 +101,18 @@ Multiple rules can fire, with aggregate confidence determining final signal.
100
101
 
101
102
  ## Strengths
102
103
 
103
- ✅ Highly customizable
104
- ✅ Combines multiple indicators
105
- ✅ Confidence scoring
106
- ✅ Forward-chaining inference
107
- ✅ Can encode expert knowledge
104
+ - ✅ Highly customizable
105
+ - ✅ Combines multiple indicators
106
+ - ✅ Confidence scoring
107
+ - ✅ Forward-chaining inference
108
+ - ✅ Can encode expert knowledge
108
109
 
109
110
  ## Weaknesses
110
111
 
111
- ❌ Complex to configure
112
- ❌ Requires domain knowledge
113
- ❌ Can be slow with many rules
114
- ❌ Overfitting risk
112
+ - ❌ Complex to configure
113
+ - ❌ Requires domain knowledge
114
+ - ❌ Can be slow with many rules
115
+ - ❌ Overfitting risk
115
116
 
116
117
  ## Tips
117
118
 
@@ -124,6 +125,7 @@ Multiple rules can fire, with aggregate confidence determining final signal.
124
125
  ## Available Facts
125
126
 
126
127
  The KBS strategy processes these fact types:
128
+
127
129
  - `:rsi` - RSI indicator data
128
130
  - `:macd` - MACD crossovers
129
131
  - `:trend` - Price trend analysis
@@ -161,4 +163,3 @@ end
161
163
 
162
164
  - [Strategy Generator](../advanced/strategy-generator.md) - Auto-generate rules
163
165
  - [Genetic Programming](../genetic_programming.md) - Optimize rule parameters
164
-