File size: 2,010 Bytes
311594e
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
# -*- coding: utf-8 -*-
"""2.7 (Optional DBS).ipynb

Automatically generated by Colab.

Original file is located at
    https://colab.research.google.com/drive/1Js2DNDDuusJx06SBvdh-lmKbuCBTBw9B

chatgpt prompt:
Please create a regression model to predict DBS base on SGD exchange rate, create the model and then use gradio for the interface
"""

# Install dependencies (uncomment if needed)
# !pip install pandas scikit-learn gradio

import pandas as pd
from sklearn.model_selection import train_test_split
from sklearn.linear_model import LinearRegression
from sklearn.metrics import mean_squared_error, r2_score
import gradio as gr

# 1. LOAD DATA
# Make sure the CSV file is in the same folder, or give full path
df = pd.read_csv("DBS_SingDollar.csv")

# If your header row is exactly: Date,DBS,SGD this will work directly
# Keep only needed columns and drop missing values
df = df[["DBS", "SGD"]].dropna()

X = df[["SGD"]]   # feature
y = df["DBS"]     # target

# 2. TRAIN / TEST SPLIT
X_train, X_test, y_train, y_test = train_test_split(
    X, y, test_size=0.2, random_state=42
)

# 3. TRAIN MODEL (Linear Regression)
model = LinearRegression()
model.fit(X_train, y_train)

# 4. EVALUATE (optional, shows in console)
y_pred = model.predict(X_test)
rmse = mean_squared_error(y_test, y_pred) ** 0.5
r2 = r2_score(y_test, y_pred)

print(f"RMSE: {rmse:.4f}")
print(f"R²:   {r2:.4f}")

# 5. PREDICTION FUNCTION FOR GRADIO
def predict_dbs_price(sgd_rate: float) -> str:
    """
    Input: SGD exchange rate (float)
    Output: predicted DBS price (string for display)
    """
    pred = model.predict([[sgd_rate]])[0]
    return f"Predicted DBS price: {pred:.2f}"

# 6. GRADIO INTERFACE
iface = gr.Interface(
    fn=predict_dbs_price,
    inputs=gr.Number(label="SGD Exchange Rate"),
    outputs=gr.Textbox(label="Predicted DBS Price"),
    title="DBS Price Predictor",
    description="Enter the SGD exchange rate to predict the DBS share price (trained with historical DBS & SGD data)."
)

iface.launch()