Skip to content

feat: add configurable SMA window for trend confirmation#13

Open
asgt2408 wants to merge 1 commit into
sreerevanth:mainfrom
asgt2408:bug
Open

feat: add configurable SMA window for trend confirmation#13
asgt2408 wants to merge 1 commit into
sreerevanth:mainfrom
asgt2408:bug

Conversation

@asgt2408

@asgt2408 asgt2408 commented Jul 4, 2026

Copy link
Copy Markdown
Contributor

Summary

This PR adds a configurable SMA Window setting to the Streamlit sidebar, allowing users to customize the trend confirmation period used by the ORB strategy without modifying the source code.

Previously, the SMA window was hardcoded to 5 candles.

Changes Made

UI (Streamlit)

Added a new SMA Window selector under Strategy Settings.

Available options:

  • 5
  • 10
  • 20
  • 50

The default value remains 5 to preserve existing behavior.

Analysis Pipeline

Passed the selected SMA window through the analysis flow:

app.py
    ↓
_analyze_cached()
    ↓
trader.py
    ↓
strategy.py

Strategy Logic

Updated the SMA calculation to use the user-selected window instead of the hardcoded value.

Previous implementation:

window = min(SMA_WINDOW, len(close))

New implementation:

window = min(sma_window, len(close))

Example

Default

SMA Window = 5

The strategy computes the moving average using the latest 5 candles.

Custom

SMA Window = 20

The strategy computes the moving average using the latest 20 candles, resulting in a slower trend filter that may change BUY/SELL/HOLD decisions.

Benefits

  • Makes the trend filter configurable.
  • Allows users to experiment with different SMA periods.
  • Improves strategy flexibility.
  • Preserves existing behavior by keeping 5 as the default value.
  • No code changes are required from end users.

Testing

Verified that:

  • The selected SMA window updates correctly from the sidebar.
  • The selected value propagates through the analysis pipeline.
  • SMA calculations use the configured window.
  • BUY/SELL/HOLD decisions respond to different SMA settings where applicable.
  • Default behavior remains unchanged when using an SMA window of 5.

Closes #12

Summary by CodeRabbit

  • New Features

    • Added a sidebar control to choose the SMA window used in symbol analysis.
    • Analysis results now reflect the selected moving-average window.
  • Performance

    • Updated analysis caching to refresh more frequently, improving responsiveness while keeping results current.
  • Data Updates

    • Refreshed trade records to include newly closed trades and a new follow-on trade entry.

@coderabbitai

coderabbitai Bot commented Jul 4, 2026

Copy link
Copy Markdown

Review Change Stack

📝 Walkthrough

Walkthrough

Adds a configurable SMA window: a Streamlit sidebar selector threads sma_window through _analyze_cached, analyze_symbols, and calculate_orb_signal into _trend_sma, replacing the fixed SMA_WINDOW constant. Also introduces CACHE_TTL_SECONDS for caching, and updates sample trade records in data/trades.json.

Changes

Configurable SMA Window

Layer / File(s) Summary
SMA calculation with parameterized window
strategy.py
calculate_orb_signal gains sma_window parameter and passes it to _trend_sma, which now bounds the lookback with min(sma_window, len(close)) instead of using the fixed SMA_WINDOW constant.
analyze_symbols threading
trader.py
analyze_symbols signature extended with sma_window: int, forwarded to calculate_orb_signal.
Sidebar selector and cached analysis wiring
app.py
Adds an "SMA Window" sidebar selectbox, threads the value through _analyze_cached into analyze_symbols, and introduces CACHE_TTL_SECONDS = 8 for caching.

Trade Data Updates

Layer / File(s) Summary
Trade lifecycle updates in sample data
data/trades.json
Two trades transitioned from OPEN to CLOSED with populated exit price/timestamp/reason and pnl values (one profitable, one STOP_LOSS), and a new AAPL BUY trade entry appended.

Estimated code review effort: 2 (Simple) | ~12 minutes

Sequence Diagram(s)

