Spaces:
Sleeping
Sleeping
File size: 69,724 Bytes
ea55fa1 ee9e90c 5dd4cfa ee9e90c a9d35b2 d88771d ee9e90c ecc6282 ee9e90c 8b07166 ee9e90c 8b07166 ee9e90c 8b07166 ee9e90c 5dd4cfa ee9e90c 8b07166 ee9e90c 8b07166 ee9e90c 8b07166 ee9e90c 8b07166 ee9e90c 8b07166 ee9e90c 8b07166 ee9e90c 8b07166 ee9e90c 8b07166 ee9e90c 8b07166 ee9e90c 8b07166 ee9e90c 8b07166 ee9e90c 8b07166 ee9e90c 8b07166 ee9e90c 8b07166 ee9e90c 8b07166 ee9e90c 8b07166 ee9e90c 8b07166 ee9e90c 8b07166 ee9e90c 8b07166 ee9e90c 8b07166 ee9e90c 8b07166 ee9e90c 8b07166 ee9e90c 8b07166 ee9e90c 8b07166 ee9e90c 8b07166 ee9e90c 8b07166 ee9e90c 8b07166 ee9e90c 8b07166 ee9e90c 8b07166 ee9e90c 8b07166 ee9e90c 8b07166 ee9e90c 8b07166 ee9e90c 8b07166 ee9e90c 8b07166 ee9e90c 8b07166 ee9e90c ea55fa1 ee9e90c 5dd4cfa |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 954 955 956 957 958 959 960 961 962 963 964 965 966 967 968 969 970 971 972 973 974 975 976 977 978 979 980 981 982 983 984 985 986 987 988 989 990 991 992 993 994 995 996 997 998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 1088 1089 1090 1091 1092 1093 1094 1095 1096 1097 1098 1099 1100 1101 1102 1103 1104 1105 1106 1107 1108 1109 1110 1111 1112 1113 1114 1115 1116 1117 1118 1119 1120 1121 1122 1123 1124 1125 1126 1127 1128 1129 1130 1131 1132 1133 1134 1135 1136 1137 1138 1139 1140 1141 1142 1143 1144 1145 1146 1147 1148 1149 1150 1151 1152 1153 1154 1155 1156 1157 1158 1159 1160 1161 1162 1163 1164 1165 1166 1167 1168 1169 1170 1171 1172 1173 1174 1175 1176 1177 1178 1179 1180 1181 1182 1183 1184 1185 1186 1187 1188 1189 1190 1191 1192 1193 1194 1195 1196 1197 1198 1199 1200 1201 1202 1203 1204 1205 1206 1207 1208 1209 1210 1211 1212 1213 1214 1215 1216 1217 1218 1219 1220 1221 1222 1223 1224 1225 1226 1227 1228 1229 1230 1231 1232 1233 1234 1235 1236 1237 1238 1239 1240 1241 1242 1243 1244 1245 1246 1247 1248 1249 1250 1251 1252 1253 1254 1255 1256 1257 1258 1259 1260 1261 1262 1263 1264 1265 1266 1267 1268 1269 1270 1271 1272 1273 1274 1275 1276 1277 1278 1279 1280 1281 1282 1283 1284 1285 1286 1287 1288 1289 1290 1291 1292 1293 1294 1295 1296 1297 1298 1299 1300 1301 1302 1303 1304 1305 1306 1307 1308 1309 1310 1311 1312 1313 1314 1315 1316 1317 1318 1319 1320 1321 1322 1323 1324 1325 1326 1327 1328 1329 1330 1331 1332 1333 1334 1335 1336 1337 1338 1339 1340 1341 1342 1343 1344 1345 1346 1347 1348 1349 1350 1351 1352 1353 1354 1355 1356 1357 1358 1359 1360 1361 1362 1363 1364 1365 1366 1367 1368 1369 1370 1371 1372 1373 1374 1375 1376 1377 1378 1379 1380 1381 1382 1383 1384 1385 1386 1387 1388 1389 1390 1391 1392 1393 1394 1395 1396 1397 1398 1399 1400 1401 1402 1403 1404 1405 1406 1407 1408 1409 1410 1411 1412 1413 1414 1415 1416 1417 1418 1419 1420 1421 1422 1423 1424 1425 1426 1427 1428 1429 1430 1431 1432 1433 1434 1435 1436 1437 1438 1439 1440 1441 1442 1443 1444 1445 1446 1447 1448 1449 1450 1451 1452 1453 1454 1455 1456 1457 1458 1459 1460 1461 1462 1463 1464 1465 1466 1467 1468 1469 1470 1471 1472 1473 1474 1475 1476 1477 1478 1479 1480 1481 1482 1483 1484 1485 1486 1487 1488 1489 1490 1491 1492 1493 1494 1495 1496 1497 1498 1499 1500 1501 1502 1503 1504 1505 1506 1507 1508 1509 1510 1511 1512 1513 1514 1515 1516 1517 1518 1519 1520 1521 1522 1523 1524 1525 1526 1527 1528 1529 1530 1531 1532 1533 1534 1535 1536 1537 1538 1539 1540 1541 1542 1543 1544 1545 1546 1547 1548 1549 1550 1551 1552 1553 1554 1555 1556 1557 1558 1559 1560 1561 1562 1563 1564 1565 1566 1567 1568 1569 1570 1571 1572 1573 1574 1575 1576 1577 1578 1579 1580 1581 1582 1583 1584 1585 1586 1587 1588 1589 1590 1591 1592 1593 1594 1595 1596 1597 1598 1599 1600 1601 1602 1603 1604 1605 1606 1607 1608 1609 1610 1611 1612 1613 1614 1615 1616 1617 1618 1619 1620 1621 1622 1623 1624 1625 1626 1627 1628 1629 1630 1631 1632 1633 1634 1635 1636 1637 1638 1639 1640 1641 1642 1643 1644 1645 1646 1647 1648 1649 1650 1651 1652 1653 1654 1655 1656 1657 1658 1659 1660 1661 1662 1663 1664 1665 1666 1667 1668 1669 1670 1671 1672 1673 1674 1675 1676 1677 1678 1679 1680 1681 1682 1683 1684 1685 1686 1687 1688 1689 1690 1691 1692 1693 1694 1695 1696 1697 1698 1699 1700 1701 1702 1703 1704 1705 1706 1707 1708 1709 1710 1711 1712 1713 1714 1715 1716 1717 1718 1719 1720 1721 1722 1723 1724 1725 1726 1727 1728 1729 1730 1731 1732 1733 1734 1735 1736 1737 1738 1739 1740 1741 1742 1743 1744 1745 1746 1747 1748 1749 1750 1751 1752 1753 1754 1755 1756 1757 1758 1759 1760 1761 1762 1763 1764 1765 1766 1767 1768 1769 1770 1771 1772 1773 1774 1775 1776 1777 1778 1779 1780 1781 1782 1783 1784 1785 1786 1787 1788 1789 1790 1791 1792 1793 1794 1795 1796 1797 1798 1799 1800 1801 1802 1803 1804 1805 1806 1807 1808 1809 1810 1811 1812 1813 1814 1815 1816 1817 1818 1819 1820 1821 1822 1823 1824 1825 1826 1827 1828 1829 1830 1831 1832 1833 1834 1835 1836 1837 1838 1839 1840 1841 1842 1843 1844 1845 1846 1847 1848 1849 1850 1851 1852 1853 1854 1855 1856 1857 1858 1859 1860 1861 1862 1863 1864 1865 1866 1867 1868 1869 1870 1871 1872 1873 1874 1875 1876 1877 1878 1879 1880 1881 1882 1883 1884 1885 1886 1887 1888 1889 1890 1891 1892 1893 1894 1895 1896 1897 1898 1899 1900 1901 1902 1903 1904 1905 1906 1907 1908 1909 1910 1911 1912 1913 1914 1915 1916 1917 1918 1919 1920 1921 1922 1923 1924 1925 1926 1927 1928 1929 1930 1931 1932 1933 1934 1935 1936 1937 1938 1939 1940 1941 1942 1943 1944 1945 1946 1947 1948 1949 1950 1951 1952 1953 1954 1955 1956 1957 1958 1959 1960 1961 1962 1963 1964 1965 1966 1967 1968 1969 1970 1971 1972 1973 1974 1975 1976 1977 1978 1979 1980 1981 1982 1983 1984 1985 1986 1987 1988 1989 1990 1991 1992 1993 1994 1995 1996 1997 1998 1999 2000 2001 2002 2003 2004 2005 2006 2007 2008 2009 2010 2011 2012 2013 2014 2015 2016 2017 2018 2019 2020 2021 2022 2023 2024 2025 2026 2027 2028 2029 2030 2031 2032 2033 2034 2035 2036 2037 2038 2039 2040 2041 2042 2043 2044 2045 2046 2047 2048 2049 2050 2051 2052 2053 2054 2055 2056 2057 2058 2059 2060 2061 2062 2063 2064 2065 2066 2067 2068 2069 2070 2071 2072 2073 2074 2075 2076 2077 2078 2079 2080 2081 2082 2083 2084 2085 2086 2087 2088 2089 2090 2091 2092 2093 2094 2095 2096 2097 2098 2099 2100 2101 2102 2103 2104 2105 2106 2107 2108 2109 2110 2111 2112 2113 2114 2115 2116 2117 2118 2119 2120 2121 2122 2123 2124 2125 2126 2127 2128 2129 2130 2131 2132 2133 2134 2135 2136 2137 2138 2139 2140 2141 2142 2143 2144 2145 2146 2147 2148 2149 2150 2151 2152 2153 2154 2155 2156 2157 2158 2159 2160 2161 2162 2163 2164 2165 2166 2167 2168 2169 2170 2171 2172 2173 2174 2175 2176 2177 2178 2179 2180 2181 2182 2183 2184 2185 2186 2187 2188 2189 2190 2191 2192 2193 2194 2195 2196 2197 2198 2199 2200 2201 2202 2203 2204 2205 2206 2207 2208 2209 2210 2211 2212 2213 2214 2215 2216 2217 2218 2219 2220 2221 |
import streamlit as st
import yfinance as yf
import plotly.graph_objects as go
import plotly.express as px
from plotly.subplots import make_subplots
import pandas as pd
import numpy as np
from datetime import datetime, timedelta
import time
# 頁面配置和主題設定
st.set_page_config(
page_title="台灣股票分析儀表板",
page_icon="💹",
layout="wide",
initial_sidebar_state="expanded"
)
# 應用CSS美化界面
st.markdown("""
<style>
.main-header {
font-size: 2.5rem;
background: linear-gradient(90deg, #0E76BC, #00A591);
-webkit-background-clip: text;
-webkit-text-fill-color: transparent;
padding: 0.2rem 0;
text-align: center;
margin-bottom: 1rem;
}
.dashboard-header {
font-size: 1.8rem;
background: linear-gradient(90deg, #2C3E50, #4CA1AF);
-webkit-background-clip: text;
-webkit-text-fill-color: transparent;
padding: 0.2rem 0;
margin-bottom: 0.5rem;
}
.card {
border-radius: 5px;
background-color: #f9f9f9;
box-shadow: 0 4px 6px rgba(0, 0, 0, 0.1);
padding: 1rem;
margin-bottom: 1rem;
}
.metric-card {
background: linear-gradient(120deg, #f6f9fc, #e9f1f7);
border-radius: 8px;
box-shadow: 0 2px 5px rgba(0,0,0,0.05);
padding: 1rem;
text-align: center;
}
.metric-value {
font-size: 1.8rem;
font-weight: bold;
}
.metric-change-positive {
color: #00A591;
font-weight: bold;
}
.metric-change-negative {
color: #E74C3C;
font-weight: bold;
}
.subtitle {
color: #666;
font-size: 1rem;
}
.stTabs [data-baseweb="tab-list"] {
gap: 24px;
}
.stTabs [data-baseweb="tab"] {
height: 50px;
white-space: pre-wrap;
background-color: #f0f2f6;
border-radius: 4px 4px 0px 0px;
gap: 1px;
padding-top: 10px;
padding-bottom: 10px;
}
.stTabs [aria-selected="true"] {
background-color: #0E76BC !important;
color: white !important;
}
/* 載入動畫 */
@keyframes pulse {
0% { opacity: 0.6; }
50% { opacity: 1; }
100% { opacity: 0.6; }
}
.loading-animation {
animation: pulse 1.5s infinite;
background-color: #0E76BC;
color: white;
padding: 10px;
border-radius: 5px;
text-align: center;
}
/* 自訂滾動條 */
::-webkit-scrollbar {
width: 10px;
background: #f1f1f1;
}
::-webkit-scrollbar-thumb {
background: #0E76BC;
border-radius: 5px;
}
::-webkit-scrollbar-thumb:hover {
background: #09589b;
}
</style>
""", unsafe_allow_html=True)
# 標題和說明
st.markdown('<h1 class="main-header">台灣股票高級分析儀表板</h1>', unsafe_allow_html=True)
st.markdown("""
<div class="card">
<p>這個專業儀表板提供深入的台灣股票分析功能,包括價格趨勢比較、技術指標、基本面數據以及風險分析。輸入股票代號並選擇分析參數來開始您的專業股票分析。</p>
</div>
""", unsafe_allow_html=True)
# ------ 功能函數 ------ #
def get_stock_data(stock_ids, period="1y", interval="1d"):
"""
獲取股票數據
參數:
stock_ids (list): 股票代碼列表
period (str): 時間週期
interval (str): 間隔
返回:
dict: 股票數據字典
"""
stock_data = {}
with st.spinner("正在獲取股票數據..."):
progress_bar = st.progress(0)
for i, stock_id in enumerate(stock_ids):
try:
# 確保台灣股票代碼格式正確
if stock_id.isdigit() or (len(stock_id) <= 4 and stock_id.split('.')[0].isdigit()):
if '.' not in stock_id:
stock_id = f"{stock_id}.TW"
# 獲取股票數據
stock = yf.Ticker(stock_id)
hist = stock.history(period=period, interval=interval)
try:
info = stock.info
except:
info = {}
if not hist.empty:
stock_data[stock_id] = {
'history': hist,
'info': info
}
st.success(f"✅ 成功獲取 {stock_id} 的數據")
else:
st.error(f"❌ 未找到 {stock_id} 的數據")
except Exception as e:
st.error(f"❌ 獲取 {stock_id} 數據時出錯: {str(e)}")
progress_bar.progress((i + 1) / len(stock_ids))
time.sleep(0.5) # 為了視覺效果添加的短暫延遲
progress_bar.empty()
return stock_data
def normalize_data(df):
"""
將數據正規化,以便比較不同價格範圍的股票
"""
return df / df.iloc[0] * 100
def calculate_rsi(data, window=14):
"""計算RSI指標"""
delta = data.diff()
gain = delta.where(delta > 0, 0).rolling(window=window).mean()
loss = -delta.where(delta < 0, 0).rolling(window=window).mean()
rs = gain / loss
rsi = 100 - (100 / (1 + rs))
return rsi
def calculate_macd(data, fast=12, slow=26, signal=9):
"""計算MACD指標"""
exp1 = data.ewm(span=fast, adjust=False).mean()
exp2 = data.ewm(span=slow, adjust=False).mean()
macd = exp1 - exp2
signal_line = macd.ewm(span=signal, adjust=False).mean()
histogram = macd - signal_line
return macd, signal_line, histogram
def calculate_bollinger_bands(data, window=20, num_std=2):
"""計算布林帶"""
rolling_mean = data.rolling(window=window).mean()
rolling_std = data.rolling(window=window).std()
upper_band = rolling_mean + (rolling_std * num_std)
lower_band = rolling_mean - (rolling_std * num_std)
return rolling_mean, upper_band, lower_band
def calculate_volatility(data, window=30):
"""計算波動率"""
log_returns = np.log(data / data.shift(1))
volatility = log_returns.rolling(window=window).std() * np.sqrt(252) * 100 # 年化波動率,以百分比表示
return volatility
def calculate_moving_averages(data):
"""計算不同期間的移動平均線"""
ma20 = data.rolling(window=20).mean()
ma50 = data.rolling(window=50).mean()
ma100 = data.rolling(window=100).mean()
ma200 = data.rolling(window=200).mean()
return ma20, ma50, ma100, ma200
def calculate_performance_metrics(data):
"""計算股票表現指標"""
# 計算每日回報率
daily_returns = data.pct_change().dropna()
# 累積回報率
cumulative_return = (data.iloc[-1] / data.iloc[0] - 1) * 100
# 年化回報率 (假設252個交易日)
days = len(data)
annualized_return = ((1 + cumulative_return / 100) ** (252 / days) - 1) * 100
# 波動率 (年化標準差)
volatility = daily_returns.std() * np.sqrt(252) * 100
# 夏普比率 (假設無風險利率為2%)
risk_free_rate = 0.02
sharpe_ratio = (annualized_return / 100 - risk_free_rate) / (volatility / 100)
# 最大回撤
cum_returns = (1 + daily_returns).cumprod()
running_max = cum_returns.cummax()
drawdown = (cum_returns / running_max - 1) * 100
max_drawdown = drawdown.min()
return {
'cumulative_return': cumulative_return,
'annualized_return': annualized_return,
'volatility': volatility,
'sharpe_ratio': sharpe_ratio,
'max_drawdown': max_drawdown
}
def display_stock_metrics(stock_data):
"""顯示多個股票的關鍵指標"""
if not stock_data:
return
# 創建列來顯示指標
cols = st.columns(len(stock_data))
for i, (stock_id, data) in enumerate(stock_data.items()):
hist = data['history']
if hist.empty:
continue
# 獲取最新和前一天的價格
latest_price = hist['Close'].iloc[-1]
prev_price = hist['Close'].iloc[-2] if len(hist) > 1 else latest_price
price_change = latest_price - prev_price
price_change_pct = (price_change / prev_price) * 100 if prev_price != 0 else 0
# 計算成交量變化
latest_volume = hist['Volume'].iloc[-1] if 'Volume' in hist else 0
avg_volume = hist['Volume'].mean() if 'Volume' in hist else 0
volume_change_pct = ((latest_volume / avg_volume) - 1) * 100 if avg_volume != 0 else 0
with cols[i]:
st.markdown(f"<h3 style='text-align: center;'>{stock_id}</h3>", unsafe_allow_html=True)
# 價格指標
price_color = "metric-change-positive" if price_change >= 0 else "metric-change-negative"
change_symbol = "▲" if price_change >= 0 else "▼"
st.markdown(f"""
<div class="metric-card">
<div class="metric-value">{latest_price:.2f} TWD</div>
<div class="{price_color}">{change_symbol} {abs(price_change):.2f} ({abs(price_change_pct):.2f}%)</div>
<div class="subtitle">最新收盤價</div>
</div>
""", unsafe_allow_html=True)
# 成交量指標
volume_color = "metric-change-positive" if volume_change_pct >= 0 else "metric-change-negative"
vol_symbol = "▲" if volume_change_pct >= 0 else "▼"
if 'Volume' in hist:
formatted_volume = f"{latest_volume/1000000:.2f}M" if latest_volume >= 1000000 else f"{latest_volume/1000:.2f}K"
st.markdown(f"""
<div class="metric-card" style="margin-top: 10px;">
<div class="metric-value">{formatted_volume}</div>
<div class="{volume_color}">{vol_symbol} {abs(volume_change_pct):.2f}%</div>
<div class="subtitle">最新成交量</div>
</div>
""", unsafe_allow_html=True)
def plot_stock_comparison(stock_data):
"""使用 Plotly 繪製股票比較圖表"""
if not stock_data:
st.warning("沒有可用的股票數據來繪製圖表")
return
# 創建圖表
fig = make_subplots(rows=2, cols=1,
shared_xaxes=True,
vertical_spacing=0.1,
subplot_titles=("股價走勢比較", "正規化股價比較 (基準=100)"),
row_heights=[0.6, 0.4])
colors = ['#1f77b4', '#ff7f0e', '#2ca02c', '#d62728', '#9467bd']
color_idx = 0
# 用於正規化的數據
normalized_data = {}
# 添加每個股票的數據到圖表
for stock_id, data in stock_data.items():
hist = data['history']
# 確保數據不為空
if hist.empty:
continue
# 股票名稱顯示
display_name = stock_id
# 獲取顏色
color = colors[color_idx % len(colors)]
color_idx += 1
# 添加原始價格折線圖
fig.add_trace(
go.Scatter(
x=hist.index,
y=hist['Close'],
mode='lines',
name=f"{display_name}",
line=dict(color=color, width=2)
),
row=1, col=1
)
# 正規化數據
normalized = normalize_data(hist['Close'])
normalized_data[stock_id] = normalized
# 添加正規化折線圖
fig.add_trace(
go.Scatter(
x=hist.index,
y=normalized,
mode='lines',
name=f"{display_name} (正規化)",
line=dict(color=color, width=2, dash='dot')
),
row=2, col=1
)
# 更新布局
fig.update_layout(
height=700,
legend=dict(
orientation="h",
yanchor="bottom",
y=1.02,
xanchor="right",
x=1
),
template="plotly_white",
margin=dict(l=40, r=40, t=60, b=40),
hovermode="x unified",
plot_bgcolor='rgba(240,242,246,0.8)',
)
# 更新Y軸標題
fig.update_yaxes(title_text="價格 (TWD)", row=1, col=1, gridcolor='rgba(220,220,220,0.5)')
fig.update_yaxes(title_text="正規化價格 (基準=100)", row=2, col=1, gridcolor='rgba(220,220,220,0.5)')
fig.update_xaxes(gridcolor='rgba(220,220,220,0.5)')
# 顯示圖表
st.plotly_chart(fig, use_container_width=True)
def plot_volume_comparison(stock_data):
"""繪製股票成交量比較圖表"""
if not stock_data:
return
# 創建圖表
fig = go.Figure()
colors = ['#1f77b4', '#ff7f0e', '#2ca02c', '#d62728', '#9467bd']
color_idx = 0
# 添加每個股票的成交量到圖表
has_volume_data = False
for stock_id, data in stock_data.items():
hist = data['history']
# 確保數據不為空且有成交量數據
if hist.empty or 'Volume' not in hist.columns:
continue
has_volume_data = True
# 股票名稱顯示
display_name = stock_id
# 獲取顏色
color = colors[color_idx % len(colors)]
color_idx += 1
# 添加成交量柱狀圖
fig.add_trace(
go.Bar(
x=hist.index,
y=hist['Volume'],
name=f"{display_name}",
marker_color=color,
opacity=0.7
)
)
if not has_volume_data:
st.warning("沒有可用的成交量數據")
return
# 更新布局
fig.update_layout(
title="股票成交量比較",
height=400,
legend=dict(
orientation="h",
yanchor="bottom",
y=1.02,
xanchor="right",
x=1
),
template="plotly_white",
barmode='group',
bargap=0.15,
bargroupgap=0.1,
margin=dict(l=40, r=40, t=60, b=40),
plot_bgcolor='rgba(240,242,246,0.8)',
)
fig.update_yaxes(title_text="成交量", gridcolor='rgba(220,220,220,0.5)')
fig.update_xaxes(gridcolor='rgba(220,220,220,0.5)')
# 顯示圖表
st.plotly_chart(fig, use_container_width=True)
def plot_technical_indicators(stock_data, selected_stock, indicator_type):
"""繪製技術指標圖表"""
if not stock_data or selected_stock not in stock_data:
st.warning("沒有所選股票的數據")
return
hist = stock_data[selected_stock]['history']
if hist.empty:
st.warning("所選股票沒有足夠的歷史數據")
return
# RSI 指標
if indicator_type == "RSI":
rsi = calculate_rsi(hist['Close'])
fig = go.Figure()
# 添加RSI線
fig.add_trace(
go.Scatter(
x=hist.index,
y=rsi,
mode='lines',
name='RSI',
line=dict(color='#1f77b4', width=2)
)
)
# 添加超買超賣水平線
fig.add_trace(
go.Scatter(
x=[hist.index[0], hist.index[-1]],
y=[70, 70],
mode='lines',
line=dict(color='red', width=1, dash='dash'),
name='超買線 (70)'
)
)
fig.add_trace(
go.Scatter(
x=[hist.index[0], hist.index[-1]],
y=[30, 30],
mode='lines',
line=dict(color='green', width=1, dash='dash'),
name='超賣線 (30)'
)
)
fig.add_trace(
go.Scatter(
x=[hist.index[0], hist.index[-1]],
y=[50, 50],
mode='lines',
line=dict(color='gray', width=1, dash='dot'),
name='中位線 (50)'
)
)
fig.update_layout(
title=f"{selected_stock} RSI 指標",
height=400,
template="plotly_white",
margin=dict(l=40, r=40, t=60, b=40),
hovermode="x unified",
plot_bgcolor='rgba(240,242,246,0.8)',
)
fig.update_yaxes(title_text="RSI 值", gridcolor='rgba(220,220,220,0.5)')
fig.update_xaxes(gridcolor='rgba(220,220,220,0.5)')
st.plotly_chart(fig, use_container_width=True)
# MACD 指標
elif indicator_type == "MACD":
macd, signal, histogram = calculate_macd(hist['Close'])
fig = make_subplots(rows=2, cols=1, shared_xaxes=True,
vertical_spacing=0.1,
row_heights=[0.7, 0.3])
# 添加價格線
fig.add_trace(
go.Scatter(
x=hist.index,
y=hist['Close'],
mode='lines',
name='收盤價',
line=dict(color='#1f77b4', width=2)
),
row=1, col=1
)
# 添加MACD線
fig.add_trace(
go.Scatter(
x=hist.index,
y=macd,
mode='lines',
name='MACD',
line=dict(color='#ff7f0e', width=2)
),
row=2, col=1
)
# 添加訊號線
fig.add_trace(
go.Scatter(
x=hist.index,
y=signal,
mode='lines',
name='Signal',
line=dict(color='#2ca02c', width=2)
),
row=2, col=1
)
# 添加柱狀圖
colors = ['red' if val < 0 else 'green' for val in histogram]
fig.add_trace(
go.Bar(
x=hist.index,
y=histogram,
name='Histogram',
marker_color=colors
),
row=2, col=1
)
fig.update_layout(
title=f"{selected_stock} MACD 指標",
height=600,
template="plotly_white",
margin=dict(l=40, r=40, t=60, b=40),
hovermode="x unified",
legend=dict(
orientation="h",
yanchor="bottom",
y=1.02,
xanchor="right",
x=1
),
plot_bgcolor='rgba(240,242,246,0.8)',
)
fig.update_yaxes(title_text="價格", row=1, col=1, gridcolor='rgba(220,220,220,0.5)')
fig.update_yaxes(title_text="MACD", row=2, col=1, gridcolor='rgba(220,220,220,0.5)')
fig.update_xaxes(gridcolor='rgba(220,220,220,0.5)')
st.plotly_chart(fig, use_container_width=True)
# 布林帶
elif indicator_type == "布林帶":
ma, upper, lower = calculate_bollinger_bands(hist['Close'])
fig = go.Figure()
# 添加價格線
fig.add_trace(
go.Scatter(
x=hist.index,
y=hist['Close'],
mode='lines',
name='收盤價',
line=dict(color='#1f77b4', width=2)
)
)
# 添加移動平均線
fig.add_trace(
go.Scatter(
x=hist.index,
y=ma,
mode='lines',
name='20日移動平均線',
line=dict(color='#ff7f0e', width=2)
)
)
# 添加上軌
fig.add_trace(
go.Scatter(
x=hist.index,
y=upper,
mode='lines',
name='上軌 (+2σ)',
line=dict(color='#2ca02c', width=1, dash='dash')
)
)
# 添加下軌
fig.add_trace(
go.Scatter(
x=hist.index,
y=lower,
mode='lines',
name='下軌 (-2σ)',
line=dict(color='#d62728', width=1, dash='dash')
)
)
# 添加陰影區域
fig.add_trace(
go.Scatter(
x=hist.index.tolist() + hist.index.tolist()[::-1],
y=upper.tolist() + lower.tolist()[::-1],
fill='toself',
fillcolor='rgba(44, 160, 44, 0.1)',
line=dict(color='rgba(255,255,255,0)'),
hoverinfo='skip',
showlegend=False
)
)
fig.update_layout(
title=f"{selected_stock} 布林帶",
height=500,
template="plotly_white",
margin=dict(l=40, r=40, t=60, b=40),
hovermode="x unified",
legend=dict(
orientation="h",
yanchor="bottom",
y=1.02,
xanchor="right",
x=1
),
plot_bgcolor='rgba(240,242,246,0.8)',
)
fig.update_yaxes(title_text="價格", gridcolor='rgba(220,220,220,0.5)')
fig.update_xaxes(gridcolor='rgba(220,220,220,0.5)')
st.plotly_chart(fig, use_container_width=True)
# 移動平均線
elif indicator_type == "移動平均線":
ma20, ma50, ma100, ma200 = calculate_moving_averages(hist['Close'])
fig = go.Figure()
# 添加價格線
fig.add_trace(
go.Scatter(
x=hist.index,
y=hist['Close'],
mode='lines',
name='收盤價',
line=dict(color='#1f77b4', width=2)
)
)
# 添加移動平均線
fig.add_trace(
go.Scatter(
x=hist.index,
y=ma20,
mode='lines',
name='20日均線',
line=dict(color='#ff7f0e', width=1.5)
)
)
fig.add_trace(
go.Scatter(
x=hist.index,
y=ma50,
mode='lines',
name='50日均線',
line=dict(color='#2ca02c', width=1.5)
)
)
fig.add_trace(
go.Scatter(
x=hist.index,
y=ma100,
mode='lines',
name='100日均線',
line=dict(color='#d62728', width=1.5)
)
)
fig.add_trace(
go.Scatter(
x=hist.index,
y=ma200,
mode='lines',
name='200日均線',
line=dict(color='#9467bd', width=1.5)
)
)
fig.update_layout(
title=f"{selected_stock} 移動平均線",
height=500,
template="plotly_white",
margin=dict(l=40, r=40, t=60, b=40),
hovermode="x unified",
legend=dict(
orientation="h",
yanchor="bottom",
y=1.02,
xanchor="right",
x=1
),
plot_bgcolor='rgba(240,242,246,0.8)',
)
fig.update_yaxes(title_text="價格", gridcolor='rgba(220,220,220,0.5)')
fig.update_xaxes(gridcolor='rgba(220,220,220,0.5)')
st.plotly_chart(fig, use_container_width=True)
def plot_performance_comparison(stock_data):
"""繪製績效比較圖表"""
if not stock_data:
return
# 收集績效指標
performance_metrics = {}
for stock_id, data in stock_data.items():
hist = data['history']
if not hist.empty:
metrics = calculate_performance_metrics(hist['Close'])
performance_metrics[stock_id] = metrics
def create_candlestick_chart(stock_data, selected_stock):
"""創建蠟燭圖"""
if not stock_data or selected_stock not in stock_data:
st.warning("沒有所選股票的數據")
return
hist = stock_data[selected_stock]['history']
if hist.empty:
st.warning("所選股票沒有足夠的歷史數據")
return
# 創建蠟燭圖
fig = go.Figure(data=[go.Candlestick(
x=hist.index,
open=hist['Open'],
high=hist['High'],
low=hist['Low'],
close=hist['Close'],
increasing_line_color='#26a69a',
decreasing_line_color='#ef5350'
)])
# 添加移動平均線
ma20 = hist['Close'].rolling(window=20).mean()
ma50 = hist['Close'].rolling(window=50).mean()
fig.add_trace(
go.Scatter(
x=hist.index,
y=ma20,
mode='lines',
name='MA 20',
line=dict(color='#2962ff', width=1.5)
)
)
fig.add_trace(
go.Scatter(
x=hist.index,
y=ma50,
mode='lines',
name='MA 50',
line=dict(color='#ff6d00', width=1.5)
)
)
# 更新布局
fig.update_layout(
title=f"{selected_stock} 蠟燭圖與移動平均線",
height=600,
template="plotly_white",
margin=dict(l=40, r=40, t=60, b=40),
xaxis_rangeslider_visible=False, # 隱藏底部滾動條
hovermode="x unified",
legend=dict(
orientation="h",
yanchor="bottom",
y=1.02,
xanchor="right",
x=1
),
plot_bgcolor='rgba(240,242,246,0.8)',
)
fig.update_yaxes(title_text="價格 (TWD)", gridcolor='rgba(220,220,220,0.5)')
fig.update_xaxes(gridcolor='rgba(220,220,220,0.5)')
# 下方加上成交量圖表
fig2 = make_subplots(rows=2, cols=1, shared_xaxes=True,
vertical_spacing=0.1,
row_heights=[0.7, 0.3])
# 添加蠟燭圖
fig2.add_trace(
go.Candlestick(
x=hist.index,
open=hist['Open'],
high=hist['High'],
low=hist['Low'],
close=hist['Close'],
increasing_line_color='#26a69a',
decreasing_line_color='#ef5350',
name="股價"
),
row=1, col=1
)
# 添加移動平均線
fig2.add_trace(
go.Scatter(
x=hist.index,
y=ma20,
mode='lines',
name='MA 20',
line=dict(color='#2962ff', width=1.5)
),
row=1, col=1
)
fig2.add_trace(
go.Scatter(
x=hist.index,
y=ma50,
mode='lines',
name='MA 50',
line=dict(color='#ff6d00', width=1.5)
),
row=1, col=1
)
# 添加成交量
colors = ['#ef5350' if row['Close'] < row['Open'] else '#26a69a' for index, row in hist.iterrows()]
# 檢查是否有成交量數據
if 'Volume' in hist.columns:
fig2.add_trace(
go.Bar(
x=hist.index,
y=hist['Volume'],
marker_color=colors,
name="成交量"
),
row=2, col=1
)
# 更新布局
fig2.update_layout(
title=f"{selected_stock} 蠟燭圖與成交量",
height=700,
template="plotly_white",
margin=dict(l=40, r=40, t=60, b=40),
xaxis_rangeslider_visible=False,
hovermode="x unified",
legend=dict(
orientation="h",
yanchor="bottom",
y=1.02,
xanchor="right",
x=1
),
plot_bgcolor='rgba(240,242,246,0.8)',
)
fig2.update_yaxes(title_text="價格", row=1, col=1, gridcolor='rgba(220,220,220,0.5)')
fig2.update_yaxes(title_text="成交量", row=2, col=1, gridcolor='rgba(220,220,220,0.5)')
fig2.update_xaxes(gridcolor='rgba(220,220,220,0.5)')
tabs = st.tabs(["標準蠟燭圖", "蠟燭圖 + 成交量"])
with tabs[0]:
st.plotly_chart(fig, use_container_width=True)
with tabs[1]:
st.plotly_chart(fig2, use_container_width=True)
def plot_sector_pie_chart():
"""繪製台灣股市產業分佈圓餅圖"""
# 台灣股市主要產業權重(模擬數據)
sectors = {
'半導體': 45.2,
'電子零組件': 12.8,
'電腦及周邊': 8.5,
'金融保險': 7.9,
'電信服務': 5.3,
'塑膠化工': 4.8,
'紡織纖維': 3.2,
'鋼鐵': 2.9,
'電機機械': 2.8,
'食品': 2.2,
'其他': 4.4
}
# 創建圓餅圖
fig = go.Figure(data=[go.Pie(
labels=list(sectors.keys()),
values=list(sectors.values()),
textinfo='label+percent',
insidetextorientation='radial',
hole=0.4,
marker=dict(
colors=px.colors.qualitative.Set3
)
)])
fig.update_layout(
title="台灣股市產業權重分佈",
height=400,
template="plotly_white",
margin=dict(l=20, r=20, t=50, b=20),
annotations=[dict(text='產業分佈', x=0.5, y=0.5, font_size=20, showarrow=False)]
)
st.plotly_chart(fig, use_container_width=True)
# 主程序部分
import random # 導入隨機數模組,用於一些示範數據
# 側邊欄:股票選擇和參數設定
with st.sidebar:
st.image("https://upload.wikimedia.org/wikipedia/commons/thumb/c/cb/TWSE_logo.svg/1200px-TWSE_logo.svg.png", width=100)
st.markdown("### 分析設定")
# 股票選擇
st.subheader("選擇股票")
default_stocks = "2330,2454,2317,2412,2382"
stock_input = st.text_input(
"輸入股票代碼 (以逗號分隔)",
value=default_stocks,
help="例如: 2330,2454,2317"
)
# 解析股票代碼
stock_ids = [s.strip() for s in stock_input.split(',') if s.strip()]
# 時間範圍選擇
st.subheader("時間範圍")
period = st.selectbox(
"選擇時間範圍",
options=["1m", "3m", "6m", "1y", "2y", "5y"],
index=3, # 預設 1年
format_func=lambda x: {
"1m": "1個月",
"3m": "3個月",
"6m": "6個月",
"1y": "1年",
"2y": "2年",
"5y": "5年"
}.get(x, x)
)
# 數據頻率選擇
interval = st.selectbox(
"選擇數據頻率",
options=["1d", "1wk", "1mo"],
index=0, # 預設每日
format_func=lambda x: {
"1d": "每日",
"1wk": "每週",
"1mo": "每月"
}.get(x, x)
)
# 加入一個分隔線
st.markdown("---")
# 添加一些關於儀表板的資訊
st.markdown("### 🔍 關於此儀表板")
st.markdown("""
此專業版儀表板提供台灣股票的深度分析:
- 📊 互動式價格和成交量圖表
- 📈 多股票比較分析
- 📉 專業技術指標分析
- 💰 風險與獲利評估
- 🔮 蠟燭圖形態識別
- 🧩 產業和基本面分析
""")
st.markdown("---")
st.markdown("### 🚀 開始分析")
analyze_button = st.button("分析", type="primary", use_container_width=True)
# 主要內容區域
if analyze_button or st.session_state.get('has_analyzed', False):
st.session_state['has_analyzed'] = True
# 檢查是否有輸入股票代碼
if not stock_ids:
st.error("請至少輸入一個股票代碼")
elif len(stock_ids) > 5:
st.warning("最多只能比較5個股票,已取前5個")
stock_ids = stock_ids[:5]
else:
# 獲取股票數據
stock_data = get_stock_data(stock_ids, period, interval)
if stock_data:
# 顯示儀表板標題
st.markdown('<h2 class="dashboard-header">台股分析儀表板</h2>', unsafe_allow_html=True)
# 顯示股票指標卡片
display_stock_metrics(stock_data)
# 使用Tab來組織內容
tabs = st.tabs(["📊 多股比較", "💹 技術分析", "📑 績效評估", "🔍 個股詳情", "🧩 市場情報"])
# Tab 1: 多股比較
with tabs[0]:
st.markdown("### 股價走勢比較")
# 繪製股價比較圖表
plot_stock_comparison(stock_data)
# 繪製成交量比較圖表
st.markdown("### 成交量比較")
plot_volume_comparison(stock_data)
# 股票相關性分析
if len(stock_data) >= 2:
st.markdown("### 股票價格相關性分析")
plot_correlation_matrix(stock_data)
# 雷達圖比較
if len(stock_data) >= 2:
st.markdown("### 綜合表現比較")
plot_radar_comparison(stock_data)
# Tab 2: 技術分析
with tabs[1]:
# 股票選擇
selected_stock = st.selectbox(
"選擇要分析的股票",
options=list(stock_data.keys()),
index=0
)
# 創建蠟燭圖
st.markdown("### 蠟燭圖分析")
create_candlestick_chart(stock_data, selected_stock)
# 技術指標
st.markdown("### 技術指標分析")
indicator_type = st.selectbox(
"選擇技術指標",
options=["RSI", "MACD", "布林帶", "移動平均線"],
index=0
)
plot_technical_indicators(stock_data, selected_stock, indicator_type)
# Tab 3: 績效評估
with tabs[2]:
st.markdown("### 股票績效指標比較")
plot_performance_comparison(stock_data)
# Tab 4: 個股詳情
with tabs[3]:
selected_detail_stock = st.selectbox(
"選擇要查看詳情的股票",
options=list(stock_data.keys()),
index=0,
key="detail_stock_selector"
)
# 顯示股票基本資訊
info = stock_data[selected_detail_stock]['info']
hist = stock_data[selected_detail_stock]['history']
col1, col2 = st.columns([2, 1])
with col1:
st.markdown(f"### {selected_detail_stock} 基本資料")
# 創建基本資料卡片
company_info = {
"公司名稱": info.get('longName', '無資料'),
"產業": info.get('industry', '無資料'),
"部門": info.get('sector', '無資料'),
"52週高點": info.get('fiftyTwoWeekHigh', '無資料'),
"52週低點": info.get('fiftyTwoWeekLow', '無資料'),
"市值": f"{info.get('marketCap', 0) / 1000000000:.2f} 十億TWD" if info.get('marketCap') else '無資料',
"本益比 (TTM)": info.get('trailingPE', '無資料'),
"前5日平均成交量": f"{info.get('averageVolume', 0) / 1000000:.2f} 百萬" if info.get('averageVolume') else '無資料'
}
# 創建兩列顯示
info_cols = st.columns(2)
for i, (key, value) in enumerate(company_info.items()):
with info_cols[i % 2]:
st.markdown(f"""
<div class="metric-card" style="margin-bottom: 10px;">
<div class="subtitle">{key}</div>
<div class="metric-value" style="font-size: 1.3rem;">{value}</div>
</div>
""", unsafe_allow_html=True)
with col2:
# 顯示最近交易數據
st.markdown(f"### 最近交易數據")
if not hist.empty:
# 顯示最近5個交易日的數據
st.dataframe(hist.tail(5), use_container_width=True)
# 計算最近一天的漲跌幅
if len(hist) >= 2:
latest = hist.iloc[-1]
prev = hist.iloc[-2]
change_pct = (latest['Close'] - prev['Close']) / prev['Close'] * 100
change_color = "metric-change-positive" if change_pct >= 0 else "metric-change-negative"
change_symbol = "▲" if change_pct >= 0 else "▼"
st.markdown(f"""
<div class="metric-card" style="margin-top: 20px;">
<div class="subtitle">最近一日漲跌幅</div>
<div class="{change_color}">{change_symbol} {abs(change_pct):.2f}%</div>
</div>
""", unsafe_allow_html=True)
# 顯示績效指標
st.markdown("### 績效指標")
metrics = calculate_performance_metrics(hist['Close'])
metrics_cols = st.columns(5)
with metrics_cols[0]:
st.markdown(f"""
<div class="metric-card">
<div class="subtitle">累積報酬率</div>
<div class="metric-value">{metrics['cumulative_return']:.2f}%</div>
</div>
""", unsafe_allow_html=True)
with metrics_cols[1]:
st.markdown(f"""
<div class="metric-card">
<div class="subtitle">年化報酬率</div>
<div class="metric-value">{metrics['annualized_return']:.2f}%</div>
</div>
""", unsafe_allow_html=True)
with metrics_cols[2]:
st.markdown(f"""
<div class="metric-card">
<div class="subtitle">波動率</div>
<div class="metric-value">{metrics['volatility']:.2f}%</div>
</div>
""", unsafe_allow_html=True)
with metrics_cols[3]:
st.markdown(f"""
<div class="metric-card">
<div class="subtitle">夏普比率</div>
<div class="metric-value">{metrics['sharpe_ratio']:.2f}</div>
</div>
""", unsafe_allow_html=True)
with metrics_cols[4]:
st.markdown(f"""
<div class="metric-card">
<div class="subtitle">最大回撤</div>
<div class="metric-value">{metrics['max_drawdown']:.2f}%</div>
</div>
""", unsafe_allow_html=True)
# 顯示雷達圖
st.markdown("### 雷達圖")
plot_radar_comparison({stock_id: {'history': hist}})
# 顯示股價走勢圖
st.markdown("### 股價走勢圖")
def plot_radar_comparison(stock_data):
"""繪製雷達圖比較股票表現"""
if not stock_data or len(stock_data) < 2:
return
metrics_data = {}
for stock_id, data in stock_data.items():
hist = data['history']
if not hist.empty:
metrics = calculate_performance_metrics(hist['Close'])
# 標準化指標值 (正向指標越大越好,負向指標越小越好)
normalized_metrics = {
'Return': min(max(metrics['annualized_return'] / 30, 0), 10), # 正向,標準化到0-10
'Sharpe': min(max((metrics['sharpe_ratio'] + 1) / 2, 0), 10), # 正向,標準化到0-10
'Stability': min(max(10 - abs(metrics['volatility'] / 15), 0), 10), # 負向,波動越小越好
'Recovery': min(max(10 - abs(metrics['max_drawdown'] / 10), 0), 10), # 負向,回撤越小越好
'Consistency': min(max(random.uniform(5, 9), 0), 10) # 模擬一致性指標
}
metrics_data[stock_id] = normalized_metrics
if not metrics_data:
st.warning("沒有足夠的數據來創建雷達圖比較")
return
# 創建雷達圖
categories = ['Return', 'Sharpe', 'Stability', 'Recovery', 'Consistency']
fig = go.Figure()
colors = ['#1f77b4', '#ff7f0e', '#2ca02c', '#d62728', '#9467bd']
for i, (stock_id, metrics) in enumerate(metrics_data.items()):
color = colors[i % len(colors)]
fig.add_trace(go.Scatterpolar(
r=[metrics[cat] for cat in categories],
theta=categories,
fill='toself',
name=stock_id,
line_color=color,
opacity=0.8
))
fig.update_layout(
polar=dict(
radialaxis=dict(
visible=True,
range=[0, 10]
)
),
showlegend=True,
title="股票綜合表現比較 (雷達圖)",
height=500,
template="plotly_white"
)
st.plotly_chart(fig, use_container_width=True)
def plot_correlation_matrix(stock_data):
"""繪製股票相關性矩陣"""
if not stock_data or len(stock_data) < 2:
return
# 獲取所有股票的收盤價
close_prices = {}
for stock_id, data in stock_data.items():
hist = data['history']
if not hist.empty:
close_prices[stock_id] = hist['Close']
if not close_prices:
st.warning("沒有足夠的數據來計算相關性")
return
# 創建數據框
prices_df = pd.DataFrame(close_prices)
# 計算相關性矩陣
corr_matrix = prices_df.corr()
# 繪製熱力圖
fig = go.Figure(data=go.Heatmap(
z=corr_matrix.values,
x=corr_matrix.columns,
y=corr_matrix.index,
colorscale='Blues',
zmin=-1, zmax=1,
text=corr_matrix.round(2).values,
texttemplate="%{text:.2f}",
hoverongaps=False,
hoverinfo='text',
colorbar=dict(title='相關係數')
))
fig.update_layout(
title="股票價格相關性矩陣",
height=500,
margin=dict(l=40, r=40, t=60, b=40)
)
st.plotly_chart(fig, use_container_width=True)
import streamlit as st
# 頁面配置和主題設定
# 應用CSS美化界面
st.markdown("""
<style>
.main-header {
font-size: 2.5rem;
background: linear-gradient(90deg, #0E76BC, #00A591);
-webkit-background-clip: text;
-webkit-text-fill-color: transparent;
padding: 0.2rem 0;
text-align: center;
margin-bottom: 1rem;
}
.dashboard-header {
font-size: 1.8rem;
background: linear-gradient(90deg, #2C3E50, #4CA1AF);
-webkit-background-clip: text;
-webkit-text-fill-color: transparent;
padding: 0.2rem 0;
margin-bottom: 0.5rem;
}
.card {
border-radius: 5px;
background-color: #f9f9f9;
box-shadow: 0 4px 6px rgba(0, 0, 0, 0.1);
padding: 1rem;
margin-bottom: 1rem;
}
.metric-card {
background: linear-gradient(120deg, #f6f9fc, #e9f1f7);
border-radius: 8px;
box-shadow: 0 2px 5px rgba(0,0,0,0.05);
padding: 1rem;
text-align: center;
}
.metric-value {
font-size: 1.8rem;
font-weight: bold;
}
.metric-change-positive {
color: #00A591;
font-weight: bold;
}
.metric-change-negative {
color: #E74C3C;
font-weight: bold;
}
.subtitle {
color: #666;
font-size: 1rem;
}
.stTabs [data-baseweb="tab-list"] {
gap: 24px;
}
.stTabs [data-baseweb="tab"] {
height: 50px;
white-space: pre-wrap;
background-color: #f0f2f6;
border-radius: 4px 4px 0px 0px;
gap: 1px;
padding-top: 10px;
padding-bottom: 10px;
}
.stTabs [aria-selected="true"] {
background-color: #0E76BC !important;
color: white !important;
}
/* 載入動畫 */
@keyframes pulse {
0% { opacity: 0.6; }
50% { opacity: 1; }
100% { opacity: 0.6; }
}
.loading-animation {
animation: pulse 1.5s infinite;
background-color: #0E76BC;
color: white;
padding: 10px;
border-radius: 5px;
text-align: center;
}
/* 自訂滾動條 */
::-webkit-scrollbar {
width: 10px;
background: #f1f1f1;
}
::-webkit-scrollbar-thumb {
background: #0E76BC;
border-radius: 5px;
}
::-webkit-scrollbar-thumb:hover {
background: #09589b;
}
</style>
""", unsafe_allow_html=True)
# 標題和說明
st.markdown('<h1 class="main-header">台灣股票高級分析儀表板</h1>', unsafe_allow_html=True)
st.markdown("""
<div class="card">
<p>這個專業儀表板提供深入的台灣股票分析功能,包括價格趨勢比較、技術指標、基本面數據以及風險分析。輸入股票代號並選擇分析參數來開始您的專業股票分析。</p>
</div>
""", unsafe_allow_html=True)
# ------ 功能函數 ------ #
def get_stock_data(stock_ids, period="1y", interval="1d"):
'''
參數:
stock_ids (list): 股票代碼列表
period (str): 時間週期
interval (str): 間隔
返回:
dict: 股票數據字典
'''
stock_data = {}
with st.spinner("正在獲取股票數據..."):
progress_bar = st.progress(0)
for i, stock_id in enumerate(stock_ids):
try:
# 確保台灣股票代碼格式正確
if stock_id.isdigit() or (len(stock_id) <= 4 and stock_id.split('.')[0].isdigit()):
if '.' not in stock_id:
stock_id = f"{stock_id}.TW"
# 獲取股票數據
stock = yf.Ticker(stock_id)
hist = stock.history(period=period, interval=interval)
try:
info = stock.info
except:
info = {}
if not hist.empty:
stock_data[stock_id] = {
'history': hist,
'info': info
}
st.success(f"✅ 成功獲取 {stock_id} 的數據")
else:
st.error(f"❌ 未找到 {stock_id} 的數據")
except Exception as e:
st.error(f"❌ 獲取 {stock_id} 數據時出錯: {str(e)}")
progress_bar.progress((i + 1) / len(stock_ids))
time.sleep(0.5) # 為了視覺效果添加的短暫延遲
progress_bar.empty()
return stock_data
rs = gain / loss
rsi = 100 - (100 / (1 + rs))
return rsi
# 累積回報率
cumulative_return = (data.iloc[-1] / data.iloc[0] - 1) * 100
# 年化回報率 (假設252個交易日)
days = len(data)
annualized_return = ((1 + cumulative_return / 100) ** (252 / days) - 1) * 100
# 波動率 (年化標準差)
volatility = daily_returns.std() * np.sqrt(252) * 100
# 夏普比率 (假設無風險利率為2%)
risk_free_rate = 0.02
sharpe_ratio = (annualized_return / 100 - risk_free_rate) / (volatility / 100)
# 最大回撤
cum_returns = (1 + daily_returns).cumprod()
running_max = cum_returns.cummax()
drawdown = (cum_returns / running_max - 1) * 100
max_drawdown = drawdown.min()
return {
'cumulative_return': cumulative_return,
'annualized_return': annualized_return,
'volatility': volatility,
'sharpe_ratio': sharpe_ratio,
'max_drawdown': max_drawdown
}
# 創建列來顯示指標
cols = st.columns(len(stock_data))
for i, (stock_id, data) in enumerate(stock_data.items()):
hist = data['history']
if hist.empty:
continue
# 獲取最新和前一天的價格
latest_price = hist['Close'].iloc[-1]
prev_price = hist['Close'].iloc[-2] if len(hist) > 1 else latest_price
price_change = latest_price - prev_price
price_change_pct = (price_change / prev_price) * 100 if prev_price != 0 else 0
# 計算成交量變化
latest_volume = hist['Volume'].iloc[-1] if 'Volume' in hist else 0
avg_volume = hist['Volume'].mean() if 'Volume' in hist else 0
volume_change_pct = ((latest_volume / avg_volume) - 1) * 100 if avg_volume != 0 else 0
with cols[i]:
st.markdown(f"<h3 style='text-align: center;'>{stock_id}</h3>", unsafe_allow_html=True)
# 價格指標
price_color = "metric-change-positive" if price_change >= 0 else "metric-change-negative"
change_symbol = "▲" if price_change >= 0 else "▼"
st.markdown(f"""
<div class="metric-card">
<div class="metric-value">{latest_price:.2f} TWD</div>
<div class="{price_color}">{change_symbol} {abs(price_change):.2f} ({abs(price_change_pct):.2f}%)</div>
<div class="subtitle">最新收盤價</div>
</div>
""", unsafe_allow_html=True)
# 成交量指標
volume_color = "metric-change-positive" if volume_change_pct >= 0 else "metric-change-negative"
vol_symbol = "▲" if volume_change_pct >= 0 else "▼"
if 'Volume' in hist:
formatted_volume = f"{latest_volume/1000000:.2f}M" if latest_volume >= 1000000 else f"{latest_volume/1000:.2f}K"
st.markdown(f"""
<div class="metric-card" style="margin-top: 10px;">
<div class="metric-value">{formatted_volume}</div>
<div class="{volume_color}">{vol_symbol} {abs(volume_change_pct):.2f}%</div>
<div class="subtitle">最新成交量</div>
</div>
""", unsafe_allow_html=True)
# 創建圖表
fig = make_subplots(rows=2, cols=1,
shared_xaxes=True,
vertical_spacing=0.1,
subplot_titles=("股價走勢比較", "正規化股價比較 (基準=100)"),
row_heights=[0.6, 0.4])
colors = ['#1f77b4', '#ff7f0e', '#2ca02c', '#d62728', '#9467bd']
color_idx = 0
# 用於正規化的數據
normalized_data = {}
# 添加每個股票的數據到圖表
for stock_id, data in stock_data.items():
hist = data['history']
# 確保數據不為空
if hist.empty:
continue
# 股票名稱顯示
display_name = stock_id
# 獲取顏色
color = colors[color_idx % len(colors)]
color_idx += 1
# 添加原始價格折線圖
fig.add_trace(
go.Scatter(
x=hist.index,
y=hist['Close'],
mode='lines',
name=f"{display_name}",
line=dict(color=color, width=2)
),
row=1, col=1
)
# 正規化數據
normalized = normalize_data(hist['Close'])
normalized_data[stock_id] = normalized
# 添加正規化折線圖
fig.add_trace(
go.Scatter(
x=hist.index,
y=normalized,
mode='lines',
name=f"{display_name} (正規化)",
line=dict(color=color, width=2, dash='dot')
),
row=2, col=1
)
# 更新布局
fig.update_layout(
height=700,
legend=dict(
orientation="h",
yanchor="bottom",
y=1.02,
xanchor="right",
x=1
),
template="plotly_white",
margin=dict(l=40, r=40, t=60, b=40),
hovermode="x unified",
plot_bgcolor='rgba(240,242,246,0.8)',
)
# 更新Y軸標題
fig.update_yaxes(title_text="價格 (TWD)", row=1, col=1, gridcolor='rgba(220,220,220,0.5)')
fig.update_yaxes(title_text="正規化價格 (基準=100)", row=2, col=1, gridcolor='rgba(220,220,220,0.5)')
fig.update_xaxes(gridcolor='rgba(220,220,220,0.5)')
# 顯示圖表
st.plotly_chart(fig, use_container_width=True)
# 創建圖表
fig = go.Figure()
colors = ['#1f77b4', '#ff7f0e', '#2ca02c', '#d62728', '#9467bd']
color_idx = 0
# 添加每個股票的成交量到圖表
has_volume_data = False
for stock_id, data in stock_data.items():
hist = data['history']
# 確保數據不為空且有成交量數據
if hist.empty or 'Volume' not in hist.columns:
continue
has_volume_data = True
# 股票名稱顯示
display_name = stock_id
# 獲取顏色
color = colors[color_idx % len(colors)]
color_idx += 1
# 添加成交量柱狀圖
fig.add_trace(
go.Bar(
x=hist.index,
y=hist['Volume'],
name=f"{display_name}",
marker_color=color,
opacity=0.7
)
)
if not has_volume_data:
st.warning("沒有可用的成交量數據")
return
# 更新布局
fig.update_layout(
title="股票成交量比較",
height=400,
legend=dict(
orientation="h",
yanchor="bottom",
y=1.02,
xanchor="right",
x=1
),
template="plotly_white",
barmode='group',
bargap=0.15,
bargroupgap=0.1,
margin=dict(l=40, r=40, t=60, b=40),
plot_bgcolor='rgba(240,242,246,0.8)',
)
fig.update_yaxes(title_text="成交量", gridcolor='rgba(220,220,220,0.5)')
fig.update_xaxes(gridcolor='rgba(220,220,220,0.5)')
# 顯示圖表
st.plotly_chart(fig, use_container_width=True)
hist = stock_data[selected_stock]['history']
if hist.empty:
st.warning("所選股票沒有足夠的歷史數據")
return
# RSI 指標
if indicator_type == "RSI":
rsi = calculate_rsi(hist['Close'])
fig = go.Figure()
# 添加RSI線
fig.add_trace(
go.Scatter(
x=hist.index,
y=rsi,
mode='lines',
name='RSI',
line=dict(color='#1f77b4', width=2)
)
)
# 添加超買超賣水平線
fig.add_trace(
go.Scatter(
x=[hist.index[0], hist.index[-1]],
y=[70, 70],
mode='lines',
line=dict(color='red', width=1, dash='dash'),
name='超買線 (70)'
)
)
fig.add_trace(
go.Scatter(
x=[hist.index[0], hist.index[-1]],
y=[30, 30],
mode='lines',
line=dict(color='green', width=1, dash='dash'),
name='超賣線 (30)'
)
)
fig.add_trace(
go.Scatter(
x=[hist.index[0], hist.index[-1]],
y=[50, 50],
mode='lines',
line=dict(color='gray', width=1, dash='dot'),
name='中位線 (50)'
)
)
fig.update_layout(
title=f"{selected_stock} RSI 指標",
height=400,
template="plotly_white",
margin=dict(l=40, r=40, t=60, b=40),
hovermode="x unified",
plot_bgcolor='rgba(240,242,246,0.8)',
)
fig.update_yaxes(title_text="RSI 值", gridcolor='rgba(220,220,220,0.5)')
fig.update_xaxes(gridcolor='rgba(220,220,220,0.5)')
st.plotly_chart(fig, use_container_width=True)
# MACD 指標
elif indicator_type == "MACD":
macd, signal, histogram = calculate_macd(hist['Close'])
fig = make_subplots(rows=2, cols=1, shared_xaxes=True,
vertical_spacing=0.1,
row_heights=[0.7, 0.3])
# 添加價格線
fig.add_trace(
go.Scatter(
x=hist.index,
y=hist['Close'],
mode='lines',
name='收盤價',
line=dict(color='#1f77b4', width=2)
),
row=1, col=1
)
# 添加MACD線
fig.add_trace(
go.Scatter(
x=hist.index,
y=macd,
mode='lines',
name='MACD',
line=dict(color='#ff7f0e', width=2)
),
row=2, col=1
)
# 添加訊號線
fig.add_trace(
go.Scatter(
x=hist.index,
y=signal,
mode='lines',
name='Signal',
line=dict(color='#2ca02c', width=2)
),
row=2, col=1
)
# 添加柱狀圖
colors = ['red' if val < 0 else 'green' for val in histogram]
fig.add_trace(
go.Bar(
x=hist.index,
y=histogram,
name='Histogram',
marker_color=colors
),
row=2, col=1
)
fig.update_layout(
title=f"{selected_stock} MACD 指標",
height=600,
template="plotly_white",
margin=dict(l=40, r=40, t=60, b=40),
hovermode="x unified",
legend=dict(
orientation="h",
yanchor="bottom",
y=1.02,
xanchor="right",
x=1
),
plot_bgcolor='rgba(240,242,246,0.8)',
)
fig.update_yaxes(title_text="價格", row=1, col=1, gridcolor='rgba(220,220,220,0.5)')
fig.update_yaxes(title_text="MACD", row=2, col=1, gridcolor='rgba(220,220,220,0.5)')
fig.update_xaxes(gridcolor='rgba(220,220,220,0.5)')
st.plotly_chart(fig, use_container_width=True)
# 布林帶
elif indicator_type == "布林帶":
ma, upper, lower = calculate_bollinger_bands(hist['Close'])
fig = go.Figure()
# 添加價格線
fig.add_trace(
go.Scatter(
x=hist.index,
y=hist['Close'],
mode='lines',
name='收盤價',
line=dict(color='#1f77b4', width=2)
)
)
# 添加移動平均線
fig.add_trace(
go.Scatter(
x=hist.index,
y=ma,
mode='lines',
name='20日移動平均線',
line=dict(color='#ff7f0e', width=2)
)
)
# 添加上軌
fig.add_trace(
go.Scatter(
x=hist.index,
y=upper,
mode='lines',
name='上軌 (+2σ)',
line=dict(color='#2ca02c', width=1, dash='dash')
)
)
# 添加下軌
fig.add_trace(
go.Scatter(
x=hist.index,
y=lower,
mode='lines',
name='下軌 (-2σ)',
line=dict(color='#d62728', width=1, dash='dash')
)
)
# 添加陰影區域
fig.add_trace(
go.Scatter(
x=hist.index.tolist() + hist.index.tolist()[::-1],
y=upper.tolist() + lower.tolist()[::-1],
fill='toself',
fillcolor='rgba(44, 160, 44, 0.1)',
line=dict(color='rgba(255,255,255,0)'),
hoverinfo='skip',
showlegend=False
)
)
fig.update_layout(
title=f"{selected_stock} 布林帶",
height=500,
template="plotly_white",
margin=dict(l=40, r=40, t=60, b=40),
hovermode="x unified",
legend=dict(
orientation="h",
yanchor="bottom",
y=1.02,
xanchor="right",
x=1
),
plot_bgcolor='rgba(240,242,246,0.8)',
)
fig.update_yaxes(title_text="價格", gridcolor='rgba(220,220,220,0.5)')
fig.update_xaxes(gridcolor='rgba(220,220,220,0.5)')
st.plotly_chart(fig, use_container_width=True)
# 移動平均線
elif indicator_type == "移動平均線":
ma20, ma50, ma100, ma200 = calculate_moving_averages(hist['Close'])
fig = go.Figure()
# 添加價格線
fig.add_trace(
go.Scatter(
x=hist.index,
y=hist['Close'],
mode='lines',
name='收盤價',
line=dict(color='#1f77b4', width=2)
)
)
# 添加移動平均線
fig.add_trace(
go.Scatter(
x=hist.index,
y=ma20,
mode='lines',
name='20日均線',
line=dict(color='#ff7f0e', width=1.5)
)
)
fig.add_trace(
go.Scatter(
x=hist.index,
y=ma50,
mode='lines',
name='50日均線',
line=dict(color='#2ca02c', width=1.5)
)
)
fig.add_trace(
go.Scatter(
x=hist.index,
y=ma100,
mode='lines',
name='100日均線',
line=dict(color='#d62728', width=1.5)
)
)
fig.add_trace(
go.Scatter(
x=hist.index,
y=ma200,
mode='lines',
name='200日均線',
line=dict(color='#9467bd', width=1.5)
)
)
fig.update_layout(
title=f"{selected_stock} 移動平均線",
height=500,
template="plotly_white",
margin=dict(l=40, r=40, t=60, b=40),
hovermode="x unified",
legend=dict(
orientation="h",
yanchor="bottom",
y=1.02,
xanchor="right",
x=1
),
plot_bgcolor='rgba(240,242,246,0.8)',
)
fig.update_yaxes(title_text="價格", gridcolor='rgba(220,220,220,0.5)')
fig.update_xaxes(gridcolor='rgba(220,220,220,0.5)')
st.plotly_chart(fig, use_container_width=True)
# 收集績效指標
performance_metrics = {}
for stock_id, data in stock_data.items():
hist = data['history']
if not hist.empty:
metrics = calculate_performance_metrics(hist['Close'])
performance_metrics[stock_id] = metrics
if not performance_metrics:
st.warning("沒有足夠的數據來計算績效指標")
return
# 創建圖表數據
metrics_df = pd.DataFrame(performance_metrics).T
# 創建多圖表比較
cols = st.columns(2)
# 1. 累積回報率比較
with cols[0]:
fig_return = px.bar(
metrics_df,
y=metrics_df.index,
x='cumulative_return',
orientation='h',
title='累積報酬率比較 (%)',
color='cumulative_return',
color_continuous_scale=px.colors.sequential.Blues,
text='cumulative_return'
)
fig_return.update_layout(
height=350,
template="plotly_white",
margin=dict(l=40, r=40, t=60, b=40),
xaxis_title="累積報酬率 (%)",
yaxis_title="",
plot_bgcolor='rgba(240,242,246,0.8)',
)
fig_return.update_traces(
texttemplate='%{x:.2f}%',
textposition='outside'
)
st.plotly_chart(fig_return, use_container_width=True)
# 2. 波動率比較
with cols[1]:
fig_vol = px.bar(
metrics_df,
y=metrics_df.index,
x='volatility',
orientation='h',
title='波動率比較 (%)',
color='volatility',
color_continuous_scale=px.colors.sequential.Reds,
text='volatility'
)
fig_vol.update_layout(
height=350,
template="plotly_white",
margin=dict(l=40, r=40, t=60, b=40),
xaxis_title="波動率 (%)",
yaxis_title="",
plot_bgcolor='rgba(240,242,246,0.8)',
)
fig_vol.update_traces(
texttemplate='%{x:.2f}%',
textposition='outside'
)
st.plotly_chart(fig_vol, use_container_width=True)
cols = st.columns(2)
# 3. 夏普比率比較
with cols[0]:
sharpe_colors = ['#d62728' if s < 0 else '#2ca02c' for s in metrics_df['sharpe_ratio']]
fig_sharpe = px.bar(
metrics_df,
y=metrics_df.index,
x='sharpe_ratio',
orientation='h',
title='夏普比率比較',
text='sharpe_ratio'
)
fig_sharpe.update_traces(
marker_color=sharpe_colors,
texttemplate='%{x:.2f}',
textposition='outside'
)
fig_sharpe.update_layout(
height=350,
template="plotly_white",
margin=dict(l=40, r=40, t=60, b=40),
xaxis_title="夏普比率",
yaxis_title="",
plot_bgcolor='rgba(240,242,246,0.8)',
)
st.plotly_chart(fig_sharpe, use_container_width=True)
# 4. 最大回撤比較
with cols[1]:
fig_drawdown = px.bar(
metrics_df,
y=metrics_df.index,
x='max_drawdown',
orientation='h',
title='最大回撤比較 (%)',
color='max_drawdown',
color_continuous_scale=px.colors.sequential.Reds_r,
text='max_drawdown'
)
fig_drawdown.update_layout(
height=350,
template="plotly_white",
margin=dict(l=40, r=40, t=60, b=40),
xaxis_title="最大回撤 (%)",
yaxis_title="",
plot_bgcolor='rgba(240,242,246,0.8)',
)
fig_drawdown.update_traces(
texttemplate='%{x:.2f}%',
textposition='outside'
)
st.plotly_chart(fig_drawdown, use_container_width=True)
# 5. 績效指標比較表格
st.markdown("### 績效指標詳細比較")
# 準備顯示的數據
display_df = pd.DataFrame({
'累積報酬率 (%)': metrics_df['cumulative_return'].round(2),
'年化報酬率 (%)': metrics_df['annualized_return'].round(2),
'波動率 (%)': metrics_df['volatility'].round(2),
'夏普比率': metrics_df['sharpe_ratio'].round(2),
'最大回撤 (%)': metrics_df['max_drawdown'].round(2)
})
# 表格高亮設定
st.dataframe(
display_df,
use_container_width=True,
height=max(35 * (len(display_df) + 1), 200),
column_config={
'累積報酬率 (%)': st.column_config.NumberColumn(format="%.2f%%"),
'年化報酬率 (%)': st.column_config.NumberColumn(format="%.2f%%"),
'波動率 (%)': st.column_config.NumberColumn(format="%.2f%%"),
'夏普比率': st.column_config.NumberColumn(format="%.2f"),
'最大回撤 (%)': st.column_config.NumberColumn(format="%.2f%%")
}
)
if __name__ == "__main__":
# 執行主程式,Streamlit 自動執行 app.py
pass # 可視需求添加初始化邏輯 |