Spaces:
Sleeping
Sleeping
| import streamlit as st import pandas as pd import numpy as np import yfinance as yf import matplotlib.pyplot as plt | |
| Fungsi untuk mengunduh data saham | |
| def get_stock_data(tickers, start, end): data = yf.download(tickers, start=start, end=end)['Adj Close'] return data | |
| Fungsi untuk menghitung portofolio optimal | |
| 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 | |
| results = np.zeros((3, num_portfolios)) | |
| weights_record = [] | |
| for i in range(num_portfolios): | |
| weights = np.random.random(num_assets) | |
| weights /= np.sum(weights) | |
| weights_record.append(weights) | |
| portfolio_return = np.sum(weights * mean_returns) | |
| portfolio_stddev = np.sqrt(np.dot(weights.T, np.dot(cov_matrix, weights))) | |
| sharpe_ratio = portfolio_return / portfolio_stddev | |
| results[0, i] = portfolio_return | |
| results[1, i] = portfolio_stddev | |
| results[2, i] = sharpe_ratio | |
| max_sharpe_idx = np.argmax(results[2]) | |
| optimal_weights = weights_record[max_sharpe_idx] | |
| optimal_portfolio = {data.columns[i]: optimal_weights[i] for i in range(num_assets)} | |
| return optimal_portfolio | |
| Streamlit UI | |
| st.title("Optimasi Portofolio dengan Model Markowitz") | |
| 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")) | |
| 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) | |
| st.subheader("Bobot Optimal Portofolio") | |
| st.write(pd.DataFrame(optimal_portfolio.items(), columns=["Saham", "Bobot"])) | |
| fig, ax = plt.subplots() | |
| ax.pie(optimal_portfolio.values(), labels=optimal_portfolio.keys(), autopct='%1.1f%%', startangle=140) | |
| ax.axis('equal') | |
| st.pyplot(fig) | |