sequenceDiagram
  participant Sidebar
  participant App as app.py
  participant Cached as _analyze_cached
  participant Trader as analyze_symbols
  participant Strategy as calculate_orb_signal

  Sidebar->>App: select sma_window
  App->>Cached: call with sma_window (cached, TTL 8s)
  Cached->>Trader: analyze_symbols(..., sma_window)
  Trader->>Strategy: calculate_orb_signal(..., sma_window)
  Strategy-->>Trader: TradeSignal using SMA(sma_window)
Loading

Suggested labels: ELUSOC, ADVENTURER

Poem

A rabbit hopped into the sidebar's glow,
Picked a window — five, ten, or more to grow.
Through cache and trader, the number did race,
Straight to the SMA, finding its place.
Trades closed out neat, both win and loss,
This bunny thumps twice — no code left to toss! 🐇📈

🚥 Pre-merge checks | ✅ 3 | ❌ 2

❌ Failed checks (1 warning, 1 inconclusive)

Check name Status Explanation Resolution
Out of Scope Changes check ⚠️ Warning data/trades.json edits change trade states and append a new trade, which is unrelated to the configurable SMA window feature. Remove the trades.json changes unless they are required for the linked feature or another approved issue.
Linked Issues check ❓ Inconclusive The SMA window is threaded through the pipeline and used in SMA calculation, but the summary doesn't confirm the required 5/10/20/50 options and 5 default. Verify the sidebar offers 5/10/20/50 and that 5 remains the default for backward compatibility.
✅ Passed checks (3 passed)
Check name Status Explanation
Description Check ✅ Passed Check skipped - CodeRabbit’s high-level summary is enabled.
Title check ✅ Passed The title clearly and concisely describes the main change: a configurable SMA window for trend confirmation.
Docstring Coverage ✅ Passed No functions found in the changed files to evaluate docstring coverage. Skipping docstring coverage check.
✨ Finishing Touches
🧪 Generate unit tests (beta)
  • Create PR with unit tests

Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.

❤️ Share

Comment @coderabbitai help to get the list of available commands.

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

🧹 Nitpick comments (1)
strategy.py (1)

179-184: 📐 Maintainability & Code Quality | 🔵 Trivial | ⚡ Quick win

Remove debug print / fix misleading unit.

print(f"SMA Window: {sma_window} minutes") is a leftover debug artifact that fires on every signal calculation for every symbol — with auto-refresh this spams stdout. Also, sma_window is a candle/bar count, not "minutes" (unlike orb_window), so the message is misleading.

🧹 Proposed fix
 def _trend_sma(data: pd.DataFrame, sma_window: int) -> float:
     close = data["Close"].dropna()
-    print(f"SMA Window: {sma_window} minutes")
     if close.empty:
         return 0.0
     window = min(sma_window, len(close))
     return float(close.tail(window).mean())
🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@strategy.py` around lines 179 - 184, The _trend_sma function in strategy.py
contains a leftover debug print that spams stdout on every signal calculation
and uses the wrong unit label for sma_window. Remove the print(f"SMA Window:
...") line entirely from _trend_sma, and if any logging is needed, make it
optional and describe sma_window as a bar/candle count rather than minutes. Keep
the rest of the window calculation logic unchanged.
🤖 Prompt for all review comments with AI agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

Nitpick comments:
In `@strategy.py`:
- Around line 179-184: The _trend_sma function in strategy.py contains a
leftover debug print that spams stdout on every signal calculation and uses the
wrong unit label for sma_window. Remove the print(f"SMA Window: ...") line
entirely from _trend_sma, and if any logging is needed, make it optional and
describe sma_window as a bar/candle count rather than minutes. Keep the rest of
the window calculation logic unchanged.

ℹ️ Review info
⚙️ Run configuration

Configuration used: Organization UI

Review profile: CHILL

Plan: Pro Plus

Run ID: e0b5db26-d33e-40f5-8421-e4eb31277427

📥 Commits

Reviewing files that changed from the base of the PR and between da1bf02 and 5951b08.

⛔ Files ignored due to path filters (3)
  • __pycache__/strategy.cpython-314.pyc is excluded by !**/*.pyc
  • __pycache__/trader.cpython-314.pyc is excluded by !**/*.pyc
  • logs/trades.csv is excluded by !**/*.csv
📒 Files selected for processing (4)
  • app.py
  • data/trades.json
  • strategy.py
  • trader.py

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.

Feature Request: Configurable SMA Window

1 participant