Spaces:
Sleeping
Sleeping
Update app.py
Browse files
app.py
CHANGED
|
@@ -8,7 +8,7 @@ import scipy.optimize as sco
|
|
| 8 |
# Fungsi untuk mengunduh data saham
|
| 9 |
def get_stock_data(tickers, start, end):
|
| 10 |
data = yf.download(tickers, start=start, end=end)
|
| 11 |
-
|
| 12 |
if data.empty:
|
| 13 |
st.error("Data saham tidak ditemukan. Periksa ticker atau rentang tanggal.")
|
| 14 |
return None
|
|
@@ -22,7 +22,7 @@ def get_stock_data(tickers, start, end):
|
|
| 22 |
else:
|
| 23 |
st.error("Data harga penutupan tidak ditemukan.")
|
| 24 |
return None
|
| 25 |
-
|
| 26 |
# Fungsi untuk menghitung return tahunan dan matriks kovarians
|
| 27 |
def calculate_returns(data):
|
| 28 |
log_returns = np.log(data / data.shift(1))
|
|
@@ -44,13 +44,30 @@ def optimize_portfolio(returns, cov_matrix):
|
|
| 44 |
result = sco.minimize(sharpe_ratio, init_guess, method='SLSQP', bounds=bounds, constraints=constraints)
|
| 45 |
return result.x if result.success else None
|
| 46 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 47 |
# Streamlit UI
|
| 48 |
st.title("Analisis Portofolio Saham Optimal (Model Markowitz)")
|
| 49 |
|
| 50 |
# Input Saham & Tanggal
|
| 51 |
tickers_list = st.text_input("Masukkan ticker saham (contoh: BBCA.JK, TLKM.JK, BBRI.JK)", "BBCA.JK, TLKM.JK, BBRI.JK").split(", ")
|
| 52 |
start_date = st.date_input("Pilih tanggal mulai", pd.to_datetime("2020-01-01"))
|
| 53 |
-
end_date = st.date_input("Pilih tanggal akhir", pd.to_datetime("
|
| 54 |
|
| 55 |
if st.button("Analisis Portofolio"):
|
| 56 |
try:
|
|
@@ -58,6 +75,8 @@ if st.button("Analisis Portofolio"):
|
|
| 58 |
stock_data = get_stock_data(tickers_list, start_date, end_date)
|
| 59 |
|
| 60 |
if stock_data is not None:
|
|
|
|
|
|
|
| 61 |
mean_returns, cov_matrix = calculate_returns(stock_data)
|
| 62 |
|
| 63 |
# Optimasi portofolio
|
|
@@ -65,16 +84,19 @@ if st.button("Analisis Portofolio"):
|
|
| 65 |
|
| 66 |
if optimal_weights is not None:
|
| 67 |
st.subheader("Bobot Portofolio Optimal:")
|
| 68 |
-
for i, stock in enumerate(
|
| 69 |
st.write(f"{stock}: {optimal_weights[i]:.2%}")
|
| 70 |
|
| 71 |
-
#
|
|
|
|
|
|
|
| 72 |
st.subheader("Efficient Frontier")
|
| 73 |
fig, ax = plt.subplots()
|
| 74 |
-
ax.scatter(
|
| 75 |
ax.set_xlabel("Risiko (Standar Deviasi)")
|
| 76 |
ax.set_ylabel("Return Tahunan")
|
| 77 |
ax.set_title("Efficient Frontier")
|
|
|
|
| 78 |
st.pyplot(fig)
|
| 79 |
else:
|
| 80 |
st.error("Optimasi portofolio gagal. Coba dengan saham yang berbeda.")
|
|
|
|
| 8 |
# Fungsi untuk mengunduh data saham
|
| 9 |
def get_stock_data(tickers, start, end):
|
| 10 |
data = yf.download(tickers, start=start, end=end)
|
| 11 |
+
|
| 12 |
if data.empty:
|
| 13 |
st.error("Data saham tidak ditemukan. Periksa ticker atau rentang tanggal.")
|
| 14 |
return None
|
|
|
|
| 22 |
else:
|
| 23 |
st.error("Data harga penutupan tidak ditemukan.")
|
| 24 |
return None
|
| 25 |
+
|
| 26 |
# Fungsi untuk menghitung return tahunan dan matriks kovarians
|
| 27 |
def calculate_returns(data):
|
| 28 |
log_returns = np.log(data / data.shift(1))
|
|
|
|
| 44 |
result = sco.minimize(sharpe_ratio, init_guess, method='SLSQP', bounds=bounds, constraints=constraints)
|
| 45 |
return result.x if result.success else None
|
| 46 |
|
| 47 |
+
# Fungsi untuk mensimulasikan portofolio acak
|
| 48 |
+
def generate_efficient_frontier(returns, cov_matrix, num_portfolios=5000):
|
| 49 |
+
num_assets = len(returns)
|
| 50 |
+
results = np.zeros((3, num_portfolios))
|
| 51 |
+
|
| 52 |
+
for i in range(num_portfolios):
|
| 53 |
+
weights = np.random.dirichlet(np.ones(num_assets), size=1)[0]
|
| 54 |
+
portfolio_return = np.dot(weights, returns)
|
| 55 |
+
portfolio_volatility = np.sqrt(np.dot(weights.T, np.dot(cov_matrix, weights)))
|
| 56 |
+
sharpe_ratio = portfolio_return / portfolio_volatility
|
| 57 |
+
|
| 58 |
+
results[0, i] = portfolio_return
|
| 59 |
+
results[1, i] = portfolio_volatility
|
| 60 |
+
results[2, i] = sharpe_ratio
|
| 61 |
+
|
| 62 |
+
return results
|
| 63 |
+
|
| 64 |
# Streamlit UI
|
| 65 |
st.title("Analisis Portofolio Saham Optimal (Model Markowitz)")
|
| 66 |
|
| 67 |
# Input Saham & Tanggal
|
| 68 |
tickers_list = st.text_input("Masukkan ticker saham (contoh: BBCA.JK, TLKM.JK, BBRI.JK)", "BBCA.JK, TLKM.JK, BBRI.JK").split(", ")
|
| 69 |
start_date = st.date_input("Pilih tanggal mulai", pd.to_datetime("2020-01-01"))
|
| 70 |
+
end_date = st.date_input("Pilih tanggal akhir", pd.to_datetime("2023-12-31"))
|
| 71 |
|
| 72 |
if st.button("Analisis Portofolio"):
|
| 73 |
try:
|
|
|
|
| 75 |
stock_data = get_stock_data(tickers_list, start_date, end_date)
|
| 76 |
|
| 77 |
if stock_data is not None:
|
| 78 |
+
st.write("Saham dengan data tersedia:", stock_data.columns) # Debugging
|
| 79 |
+
|
| 80 |
mean_returns, cov_matrix = calculate_returns(stock_data)
|
| 81 |
|
| 82 |
# Optimasi portofolio
|
|
|
|
| 84 |
|
| 85 |
if optimal_weights is not None:
|
| 86 |
st.subheader("Bobot Portofolio Optimal:")
|
| 87 |
+
for i, stock in enumerate(stock_data.columns):
|
| 88 |
st.write(f"{stock}: {optimal_weights[i]:.2%}")
|
| 89 |
|
| 90 |
+
# Simulasi Efficient Frontier
|
| 91 |
+
results = generate_efficient_frontier(mean_returns, cov_matrix)
|
| 92 |
+
|
| 93 |
st.subheader("Efficient Frontier")
|
| 94 |
fig, ax = plt.subplots()
|
| 95 |
+
scatter = ax.scatter(results[1, :], results[0, :], c=results[2, :], cmap="viridis", marker='o')
|
| 96 |
ax.set_xlabel("Risiko (Standar Deviasi)")
|
| 97 |
ax.set_ylabel("Return Tahunan")
|
| 98 |
ax.set_title("Efficient Frontier")
|
| 99 |
+
fig.colorbar(scatter, label="Sharpe Ratio")
|
| 100 |
st.pyplot(fig)
|
| 101 |
else:
|
| 102 |
st.error("Optimasi portofolio gagal. Coba dengan saham yang berbeda.")
|