Skip to content

Configuration & Parameters

Leonardo Bitto edited this page Jan 5, 2026 · 2 revisions

Configuration Guide

Petunia uses a centralized JSON configuration file located at config/strategies.json. This file controls the active strategy, risk rules, and broker fee simulation.

File Structure (strategies.json)

{
    "active_strategy": "RSI",
    "risk_params": {
        "risk_per_trade": 0.02,
        "stop_atr_multiplier": 2.0
    },
    "fees_config": {
        "fixed_euro": 2.0,
        "percentage": 0.0005
    },
    "strategies_params": {
        "RSI": { ... },
        "EMA": { ... }
    }
}

Parameters Dictionary

1. General Settings

  • active_strategy: The exact class name key (e.g., "RSI", "EMA") that the WeeklyRun will execute.

2. Risk Management (risk_params)

  • risk_per_trade (float): The portion of Total Equity to risk on a single trade.

  • Example: 0.02 = 2%. If Equity is €10,000, max risk is €200.

  • stop_atr_multiplier (float): Determines the Stop Loss distance based on volatility.

  • Example: 2.0. If ATR is 5€, Stop Loss is placed 10€ below entry.

3. Fee Structure (fees_config)

Used in Backtesting (to calculate Net ROI) and Weekly Run (to update cash).

  • fixed_euro (float): Flat fee per order execution.
  • percentage (float): Variable fee based on order value. 0.0005 = 0.05%.

4. Strategy Parameters (strategies_params)

Parameters specific to each algorithm.

  • RSI: rsi_period, rsi_lower (Buy Zone), rsi_upper (Sell Zone).
  • EMA: short_window (Fast MA), long_window (Slow MA).

---

### 📄 Pagina 2: Developer Guide (Strategy Implementation)
*Qui documentiamo il cambiamento "Vettoriale" che abbiamo appena fatto, cruciale per chi scrive codice.*

**Titolo:** `Strategy Development (Vectorized)`

```markdown
# Writing New Strategies

As of v1.4.0, Petunia uses a **Vectorized Engine**. This means strategies must calculate indicators and signals for the *entire history* of the dataframe at once, rather than iterating row-by-row.

## The `compute` Method
Every strategy must implement the `compute` method.

**Input:** `data_map` (Dict[str, pd.DataFrame]) containing OHLCV data.
**Output:** `pd.DataFrame` containing ALL historical signals.

### Rules:
1.  **Do NOT use `iloc[-1]`**: Calculate the logic for the whole column (e.g., `df['rsi'] < 30`).
2.  **Preserve Dates**: The output DataFrame must contain the original `date` column.
3.  **Lowercase Columns**: Create output columns in lowercase (`rsi`, `signal`, `atr`).
4.  **Meta Data**: Add a `meta` column (dict) for debugging details in the Dashboard.

### Example Template (Vectorized)

```python
def compute(self, data_map):
    signals_list = []
    for ticker, df in data_map.items():
        d = df.copy().sort_values('date')
        
        # 1. Vectorized Indicator Calculation
        d['ma_50'] = d['close'].rolling(50).mean()
        
        # 2. Vectorized Logic
        d['signal'] = 'HOLD'
        d.loc[d['close'] > d['ma_50'], 'signal'] = 'BUY'
        
        # 3. Format Output
        output = d[['date', 'ticker', 'close', 'signal', 'atr']].copy()
        output.rename(columns={'close': 'price'}, inplace=True)
        signals_list.append(output)
        
    return pd.concat(signals_list)

Why Vectorized?

  1. Performance: 100x faster backtests compared to iteration.
  2. Backtest Accuracy: Allows the Backtester to simulate past dates accurately.
  3. Code Cleanliness: Leverages Pandas native power.

---

### 📄 Pagina 3: Risk Management Bible
*Aggiorniamo la logica dei costi.*

**Titolo:** `Risk & Fee Management`

```markdown
# Risk & Fees Logic

## 1. Position Sizing (The 2% Rule)
Petunia calculates position size based on the distance to the Stop Loss, ensuring that if the Stop is hit, the loss is exactly X% of the account.

$$Size = \frac{Total Equity \times Risk \%}{Entry Price - Stop Price}$$

* **Entry:** Current Close Price.
* **Stop Price:** $Entry - (ATR \times Multiplier)$.

## 2. Fee Management (New in v1.4)
Trading costs are inevitable. Petunia simulates them in two ways:

### A. Backtesting Lab
* At every trade (BUY or SELL), the `fees_config` is applied.
* Fees are subtracted from the simulated cash.
* **Metrics:** The Dashboard displays "Fees Paid" separately and calculates ROI *net of fees*.

### B. Live/Weekly Execution
* When `WeeklyRun` executes a trade, it calculates the estimated fee.
* This amount is **permanently subtracted** from the Portfolio Cash database.
* This ensures the "Virtual Cash" in Petunia closely tracks the "Real Cash" in your broker account.

Clone this wiki locally