Spaces:
Sleeping
Sleeping
Update app.py
Browse files
app.py
CHANGED
|
@@ -3,49 +3,61 @@ import pandas as pd
|
|
| 3 |
import numpy as np
|
| 4 |
import yfinance as yf
|
| 5 |
import matplotlib.pyplot as plt
|
|
|
|
| 6 |
|
| 7 |
-
#Fungsi untuk mengunduh data saham
|
|
|
|
|
|
|
|
|
|
| 8 |
|
| 9 |
-
|
|
|
|
|
|
|
| 10 |
|
| 11 |
-
#Fungsi untuk menghitung portofolio optimal
|
| 12 |
-
|
| 13 |
-
|
| 14 |
-
|
| 15 |
-
results = np.zeros((3, num_portfolios))
|
| 16 |
-
weights_record = []
|
| 17 |
-
|
| 18 |
-
for i in range(num_portfolios):
|
| 19 |
weights = np.random.random(num_assets)
|
| 20 |
weights /= np.sum(weights)
|
| 21 |
-
weights_record.append(weights)
|
| 22 |
-
|
| 23 |
-
portfolio_return = np.sum(weights * mean_returns)
|
| 24 |
-
portfolio_stddev = np.sqrt(np.dot(weights.T, np.dot(cov_matrix, weights)))
|
| 25 |
-
sharpe_ratio = portfolio_return / portfolio_stddev
|
| 26 |
-
|
| 27 |
-
results[0, i] = portfolio_return
|
| 28 |
-
results[1, i] = portfolio_stddev
|
| 29 |
-
results[2, i] = sharpe_ratio
|
| 30 |
|
| 31 |
-
|
| 32 |
-
|
| 33 |
-
|
| 34 |
-
return
|
| 35 |
|
| 36 |
-
|
| 37 |
-
|
| 38 |
-
|
| 39 |
-
|
| 40 |
-
|
| 41 |
-
|
| 42 |
-
if st.button("Optimasi Portofolio"): tickers_list = [ticker.strip() for ticker in tickers.split(",")] data = get_stock_data(tickers_list, start_date, end_date) optimal_portfolio = optimize_portfolio(data)
|
| 43 |
|
| 44 |
-
|
| 45 |
-
st.
|
| 46 |
|
| 47 |
-
|
| 48 |
-
|
| 49 |
-
|
| 50 |
-
st.
|
| 51 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 3 |
import numpy as np
|
| 4 |
import yfinance as yf
|
| 5 |
import matplotlib.pyplot as plt
|
| 6 |
+
from scipy.optimize import minimize
|
| 7 |
|
| 8 |
+
# Fungsi untuk mengunduh data saham
|
| 9 |
+
def get_stock_data(tickers, start, end):
|
| 10 |
+
data = yf.download(tickers, start=start, end=end)['Adj Close']
|
| 11 |
+
return data
|
| 12 |
|
| 13 |
+
# Fungsi untuk menghitung return harian
|
| 14 |
+
def calculate_daily_returns(data):
|
| 15 |
+
return data.pct_change().dropna()
|
| 16 |
|
| 17 |
+
# Fungsi untuk menghitung portofolio optimal dengan Model Markowitz
|
| 18 |
+
def optimize_portfolio(returns):
|
| 19 |
+
num_assets = len(returns.columns)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 20 |
weights = np.random.random(num_assets)
|
| 21 |
weights /= np.sum(weights)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 22 |
|
| 23 |
+
def portfolio_performance(weights):
|
| 24 |
+
port_return = np.sum(returns.mean() * weights) * 252
|
| 25 |
+
port_volatility = np.sqrt(np.dot(weights.T, np.dot(returns.cov() * 252, weights)))
|
| 26 |
+
return port_volatility
|
| 27 |
|
| 28 |
+
constraints = ({'type': 'eq', 'fun': lambda x: np.sum(x) - 1})
|
| 29 |
+
bounds = tuple((0, 1) for _ in range(num_assets))
|
| 30 |
+
result = minimize(portfolio_performance, weights, method='SLSQP', bounds=bounds, constraints=constraints)
|
| 31 |
+
|
| 32 |
+
return result.x
|
|
|
|
|
|
|
| 33 |
|
| 34 |
+
# Streamlit UI
|
| 35 |
+
st.title("Analisis Portofolio Saham Model Markowitz")
|
| 36 |
|
| 37 |
+
# Input pengguna untuk daftar saham
|
| 38 |
+
tickers = st.text_input("Masukkan kode saham (pisahkan dengan koma)", "BBCA.JK,TLKM.JK,UNVR.JK")
|
| 39 |
+
start_date = st.date_input("Pilih tanggal mulai", pd.to_datetime("2020-01-01"))
|
| 40 |
+
end_date = st.date_input("Pilih tanggal akhir", pd.to_datetime("2020-12-31"))
|
| 41 |
|
| 42 |
+
if st.button("Analisis"):
|
| 43 |
+
tickers_list = [t.strip() for t in tickers.split(',')]
|
| 44 |
+
data = get_stock_data(tickers_list, start_date, end_date)
|
| 45 |
+
|
| 46 |
+
if not data.empty:
|
| 47 |
+
st.write("Data Harga Saham")
|
| 48 |
+
st.line_chart(data)
|
| 49 |
+
|
| 50 |
+
returns = calculate_daily_returns(data)
|
| 51 |
+
optimal_weights = optimize_portfolio(returns)
|
| 52 |
+
|
| 53 |
+
st.write("Bobot Optimal Portofolio:")
|
| 54 |
+
for ticker, weight in zip(tickers_list, optimal_weights):
|
| 55 |
+
st.write(f"{ticker}: {weight:.2%}")
|
| 56 |
+
|
| 57 |
+
# Visualisasi Portofolio
|
| 58 |
+
fig, ax = plt.subplots()
|
| 59 |
+
ax.pie(optimal_weights, labels=tickers_list, autopct='%1.1f%%', startangle=90)
|
| 60 |
+
ax.axis("equal")
|
| 61 |
+
st.pyplot(fig)
|
| 62 |
+
else:
|
| 63 |
+
st.error("Gagal mengambil data saham. Pastikan kode saham benar.")
|