Create app.p
Browse files
app.p
ADDED
|
@@ -0,0 +1,90 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import gradio as gr
|
| 2 |
+
import pandas as pd
|
| 3 |
+
import numpy as np
|
| 4 |
+
import matplotlib.pyplot as plt
|
| 5 |
+
from sklearn.svm import SVC
|
| 6 |
+
from sklearn.model_selection import train_test_split
|
| 7 |
+
from sklearn.preprocessing import StandardScaler
|
| 8 |
+
|
| 9 |
+
# --- Mock Morningstar-style data ---
|
| 10 |
+
data = {
|
| 11 |
+
"5Y_Return": [14.0, 7.5, 13.2, 6.0, 15.0, 8.0, 12.0, 6.5, 10.5, 7.2],
|
| 12 |
+
"Volatility": [8.0, 6.5, 7.8, 9.0, 7.0, 6.2, 7.1, 8.5, 6.8, 7.9],
|
| 13 |
+
"Risk_Score": [2, 3, 2, 4, 1, 3, 2, 4, 2, 3],
|
| 14 |
+
"Rating": ["Good", "Bad", "Good", "Bad", "Good", "Bad", "Good", "Bad", "Good", "Bad"]
|
| 15 |
+
}
|
| 16 |
+
df = pd.DataFrame(data)
|
| 17 |
+
df['Label'] = df['Rating'].map({'Good': 1, 'Bad': 0})
|
| 18 |
+
|
| 19 |
+
X = df[["5Y_Return", "Volatility", "Risk_Score"]]
|
| 20 |
+
y = df["Label"]
|
| 21 |
+
|
| 22 |
+
# Scaling
|
| 23 |
+
scaler = StandardScaler()
|
| 24 |
+
X_scaled = scaler.fit_transform(X)
|
| 25 |
+
|
| 26 |
+
# Train SVM
|
| 27 |
+
model = SVC(kernel="linear", probability=True)
|
| 28 |
+
model.fit(X_scaled, y)
|
| 29 |
+
|
| 30 |
+
# --- Classify and plot function ---
|
| 31 |
+
def classify_and_plot(return_5y, volatility, risk_score):
|
| 32 |
+
input_data = [[return_5y, volatility, risk_score]]
|
| 33 |
+
input_scaled = scaler.transform(input_data)
|
| 34 |
+
prediction = model.predict(input_scaled)[0]
|
| 35 |
+
confidence = model.predict_proba(input_scaled)[0][prediction]
|
| 36 |
+
result = "Good Investment" if prediction == 1 else "Bad Investment"
|
| 37 |
+
|
| 38 |
+
# --- Create plot ---
|
| 39 |
+
fig, ax = plt.subplots(figsize=(6, 5))
|
| 40 |
+
|
| 41 |
+
# Plot original data
|
| 42 |
+
scatter = ax.scatter(X_scaled[:, 0], X_scaled[:, 1], c=y, cmap="bwr", edgecolors="k", s=60)
|
| 43 |
+
ax.scatter(model.support_vectors_[:, 0], model.support_vectors_[:, 1],
|
| 44 |
+
s=150, facecolors='none', edgecolors='k', linewidths=1.5, label="Support Vectors")
|
| 45 |
+
|
| 46 |
+
# Grid for decision boundary
|
| 47 |
+
xlim = ax.get_xlim()
|
| 48 |
+
ylim = ax.get_ylim()
|
| 49 |
+
xx = np.linspace(xlim[0], xlim[1], 30)
|
| 50 |
+
yy = np.linspace(ylim[0], ylim[1], 30)
|
| 51 |
+
YY, XX = np.meshgrid(yy, xx)
|
| 52 |
+
xy = np.vstack([XX.ravel(), YY.ravel()]).T
|
| 53 |
+
Z = model.decision_function(xy).reshape(XX.shape)
|
| 54 |
+
|
| 55 |
+
ax.contour(XX, YY, Z, colors='k', levels=[-1, 0, 1],
|
| 56 |
+
alpha=0.7, linestyles=['--', '-', '--'])
|
| 57 |
+
|
| 58 |
+
ax.set_title("SVM Decision Boundary")
|
| 59 |
+
ax.set_xlabel("5Y Return (scaled)")
|
| 60 |
+
ax.set_ylabel("Volatility (scaled)")
|
| 61 |
+
ax.legend()
|
| 62 |
+
ax.grid(True)
|
| 63 |
+
|
| 64 |
+
# Save and return the figure
|
| 65 |
+
plot_path = "/tmp/svm_plot.png"
|
| 66 |
+
fig.savefig(plot_path)
|
| 67 |
+
plt.close(fig)
|
| 68 |
+
|
| 69 |
+
return f"{result} (Confidence: {confidence:.2f})", plot_path
|
| 70 |
+
|
| 71 |
+
# --- Gradio UI ---
|
| 72 |
+
with gr.Blocks() as demo:
|
| 73 |
+
gr.Markdown("## 🧠 SVM Classifier: Good or Bad Mutual Fund?")
|
| 74 |
+
with gr.Row():
|
| 75 |
+
return_input = gr.Number(label="5-Year Return (%)", value=10.0)
|
| 76 |
+
vol_input = gr.Number(label="Volatility (%)", value=7.0)
|
| 77 |
+
risk_input = gr.Number(label="Risk Score (1=Low, 5=High)", value=3)
|
| 78 |
+
classify_btn = gr.Button("Classify and Show Decision Boundary")
|
| 79 |
+
output_label = gr.Textbox(label="Prediction")
|
| 80 |
+
output_plot = gr.Image(label="SVM Decision Boundary")
|
| 81 |
+
|
| 82 |
+
classify_btn.click(
|
| 83 |
+
fn=classify_and_plot,
|
| 84 |
+
inputs=[return_input, vol_input, risk_input],
|
| 85 |
+
outputs=[output_label, output_plot]
|
| 86 |
+
)
|
| 87 |
+
|
| 88 |
+
# Run app
|
| 89 |
+
if __name__ == "__main__":
|
| 90 |
+
demo.launch()
|