"""
Lesson 2: three classic rule-based strategies, written as small readable functions.
Each takes a DataFrame `df` with columns Open, High, Low, Close (one row per day).
"""
import numpy as np
import pandas as pd


# ---------------------------------------------------------------- helpers
def average_true_range(df, n=14):
    """ATR = the typical daily range, including overnight gaps. A volatility ruler in price units."""
    prev_close = df.Close.shift(1)
    true_range = pd.concat([df.High - df.Low,
                            (df.High - prev_close).abs(),
                            (df.Low - prev_close).abs()], axis=1).max(axis=1)
    return true_range.rolling(n).mean()


def to_returns(signal, close, cost=0.0005):
    """Turn 'what I want to hold at the close of day t' into daily strategy returns.
    The shift(1) is the no-cheating rule: today's signal earns tomorrow's return."""
    position = signal.shift(1).fillna(0)
    daily = close.pct_change().fillna(0)
    return position * daily - position.diff().abs().fillna(0) * cost


# ---------------------------------------------------------------- 1. Turtle (breakout, long only)
def turtle_signal(df, entry=20, exit_=10, atr_n=14, atr_stop=2.0, risk=0.01):
    """Buy when Close beats the highest High of the previous `entry` days.
    Sell when Close drops below the lowest Low of the previous `exit_` days,
    or falls `atr_stop` ATRs below our entry price (the stop-loss).
    Size: risk 1% of capital per ATR of movement (capped at 100% invested)."""
    highest = df.High.rolling(entry).max().shift(1)      # shift(1): channel built from PAST days only
    lowest = df.Low.rolling(exit_).min().shift(1)
    atr = average_true_range(df, atr_n)
    close, hi, lo, a = df.Close.values, highest.values, lowest.values, atr.values   # plain arrays = fast loops
    out = np.zeros(len(df))
    holding, entry_price, size = False, 0.0, 0.0
    for t in range(len(df)):
        if np.isnan(hi[t]) or np.isnan(a[t]):
            continue
        if not holding and close[t] > hi[t]:              # breakout -> buy
            holding, entry_price = True, close[t]
            size = min(1.0, risk * close[t] / a[t])
        elif holding and (close[t] < lo[t] or close[t] < entry_price - atr_stop * a[t]):
            holding = False                               # channel exit or stop-loss -> sell
        out[t] = size if holding else 0.0
    return pd.Series(out, index=df.index)


# ---------------------------------------------------------------- 2. Bollinger Bands (mean reversion)
def bollinger_signal(df, n=20, k=2.0):
    """Bands = average +/- k standard deviations. Buy when price climbs back above the LOWER band
    (a stretched drop is ending); sell short when it falls back below the UPPER band.
    Close the trade when price returns to the middle line (the average)."""
    mid = df.Close.rolling(n).mean()
    sd = df.Close.rolling(n).std(ddof=0)
    upper, lower = mid + k * sd, mid - k * sd
    close, up, lo, md = df.Close.values, upper.values, lower.values, mid.values
    out = np.zeros(len(df))
    pos = 0
    for t in range(1, len(df)):
        if np.isnan(up[t - 1]):
            continue
        c, pc = close[t], close[t - 1]
        if pos <= 0 and c > lo[t] and pc < lo[t - 1]:
            pos = 1                                       # bounced up off the lower band
        elif pos >= 0 and c < up[t] and pc > up[t - 1]:
            pos = -1                                      # rolled over from the upper band
        elif pos < 0 and c < md[t]:
            pos = 0                                       # short reached the middle: take profit
        elif pos > 0 and c > md[t]:
            pos = 0                                       # long reached the middle: take profit
        out[t] = pos
    return pd.Series(out, index=df.index), mid, upper, lower


# ---------------------------------------------------------------- 3. Dual Thrust (open-based breakout)
def dual_thrust_returns(df, n=4, k1=0.5, k2=0.5, cost=0.0005):
    """Each morning, set two trigger prices around TODAY'S OPEN, sized by the recent range:
        buy trigger  = open + k1 * range      sell trigger = open - k2 * range
    If the day's High touches the buy trigger -> go long (filled at the trigger).
    If the day's Low touches the sell trigger -> go short. Otherwise keep yesterday's position.
    Because the fill happens INSIDE the day, this one returns daily returns directly."""
    hh = df.High.rolling(n).max().shift(1)
    ll = df.Low.rolling(n).min().shift(1)
    hc = df.Close.rolling(n).max().shift(1)
    lc = df.Close.rolling(n).min().shift(1)
    rng = np.maximum(hh - lc, hc - ll)                    # the "range" from the previous n days
    buy_trig, sell_trig = df.Open + k1 * rng, df.Open - k2 * rng
    close, high, low = df.Close.values, df.High.values, df.Low.values
    rg, bt, st = rng.values, buy_trig.values, sell_trig.values
    out = np.zeros(len(df))
    pos = 0
    for t in range(1, len(df)):
        if np.isnan(rg[t]):
            continue
        hit_buy, hit_sell = high[t] >= bt[t], low[t] <= st[t]
        new, fill = pos, None
        if hit_buy and not hit_sell:
            new, fill = 1, bt[t]
        elif hit_sell and not hit_buy:
            new, fill = -1, st[t]
        if new != pos:   # held the old position until the fill, then the new one until the close
            out[t] = pos * (fill / close[t-1] - 1) + new * (close[t] / fill - 1) - abs(new - pos) * cost
        else:
            out[t] = pos * (close[t] / close[t-1] - 1)
        pos = new
    return pd.Series(out, index=df.index)
