Spaces:
Sleeping
Sleeping
File size: 77,025 Bytes
9276485 19bcf24 9276485 feeebce 9276485 9d0c0cb 9276485 ca6b430 9276485 a89de2b 9276485 2a96eba 9276485 2a96eba 9276485 9d0c0cb 9276485 ca6b430 9276485 a89de2b 9276485 2a96eba 9276485 a89de2b 9276485 9d0c0cb 9276485 740fca2 d375470 740fca2 a89de2b 9276485 97c78c6 | 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 2222 2223 2224 2225 2226 2227 2228 2229 2230 2231 2232 2233 2234 2235 2236 2237 2238 2239 2240 2241 2242 2243 2244 2245 2246 2247 2248 2249 2250 2251 2252 2253 2254 2255 2256 2257 2258 2259 2260 2261 2262 2263 2264 2265 2266 2267 2268 2269 2270 2271 2272 2273 2274 2275 2276 2277 2278 2279 2280 2281 2282 2283 2284 2285 2286 2287 2288 2289 2290 2291 2292 2293 2294 2295 2296 2297 2298 2299 2300 2301 2302 2303 2304 2305 2306 2307 2308 2309 2310 2311 2312 2313 2314 2315 2316 2317 2318 2319 2320 2321 2322 2323 2324 2325 2326 2327 2328 2329 2330 2331 2332 2333 2334 2335 2336 2337 2338 2339 2340 2341 2342 2343 2344 2345 2346 2347 2348 2349 2350 2351 2352 2353 2354 2355 2356 2357 2358 2359 2360 2361 2362 2363 2364 2365 2366 2367 2368 2369 2370 2371 2372 2373 2374 2375 2376 2377 2378 2379 2380 2381 2382 2383 2384 2385 2386 2387 2388 2389 2390 2391 2392 2393 2394 2395 2396 2397 2398 2399 2400 2401 2402 2403 2404 2405 2406 2407 2408 2409 2410 2411 2412 2413 2414 2415 2416 2417 2418 2419 2420 2421 2422 2423 2424 2425 2426 2427 2428 2429 2430 2431 2432 2433 2434 2435 2436 2437 2438 2439 2440 2441 2442 2443 2444 2445 2446 2447 2448 2449 2450 2451 2452 2453 2454 2455 2456 2457 2458 2459 2460 2461 2462 2463 2464 2465 2466 2467 2468 2469 2470 2471 2472 2473 2474 2475 2476 2477 2478 2479 2480 2481 2482 2483 2484 2485 2486 2487 2488 2489 2490 2491 2492 2493 2494 2495 2496 2497 2498 2499 2500 2501 2502 2503 2504 2505 2506 2507 2508 2509 2510 2511 2512 2513 2514 2515 2516 2517 2518 2519 2520 2521 2522 2523 2524 2525 2526 2527 2528 2529 2530 2531 2532 2533 2534 2535 2536 2537 2538 2539 2540 2541 2542 2543 2544 2545 2546 2547 2548 2549 2550 2551 2552 2553 2554 2555 2556 2557 2558 2559 2560 2561 2562 2563 2564 2565 2566 2567 2568 2569 2570 2571 2572 2573 2574 2575 2576 2577 2578 2579 2580 2581 2582 2583 2584 2585 2586 2587 2588 2589 2590 2591 2592 2593 2594 2595 2596 2597 2598 2599 2600 2601 2602 2603 2604 2605 2606 2607 2608 2609 2610 2611 2612 2613 2614 2615 2616 | import streamlit as st
import pandas as pd
import numpy as np
import torch
import plotly.graph_objects as go
import joblib
from transformers import (
TimesFmModelForPrediction,
PatchTSTConfig,
PatchTSTForPrediction
)
from nixtla import NixtlaClient
from sklearn.metrics import mean_absolute_error, root_mean_squared_error
from datetime import datetime
from statsmodels.tsa.statespace.sarimax import SARIMAX
from vnstock import Vnstock
import time
from datetime import timedelta
import warnings
warnings.filterwarnings("ignore", message="To copy construct from a tensor")
st.markdown("""
<style>
/* Import fonts */
@import url('https://fonts.googleapis.com/css2?family=Inter:wght@300;400;500;600;700;800&family=JetBrains+Mono:wght@400;500;600&display=swap');
/* Root Variables */
:root {
--primary: #00D9FF;
--secondary: #A855F7;
--accent: #FFD93D;
--success: #10B981;
--warning: #F59E0B;
--error: #EF4444;
--dark-bg: #0A0E1A;
--dark-surface: #12182B;
--dark-elevated: #1E293B;
--glass: rgba(18, 24, 43, 0.6);
--glass-border: rgba(255, 255, 255, 0.12);
--text-primary: #F9FAFB;
--text-secondary: #E5E7EB;
--text-muted: #9CA3AF;
}
/* Global Styles */
.stApp {
background: linear-gradient(135deg, var(--dark-bg) 0%, #12182B 50%, var(--dark-bg) 100%);
font-family: 'Inter', -apple-system, BlinkMacSystemFont, sans-serif;
}
/* Animated Background với nhiều layer */
.stApp::before {
content: "";
position: fixed;
inset: 0;
background:
radial-gradient(circle at 20% 30%, rgba(0, 217, 255, 0.12) 0%, transparent 50%),
radial-gradient(circle at 80% 70%, rgba(168, 85, 247, 0.10) 0%, transparent 50%),
radial-gradient(circle at 50% 50%, rgba(255, 217, 61, 0.05) 0%, transparent 60%);
animation: bgPulse 20s ease-in-out infinite;
pointer-events: none;
z-index: 0;
}
@keyframes bgPulse {
0%, 100% {
opacity: 1;
transform: scale(1) rotate(0deg);
}
25% {
opacity: 0.8;
transform: scale(1.05) rotate(1deg);
}
50% {
opacity: 0.7;
transform: scale(1.1) rotate(0deg);
}
75% {
opacity: 0.8;
transform: scale(1.05) rotate(-1deg);
}
}
/* Grid Pattern với animation */
.stApp::after {
content: "";
position: fixed;
inset: 0;
background-image:
linear-gradient(rgba(0, 217, 255, 0.03) 1px, transparent 1px),
linear-gradient(90deg, rgba(0, 217, 255, 0.03) 1px, transparent 1px);
background-size: 50px 50px;
pointer-events: none;
z-index: 1;
animation: gridMove 30s linear infinite;
}
@keyframes gridMove {
0% {
transform: translate(0, 0);
opacity: 1;
}
50% {
opacity: 0.5;
}
100% {
transform: translate(50px, 50px);
opacity: 1;
}
}
/* Container */
.block-container {
position: relative;
z-index: 2;
padding: 2rem 2.5rem;
max-width: 1400px;
}
/* Typography */
h1 {
font-weight: 800 !important;
font-size: 3rem !important;
background: linear-gradient(135deg, var(--primary) 0%, var(--secondary) 100%);
-webkit-background-clip: text;
-webkit-text-fill-color: transparent;
background-clip: text;
margin-bottom: 1.5rem !important;
letter-spacing: -0.02em;
text-align: center !important;
animation: slideDown 0.8s cubic-bezier(0.16, 1, 0.3, 1);
}
h1 .emoji {
-webkit-text-fill-color: currentColor !important;
background: none !important;
filter: drop-shadow(0 0 20px rgba(0, 217, 255, 0.5));
}
h2 {
color: #FFFFFF;
font-weight: 700 !important;
font-size: 1.75rem !important;
margin-top: 3rem !important;
margin-bottom: 1.5rem !important;
padding-bottom: 0.75rem;
border-bottom: 2px solid var(--dark-elevated);
position: relative;
animation: slideUp 0.6s cubic-bezier(0.16, 1, 0.3, 1);
}
h2::before {
content: "";
position: absolute;
left: 0;
bottom: -2px;
width: 80px;
height: 2px;
background: linear-gradient(90deg, var(--primary), var(--secondary));
border-radius: 2px;
}
h3 {
color: var(--primary);
font-weight: 600 !important;
font-size: 1.25rem !important;
margin-top: 2rem !important;
margin-bottom: 1rem !important;
}
/* Paragraphs - TĂNG ĐỘ SÁNG */
p, li {
color: #E5E7EB !important;
line-height: 1.7;
font-size: 1.05rem;
font-weight: 400;
}
/* Chữ trong danh sách */
ul, ol {
color: #E5E7EB !important;
}
ul li, ol li {
color: #E5E7EB !important;
margin-bottom: 0.5rem;
}
/* Text được highlight hoặc bold */
strong, b {
color: #F9FAFB !important;
font-weight: 600;
}
/* Sidebar */
[data-testid="stSidebar"] {
background: linear-gradient(180deg, var(--dark-surface) 0%, var(--dark-bg) 100%);
border-right: 1px solid var(--dark-elevated);
}
[data-testid="stSidebar"] [data-testid="stMarkdownContainer"] p {
color: #E5E7EB !important;
font-size: 0.95rem;
}
[data-testid="stSidebar"] .stRadio > label {
color: #FFFFFF !important;
font-weight: 600;
font-size: 1rem;
}
/* Cards & Containers */
.hero-intro {
background: var(--glass);
backdrop-filter: blur(20px);
border: 1px solid var(--glass-border);
border-left: 3px solid var(--primary);
border-radius: 16px;
padding: 2rem;
margin: 1.5rem 0;
box-shadow:
0 8px 32px rgba(0, 0, 0, 0.3),
inset 0 1px 0 rgba(255, 255, 255, 0.08);
animation: slideUp 0.8s cubic-bezier(0.16, 1, 0.3, 1) 0.2s both;
transition: all 0.3s ease;
}
.hero-intro:hover {
border-left-color: var(--secondary);
box-shadow:
0 12px 48px rgba(0, 0, 0, 0.4),
0 0 40px rgba(0, 217, 255, 0.15);
}
.hero-intro h3 {
color: var(--primary);
margin-top: 0 !important;
margin-bottom: 1rem !important;
}
.hero-intro p {
color: #F9FAFB !important;
line-height: 1.7;
font-size: 1.05rem;
margin-bottom: 1rem;
}
.hero-intro ul {
color: #E5E7EB !important;
line-height: 1.8;
margin-left: 1.5rem;
}
.hero-intro li {
color: #E5E7EB !important;
}
.hero-intro strong {
color: var(--secondary);
font-weight: 600;
}
/* Date Display - CĂN LỀ TRÁI */
.date-display {
background: linear-gradient(135deg, rgba(0, 217, 255, 0.08) 0%, rgba(168, 85, 247, 0.08) 100%);
border: 1px solid var(--glass-border);
border-radius: 12px;
padding: 1rem 1.5rem;
margin: 1.5rem 0;
text-align: left;
backdrop-filter: blur(10px);
animation: fadeIn 0.8s ease;
}
.date-display p {
color: #F9FAFB !important;
font-size: 1.05rem;
margin: 0;
font-family: 'JetBrains Mono', monospace;
}
.date-display b {
color: var(--primary);
font-weight: 700;
}
/* Buttons */
.stButton > button {
background: linear-gradient(135deg, #0099B8 0%, #7C3AAC 100%) !important;
color: #FFFFFF !important;
border: none !important;
border-radius: 12px !important;
padding: 0.85rem 2.5rem !important;
font-weight: 700 !important;
font-size: 1.05rem !important;
letter-spacing: 0.05em;
text-transform: uppercase;
transition: all 0.4s cubic-bezier(0.16, 1, 0.3, 1) !important;
box-shadow:
0 4px 20px rgba(0, 153, 184, 0.4),
0 0 40px rgba(124, 58, 172, 0.25) !important;
position: relative;
overflow: hidden;
background-size: 200% 200% !important;
animation: gradientShift 3s ease infinite;
}
/* Animated gradient background */
@keyframes gradientShift {
0% {
background-position: 0% 50%;
}
50% {
background-position: 100% 50%;
}
100% {
background-position: 0% 50%;
}
}
/* Ripple effect */
.stButton > button::before {
content: "";
position: absolute;
top: 50%;
left: 50%;
width: 0;
height: 0;
border-radius: 50%;
background: rgba(255, 255, 255, 0.3);
transform: translate(-50%, -50%);
transition: width 0.6s, height 0.6s;
}
/* Shimmer effect */
.stButton > button::after {
content: "";
position: absolute;
top: -50%;
left: -50%;
width: 200%;
height: 200%;
background: linear-gradient(
45deg,
transparent 30%,
rgba(255, 255, 255, 0.2) 50%,
transparent 70%
);
animation: shimmer 3s infinite;
}
@keyframes shimmer {
0% {
transform: translateX(-100%) translateY(-100%) rotate(45deg);
}
100% {
transform: translateX(100%) translateY(100%) rotate(45deg);
}
}
/* Text styling */
.stButton > button span,
.stButton > button p,
.stButton > button div {
color: #FFFFFF !important;
position: relative;
z-index: 2;
font-weight: 700 !important;
}
.stButton > button:hover {
transform: translateY(-4px) scale(1.03) !important;
box-shadow:
0 10px 40px rgba(0, 153, 184, 0.6),
0 0 80px rgba(124, 58, 172, 0.4),
inset 0 0 30px rgba(255, 255, 255, 0.15) !important;
animation: gradientShift 1.5s ease infinite, buttonPulse 1s ease infinite;
}
@keyframes buttonPulse {
0%, 100% {
box-shadow:
0 10px 40px rgba(0, 153, 184, 0.6),
0 0 80px rgba(124, 58, 172, 0.4);
}
50% {
box-shadow:
0 10px 50px rgba(0, 153, 184, 0.8),
0 0 100px rgba(124, 58, 172, 0.6);
}
}
.stButton > button:hover::before {
width: 400px;
height: 400px;
}
.stButton > button:active {
transform: translateY(-2px) scale(0.98) !important;
}
/* Selectbox & Input */
.stSelectbox > div > div,
.stNumberInput > div > div > input {
background: rgba(255, 255, 255, 0.04) !important;
border: 1px solid var(--glass-border) !important;
border-radius: 10px !important;
color: #F9FAFB !important;
font-family: 'Inter', sans-serif;
transition: all 0.3s ease !important;
}
.stSelectbox > div > div:hover,
.stNumberInput > div > div > input:hover {
background: rgba(255, 255, 255, 0.06) !important;
border-color: var(--primary) !important;
}
.stSelectbox > div > div:focus,
.stNumberInput > div > div > input:focus {
border-color: var(--primary) !important;
box-shadow: 0 0 0 3px rgba(0, 217, 255, 0.15) !important;
}
/* Widget Labels */
div[data-testid="stWidgetLabel"] > label {
font-size: 1rem !important;
font-weight: 600 !important;
color: #FFFFFF !important;
margin-bottom: 0.5rem !important;
letter-spacing: 0.02em;
}
/* Checkboxes */
.stCheckbox {
background: var(--glass);
border: 1px solid var(--glass-border);
border-radius: 10px;
padding: 0.85rem 1.2rem;
margin-bottom: 0.75rem;
transition: all 0.2s ease;
backdrop-filter: blur(10px);
}
.stCheckbox:hover {
border-color: var(--primary);
background: rgba(0, 217, 255, 0.08);
transform: translateX(4px);
}
.stCheckbox label {
color: #F9FAFB !important;
font-weight: 500;
font-size: 1rem;
}
/* Radio Buttons */
.stRadio > div {
background: var(--glass);
border: 1px solid var(--glass-border);
border-radius: 12px;
padding: 1.2rem;
backdrop-filter: blur(10px);
}
.stRadio label {
color: #F9FAFB !important;
font-weight: 500;
}
/* Expander */
.streamlit-expanderHeader {
background: var(--glass) !important;
backdrop-filter: blur(10px) !important;
border: 1px solid var(--glass-border) !important;
border-radius: 10px !important;
color: var(--primary) !important;
font-weight: 600 !important;
transition: all 0.3s ease !important;
}
.streamlit-expanderHeader:hover {
border-color: var(--primary) !important;
background: rgba(0, 217, 255, 0.08) !important;
transform: translateX(4px);
}
.streamlit-expanderContent {
background: rgba(18, 24, 43, 0.4);
border: 1px solid var(--glass-border);
border-top: none;
border-radius: 0 0 10px 10px;
backdrop-filter: blur(10px);
}
/* Metrics */
[data-testid="stMetricValue"] {
color: var(--primary);
font-family: 'JetBrains Mono', monospace;
font-size: 2rem;
font-weight: 800;
}
[data-testid="stMetricLabel"] {
color: #E5E7EB;
font-size: 0.9rem;
font-weight: 600;
text-transform: uppercase;
letter-spacing: 0.08em;
}
.stMetric {
background: var(--glass) !important;
backdrop-filter: blur(20px) !important;
border: 1px solid var(--glass-border) !important;
border-radius: 16px !important;
padding: 1.5rem !important;
transition: all 0.3s cubic-bezier(0.16, 1, 0.3, 1) !important;
box-shadow:
0 4px 16px rgba(0, 0, 0, 0.2),
inset 0 1px 0 rgba(255, 255, 255, 0.08) !important;
}
.stMetric:hover {
transform: translateY(-4px) !important;
border-color: var(--primary) !important;
box-shadow:
0 8px 32px rgba(0, 0, 0, 0.3),
0 0 30px rgba(0, 217, 255, 0.2) !important;
}
/* DataFrames */
.stDataFrame {
background: var(--glass) !important;
backdrop-filter: blur(20px) !important;
border: 1px solid var(--glass-border) !important;
border-radius: 12px !important;
overflow: hidden;
box-shadow:
0 8px 32px rgba(0, 0, 0, 0.3),
inset 0 1px 0 rgba(255, 255, 255, 0.08);
}
.stDataFrame thead tr th {
background: linear-gradient(135deg, rgba(0, 217, 255, 0.12), rgba(168, 85, 247, 0.12)) !important;
color: #FFFFFF !important;
font-weight: 700 !important;
font-size: 0.9rem !important;
text-transform: uppercase;
letter-spacing: 0.05em;
padding: 1rem 0.8rem !important;
border: none !important;
}
.stDataFrame tbody tr:hover {
background: rgba(0, 217, 255, 0.06) !important;
}
.stDataFrame tbody tr td {
color: #E5E7EB !important;
font-size: 0.95rem !important;
padding: 0.9rem 0.8rem !important;
font-family: 'JetBrains Mono', monospace;
border-color: rgba(255, 255, 255, 0.05) !important;
}
/* Progress Bar */
.stProgress > div > div {
background: linear-gradient(90deg, var(--primary) 0%, var(--secondary) 100%) !important;
border-radius: 10px;
animation: progressPulse 2s ease infinite;
}
@keyframes progressPulse {
0%, 100% {
opacity: 1;
}
50% {
opacity: 0.8;
}
}
/* Status Messages */
.stSuccess {
background: rgba(16, 185, 129, 0.1) !important;
border-left: 4px solid var(--success) !important;
color: var(--success) !important;
border-radius: 8px;
}
.stWarning {
background: rgba(245, 158, 11, 0.1) !important;
border-left: 4px solid var(--warning) !important;
color: var(--warning) !important;
border-radius: 8px;
}
.stInfo {
background: rgba(0, 217, 255, 0.1) !important;
border-left: 4px solid var(--primary) !important;
color: var(--primary) !important;
border-radius: 8px;
}
.stError {
background: rgba(239, 68, 68, 0.1) !important;
border-left: 4px solid var(--error) !important;
color: var(--error) !important;
border-radius: 8px;
}
/* Plotly Charts */
.js-plotly-plot {
border: 1px solid var(--glass-border);
border-radius: 16px;
overflow: hidden;
box-shadow: 0 8px 32px rgba(0, 0, 0, 0.3);
}
/* Divider */
hr {
border-color: var(--dark-elevated);
margin: 2.5rem 0;
opacity: 0.5;
}
/* Scrollbar */
::-webkit-scrollbar {
width: 10px;
height: 10px;
}
::-webkit-scrollbar-track {
background: var(--dark-surface);
}
::-webkit-scrollbar-thumb {
background: linear-gradient(180deg, var(--primary), var(--secondary));
border-radius: 10px;
}
::-webkit-scrollbar-thumb:hover {
background: linear-gradient(180deg, var(--secondary), var(--primary));
}
/* Animations */
@keyframes slideDown {
from {
opacity: 0;
transform: translateY(-20px);
}
to {
opacity: 1;
transform: translateY(0);
}
}
@keyframes slideUp {
from {
opacity: 0;
transform: translateY(20px);
}
to {
opacity: 1;
transform: translateY(0);
}
}
@keyframes fadeIn {
from {
opacity: 0;
}
to {
opacity: 1;
}
}
/* Responsive */
@media (max-width: 768px) {
.block-container {
padding: 1.5rem;
}
h1 {
font-size: 2rem !important;
}
h2 {
font-size: 1.5rem !important;
}
.hero-intro {
padding: 1.5rem;
}
}
</style>
""", unsafe_allow_html=True)
# 1. Page Config
st.set_page_config(
page_title="VN30 Forecast - Model Comparison",
layout="wide"
)
# Sitebar navigation
st.sidebar.title("📂 VN30 Forecast")
st.sidebar.markdown("---")
menu = st.sidebar.radio(
"Menu",
[
"📊 So sánh model",
"🧪 Demo sản phẩm",
"📘 Tài liệu"
]
)
if menu == "📊 So sánh model":
# 2. Load data
@st.cache_data
def load_data():
df = pd.read_csv("VN30_Train.csv")
df["time"] = pd.to_datetime(df["time"])
df = df.sort_values(["symbol", "time"])
return df
df_train = load_data()
symbols = sorted(df_train["symbol"].unique())
def load_test_data():
df = pd.read_csv("VN30_Test.csv")
df["time"] = pd.to_datetime(df["time"])
df = df.sort_values(["symbol", "time"])
return df
df_test = load_test_data()
@st.cache_data
def load_news():
df = pd.read_csv("VN30_news_with_sentiment.csv")
df["date"] = pd.to_datetime(df["date"])
return df
df_news = load_news()
# 3. UI
st.markdown('<h1 style="text-align: center;"><span class="emoji">📈</span> VN30 Stock Forecast - Model Comparison</h1>', unsafe_allow_html=True)
a1, a2, a3 = st.columns([1, 2, 1])
with a2:
st.image(
"VN30_Model_Thumb.png",
width=1000
)
st.markdown("---")
with st.expander("🎯 **Mục tiêu dự án** (bấm để xem chi tiết)"):
st.markdown(
"""
<div class="hero-intro">
<h3 style="margin-top: 0;">🎯 Mục tiêu dự án</h3>
<p>Dự án này nhằm xây dựng một <strong>ứng dụng dự báo giá cổ phiếu VN30 theo ngày</strong> bằng nhiều phương pháp forecasting khác nhau, bao gồm:</p>
<ul style="margin: 1rem 0;">
<li><strong>Technical Analysis</strong>: Dự báo dựa trên xu hướng, động lượng và biến động giá thông qua các chỉ báo kỹ thuật.</li>
<li><strong>SARIMA</strong>: Mô hình machine learning thống kê cổ điển cho chuỗi thời gian, kết hợp xu hướng, mùa vụ và biến ngoại sinh.</li>
<li><strong>PatchTST</strong>: Mô hình deep learning - Transformer time-series dùng patch để tối ưu bộ nhớ.</li>
<li><strong>TimeFM</strong>: Foundation model cho time series, model này chỉ nên ở mức tham khảo vì khả năng dự đoán không tốt. Kiêm thêm việc nó khá nặng với một con CPU free như hugging face nên nó chạy lâu hoặc đôi khi chạy không được.</li>
<li><strong>TimeGPT</strong>: Generative forecasting model.</li>
<li><strong>TimeGPT with news</strong>: TimeGPT kết hợp qwen3 xuất ra sentiment từ tin tức (beta), tin tức được lấy từ https://cafef.vn/</li>
</ul>
</div>
""",
unsafe_allow_html=True
)
# Xuất ra ngày hiện tại
today_str = datetime.now().strftime("%d/%m/%Y")
st.markdown(
f"""
<div class="date-display">
<p>📅 Ngày hiện tại: <b>{today_str}</b></p>
</div>
""",
unsafe_allow_html=True
)
# 4. Crawl data
def crawl_vn30_data(start_date, end_date, filename):
symbols = [
"ACB","DGC","BCM","BID","FPT","HDB","HPG","LPB","MSN","MBB",
"MWG","PLX","GAS","SAB","STB","SHB","SSB","SSI","TCB","TPB",
"VCB","CTG","VJC","VIB","GVR","VNM","VRE","VIC","VHM","VPB"
]
all_dfs = []
progress = st.progress(0)
status = st.empty()
for i, symbol in enumerate(symbols):
try:
stock = Vnstock().stock(symbol=symbol, source="VCI")
df = stock.quote.history(
start=start_date,
end=end_date,
interval="1D"
)
if df.empty:
status.warning(f"{symbol} không có dữ liệu")
continue
# Feature engineering (GIỮ NGUYÊN)
df["estimated_value"] = (
(df["open"] + df["high"] + df["low"] + df["close"]) / 4
) * df["volume"]
df["+/- price percent"] = df["close"].pct_change().mul(100).round(2)
df["symbol"] = symbol
all_dfs.append(df)
status.info(f"Đã crawl xong {symbol}")
except Exception as e:
status.error(f"Lỗi {symbol}: {e}")
progress.progress((i + 1) / len(symbols))
time.sleep(10)
if len(all_dfs) == 0:
st.error("Không crawl được dữ liệu nào")
return
final_df = pd.concat(all_dfs, ignore_index=True)
final_df.to_csv(filename, index=False)
st.success(f"Đã lưu {filename}")
st.markdown("## 📥 Crawl dữ liệu VN30 thành 2 tập train và test")
c1, c2 = st.columns(2)
with c1:
if st.button("⬇️ Crawl Train Data (Từ 2022 đến 2 tuần trước hiện tại)"):
with st.spinner("Đang crawl Train data..."):
end_date = (datetime.now() - timedelta(days=14)).strftime("%Y-%m-%d")
crawl_vn30_data(
start_date="2022-01-01",
end_date=end_date,
filename="VN30_Train.csv"
)
st.cache_data.clear()
st.rerun()
with c2:
if st.button("⬇️ Crawl Test Data (Từ 2 tuần trước đến hiện tại)"):
with st.spinner("Đang crawl Test data..."):
end_date = datetime.now().strftime("%Y-%m-%d")
crawl_vn30_data(
start_date="2022-01-01",
end_date=end_date,
filename="VN30_Test.csv"
)
st.cache_data.clear()
st.rerun()
# 5. Làm button để cho người dùng chọn cổ phiếu và model
st.markdown("## 📌 Chọn cổ phiếu và ngày sắp tới để dự đoán")
left, right = st.columns([1, 1])
with left:
symbol = st.selectbox(
"Bạn hãy chọn cổ phiếu",
symbols
)
with right:
horizon = st.number_input(
"Bạn muốn forecast trong bao nhiêu ngày sắp tới",
min_value=1,
max_value=30,
value=14,
step=1
)
st.markdown("## 🧠 Chọn model để dự đoán")
MODEL_OPTIONS = [
"Technical Analysis",
"SARIMA",
"PatchTST",
"TimeFM",
"TimeGPT (Recommended)",
"TimeGPT with news (Beta)"
]
selected_models = []
cols = st.columns(3)
for i, m in enumerate(MODEL_OPTIONS):
with cols[i % 3]:
if st.checkbox(m, value=(m == "TimeGPT (Recommended)")):
selected_models.append(m)
if len(selected_models) == 0:
st.warning("⚠️ Bạn cần chọn ít nhất 1 model")
# 6. Load Models
@st.cache_resource
def load_timefm():
model = TimesFmModelForPrediction.from_pretrained(
"google/timesfm-2.0-500m-pytorch",
dtype=torch.bfloat16,
attn_implementation="sdpa",
device_map="auto"
)
model.eval()
return model
@st.cache_resource
def load_timegpt():
return NixtlaClient(
api_key="nixak-JVn8HSNEBEQoCKe3IAu2eelJ5BCk0rzt4u2GlztT9h1F9FGKLxj73jga4vg4DGPNsjakIzGG6yN8P4my"
)
@st.cache_resource
def load_patchtst():
config = PatchTSTConfig(
context_length=31,
prediction_length=3,
input_size=1,
patch_len=6,
stride=3,
d_model=96,
num_hidden_layers=4,
num_attention_heads=4,
dropout=0.15
)
model = PatchTSTForPrediction(config)
model.load_state_dict(
torch.load("best_patchtst_vn30.pt", map_location="cpu")
)
model.eval()
scalers = joblib.load("patchtst_scalers_vn30.pkl")
return model, scalers
# 7. Forecast Function
def compute_ci(df_sym, preds):
returns = df_sym["close"].diff().dropna()
vol = returns.rolling(20, min_periods=5).std().iloc[-1]
z = 1.96
return preds - z * vol, preds + z * vol
def forecast_timefm(symbol, horizon):
model = load_timefm()
df_sym = df_train[df_train["symbol"] == symbol]
series = df_sym["close"].astype(float).values
past_tensor = (
torch.from_numpy(series)
.to(dtype=torch.bfloat16, device=model.device)
.unsqueeze(0)
)
freq_tensor = torch.tensor([0], dtype=torch.long, device=model.device)
with torch.no_grad():
outputs = model(
past_values=past_tensor,
freq=freq_tensor,
return_dict=True
)
preds = outputs.mean_predictions[0].float().cpu().numpy()[:horizon]
future_time = pd.bdate_range(
start=df_sym["time"].iloc[-1] + pd.offsets.BDay(),
periods=horizon
)
lo, hi = compute_ci(df_sym, preds)
return pd.DataFrame({
"time": future_time,
"forecast_close": preds,
"lower_95": lo,
"upper_95": hi
})
def forecast_timegpt(symbol, horizon):
client = load_timegpt()
df_sym = df_train[df_train["symbol"] == symbol].copy()
df_sym = df_sym.rename(columns={"time": "ds", "close": "y"})[["ds", "y"]]
df_sym = df_sym.sort_values("ds").drop_duplicates(subset="ds")
# Create full business-day range
full_range = pd.date_range(
start=df_sym["ds"].min(),
end=df_sym["ds"].max(),
freq="B"
)
df_sym = (
df_sym
.set_index("ds")
.reindex(full_range)
.rename_axis("ds")
.reset_index()
)
# Fill missing prices
df_sym["y"] = df_sym["y"].ffill().bfill()
df_ts = df_sym.rename(
columns={"time": "ds", "close": "y"}
)[["ds", "y"]]
df_ts["unique_id"] = symbol
df_fc = client.forecast(
df=df_ts,
h=horizon,
freq="B",
level=[95]
)
return df_fc.rename(columns={
"ds": "time",
"TimeGPT": "forecast_close",
"TimeGPT-lo-95": "lower_95",
"TimeGPT-hi-95": "upper_95"
})[["time", "forecast_close", "lower_95", "upper_95"]]
def forecast_timegpt_news(symbol, horizon):
client = load_timegpt()
df_sym = df_train[df_train["symbol"] == symbol].copy()
df_sym = df_sym.rename(columns={"time": "ds", "close": "y"})[["ds", "y"]]
df_sym = df_sym.sort_values("ds").drop_duplicates(subset="ds")
# Create full business-day range
full_range = pd.date_range(
start=df_sym["ds"].min(),
end=df_sym["ds"].max(),
freq="B"
)
df_sym = (
df_sym
.set_index("ds")
.reindex(full_range)
.rename_axis("ds")
.reset_index()
)
# Fill missing prices
df_sym["y"] = df_sym["y"].ffill().bfill()
# News
df_news_sym = df_news[df_news["symbol"] == symbol].copy()
df_news_sym["date"] = pd.to_datetime(df_news_sym["date"])
df_sent = (
df_news_sym
.groupby("date")["sentiment"]
.mean()
.reset_index()
)
df_sym["date"] = df_sym["ds"].dt.normalize()
df_ts = df_sym.merge(df_sent, on="date", how="left")
# Fill missing sentiment
df_ts["sentiment"] = df_ts["sentiment"].fillna(0.0)
df_ts["unique_id"] = symbol
df_fc = client.forecast(
df=df_ts[["unique_id", "ds", "y", "sentiment"]],
h=horizon,
freq="B",
level=[95]
)
return df_fc.rename(columns={
"ds": "time",
"TimeGPT": "forecast_close",
"TimeGPT-lo-95": "lower_95",
"TimeGPT-hi-95": "upper_95"
})[["time", "forecast_close", "lower_95", "upper_95"]]
def forecast_patchtst(symbol, horizon):
model, scalers = load_patchtst()
df_sym = df_train[df_train["symbol"] == symbol]
scaler = scalers[symbol]
values = df_sym["close"].values.reshape(-1, 1)
scaled = scaler.transform(values).flatten()
context = scaled[-31:].copy()
preds_scaled = []
with torch.no_grad():
for _ in range(horizon):
xb = torch.tensor(context, dtype=torch.float32).unsqueeze(0).unsqueeze(-1)
out = model(past_values=xb)
next_pred = out.prediction_outputs[0, 0, 0].item()
preds_scaled.append(next_pred)
context = np.roll(context, -1)
context[-1] = next_pred
preds = scaler.inverse_transform(
np.array(preds_scaled).reshape(-1, 1)
).flatten()
future_time = pd.bdate_range(
start=df_sym["time"].iloc[-1] + pd.offsets.BDay(),
periods=horizon
)
lo, hi = compute_ci(df_sym, preds)
return pd.DataFrame({
"time": future_time,
"forecast_close": preds,
"lower_95": lo,
"upper_95": hi
})
def forecast_sarima(symbol, horizon=7):
df_sym = df_train[df_train["symbol"] == symbol].copy()
df_sym = df_sym.sort_values("time").drop_duplicates(subset="time")
# Endogenous (price)
ts = (
df_sym
.set_index("time")["close"]
.astype(float)
.asfreq("B")
.ffill()
)
# Exogenous variables
df_exog = df_sym.set_index("time").asfreq("B").ffill()
df_exog["return"] = df_exog["close"].pct_change().shift(1)
df_exog["volume"] = np.log1p(df_exog["volume"])
exog = df_exog[["return", "volume"]].fillna(0)
# Đồng bộ index
exog = exog.loc[ts.index]
# Model
model = SARIMAX(
ts,
exog=exog,
order=(2, 0, 2),
seasonal_order=(1, 0, 1, 5),
enforce_stationarity=False,
enforce_invertibility=False
)
result = model.fit(disp=False, maxiter=50)
# Future exog
future_time = pd.bdate_range(
start=ts.index[-1] + pd.offsets.BDay(),
periods=horizon
)
mean_ret = df_exog["return"].tail(20).mean()
mean_vol = df_exog["volume"].tail(20).mean()
future_exog = pd.DataFrame(
{
"return": np.full(horizon, mean_ret),
"volume": np.full(horizon, mean_vol)
},
index=future_time
)
fc = result.get_forecast(
steps=horizon,
exog=future_exog
)
conf_int = fc.conf_int(alpha=0.05)
return pd.DataFrame({
"time": future_time,
"forecast_close": fc.predicted_mean.values,
"lower_95": conf_int.iloc[:, 0].values,
"upper_95": conf_int.iloc[:, 1].values
})
def forecast_technical(symbol, horizon=7):
df = df_train[df_train["symbol"] == symbol].copy()
df = df.sort_values("time").reset_index(drop=True)
# Indicators
df["MA20"] = df["close"].rolling(20).mean()
df["MA50"] = df["close"].rolling(50).mean()
delta = df["close"].diff()
gain = delta.clip(lower=0)
loss = -delta.clip(upper=0)
avg_gain = gain.rolling(14).mean()
avg_loss = loss.rolling(14).mean()
rs = avg_gain / avg_loss
df["RSI"] = 100 - (100 / (1 + rs))
def signal(row):
if row["close"] > row["MA20"] > row["MA50"] and row["RSI"] > 50:
return 1
elif row["close"] < row["MA20"] < row["MA50"] and row["RSI"] < 50:
return -1
else:
return 0
df["signal"] = df.apply(signal, axis=1)
# Forecast
last_price = df["close"].iloc[-1]
last_signal = df["signal"].iloc[-1]
returns = df["close"].pct_change().rolling(10).std()
vol = returns.iloc[-1]
vol = 0 if np.isnan(vol) else min(vol, 0.01)
future_time = pd.bdate_range(
start=df["time"].iloc[-1] + pd.offsets.BDay(),
periods=horizon
)
prices = []
price = last_price
for _ in range(horizon):
if last_signal == 1:
price *= (1 + vol)
elif last_signal == -1:
price *= (1 - vol)
else:
price *= (1 + 0.1 * vol)
prices.append(price)
preds = np.array(prices)
lo, hi = compute_ci(df, preds)
return pd.DataFrame({
"time": future_time,
"forecast_close": preds,
"lower_95": lo,
"upper_95": hi
})
# 8. Rolling backtest
def rolling_backtest(df_sym, forecast_fn, window=500, step=5):
errors = []
for start in range(0, len(df_sym) - window - horizon, step):
train_slice = df_sym.iloc[start:start + window]
test_slice = df_sym.iloc[start + window:start + window + horizon]
df_pred = forecast_fn(
train_slice["symbol"].iloc[0],
horizon
)
y_true = test_slice["close"].values[:len(df_pred)]
y_pred = df_pred["forecast_close"].values
# MAE
mae = mean_absolute_error(y_true, y_pred)
# RMSE
rmse = root_mean_squared_error(y_true, y_pred)
# MASE (naive = yesterday)
naive = train_slice["close"].diff().dropna()
mae_naive = naive.abs().mean()
mase = mae / mae_naive if mae_naive != 0 else np.nan
# Directional Accuracy
actual_dir = np.sign(np.diff(y_true))
pred_dir = np.sign(np.diff(y_pred))
da = (actual_dir == pred_dir).mean() if len(actual_dir) > 0 else np.nan
errors.append({
"MAE": mae,
"RMSE": rmse,
"MASE": mase,
"DA": da
})
return pd.DataFrame(errors)
def backtest_sarima(symbol, n_test=7):
df_sym = df_train[df_train["symbol"] == symbol].copy()
df_sym = df_sym.sort_values("time").drop_duplicates(subset="time")
# Endogenous
ts = (
df_sym
.set_index("time")["close"]
.astype(float)
.asfreq("B")
.ffill()
)
# Exogenous
df_exog = df_sym.set_index("time").asfreq("B").ffill()
df_exog["return"] = df_exog["close"].pct_change().shift(1)
df_exog["volume"] = np.log1p(df_exog["volume"])
exog = df_exog[["return", "volume"]].fillna(0)
# Đồng bộ index
exog = exog.loc[ts.index]
# Train / Test split
ts_train = ts.iloc[:-n_test]
ts_test = ts.iloc[-n_test:]
exog_train = exog.loc[ts_train.index]
exog_test = exog.loc[ts_test.index]
# Model
model = SARIMAX(
ts_train,
exog=exog_train,
order=(2, 0, 2),
seasonal_order=(1, 0, 1, 5),
enforce_stationarity=False,
enforce_invertibility=False
)
result = model.fit(disp=False, maxiter=50)
fc = result.get_forecast(
steps=n_test,
exog=exog_test
)
y_pred = fc.predicted_mean
y_true = ts_test
# Metrics
mae = mean_absolute_error(y_true, y_pred)
rmse = root_mean_squared_error(y_true, y_pred)
naive = ts_train.shift(1).dropna()
mae_naive = mean_absolute_error(
ts_train.loc[naive.index],
naive
)
mase = mae / mae_naive if mae_naive != 0 else np.nan
actual_dir = np.sign(y_true.diff().iloc[1:])
pred_dir = np.sign(y_pred.diff().iloc[1:])
da = (actual_dir == pred_dir).mean()
return {
"MAE": mae,
"RMSE": rmse,
"MASE": mase,
"DA": da
}
def backtest_technical(symbol, n_test=7):
df = df_train[df_train["symbol"] == symbol].copy()
df = df.sort_values("time").reset_index(drop=True)
train = df.iloc[:-n_test]
test = df.iloc[-n_test:]
df_fc = forecast_technical(symbol, horizon=n_test)
y_true = test["close"].values
y_pred = df_fc["forecast_close"].values
# MAE
mae = mean_absolute_error(y_true, y_pred)
# RMSE
rmse = root_mean_squared_error(y_true, y_pred)
# MASE
naive = train["close"].shift(1).dropna()
mae_naive = np.abs(naive.values - train["close"].iloc[1:].values).mean()
mase = mae / mae_naive if mae_naive != 0 else np.nan
# Directional Accuracy
actual_dir = np.sign(np.diff(y_true))
pred_dir = np.sign(np.diff(y_pred))
da = (actual_dir == pred_dir).mean()
return {
"MAE": mae,
"RMSE": rmse,
"MASE": mase,
"DA": da
}
# 9. Run Forecast
if st.button("🚀 Forecast") and len(selected_models) > 0:
progress = st.progress(0)
status = st.empty()
all_forecasts = {}
all_metrics = {}
total = len(selected_models)
for i, model_name in enumerate(selected_models):
status.info(f"⏳ Đang chạy model: **{model_name}**")
# Forecast
if model_name == "TimeFM":
df_fc = forecast_timefm(symbol, horizon)
bt_fn = forecast_timefm
df_bt = rolling_backtest(
df_train[df_train["symbol"] == symbol].reset_index(drop=True),
bt_fn
)
elif model_name == "TimeGPT (Recommended)":
df_fc = forecast_timegpt(symbol, horizon)
bt_fn = forecast_timegpt
df_bt = rolling_backtest(
df_train[df_train["symbol"] == symbol].reset_index(drop=True),
bt_fn
)
elif model_name == "TimeGPT with news (Beta)":
df_fc = forecast_timegpt_news(symbol, horizon)
bt_fn = forecast_timegpt_news
df_bt = rolling_backtest(
df_train[df_train["symbol"] == symbol].reset_index(drop=True),
bt_fn
)
elif model_name == "SARIMA":
df_fc = forecast_sarima(symbol, horizon)
df_bt = pd.DataFrame([backtest_sarima(symbol, n_test=horizon)])
elif model_name == "Technical Analysis":
df_fc = forecast_technical(symbol, horizon)
df_bt = pd.DataFrame([backtest_technical(symbol, n_test=horizon)])
else: # PatchTST
df_fc = forecast_patchtst(symbol, horizon)
bt_fn = forecast_patchtst
df_bt = rolling_backtest(
df_train[df_train["symbol"] == symbol].reset_index(drop=True),
bt_fn
)
all_forecasts[model_name] = df_fc
all_metrics[model_name] = df_bt.mean(numeric_only=True)
progress.progress((i + 1) / total)
status.success("Forecast hoàn tất!")
st.session_state.all_forecasts = all_forecasts
st.session_state.all_metrics = pd.DataFrame(all_metrics).T.reset_index().rename(
columns={"index": "Model"}
)
# 11. Plot
if "all_forecasts" in st.session_state:
st.subheader(f"📊 Forecast plot {symbol} – {horizon} ngày")
model_to_view = st.selectbox(
"🎛️ Chọn model để hiển thị",
list(st.session_state.all_forecasts.keys())
)
df_fc = st.session_state.all_forecasts[model_to_view]
df_hist = df_train[df_train["symbol"] == symbol]
df_test_sym = df_test[df_test["symbol"] == symbol]
last_train_time = df_hist["time"].iloc[-1]
df_actual_future = df_test_sym[
df_test_sym["time"] >= last_train_time
].iloc[:horizon]
fig = go.Figure()
# Historical
fig.add_trace(go.Scatter(
x=df_hist["time"],
y=df_hist["close"],
mode="lines",
name="Historical",
line=dict(width=2.5)
))
# Actual
if len(df_actual_future) > 0:
fig.add_trace(go.Scatter(
x=df_actual_future["time"],
y=df_actual_future["close"],
mode="lines+markers",
name="Actual"
))
# CI
fig.add_trace(go.Scatter(
x=df_fc["time"],
y=df_fc["upper_95"],
mode="lines",
line=dict(width=0),
name="95% CI",
showlegend=True
)
)
fig.add_trace(go.Scatter(
x=df_fc["time"],
y=df_fc["lower_95"],
mode="lines",
line=dict(width=0),
fill="tonexty",
fillcolor="rgba(168, 85, 247, 0.35)", # tím xịn
name=None,
showlegend=False
)
)
# Forecast
fig.add_trace(go.Scatter(
x=df_fc["time"],
y=df_fc["forecast_close"],
mode="lines+markers",
name=f"Forecast ({model_to_view})"
))
fig.update_layout(
template="plotly_dark",
hovermode="x unified",
dragmode="pan",
)
st.plotly_chart(
fig,
use_container_width=True,
config={"scrollZoom": True}
)
# 12. Metrics
if "all_metrics" in st.session_state:
st.subheader("📐 So sánh Metrics")
metric_options = {
"MAE (giá trị càng nhỏ model càng tốt)": "MAE",
"RMSE (giá trị càng nhỏ model càng tốt)": "RMSE",
"MASE (giá trị càng nhỏ model càng tốt)": "MASE",
"DA (giá trị càng lớn model càng tốt, trên 0.5 là model rất tốt)": "DA",
}
metric_label = st.selectbox(
"🎛️ Chọn metric để so sánh",
list(metric_options.keys())
)
metric_to_view = metric_options[metric_label]
df_m = st.session_state.all_metrics.sort_values(
metric_to_view,
ascending=(metric_to_view != "DA") # DA càng cao càng tốt
)
fig = go.Figure()
fig.add_trace(go.Bar(
x=df_m["Model"],
y=df_m[metric_to_view],
text=df_m[metric_to_view].round(3),
textposition="auto"
))
fig.update_layout(
template="plotly_dark",
yaxis_title=metric_to_view,
xaxis_title="Model",
dragmode="pan",
)
st.plotly_chart(
fig,
use_container_width=True,
config={"scrollZoom": True}
)
if menu == "🧪 Demo sản phẩm":
# 1. Page Config
st.set_page_config(
page_title="VN30 Forecast - Demo Product",
layout="wide"
)
# 2. Load data
@st.cache_data
def load_data():
df = pd.read_csv("VN30_Test.csv")
df["time"] = pd.to_datetime(df["time"])
df = df.sort_values(["symbol", "time"])
return df
df_train = load_data()
symbols = sorted(df_train["symbol"].unique())
@st.cache_data
def load_news():
df = pd.read_csv("VN30_news_with_sentiment.csv")
df["date"] = pd.to_datetime(df["date"])
return df
df_news = load_news()
# 3. UI
st.markdown('<h1 style="text-align: center;"><span class="emoji">📈</span> VN30 Stock Forecast - Demo Product</h1>', unsafe_allow_html=True)
a1, a2, a3 = st.columns([1, 2, 1])
with a2:
st.image(
"VN30_Product_Thumb.png",
width=1000
)
st.markdown("---")
with st.expander("🎯 **Mục tiêu dự án** (bấm để xem chi tiết)"):
st.markdown(
"""
<div class="hero-intro">
<h3 style="margin-top: 0;">🎯 Mục tiêu dự án</h3>
<p>Dự án này nhằm xây dựng một <strong>ứng dụng dự báo giá cổ phiếu VN30 theo ngày</strong> bằng nhiều phương pháp forecasting khác nhau, bao gồm:</p>
<ul style="margin: 1rem 0;">
<li><strong>Technical Analysis</strong>: Dự báo dựa trên xu hướng, động lượng và biến động giá thông qua các chỉ báo kỹ thuật.</li>
<li><strong>SARIMA</strong>: Mô hình machine learning thống kê cổ điển cho chuỗi thời gian, kết hợp xu hướng, mùa vụ và biến ngoại sinh.</li>
<li><strong>PatchTST</strong>: Mô hình deep learning - Transformer time-series dùng patch để tối ưu bộ nhớ.</li>
<li><strong>TimeFM</strong>: Foundation model cho time series, model này chỉ nên ở mức tham khảo vì khả năng dự đoán không tốt. Kiêm thêm việc nó khá nặng với một con CPU free như hugging face nên nó chạy lâu hoặc đôi khi chạy không được.</li>
<li><strong>TimeGPT</strong>: Generative forecasting model. Đây là model sử dụng API đến từ nixtla.</li>
<li><strong>TimeGPT with news</strong>: TimeGPT kết hợp qwen3 xuất ra sentiment từ tin tức (beta), tin tức được lấy từ https://cafef.vn/</li>
</ul>
</div>
""",
unsafe_allow_html=True
)
# Xuất ra ngày hiện tại
today_str = datetime.now().strftime("%d/%m/%Y")
st.markdown(
f"""
<div class="date-display">
<p>📅 Ngày hiện tại: <b>{today_str}</b></p>
</div>
""",
unsafe_allow_html=True
)
# 4. Crawl data
def crawl_vn30_data(start_date, end_date, filename):
symbols = [
"ACB","DGC","BCM","BID","FPT","HDB","HPG","LPB","MSN","MBB",
"MWG","PLX","GAS","SAB","STB","SHB","SSB","SSI","TCB","TPB",
"VCB","CTG","VJC","VIB","GVR","VNM","VRE","VIC","VHM","VPB"
]
all_dfs = []
progress = st.progress(0)
status = st.empty()
for i, symbol in enumerate(symbols):
try:
stock = Vnstock().stock(symbol=symbol, source="VCI")
df = stock.quote.history(
start=start_date,
end=end_date,
interval="1D"
)
if df.empty:
status.warning(f"{symbol} không có dữ liệu")
continue
# Feature engineering (GIỮ NGUYÊN)
df["estimated_value"] = (
(df["open"] + df["high"] + df["low"] + df["close"]) / 4
) * df["volume"]
df["+/- price percent"] = df["close"].pct_change().mul(100).round(2)
df["symbol"] = symbol
all_dfs.append(df)
status.info(f"Đã crawl xong {symbol}")
except Exception as e:
status.error(f"Lỗi {symbol}: {e}")
progress.progress((i + 1) / len(symbols))
time.sleep(10)
if len(all_dfs) == 0:
st.error("Không crawl được dữ liệu nào")
return
final_df = pd.concat(all_dfs, ignore_index=True)
final_df.to_csv(filename, index=False)
st.success(f"Đã lưu {filename}")
st.markdown("## 📥 Crawl dữ liệu VN30")
if st.button("⬇️ Crawl Data (Từ 2022 đến hiện tại)"):
with st.spinner("Đang crawl data..."):
end_date = datetime.now().strftime("%Y-%m-%d")
crawl_vn30_data(
start_date="2022-01-01",
end_date=end_date,
filename="VN30_Test.csv"
)
st.cache_data.clear()
st.rerun()
# 5. Làm button để cho người dùng chọn cổ phiếu và model
st.markdown("## 📌 Chọn cổ phiếu và ngày sắp tới để dự đoán")
left, right = st.columns([1, 1])
with left:
symbol = st.selectbox(
"Bạn hãy chọn cổ phiếu",
symbols
)
with right:
horizon = st.number_input(
"Bạn muốn forecast trong bao nhiêu ngày sắp tới",
min_value=1,
max_value=30,
value=14,
step=1
)
st.markdown("## 🧠 Chọn model để dự đoán")
model_name = st.radio(
"",
[
"Technical Analysis",
"SARIMA",
"PatchTST",
"TimeFM",
"TimeGPT (Recommended)",
"TimeGPT with news (Beta)"
],
horizontal=True
)
# 6. Load Models
@st.cache_resource
def load_timefm():
model = TimesFmModelForPrediction.from_pretrained(
"google/timesfm-2.0-500m-pytorch",
dtype=torch.bfloat16,
attn_implementation="sdpa",
device_map="auto"
)
model.eval()
return model
@st.cache_resource
def load_timegpt():
return NixtlaClient(
api_key="nixak-JVn8HSNEBEQoCKe3IAu2eelJ5BCk0rzt4u2GlztT9h1F9FGKLxj73jga4vg4DGPNsjakIzGG6yN8P4my"
)
@st.cache_resource
def load_patchtst():
config = PatchTSTConfig(
context_length=31,
prediction_length=3,
input_size=1,
patch_len=6,
stride=3,
d_model=96,
num_hidden_layers=4,
num_attention_heads=4,
dropout=0.15
)
model = PatchTSTForPrediction(config)
model.load_state_dict(
torch.load("best_patchtst_vn30.pt", map_location="cpu")
)
model.eval()
scalers = joblib.load("patchtst_scalers_vn30.pkl")
return model, scalers
# 7. Forecast Function
def compute_ci(df_sym, preds):
returns = df_sym["close"].diff().dropna()
vol = returns.rolling(20, min_periods=5).std().iloc[-1]
z = 1.96
return preds - z * vol, preds + z * vol
def forecast_timefm(symbol, horizon):
model = load_timefm()
df_sym = df_train[df_train["symbol"] == symbol]
series = df_sym["close"].astype(float).values
past_tensor = (
torch.from_numpy(series)
.to(dtype=torch.bfloat16, device=model.device)
.unsqueeze(0)
)
freq_tensor = torch.tensor([0], dtype=torch.long, device=model.device)
with torch.no_grad():
outputs = model(
past_values=past_tensor,
freq=freq_tensor,
return_dict=True
)
preds = outputs.mean_predictions[0].float().cpu().numpy()[:horizon]
future_time = pd.bdate_range(
start=df_sym["time"].iloc[-1] + pd.offsets.BDay(),
periods=horizon
)
lo, hi = compute_ci(df_sym, preds)
return pd.DataFrame({
"time": future_time,
"forecast_close": preds,
"lower_95": lo,
"upper_95": hi
})
def forecast_timegpt(symbol, horizon):
client = load_timegpt()
df_sym = df_train[df_train["symbol"] == symbol].copy()
df_sym = df_sym.rename(columns={"time": "ds", "close": "y"})[["ds", "y"]]
df_sym = df_sym.sort_values("ds").drop_duplicates(subset="ds")
# Create full business-day range
full_range = pd.date_range(
start=df_sym["ds"].min(),
end=df_sym["ds"].max(),
freq="B"
)
df_sym = (
df_sym
.set_index("ds")
.reindex(full_range)
.rename_axis("ds")
.reset_index()
)
# Fill missing prices
df_sym["y"] = df_sym["y"].ffill().bfill()
df_ts = df_sym.rename(
columns={"time": "ds", "close": "y"}
)[["ds", "y"]]
df_ts["unique_id"] = symbol
df_fc = client.forecast(
df=df_ts,
h=horizon,
freq="B",
level=[95]
)
return df_fc.rename(columns={
"ds": "time",
"TimeGPT": "forecast_close",
"TimeGPT-lo-95": "lower_95",
"TimeGPT-hi-95": "upper_95"
})[["time", "forecast_close", "lower_95", "upper_95"]]
def forecast_timegpt_news(symbol, horizon):
client = load_timegpt()
df_sym = df_train[df_train["symbol"] == symbol].copy()
df_sym = df_sym.rename(columns={"time": "ds", "close": "y"})[["ds", "y"]]
df_sym = df_sym.sort_values("ds").drop_duplicates(subset="ds")
# Create full business-day range
full_range = pd.date_range(
start=df_sym["ds"].min(),
end=df_sym["ds"].max(),
freq="B"
)
df_sym = (
df_sym
.set_index("ds")
.reindex(full_range)
.rename_axis("ds")
.reset_index()
)
# Fill missing prices
df_sym["y"] = df_sym["y"].ffill().bfill()
# News
df_news_sym = df_news[df_news["symbol"] == symbol].copy()
df_news_sym["date"] = pd.to_datetime(df_news_sym["date"])
df_sent = (
df_news_sym
.groupby("date")["sentiment"]
.mean()
.reset_index()
)
df_sym["date"] = df_sym["ds"].dt.normalize()
df_ts = df_sym.merge(df_sent, on="date", how="left")
# Fill missing sentiment
df_ts["sentiment"] = df_ts["sentiment"].fillna(0.0)
df_ts["unique_id"] = symbol
df_fc = client.forecast(
df=df_ts[["unique_id", "ds", "y", "sentiment"]],
h=horizon,
freq="B",
level=[95]
)
return df_fc.rename(columns={
"ds": "time",
"TimeGPT": "forecast_close",
"TimeGPT-lo-95": "lower_95",
"TimeGPT-hi-95": "upper_95"
})[["time", "forecast_close", "lower_95", "upper_95"]]
def forecast_patchtst(symbol, horizon):
model, scalers = load_patchtst()
df_sym = df_train[df_train["symbol"] == symbol]
scaler = scalers[symbol]
values = df_sym["close"].values.reshape(-1, 1)
scaled = scaler.transform(values).flatten()
context = scaled[-31:].copy()
preds_scaled = []
with torch.no_grad():
for _ in range(horizon):
xb = torch.tensor(context, dtype=torch.float32).unsqueeze(0).unsqueeze(-1)
out = model(past_values=xb)
next_pred = out.prediction_outputs[0, 0, 0].item()
preds_scaled.append(next_pred)
context = np.roll(context, -1)
context[-1] = next_pred
preds = scaler.inverse_transform(
np.array(preds_scaled).reshape(-1, 1)
).flatten()
future_time = pd.bdate_range(
start=df_sym["time"].iloc[-1] + pd.offsets.BDay(),
periods=horizon
)
lo, hi = compute_ci(df_sym, preds)
return pd.DataFrame({
"time": future_time,
"forecast_close": preds,
"lower_95": lo,
"upper_95": hi
})
def forecast_sarima(symbol, horizon=7):
df_sym = df_train[df_train["symbol"] == symbol].copy()
df_sym = df_sym.sort_values("time").drop_duplicates(subset="time")
# Endogenous (price)
ts = (
df_sym
.set_index("time")["close"]
.astype(float)
.asfreq("B")
.ffill()
)
# Exogenous variables
df_exog = df_sym.set_index("time").asfreq("B").ffill()
df_exog["return"] = df_exog["close"].pct_change().shift(1)
df_exog["volume"] = np.log1p(df_exog["volume"])
exog = df_exog[["return", "volume"]].fillna(0)
# Đồng bộ index
exog = exog.loc[ts.index]
# Model
model = SARIMAX(
ts,
exog=exog,
order=(2, 0, 2),
seasonal_order=(1, 0, 1, 5),
enforce_stationarity=False,
enforce_invertibility=False
)
result = model.fit(disp=False, maxiter=50)
# Future exog
future_time = pd.bdate_range(
start=ts.index[-1] + pd.offsets.BDay(),
periods=horizon
)
mean_ret = df_exog["return"].tail(20).mean()
mean_vol = df_exog["volume"].tail(20).mean()
future_exog = pd.DataFrame(
{
"return": np.full(horizon, mean_ret),
"volume": np.full(horizon, mean_vol)
},
index=future_time
)
fc = result.get_forecast(
steps=horizon,
exog=future_exog
)
conf_int = fc.conf_int(alpha=0.05)
return pd.DataFrame({
"time": future_time,
"forecast_close": fc.predicted_mean.values,
"lower_95": conf_int.iloc[:, 0].values,
"upper_95": conf_int.iloc[:, 1].values
})
def forecast_technical(symbol, horizon=7):
df = df_train[df_train["symbol"] == symbol].copy()
df = df.sort_values("time").reset_index(drop=True)
# Indicators
df["MA20"] = df["close"].rolling(20).mean()
df["MA50"] = df["close"].rolling(50).mean()
delta = df["close"].diff()
gain = delta.clip(lower=0)
loss = -delta.clip(upper=0)
avg_gain = gain.rolling(14).mean()
avg_loss = loss.rolling(14).mean()
rs = avg_gain / avg_loss
df["RSI"] = 100 - (100 / (1 + rs))
def signal(row):
if row["close"] > row["MA20"] > row["MA50"] and row["RSI"] > 50:
return 1
elif row["close"] < row["MA20"] < row["MA50"] and row["RSI"] < 50:
return -1
else:
return 0
df["signal"] = df.apply(signal, axis=1)
# Forecast
last_price = df["close"].iloc[-1]
last_signal = df["signal"].iloc[-1]
returns = df["close"].pct_change().rolling(10).std()
vol = returns.iloc[-1]
vol = 0 if np.isnan(vol) else min(vol, 0.01)
future_time = pd.bdate_range(
start=df["time"].iloc[-1] + pd.offsets.BDay(),
periods=horizon
)
prices = []
price = last_price
for _ in range(horizon):
if last_signal == 1:
price *= (1 + vol)
elif last_signal == -1:
price *= (1 - vol)
else:
price *= (1 + 0.1 * vol)
prices.append(price)
preds = np.array(prices)
lo, hi = compute_ci(df, preds)
return pd.DataFrame({
"time": future_time,
"forecast_close": preds,
"lower_95": lo,
"upper_95": hi
})
# 8. Rolling backtest
def rolling_backtest(df_sym, forecast_fn, window=500, step=5):
errors = []
for start in range(0, len(df_sym) - window - horizon, step):
train_slice = df_sym.iloc[start:start + window]
test_slice = df_sym.iloc[start + window:start + window + horizon]
df_pred = forecast_fn(
train_slice["symbol"].iloc[0],
horizon
)
y_true = test_slice["close"].values[:len(df_pred)]
y_pred = df_pred["forecast_close"].values
# MAE
mae = mean_absolute_error(y_true, y_pred)
# RMSE
rmse = root_mean_squared_error(y_true, y_pred)
# MASE (naive = yesterday)
naive = train_slice["close"].diff().dropna()
mae_naive = naive.abs().mean()
mase = mae / mae_naive if mae_naive != 0 else np.nan
# Directional Accuracy
actual_dir = np.sign(np.diff(y_true))
pred_dir = np.sign(np.diff(y_pred))
da = (actual_dir == pred_dir).mean() if len(actual_dir) > 0 else np.nan
errors.append({
"MAE": mae,
"RMSE": rmse,
"MASE": mase,
"DA": da
})
return pd.DataFrame(errors)
def backtest_sarima(symbol, n_test=7):
df_sym = df_train[df_train["symbol"] == symbol].copy()
df_sym = df_sym.sort_values("time").drop_duplicates(subset="time")
# Endogenous
ts = (
df_sym
.set_index("time")["close"]
.astype(float)
.asfreq("B")
.ffill()
)
# Exogenous
df_exog = df_sym.set_index("time").asfreq("B").ffill()
df_exog["return"] = df_exog["close"].pct_change().shift(1)
df_exog["volume"] = np.log1p(df_exog["volume"])
exog = df_exog[["return", "volume"]].fillna(0)
# Đồng bộ index
exog = exog.loc[ts.index]
# Train / Test split
ts_train = ts.iloc[:-n_test]
ts_test = ts.iloc[-n_test:]
exog_train = exog.loc[ts_train.index]
exog_test = exog.loc[ts_test.index]
# Model
model = SARIMAX(
ts_train,
exog=exog_train,
order=(2, 0, 2),
seasonal_order=(1, 0, 1, 5),
enforce_stationarity=False,
enforce_invertibility=False
)
result = model.fit(disp=False, maxiter=50)
fc = result.get_forecast(
steps=n_test,
exog=exog_test
)
y_pred = fc.predicted_mean
y_true = ts_test
# Metrics
mae = mean_absolute_error(y_true, y_pred)
rmse = root_mean_squared_error(y_true, y_pred)
naive = ts_train.shift(1).dropna()
mae_naive = mean_absolute_error(
ts_train.loc[naive.index],
naive
)
mase = mae / mae_naive if mae_naive != 0 else np.nan
actual_dir = np.sign(y_true.diff().iloc[1:])
pred_dir = np.sign(y_pred.diff().iloc[1:])
da = (actual_dir == pred_dir).mean()
return {
"MAE": mae,
"RMSE": rmse,
"MASE": mase,
"DA": da
}
def backtest_technical(symbol, n_test=7):
df = df_train[df_train["symbol"] == symbol].copy()
df = df.sort_values("time").reset_index(drop=True)
train = df.iloc[:-n_test]
test = df.iloc[-n_test:]
df_fc = forecast_technical(symbol, horizon=n_test)
y_true = test["close"].values
y_pred = df_fc["forecast_close"].values
# MAE
mae = mean_absolute_error(y_true, y_pred)
# RMSE
rmse = root_mean_squared_error(y_true, y_pred)
# MASE
naive = train["close"].shift(1).dropna()
mae_naive = np.abs(naive.values - train["close"].iloc[1:].values).mean()
mase = mae / mae_naive if mae_naive != 0 else np.nan
# Directional Accuracy
actual_dir = np.sign(np.diff(y_true))
pred_dir = np.sign(np.diff(y_pred))
da = (actual_dir == pred_dir).mean()
return {
"MAE": mae,
"RMSE": rmse,
"MASE": mase,
"DA": da
}
# 7. Run Forecast
if st.button("🚀 Forecast"):
status = st.empty()
status.info(f"⏳ Đang chạy model: **{model_name}**")
# Forecast theo model được chọn
if model_name == "TimeFM":
df_fc = forecast_timefm(symbol, horizon)
bt_fn = forecast_timefm
bt_err = rolling_backtest(
df_train[df_train["symbol"] == symbol].reset_index(drop=True),
bt_fn
)
elif model_name == "TimeGPT (Recommended)":
df_fc = forecast_timegpt(symbol, horizon)
bt_fn = forecast_timegpt
bt_err = rolling_backtest(
df_train[df_train["symbol"] == symbol].reset_index(drop=True),
bt_fn
)
elif model_name == "TimeGPT with news (Beta)":
df_fc = forecast_timegpt_news(symbol, horizon)
bt_fn = forecast_timegpt_news
bt_err = rolling_backtest(
df_train[df_train["symbol"] == symbol].reset_index(drop=True),
bt_fn
)
elif model_name == "SARIMA":
df_fc = forecast_sarima(symbol, horizon)
bt_err = pd.DataFrame([backtest_sarima(symbol, n_test=horizon)])
elif model_name == "Technical Analysis":
df_fc = forecast_technical(symbol, horizon)
bt_err = pd.DataFrame([backtest_technical(symbol, n_test=horizon)])
else: # PatchTST
df_fc = forecast_patchtst(symbol, horizon)
bt_fn = forecast_patchtst
bt_err = rolling_backtest(
df_train[df_train["symbol"] == symbol].reset_index(drop=True),
bt_fn
)
# Lưu vào session_state
st.session_state.df_fc = df_fc
st.session_state.bt_err = bt_err
status.success("Forecast hoàn tất!")
# 9. Table
if "df_fc" in st.session_state:
st.subheader(f"📋 Forecast Table {symbol} – {horizon} ngày ({model_name})")
df_display = (
st.session_state.df_fc
.rename(columns={
"time": "Time",
"forecast_close": "Forecast Close Price",
"lower_95": "Lower 95% CI",
"upper_95": "Upper 95% CI"
})
.assign(
**{
"Forecast Close Price": lambda x: x["Forecast Close Price"].round(2),
"Lower 95% CI": lambda x: x["Lower 95% CI"].round(2),
"Upper 95% CI": lambda x: x["Upper 95% CI"].round(2),
}
)
)
st.dataframe(df_display, use_container_width=True, height=min(len(df_display), 30) * 35 + 40)
# 10. Plot
if "df_fc" in st.session_state:
df_fc = st.session_state.df_fc
df_hist = df_train[df_train["symbol"] == symbol]
st.subheader(f"📊 Forecast plot {symbol} – {horizon} ngày ({model_name})")
fig = go.Figure()
# Historical
fig.add_trace(go.Scatter(
x=df_hist["time"],
y=df_hist["close"],
mode="lines",
name="Historical",
line=dict(width=2.5)
))
# CI
fig.add_trace(go.Scatter(
x=df_fc["time"],
y=df_fc["upper_95"],
mode="lines",
line=dict(width=0),
name="95% CI",
showlegend=True
)
)
fig.add_trace(go.Scatter(
x=df_fc["time"],
y=df_fc["lower_95"],
mode="lines",
line=dict(width=0),
fill="tonexty",
fillcolor="rgba(168, 85, 247, 0.35)", # tím xịn
name=None,
showlegend=False
)
)
# Forecast
fig.add_trace(go.Scatter(
x=df_fc["time"],
y=df_fc["forecast_close"],
mode="lines+markers",
name=f"Forecast ({model_name})"
))
fig.update_layout(
template="plotly_dark",
hovermode="x unified",
dragmode="pan",
)
st.plotly_chart(
fig,
use_container_width=True,
config={"scrollZoom": True}
)
# 11. Metrics
if "bt_err" in st.session_state:
st.subheader("📐 Metrics")
c1, c2, c3, c4 = st.columns(4)
with c1:
st.metric(
"MAE (avg)",
f"{st.session_state.bt_err['MAE'].mean():.3f}"
)
with c2:
st.metric(
"RMSE (avg)",
f"{st.session_state.bt_err['RMSE'].mean():.3f}"
)
with c3:
st.metric(
"MASE (avg)",
f"{st.session_state.bt_err['MASE'].mean():.3f}"
)
with c4:
st.metric(
"DA (avg)",
f"{st.session_state.bt_err['DA'].mean() * 100:.1f}%"
)
if menu == "📘 Tài liệu":
# 1. Page Config
st.set_page_config(
page_title="VN30 Forecast - Documentation",
layout="wide"
)
# 2. UI
st.markdown('<h1 style="text-align: center;"><span class="emoji">📈</span> VN30 Stock Forecast - Documentation</h1>', unsafe_allow_html=True)
a1, a2, a3 = st.columns([1, 2, 1])
with a2:
st.image(
"VN30_Doc_Thumb.png",
width=1000
)
st.markdown("---")
# 3. Tổng quan hệ thống
st.markdown("## 🔍 Tổng quan hệ thống")
st.markdown(
"""
Ứng dụng **VN30 Stock Forecast** được xây dựng nhằm mục tiêu dự báo **giá đóng cửa (Close price)**
của các cổ phiếu thuộc rổ **VN30** theo tần suất **ngày giao dịch (Business Day)**.
Hệ thống kết hợp nhiều phương pháp dự báo khác nhau, từ:
- Phương pháp truyền thống
- Mô hình thống kê
- Deep Learning
- Foundation & Generative Models
Pipeline tổng thể gồm **3 bước chính**:
1. Thu thập dữ liệu (Crawl data)
2. Dự báo bằng nhiều mô hình
3. Đánh giá và so sánh mô hình
"""
)
# 4. Crawl data
st.markdown("## 📥 Thu thập dữ liệu (Crawl Data)")
st.markdown(
"""
### 🔹 Nguồn dữ liệu
Dữ liệu giá cổ phiếu được thu thập thông qua thư viện **`vnstock`**,
sử dụng API từ các công ty chứng khoán tại Việt Nam (VCI).
Các mã cổ phiếu thuộc rổ **VN30** được crawl với các trường:
- `open`, `high`, `low`, `close` (giá mở cửa, cao nhất, thấp nhất, đóng cửa)
- `volume` (khối lượng giao dịch)
- `time` (ngày giao dịch)
**Tần suất dữ liệu:** theo ngày
**Khoảng thời gian:** từ năm 2022 đến hiện tại
"""
)
st.markdown(
"""
### 🔹 Xử lý dữ liệu
- Chuẩn hóa định dạng thời gian
- Sắp xếp theo `symbol` và `time`
- Đồng bộ theo ngày giao dịch (Business Day)
- Forward fill / Backward fill cho các ngày thiếu dữ liệu
"""
)
st.markdown(
"""
### 🔹 Tin tức & Sentiment (tuỳ chọn)
- Tin tức được crawl từ **cafef.vn**
- Mỗi bài viết được gán **sentiment score**
- Sentiment được tổng hợp theo ngày
- Sentiment được sử dụng như **biến ngoại sinh** cho mô hình TimeGPT with news
"""
)
# 3. Forecasting models
st.markdown("## 🧠 Các mô hình dự báo")
st.markdown("### 1. Technical Analysis")
st.markdown(
"""
Mô hình dựa trên các chỉ báo kỹ thuật phổ biến:
- Moving Average (MA20, MA50)
- RSI (Relative Strength Index)
Ý tưởng chính:
- Xác định xu hướng giá
- Xác định động lượng thị trường
- Sinh tín hiệu mua / bán / giữ
👉 Đây là mô hình **baseline**, đơn giản và dễ diễn giải.
"""
)
st.markdown("### 2. SARIMA")
st.markdown(
"""
SARIMA (Seasonal ARIMA) là mô hình thống kê cổ điển cho chuỗi thời gian.
Đặc điểm:
- Mô hình hóa xu hướng
- Mô hình hóa mùa vụ
- Kết hợp biến ngoại sinh
Trong hệ thống:
- Endogenous: giá đóng cửa
- Exogenous: return, volume (log-transform)
👉 Phù hợp với dữ liệu tài chính có tính mùa vụ.
"""
)
st.markdown("### 3. PatchTST")
st.markdown(
"""
PatchTST là mô hình Transformer cho chuỗi thời gian.
Ý tưởng chính:
- Chia chuỗi thời gian thành các patch
- Giảm độ dài sequence
- Học quan hệ dài hạn hiệu quả hơn
👉 Phù hợp cho dự báo nhiều bước (multi-step forecasting).
"""
)
st.markdown("### 4. TimeFM")
st.markdown(
"""
TimeFM là **foundation model cho time series**, được huấn luyện trước trên tập dữ liệu lớn.
Đặc điểm:
- Không cần huấn luyện lại nhiều
- Dự báo nhanh
- Tổng quát hóa tốt
👉 Trong project, TimeFM được dùng ở mức **tham khảo**.
"""
)
st.markdown("### 5. TimeGPT (Recommended)")
st.markdown(
"""
TimeGPT là **Generative Forecasting Model** của Nixtla.
Đặc điểm:
- Tự động học trend và seasonality
- Sinh dự báo xác suất
- Trả về khoảng tin cậy (Confidence Interval)
👉 Đây là **mô hình được khuyến nghị sử dụng** trong ứng dụng.
"""
)
st.markdown("### 6. TimeGPT with News (Beta)")
st.markdown(
"""
Mở rộng của TimeGPT bằng cách thêm biến **sentiment từ tin tức** từ model LLM **qwen3** và crawl data tin tức từ [CafeF](https://cafef.vn/).
Ý tưởng:
- Giá cổ phiếu chịu ảnh hưởng bởi thông tin thị trường.
- Sentiment được đưa vào như biến ngoại sinh.
👉 Hiện tại ở mức **Beta** vì Qwen3 khá nặng chỉ chạy trên máy local, nên chỉ mang tính thử nghiệm.
Crawl data tin tức từ file .ipynb: [Link google drive](https://drive.google.com/file/d/1dPFu0s62edmgJb2-3aqXK8Q3SrTrGz6p/view?usp=sharing)
Tải qwen3.py: [Link google drive](https://drive.google.com/file/d/1xPsNFVOTI6avESiY-wcyKKCQxppxWIon/view?usp=sharing) sau đó chạy trên cmd với cd "C:/Users/<tên user>/Downloads" và "python qwen3.py" cùng với data tin tức đã được crawl trước đó trong file .ipynb. Lưu ý nếu lỗi thì nên cài các thư viện cần thiết trước.
"""
)
# 4. Metrics
st.markdown("## 📐 Các chỉ số đánh giá (Metrics)")
st.markdown("### 🔹 MAE – Mean Absolute Error")
st.markdown(
"""
Đo sai số tuyệt đối trung bình giữa giá thực tế và giá dự báo.
👉 **Giá trị càng nhỏ → model càng tốt**
"""
)
st.markdown("### 🔹 RMSE – Root Mean Squared Error")
st.markdown(
"""
Đo sai số bình phương trung bình, nhạy cảm với các lỗi lớn.
👉 **Giá trị càng nhỏ → model càng tốt**
"""
)
st.markdown("### 🔹 MASE – Mean Absolute Scaled Error")
st.markdown(
"""
So sánh mô hình với baseline naive (giá hôm nay = giá hôm qua).
👉 MASE < 1: model tốt hơn naive
👉 **Giá trị càng nhỏ → model càng tốt**
"""
)
st.markdown("### 🔹 DA – Directional Accuracy")
st.markdown(
"""
Đo độ chính xác trong việc dự đoán **chiều hướng tăng / giảm** của giá.
👉 Giá trị từ 0 đến 1
👉 **DA > 0.5: model dự đoán xu hướng tốt**
"""
) |