import pandas as pd
import numpy as np
import matplotlib.pyplot as plt

# === 1. Load data ===
# If the analysis result is present:
df = pd.read_csv("eurusd_astro_binary.csv", parse_dates=["date"])
# If not, create synthetic data for the example:
np.random.seed(42)
dates = pd.date_range("2015-01-01", "2025-01-01", freq="W-MON")
n = len(dates)
df = pd.DataFrame(
    {
        "date": dates,
        "moon_phase_angle": np.random.uniform(0, 360, n),
        "return": np.random.normal(0, 0.005, n),
    }
)


# === 2. Classify Lunar phase ===
def moon_phase_name(angle):
    if angle < 15 or angle > 345:
        return "new_moon"
    elif 15 <= angle < 75:
        return "waxing_crescent"
    elif 75 <= angle < 105:
        return "first_quarter"
    elif 105 <= angle < 165:
        return "waxing_gibbous"
    elif 165 <= angle < 195:
        return "full_moon"
    elif 195 <= angle < 255:
        return "waning_gibbous"
    elif 255 <= angle < 285:
        return "last_quarter"
    else:
        return "waning_crescent"


df["phase"] = df["moon_phase_angle"].apply(moon_phase_name)
df["volatility"] = np.abs(df["return"]) * 10  # simple volatility metric

# === 3. Average returns by lunar phase ===
plt.figure(figsize=(8, 5))
phase_order = [
    "new_moon",
    "waxing_crescent",
    "first_quarter",
    "waxing_gibbous",
    "full_moon",
    "waning_gibbous",
    "last_quarter",
    "waning_crescent",
]
phase_returns = df.groupby("phase")["return"].mean().reindex(phase_order)
phase_returns.plot(kind="bar", color="skyblue")
plt.title("Average returns by lunar phase")
plt.ylabel("Average weekly returns")
plt.grid(True, axis="y")
plt.tight_layout()
plt.show()

# === 4. Average volatility by lunar phase ===
plt.figure(figsize=(8, 5))
phase_vol = df.groupby("phase")["volatility"].mean().reindex(phase_order)
phase_vol.plot(kind="bar", color="salmon")
plt.title("Average volatility by lunar phase")
plt.ylabel("Volatility")
plt.grid(True, axis="y")
plt.tight_layout()
plt.show()

# === 5. Returns vs lunar phase angle ===
plt.figure(figsize=(8, 5))
plt.scatter(df["moon_phase_angle"], df["return"], alpha=0.4, s=10, color="purple")
plt.title("Returns vs lunar phase angle")
plt.xlabel("Lunar phase (°)")
plt.ylabel("Returns")
plt.grid(True)
plt.tight_layout()
plt.show()
