Spaces:
Sleeping
Sleeping
Create app.py
Browse files
app.py
ADDED
@@ -0,0 +1,47 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
import streamlit as st import pandas as pd import numpy as np import yfinance as yf import matplotlib.pyplot as plt
|
2 |
+
|
3 |
+
Fungsi untuk mengunduh data saham
|
4 |
+
|
5 |
+
def get_stock_data(tickers, start, end): data = yf.download(tickers, start=start, end=end)['Adj Close'] return data
|
6 |
+
|
7 |
+
Fungsi untuk menghitung portofolio optimal
|
8 |
+
|
9 |
+
def optimize_portfolio(data): returns = data.pct_change().dropna() mean_returns = returns.mean() cov_matrix = returns.cov() num_assets = len(data.columns) num_portfolios = 10000
|
10 |
+
|
11 |
+
results = np.zeros((3, num_portfolios))
|
12 |
+
weights_record = []
|
13 |
+
|
14 |
+
for i in range(num_portfolios):
|
15 |
+
weights = np.random.random(num_assets)
|
16 |
+
weights /= np.sum(weights)
|
17 |
+
weights_record.append(weights)
|
18 |
+
|
19 |
+
portfolio_return = np.sum(weights * mean_returns)
|
20 |
+
portfolio_stddev = np.sqrt(np.dot(weights.T, np.dot(cov_matrix, weights)))
|
21 |
+
sharpe_ratio = portfolio_return / portfolio_stddev
|
22 |
+
|
23 |
+
results[0, i] = portfolio_return
|
24 |
+
results[1, i] = portfolio_stddev
|
25 |
+
results[2, i] = sharpe_ratio
|
26 |
+
|
27 |
+
max_sharpe_idx = np.argmax(results[2])
|
28 |
+
optimal_weights = weights_record[max_sharpe_idx]
|
29 |
+
optimal_portfolio = {data.columns[i]: optimal_weights[i] for i in range(num_assets)}
|
30 |
+
return optimal_portfolio
|
31 |
+
|
32 |
+
Streamlit UI
|
33 |
+
|
34 |
+
st.title("Optimasi Portofolio dengan Model Markowitz")
|
35 |
+
|
36 |
+
tickers = st.text_input("Masukkan kode saham (pisahkan dengan koma):", "BBCA.JK, TLKM.JK, UNVR.JK") start_date = st.date_input("Pilih tanggal mulai", pd.to_datetime("2020-01-01")) end_date = st.date_input("Pilih tanggal akhir", pd.to_datetime("2020-12-31"))
|
37 |
+
|
38 |
+
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)
|
39 |
+
|
40 |
+
st.subheader("Bobot Optimal Portofolio")
|
41 |
+
st.write(pd.DataFrame(optimal_portfolio.items(), columns=["Saham", "Bobot"]))
|
42 |
+
|
43 |
+
fig, ax = plt.subplots()
|
44 |
+
ax.pie(optimal_portfolio.values(), labels=optimal_portfolio.keys(), autopct='%1.1f%%', startangle=140)
|
45 |
+
ax.axis('equal')
|
46 |
+
st.pyplot(fig)
|
47 |
+
|