Spaces:
Sleeping
Sleeping
Update app.py
Browse files
app.py
CHANGED
|
@@ -5,9 +5,11 @@ import pandas as pd
|
|
| 5 |
import matplotlib.pyplot as plt
|
| 6 |
import seaborn as sns
|
| 7 |
import scipy.optimize as sco
|
| 8 |
-
|
| 9 |
-
from
|
| 10 |
-
from
|
|
|
|
|
|
|
| 11 |
|
| 12 |
def get_stock_data(tickers, start, end):
|
| 13 |
data = yf.download(tickers, start=start, end=end)
|
|
@@ -60,27 +62,6 @@ def generate_efficient_frontier(returns, cov_matrix, num_portfolios=5000):
|
|
| 60 |
|
| 61 |
return results
|
| 62 |
|
| 63 |
-
def predict_stock_price(data, days=30):
|
| 64 |
-
stock = st.selectbox("Pilih saham untuk prediksi", data.columns)
|
| 65 |
-
df = data[[stock]].dropna()
|
| 66 |
-
df['Days'] = np.arange(len(df))
|
| 67 |
-
|
| 68 |
-
X = df[['Days']]
|
| 69 |
-
y = df[stock]
|
| 70 |
-
|
| 71 |
-
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, random_state=42)
|
| 72 |
-
model = LinearRegression()
|
| 73 |
-
model.fit(X_train, y_train)
|
| 74 |
-
|
| 75 |
-
future_days = np.arange(len(df), len(df) + days).reshape(-1, 1)
|
| 76 |
-
predictions = model.predict(future_days)
|
| 77 |
-
|
| 78 |
-
fig, ax = plt.subplots()
|
| 79 |
-
ax.plot(df.index, df[stock], label='Harga Aktual')
|
| 80 |
-
ax.plot(pd.date_range(df.index[-1], periods=days, freq='D'), predictions, label='Prediksi', linestyle='dashed')
|
| 81 |
-
ax.legend()
|
| 82 |
-
st.pyplot(fig)
|
| 83 |
-
|
| 84 |
def plot_correlation_heatmap(data):
|
| 85 |
correlation_matrix = data.corr()
|
| 86 |
fig, ax = plt.subplots()
|
|
@@ -103,6 +84,39 @@ def simulate_dca(data, investment_amount=100):
|
|
| 103 |
total_value.plot(ax=ax, title='Simulasi Investasi DCA')
|
| 104 |
st.pyplot(fig)
|
| 105 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 106 |
st.title("Analisis Portofolio Saham Optimal (Model Markowitz)")
|
| 107 |
|
| 108 |
st.write("Rekomendasi Saham yang Bertahan Saat COVID-19:")
|
|
@@ -131,21 +145,12 @@ if st.button("Analisis Portofolio"):
|
|
| 131 |
st.subheader("Simulasi Investasi Dollar Cost Averaging (DCA)")
|
| 132 |
simulate_dca(stock_data)
|
| 133 |
|
| 134 |
-
st.subheader("Prediksi Harga Saham")
|
| 135 |
-
predict_stock_price(stock_data)
|
| 136 |
|
| 137 |
if optimal_weights is not None:
|
| 138 |
st.subheader("Bobot Portofolio Optimal")
|
| 139 |
portfolio_weights = {stock: weight for stock, weight in zip(stock_data.columns, optimal_weights)}
|
| 140 |
st.write(portfolio_weights)
|
| 141 |
-
|
| 142 |
-
fig, ax = plt.subplots()
|
| 143 |
-
ax.pie(portfolio_weights.values(), labels=portfolio_weights.keys(), autopct='%1.1f%%', startangle=140)
|
| 144 |
-
ax.axis('equal')
|
| 145 |
-
st.pyplot(fig)
|
| 146 |
-
else:
|
| 147 |
-
st.error("Optimasi portofolio gagal. Coba dengan saham yang berbeda.")
|
| 148 |
-
|
| 149 |
|
| 150 |
-
#Saya telah menambahkan fitur prediksi harga saham menggunakan model Linear Regression. Sekarang, pengguna dapat memilih saham dan melihat prediksi harganya dalam beberapa hari ke depan. Grafik juga telah disertakan untuk membandingkan harga aktual dengan prediksi. Silakan coba dan beri tahu jika ada yang perlu diperbaiki!
|
| 151 |
|
|
|
|
| 5 |
import matplotlib.pyplot as plt
|
| 6 |
import seaborn as sns
|
| 7 |
import scipy.optimize as sco
|
| 8 |
+
import tensorflow as tf
|
| 9 |
+
from tensorflow import keras
|
| 10 |
+
from tensorflow.keras.models import Sequential
|
| 11 |
+
from tensorflow.keras.layers import LSTM, Dense, Dropout
|
| 12 |
+
from sklearn.preprocessing import MinMaxScaler
|
| 13 |
|
| 14 |
def get_stock_data(tickers, start, end):
|
| 15 |
data = yf.download(tickers, start=start, end=end)
|
|
|
|
| 62 |
|
| 63 |
return results
|
| 64 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 65 |
def plot_correlation_heatmap(data):
|
| 66 |
correlation_matrix = data.corr()
|
| 67 |
fig, ax = plt.subplots()
|
|
|
|
| 84 |
total_value.plot(ax=ax, title='Simulasi Investasi DCA')
|
| 85 |
st.pyplot(fig)
|
| 86 |
|
| 87 |
+
def predict_stock_price(data, stock, days=30):
|
| 88 |
+
st.subheader(f"Prediksi Harga Saham {stock} (LSTM Model)")
|
| 89 |
+
scaler = MinMaxScaler(feature_range=(0, 1))
|
| 90 |
+
scaled_data = scaler.fit_transform(data[stock].values.reshape(-1,1))
|
| 91 |
+
|
| 92 |
+
X, y = [], []
|
| 93 |
+
for i in range(60, len(scaled_data) - days):
|
| 94 |
+
X.append(scaled_data[i-60:i, 0])
|
| 95 |
+
y.append(scaled_data[i:i+days, 0])
|
| 96 |
+
|
| 97 |
+
X, y = np.array(X), np.array(y)
|
| 98 |
+
X = np.reshape(X, (X.shape[0], X.shape[1], 1))
|
| 99 |
+
|
| 100 |
+
model = Sequential()
|
| 101 |
+
model.add(LSTM(units=50, return_sequences=True, input_shape=(X.shape[1], 1)))
|
| 102 |
+
model.add(LSTM(units=50, return_sequences=False))
|
| 103 |
+
model.add(Dense(units=25))
|
| 104 |
+
model.add(Dense(units=days))
|
| 105 |
+
|
| 106 |
+
model.compile(optimizer='adam', loss='mean_squared_error')
|
| 107 |
+
model.fit(X, y, epochs=10, batch_size=16)
|
| 108 |
+
|
| 109 |
+
predicted_prices = model.predict(X[-1].reshape(1, X.shape[1], 1))
|
| 110 |
+
predicted_prices = scaler.inverse_transform(predicted_prices)
|
| 111 |
+
|
| 112 |
+
future_dates = pd.date_range(data.index[-1], periods=days+1)[1:]
|
| 113 |
+
|
| 114 |
+
fig, ax = plt.subplots()
|
| 115 |
+
ax.plot(data.index, data[stock], label='Data Historis')
|
| 116 |
+
ax.plot(future_dates, predicted_prices.flatten(), label='Prediksi', linestyle='dashed')
|
| 117 |
+
ax.legend()
|
| 118 |
+
st.pyplot(fig)
|
| 119 |
+
|
| 120 |
st.title("Analisis Portofolio Saham Optimal (Model Markowitz)")
|
| 121 |
|
| 122 |
st.write("Rekomendasi Saham yang Bertahan Saat COVID-19:")
|
|
|
|
| 145 |
st.subheader("Simulasi Investasi Dollar Cost Averaging (DCA)")
|
| 146 |
simulate_dca(stock_data)
|
| 147 |
|
| 148 |
+
st.subheader("Prediksi Harga Saham dengan AI")
|
| 149 |
+
predict_stock_price(stock_data, selected_stock)
|
| 150 |
|
| 151 |
if optimal_weights is not None:
|
| 152 |
st.subheader("Bobot Portofolio Optimal")
|
| 153 |
portfolio_weights = {stock: weight for stock, weight in zip(stock_data.columns, optimal_weights)}
|
| 154 |
st.write(portfolio_weights)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 155 |
|
|
|
|
| 156 |
|