"""
Pine Script to Python Conversion Examples
Common Indicators: MA, RSI, MACD
"""

import numpy as np
import pandas as pd
import matplotlib.pyplot as plt


def get_sample_data():
    """Generate sample historical data for testing (no external dependencies)"""
    # Create a date range
    dates = pd.date_range(start="2024-01-01", periods=252, freq="D")
    
    # Generate synthetic price data (random walk)
    np.random.seed(42)
    returns = np.random.normal(loc=0.001, scale=0.02, size=len(dates))
    price = 100 * (1 + returns).cumprod()
    
    # Create OHLCV DataFrame
    data = pd.DataFrame({
        "Open": price * (1 + np.random.normal(0, 0.005, len(dates))),
        "High": price * (1 + np.random.uniform(0, 0.02, len(dates))),
        "Low": price * (1 - np.random.uniform(0, 0.02, len(dates))),
        "Close": price,
        "Volume": np.random.randint(1000000, 10000000, len(dates))
    }, index=dates)
    
    return data


def sma(series, length):
    """Calculate Simple Moving Average (SMA)"""
    return series.rolling(window=length).mean()


def ema(series, length):
    """Calculate Exponential Moving Average (EMA)"""
    return series.ewm(span=length, adjust=False).mean()


def rsi(series, length=14):
    """Calculate Relative Strength Index (RSI)"""
    delta = series.diff()
    gain = (delta.where(delta > 0, 0)).rolling(window=length).mean()
    loss = (-delta.where(delta < 0, 0)).rolling(window=length).mean()
    rs = gain / loss
    rsi = 100 - (100 / (1 + rs))
    return rsi


def macd(series, fast=12, slow=26, signal=9):
    """Calculate MACD (Moving Average Convergence Divergence)"""
    ema_fast = ema(series, fast)
    ema_slow = ema(series, slow)
    macd_line = ema_fast - ema_slow
    signal_line = ema(macd_line, signal)
    histogram = macd_line - signal_line
    return macd_line, signal_line, histogram


def example_ma(data):
    """
    Moving Average (MA) Example
    
    Pine Script:
    ma5 = ta.sma(close, 5)
    ma20 = ta.ema(close, 20)
    """
    # Calculate SMA (Simple Moving Average) and EMA (Exponential Moving Average)
    data["MA5"] = sma(data["Close"], 5)
    data["MA20"] = ema(data["Close"], 20)
    return data


def example_rsi(data):
    """
    RSI (Relative Strength Index) Example
    
    Pine Script:
    rsiVal = ta.rsi(close, 14)
    overbought = 70
    oversold = 30
    """
    data["RSI"] = rsi(data["Close"], 14)
    return data


def example_macd(data):
    """
    MACD (Moving Average Convergence Divergence) Example
    
    Pine Script:
    [macdLine, signalLine, histLine] = ta.macd(close, 12, 26, 9)
    """
    macd_line, signal_line, histogram = macd(data["Close"], 12, 26, 9)
    data["MACD"] = macd_line
    data["MACD_Signal"] = signal_line
    data["MACD_Histogram"] = histogram
    return data


def plot_examples(data):
    """Plot the indicators"""
    fig, (ax1, ax2, ax3) = plt.subplots(3, 1, figsize=(14, 10), sharex=True)
    
    # Price and MAs
    ax1.plot(data["Close"], label="Close", color="black", alpha=0.5)
    ax1.plot(data["MA5"], label="MA5 (SMA)", color="blue")
    ax1.plot(data["MA20"], label="MA20 (EMA)", color="red")
    ax1.set_title("Price and Moving Averages")
    ax1.legend()
    ax1.grid(True)
    
    # RSI
    ax2.plot(data["RSI"], label="RSI", color="purple")
    ax2.axhline(y=70, color="red", linestyle="--", label="Overbought (70)")
    ax2.axhline(y=30, color="green", linestyle="--", label="Oversold (30)")
    ax2.set_title("RSI (14)")
    ax2.legend()
    ax2.grid(True)
    ax2.set_ylim(0, 100)
    
    # MACD
    ax3.plot(data["MACD"], label="MACD Line", color="blue")
    ax3.plot(data["MACD_Signal"], label="Signal Line", color="orange")
    ax3.bar(data.index, data["MACD_Histogram"], label="Histogram", 
             color=data["MACD_Histogram"].apply(lambda x: "green" if x >= 0 else "red"))
    ax3.set_title("MACD (12, 26, 9)")
    ax3.legend()
    ax3.grid(True)
    
    plt.tight_layout()
    plt.savefig("indicators_plot.png")
    print("Plot saved as indicators_plot.png")


def main():
    print("=== Pine Script to Python Conversion Examples ===")
    
    # Get data
    print("\nGenerating sample data...")
    data = get_sample_data()
    
    # Calculate indicators
    print("\nCalculating indicators...")
    data = example_ma(data)
    data = example_rsi(data)
    data = example_macd(data)
    
    # Print first few rows
    print("\nSample data (last 5 rows):")
    print(data.tail())
    
    # Save data to CSV
    data.to_csv("sample_data_with_indicators.csv")
    print("\nData saved to sample_data_with_indicators.csv")
    
    # Plot
    print("\nGenerating plot...")
    plot_examples(data)
    
    print("\nDone!")


if __name__ == "__main__":
    main()
