Spaces:
Paused
Paused
Delete app.py
Browse files
app.py
DELETED
|
@@ -1,208 +0,0 @@
|
|
| 1 |
-
# ============================================================
|
| 2 |
-
# PORTFOLIO INTELLIGENCE ENGINE - FULL APP.PY
|
| 3 |
-
# Live + Historical Data Enabled
|
| 4 |
-
# ============================================================
|
| 5 |
-
|
| 6 |
-
import yfinance as yf
|
| 7 |
-
import numpy as np
|
| 8 |
-
import pandas as pd
|
| 9 |
-
from datetime import datetime, timedelta
|
| 10 |
-
from scipy.optimize import minimize
|
| 11 |
-
from scipy import stats
|
| 12 |
-
from dataclasses import dataclass
|
| 13 |
-
from typing import Dict, List
|
| 14 |
-
import warnings
|
| 15 |
-
|
| 16 |
-
warnings.filterwarnings("ignore")
|
| 17 |
-
|
| 18 |
-
# ============================================================
|
| 19 |
-
# DATA ENGINE
|
| 20 |
-
# ============================================================
|
| 21 |
-
|
| 22 |
-
class MarketDataLoader:
|
| 23 |
-
def __init__(self, lookback_days=365, interval="1d"):
|
| 24 |
-
self.lookback_days = lookback_days
|
| 25 |
-
self.interval = interval
|
| 26 |
-
|
| 27 |
-
def fetch(self, symbols: List[str]) -> Dict[str, pd.DataFrame]:
|
| 28 |
-
end = datetime.now()
|
| 29 |
-
start = end - timedelta(days=self.lookback_days)
|
| 30 |
-
|
| 31 |
-
data = {}
|
| 32 |
-
for s in symbols:
|
| 33 |
-
df = yf.download(
|
| 34 |
-
s,
|
| 35 |
-
start=start.strftime("%Y-%m-%d"),
|
| 36 |
-
end=end.strftime("%Y-%m-%d"),
|
| 37 |
-
interval=self.interval,
|
| 38 |
-
auto_adjust=True,
|
| 39 |
-
progress=False
|
| 40 |
-
)
|
| 41 |
-
if not df.empty:
|
| 42 |
-
data[s] = df[["Open", "High", "Low", "Close", "Volume"]].dropna()
|
| 43 |
-
return data
|
| 44 |
-
|
| 45 |
-
|
| 46 |
-
# ============================================================
|
| 47 |
-
# AI FORECAST ENGINE (PROXY)
|
| 48 |
-
# ============================================================
|
| 49 |
-
|
| 50 |
-
class SimpleAIForecaster:
|
| 51 |
-
def forecast(self, prices: pd.Series, horizon=30) -> Dict:
|
| 52 |
-
returns = np.log(prices / prices.shift(1)).dropna()
|
| 53 |
-
mu = returns.mean() * horizon
|
| 54 |
-
sigma = returns.std() * np.sqrt(horizon)
|
| 55 |
-
|
| 56 |
-
samples = np.random.normal(mu, sigma, 1000)
|
| 57 |
-
|
| 58 |
-
return {
|
| 59 |
-
"samples": samples,
|
| 60 |
-
"expected_return": mu,
|
| 61 |
-
"confidence": float(np.clip(1 / (1 + sigma * 10), 0.3, 0.9))
|
| 62 |
-
}
|
| 63 |
-
|
| 64 |
-
|
| 65 |
-
# ============================================================
|
| 66 |
-
# REGIME DETECTOR
|
| 67 |
-
# ============================================================
|
| 68 |
-
|
| 69 |
-
class RegimeDetector:
|
| 70 |
-
def detect(self, returns: pd.Series) -> Dict:
|
| 71 |
-
vol = returns.std() * np.sqrt(252)
|
| 72 |
-
momentum = returns.rolling(20).mean().iloc[-1]
|
| 73 |
-
|
| 74 |
-
if momentum > 0 and vol < 0.25:
|
| 75 |
-
return {"regime": "bull", "confidence": 0.7}
|
| 76 |
-
elif momentum < 0:
|
| 77 |
-
return {"regime": "bear", "confidence": 0.7}
|
| 78 |
-
else:
|
| 79 |
-
return {"regime": "sideways", "confidence": 0.6}
|
| 80 |
-
|
| 81 |
-
|
| 82 |
-
# ============================================================
|
| 83 |
-
# FEATURE ENGINE
|
| 84 |
-
# ============================================================
|
| 85 |
-
|
| 86 |
-
@dataclass
|
| 87 |
-
class AssetFeature:
|
| 88 |
-
symbol: str
|
| 89 |
-
expected_return: float
|
| 90 |
-
confidence: float
|
| 91 |
-
volatility: float
|
| 92 |
-
returns: pd.Series
|
| 93 |
-
regime: str
|
| 94 |
-
|
| 95 |
-
|
| 96 |
-
class FeatureBuilder:
|
| 97 |
-
def build(self, symbol, df, forecast, regime) -> AssetFeature:
|
| 98 |
-
returns = np.log(df["Close"] / df["Close"].shift(1)).dropna()
|
| 99 |
-
vol = returns.std() * np.sqrt(252)
|
| 100 |
-
|
| 101 |
-
return AssetFeature(
|
| 102 |
-
symbol=symbol,
|
| 103 |
-
expected_return=forecast["expected_return"] * forecast["confidence"],
|
| 104 |
-
confidence=forecast["confidence"],
|
| 105 |
-
volatility=vol,
|
| 106 |
-
returns=returns,
|
| 107 |
-
regime=regime["regime"]
|
| 108 |
-
)
|
| 109 |
-
|
| 110 |
-
|
| 111 |
-
# ============================================================
|
| 112 |
-
# OPTIMIZATION ENGINE
|
| 113 |
-
# ============================================================
|
| 114 |
-
|
| 115 |
-
class Optimizer:
|
| 116 |
-
def optimize(self, features: List[AssetFeature]) -> np.ndarray:
|
| 117 |
-
returns = np.array([f.expected_return for f in features])
|
| 118 |
-
returns = np.clip(returns, -0.5, 0.5)
|
| 119 |
-
|
| 120 |
-
returns_df = pd.concat(
|
| 121 |
-
[f.returns for f in features],
|
| 122 |
-
axis=1
|
| 123 |
-
)
|
| 124 |
-
returns_df.columns = [f.symbol for f in features]
|
| 125 |
-
|
| 126 |
-
cov = returns_df.cov().values
|
| 127 |
-
n = len(features)
|
| 128 |
-
|
| 129 |
-
def objective(w):
|
| 130 |
-
port_ret = w @ returns
|
| 131 |
-
port_vol = np.sqrt(w @ cov @ w)
|
| 132 |
-
return -(port_ret / (port_vol + 1e-8))
|
| 133 |
-
|
| 134 |
-
bounds = [(0.05, 0.5) for _ in range(n)]
|
| 135 |
-
cons = [{"type": "eq", "fun": lambda w: np.sum(w) - 1}]
|
| 136 |
-
w0 = np.ones(n) / n
|
| 137 |
-
|
| 138 |
-
res = minimize(objective, w0, bounds=bounds, constraints=cons)
|
| 139 |
-
return res.x if res.success else w0
|
| 140 |
-
|
| 141 |
-
|
| 142 |
-
# ============================================================
|
| 143 |
-
# RISK ANALYTICS
|
| 144 |
-
# ============================================================
|
| 145 |
-
|
| 146 |
-
class RiskEngine:
|
| 147 |
-
def analyze(self, weights, features):
|
| 148 |
-
returns = np.array([f.expected_return for f in features])
|
| 149 |
-
returns_df = pd.concat([f.returns for f in features], axis=1)
|
| 150 |
-
cov = returns_df.cov().values
|
| 151 |
-
|
| 152 |
-
port_ret = weights @ returns
|
| 153 |
-
port_vol = np.sqrt(weights @ cov @ weights)
|
| 154 |
-
sharpe = (port_ret - 0.04) / port_vol if port_vol > 0 else 0
|
| 155 |
-
|
| 156 |
-
return {
|
| 157 |
-
"expected_return": port_ret,
|
| 158 |
-
"volatility": port_vol,
|
| 159 |
-
"sharpe": sharpe
|
| 160 |
-
}
|
| 161 |
-
|
| 162 |
-
|
| 163 |
-
# ============================================================
|
| 164 |
-
# MAIN ORCHESTRATOR
|
| 165 |
-
# ============================================================
|
| 166 |
-
|
| 167 |
-
class PortfolioApp:
|
| 168 |
-
def __init__(self, symbols):
|
| 169 |
-
self.symbols = symbols
|
| 170 |
-
self.data_loader = MarketDataLoader()
|
| 171 |
-
self.forecaster = SimpleAIForecaster()
|
| 172 |
-
self.regime_detector = RegimeDetector()
|
| 173 |
-
self.feature_builder = FeatureBuilder()
|
| 174 |
-
self.optimizer = Optimizer()
|
| 175 |
-
self.risk_engine = RiskEngine()
|
| 176 |
-
|
| 177 |
-
def run(self):
|
| 178 |
-
market_data = self.data_loader.fetch(self.symbols)
|
| 179 |
-
features = []
|
| 180 |
-
|
| 181 |
-
for s, df in market_data.items():
|
| 182 |
-
forecast = self.forecaster.forecast(df["Close"])
|
| 183 |
-
returns = np.log(df["Close"] / df["Close"].shift(1)).dropna()
|
| 184 |
-
regime = self.regime_detector.detect(returns)
|
| 185 |
-
feature = self.feature_builder.build(s, df, forecast, regime)
|
| 186 |
-
features.append(feature)
|
| 187 |
-
|
| 188 |
-
weights = self.optimizer.optimize(features)
|
| 189 |
-
risk = self.risk_engine.analyze(weights, features)
|
| 190 |
-
|
| 191 |
-
print("\n📊 PORTFÖY SONUCU\n")
|
| 192 |
-
for i, f in enumerate(features):
|
| 193 |
-
print(f"{f.symbol:5s} | Weight: {weights[i]:.2%} | Regime: {f.regime}")
|
| 194 |
-
|
| 195 |
-
print("\n--- RISK METRICS ---")
|
| 196 |
-
print(f"Expected Return : {risk['expected_return']:.2%}")
|
| 197 |
-
print(f"Volatility : {risk['volatility']:.2%}")
|
| 198 |
-
print(f"Sharpe Ratio : {risk['sharpe']:.2f}")
|
| 199 |
-
|
| 200 |
-
|
| 201 |
-
# ============================================================
|
| 202 |
-
# RUN
|
| 203 |
-
# ============================================================
|
| 204 |
-
|
| 205 |
-
if __name__ == "__main__":
|
| 206 |
-
symbols = ["XOM", "GOOGL", "WMT", "JNJ"]
|
| 207 |
-
app = PortfolioApp(symbols)
|
| 208 |
-
app.run()
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|