AarthiAI / backend /backtest.py
PROSTLE's picture
Refined dashboard UI layout, integrated taskbar, fixed chart rendering bug
7d603aa
Raw History Blame Contribute Delete
1.58 kB
import pandas as pd
import yfinance as yf
import numpy as np
import sys
import os
from stock_data import fetch_stock_data, add_technical_indicators
from technical_signals import score_technical_signals
from model import train_and_predict
def run_backtest(ticker="RELIANCE.NS", test_days=5):
print(f"Running Backtest for {ticker} over {test_days} periods...")
raw_df = fetch_stock_data(ticker, period="1y")
full_df = add_technical_indicators(raw_df)
T = len(full_df) - test_days
df_train = full_df.iloc[:T].copy()
actual_future = full_df["Close"].iloc[T:T+test_days].values
current_price = df_train["Close"].iloc[-1]
tech = score_technical_signals(df_train)
tech_score = tech.get("score", 0.0)
atr_pct = (df_train["ATR"].iloc[-1] / current_price * 100) if "ATR" in df_train else 0.0
print(f"Current Price before test window: {current_price:.2f}")
res = train_and_predict(
df_train,
epochs=30, # Decent train time
sentiment_score=0.0,
technical_score=tech_score,
llm_score=0.0,
atr_pct=atr_pct,
vix_level=15.0
)
preds = res["predicted_prices"]
print("Actual Prices: ", [round(x, 2) for x in actual_future])
print("Predicted Prices:", preds)
mape = np.mean([abs(a - p) / a for a, p in zip(actual_future, preds)]) * 100
acc = 100 - mape
print(f"Prediction Accuracy: {acc:.2f}%")
return acc
if __name__ == "__main__":
ticker = sys.argv[1] if len(sys.argv) > 1 else "RELIANCE.NS"
run_backtest(ticker, 5)