GarGerry commited on
Commit
35ba371
·
verified ·
1 Parent(s): 25deb13

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +17 -26
app.py CHANGED
@@ -5,60 +5,52 @@ import pandas as pd
5
  import matplotlib.pyplot as plt
6
  import scipy.optimize as sco
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 tahunan dan matriks kovarians
14
  def calculate_returns(data):
15
  log_returns = np.log(data / data.shift(1))
16
  return log_returns.mean() * 252, log_returns.cov() * 252
17
 
18
- # Fungsi untuk menghitung portofolio optimal
19
  def optimize_portfolio(returns, cov_matrix):
20
  num_assets = len(returns)
21
 
22
- # Fungsi untuk menghitung rasio Sharpe (return / risiko)
23
  def sharpe_ratio(weights):
24
  portfolio_return = np.dot(weights, returns)
25
  portfolio_volatility = np.sqrt(np.dot(weights.T, np.dot(cov_matrix, weights)))
26
- return -portfolio_return / portfolio_volatility # Negatif untuk minimisasi
27
-
28
- constraints = ({'type': 'eq', 'fun': lambda x: np.sum(x) - 1}) # Total bobot = 100%
29
- bounds = tuple((0, 1) for _ in range(num_assets)) # Bobot saham antara 0 - 1
30
- init_guess = num_assets * [1. / num_assets] # Tebakan awal
31
 
 
 
 
 
32
  result = sco.minimize(sharpe_ratio, init_guess, method='SLSQP', bounds=bounds, constraints=constraints)
33
- return result.x # Bobot optimal
34
 
35
- # Streamlit UI
36
  st.title("Analisis Portofolio Saham Optimal (Model Markowitz)")
37
 
38
- # Input Saham & Tanggal
39
  tickers_list = st.text_input("Masukkan ticker saham (contoh: BBCA.JK, TLKM.JK, BBRI.JK)", "BBCA.JK, TLKM.JK, BBRI.JK").split(", ")
40
  start_date = st.date_input("Pilih tanggal mulai", pd.to_datetime("2020-01-01"))
41
  end_date = st.date_input("Pilih tanggal akhir", pd.to_datetime("2020-12-31"))
42
 
43
  if st.button("Analisis Portofolio"):
44
  try:
45
- # Ambil data saham
46
  stock_data = get_stock_data(tickers_list, start_date, end_date)
47
- if stock_data.isnull().values.any():
48
- st.error("Data tidak lengkap atau saham tidak ditemukan.")
 
49
  else:
50
- # Hitung return dan kovarians
51
  mean_returns, cov_matrix = calculate_returns(stock_data)
52
-
53
- # Optimasi portofolio
54
  optimal_weights = optimize_portfolio(mean_returns, cov_matrix)
55
-
56
- # Tampilkan hasil
57
  st.subheader("Bobot Portofolio Optimal:")
58
  for i, stock in enumerate(tickers_list):
59
  st.write(f"{stock}: {optimal_weights[i]:.2%}")
60
-
61
- # Plot Efficient Frontier
62
  st.subheader("Efficient Frontier")
63
  fig, ax = plt.subplots()
64
  ax.scatter(np.sqrt(np.diag(cov_matrix)), mean_returns, c=mean_returns / np.sqrt(np.diag(cov_matrix)), marker='o')
@@ -66,6 +58,5 @@ if st.button("Analisis Portofolio"):
66
  ax.set_ylabel("Return Tahunan")
67
  ax.set_title("Efficient Frontier")
68
  st.pyplot(fig)
69
-
70
  except Exception as e:
71
- st.error(f"Terjadi kesalahan: {e}")
 
5
  import matplotlib.pyplot as plt
6
  import scipy.optimize as sco
7
 
 
8
  def get_stock_data(tickers, start, end):
9
+ data = yf.download(tickers, start=start, end=end)
10
+ if 'Adj Close' in data.columns:
11
+ return data['Adj Close']
12
+ else:
13
+ return None
14
 
 
15
  def calculate_returns(data):
16
  log_returns = np.log(data / data.shift(1))
17
  return log_returns.mean() * 252, log_returns.cov() * 252
18
 
 
19
  def optimize_portfolio(returns, cov_matrix):
20
  num_assets = len(returns)
21
 
 
22
  def sharpe_ratio(weights):
23
  portfolio_return = np.dot(weights, returns)
24
  portfolio_volatility = np.sqrt(np.dot(weights.T, np.dot(cov_matrix, weights)))
25
+ return -portfolio_return / portfolio_volatility
 
 
 
 
26
 
27
+ constraints = ({'type': 'eq', 'fun': lambda x: np.sum(x) - 1})
28
+ bounds = tuple((0, 1) for _ in range(num_assets))
29
+ init_guess = num_assets * [1. / num_assets]
30
+
31
  result = sco.minimize(sharpe_ratio, init_guess, method='SLSQP', bounds=bounds, constraints=constraints)
32
+ return result.x
33
 
 
34
  st.title("Analisis Portofolio Saham Optimal (Model Markowitz)")
35
 
 
36
  tickers_list = st.text_input("Masukkan ticker saham (contoh: BBCA.JK, TLKM.JK, BBRI.JK)", "BBCA.JK, TLKM.JK, BBRI.JK").split(", ")
37
  start_date = st.date_input("Pilih tanggal mulai", pd.to_datetime("2020-01-01"))
38
  end_date = st.date_input("Pilih tanggal akhir", pd.to_datetime("2020-12-31"))
39
 
40
  if st.button("Analisis Portofolio"):
41
  try:
 
42
  stock_data = get_stock_data(tickers_list, start_date, end_date)
43
+
44
+ if stock_data is None or stock_data.isnull().values.any():
45
+ st.error("Data tidak ditemukan atau tidak lengkap. Periksa ticker atau tanggal yang dipilih.")
46
  else:
 
47
  mean_returns, cov_matrix = calculate_returns(stock_data)
 
 
48
  optimal_weights = optimize_portfolio(mean_returns, cov_matrix)
49
+
 
50
  st.subheader("Bobot Portofolio Optimal:")
51
  for i, stock in enumerate(tickers_list):
52
  st.write(f"{stock}: {optimal_weights[i]:.2%}")
53
+
 
54
  st.subheader("Efficient Frontier")
55
  fig, ax = plt.subplots()
56
  ax.scatter(np.sqrt(np.diag(cov_matrix)), mean_returns, c=mean_returns / np.sqrt(np.diag(cov_matrix)), marker='o')
 
58
  ax.set_ylabel("Return Tahunan")
59
  ax.set_title("Efficient Frontier")
60
  st.pyplot(fig)
 
61
  except Exception as e:
62
+ st.error(f"Terjadi kesalahan: {e}")