{"id":5637,"date":"2025-05-23T22:00:01","date_gmt":"2025-05-23T14:00:01","guid":{"rendered":"http:\/\/cnliutz.pgrm.cc\/?p=5637"},"modified":"2025-05-23T22:00:01","modified_gmt":"2025-05-23T14:00:01","slug":"%e7%bb%98%e5%88%b6%e6%9f%90%e5%8f%aa%e8%82%a1%e7%a5%a8%e7%9a%84k%e7%ba%bf%e5%9b%be%e3%80%81%e6%94%b6%e7%9b%8a%e7%8e%87%e3%80%81%e8%ae%a1%e7%ae%97var%e5%b9%b6%e7%bb%98%e5%9b%be","status":"publish","type":"post","link":"http:\/\/g1n29wqq.ipyingshe.net:5347\/?p=5637","title":{"rendered":"\u7ed8\u5236\u67d0\u53ea\u80a1\u7968\u7684K\u7ebf\u56fe\u3001\u6536\u76ca\u7387\u3001\u8ba1\u7b97VaR\u5e76\u7ed8\u56fe"},"content":{"rendered":"\n<pre class=\"wp-block-code\"><code># -*- coding: utf-8 -*-\n\"\"\"\n\u83b7\u53d6\u67d0\u53ea\u80a1\u7968\u7684\u6570\u636e\u7ed8\u5236K\u7ebf\u56fe\u3001\u8ba1\u7b97\u65e5\u6536\u76ca\u7387\u3001\u7ed8\u5236\u6536\u76ca\u7387\u76f4\u65b9\u56fe\u3001\u8ba1\u7b97VaR\n\u5e76\u7ed8\u5236VaR\u56fe \nCreated on Sun Sep 15 13:15:50 2024\n@author: 24384\n\"\"\"\n\nimport matplotlib.pyplot as plt\nimport matplotlib.font_manager as fm\nimport akshare as ak\nimport numpy as np\nimport pandas as pd\nimport mplfinance as mpf  # \u9700\u5148 pip install mplfinance\nimport seaborn as sns\nimport time\nfrom requests.exceptions import ConnectionError, Timeout, TooManyRedirects\n\n# # \u5217\u51fa\u7cfb\u7edf\u6240\u6709\u53ef\u7528\u5b57\u4f53\n# fonts = fm.findSystemFonts()\n# font_names = &#91;fm.FontProperties(fname=font).get_name() for font in fonts]\n# print(\"\u7cfb\u7edf\u53ef\u7528\u5b57\u4f53:\")\n# for font_name in font_names:\n#     print(font_name)\n\n# \u624b\u52a8\u9009\u62e9\u4e00\u4e2a\u652f\u6301\u4e2d\u6587\u7684\u5b57\u4f53\nfont_name = 'Microsoft YaHei'  # \u6839\u636e\u8f93\u51fa\u7ed3\u679c\u4fee\u6539\ntry:\n    plt.rcParams&#91;'font.family'] = font_name\n    plt.rcParams&#91;'axes.unicode_minus'] = False  # \u8d1f\u53f7\u6b63\u5e38\u663e\u793a\n    print(f\"\u6210\u529f\u4f7f\u7528\u5b57\u4f53: {font_name}\")\nexcept Exception as e:\n    print(f\"\u52a0\u8f7d\u5b57\u4f53\u65f6\u53d1\u751f\u9519\u8bef: {e}\uff0c\u4f7f\u7528\u9ed8\u8ba4\u5b57\u4f53\u3002\")\n\ndef get_stock_data(stock_code, start_date, end_date, max_retries=3, retry_delay=5):\n    \"\"\"\u83b7\u53d6\u80a1\u7968\u6570\u636e\uff0c\u6dfb\u52a0\u91cd\u8bd5\u673a\u5236\u548c\u9519\u8bef\u5904\u7406\"\"\"\n    for attempt in range(max_retries):\n        try:\n            print(f\"\u5c1d\u8bd5\u83b7\u53d6 {stock_code} \u7684\u6570\u636e\uff0c\u5c1d\u8bd5\u6b21\u6570: {attempt + 1}\/{max_retries}\")\n            stock_df = ak.stock_zh_a_hist_tx(\n                symbol=stock_code,\n                start_date=start_date,\n                end_date=end_date,\n                adjust=\"\"\n            )\n            if stock_df is None or stock_df.empty:\n                print(f\"\u8b66\u544a\uff1a\u83b7\u53d6\u5230\u7684 {stock_code} \u6570\u636e\u4e3a\u7a7a\")\n                return None\n            if 'date' in stock_df.columns:\n                stock_df = stock_df.set_index('date')\n                stock_df.index = pd.to_datetime(stock_df.index)\n            else:\n                print(f\"\u9519\u8bef\uff1a\u672a\u627e\u5230\u65e5\u671f\u5217\u3002\u53ef\u7528\u5217\u540d: {stock_df.columns.tolist()}\")\n                return None\n            return stock_df&#91;'close']\n        except (ConnectionError, Timeout, TooManyRedirects) as e:\n            print(f\"\u7f51\u7edc\u8fde\u63a5\u9519\u8bef: {e}\")\n            if attempt &lt; max_retries - 1:\n                print(f\"\u5c06\u5728 {retry_delay} \u79d2\u540e\u91cd\u8bd5...\")\n                time.sleep(retry_delay)\n            else:\n                print(\"\u8fbe\u5230\u6700\u5927\u91cd\u8bd5\u6b21\u6570\uff0c\u83b7\u53d6\u6570\u636e\u5931\u8d25\")\n                return None\n        except Exception as e:\n            print(f\"\u53d1\u751f\u672a\u77e5\u9519\u8bef: {e}\")\n            return None\n\ndef plot_kline(stock_code, start_date, end_date):\n    try:\n        stock_df = ak.stock_zh_a_hist_tx(\n            symbol=stock_code,\n            start_date=start_date,\n            end_date=end_date,\n            adjust=\"\"\n        )\n        if stock_df is None or stock_df.empty:\n            print(\"K\u7ebf\u6570\u636e\u4e3a\u7a7a\uff0c\u65e0\u6cd5\u7ed8\u5236K\u7ebf\u56fe\")\n            return\n        stock_df = stock_df.rename(columns={'date': 'Date', 'open': 'Open', 'high': 'High', 'low': 'Low', 'close': 'Close', 'amount': 'Volume'})\n        stock_df&#91;'Date'] = pd.to_datetime(stock_df&#91;'Date'])\n        stock_df.set_index('Date', inplace=True)\n        title = f'{stock_code} K\u7ebf\u56fe'\n        mpf.plot(stock_df&#91;&#91;'Open', 'High', 'Low', 'Close', 'Volume']], type='candle', volume=True, style='yahoo', title=title)\n    except RequestException as e:\n        print(f\"\u83b7\u53d6\u6570\u636e\u65f6\u53d1\u751f\u7f51\u7edc\u8bf7\u6c42\u9519\u8bef: {e}\")\n    except Exception as e:\n        print(f\"\u7ed8\u5236K\u7ebf\u56fe\u65f6\u53d1\u751f\u9519\u8bef: {e}\")\n\n\ndef monte_carlo_simulations(close_prices, num_simulations=10000, days=1):\n    \"\"\"\u8fd4\u56de\u8499\u7279\u5361\u6d1b\u6a21\u62df\u7684\u6240\u6709\u6536\u76ca\u7387\u6570\u7ec4\"\"\"\n    returns = close_prices.pct_change().dropna()\n    mean_return = returns.mean()\n    std_return = returns.std()\n    simulations = np.zeros(num_simulations)\n    for i in range(num_simulations):\n        daily_returns = np.random.normal(mean_return, std_return, days)\n        final_return = np.prod(1 + daily_returns) - 1\n        simulations&#91;i] = final_return\n    return simulations\n\ndef monte_carlo_var(simulations, confidence_level=0.95):\n    \"\"\"\u6839\u636e\u6a21\u62df\u7ed3\u679c\u8ba1\u7b97VaR\"\"\"\n    var = np.percentile(simulations, 100 * (1 - confidence_level))\n    return var\n\ndef plot_var_results(simulations, var_value, confidence_level=0.95, days=1):\n    \"\"\"\u7ed8\u5236\u8499\u7279\u5361\u6d1b\u6a21\u62df\u6536\u76ca\u7387\u5206\u5e03\u548cVaR\"\"\"\n    plt.figure(figsize=(10, 6))\n    sns.histplot(simulations, bins=30, kde=True, stat=\"density\", color='skyblue')\n    plt.axvline(x=var_value, color='red', linestyle='--', \n                label=f\"{int(confidence_level*100)}% VaR: {var_value:.2%}\")\n    plt.title(f\"\u8499\u7279\u5361\u6d1b\u6a21\u62df\u80a1\u7968\u6536\u76ca\u7387\u5206\u5e03\u4e0eVaR\uff08{days}\u5929\uff09\")\n    plt.xlabel(\"\u6536\u76ca\u7387\")\n    plt.ylabel(\"\u5bc6\u5ea6\")\n    plt.legend()\n    plt.grid(True, linestyle='--', alpha=0.7)\n    plt.tight_layout()\n    plt.show()\n\ndef plot_price_history(stock_prices):\n    plt.figure(figsize=(10, 4))\n    sns.lineplot(data=stock_prices)\n    plt.title(\"\u5386\u53f2\u80a1\u7968\u4ef7\u683c\u8d70\u52bf\")\n    plt.xlabel(\"\u65e5\u671f\")\n    plt.ylabel(\"\u4ef7\u683c\")\n    plt.grid(True, linestyle='--', alpha=0.7)\n    plt.tight_layout()\n    plt.show()\n\nif __name__ == \"__main__\":\n    # \u53c2\u6570\u8bbe\u7f6e\n    stock_code = 'sh600938'  # \u4e2d\u56fd\u6d77\u6cb9\n    start_date = '20240101'\n    end_date = '20250521'\n    num_simulations = 10000\n    days = 10\n    confidence_level = 0.95\n\n    # \u83b7\u53d6\u80a1\u7968\u6570\u636e\n    close_prices = get_stock_data(stock_code, start_date, end_date)\n    if close_prices is None:\n        print(\"\u65e0\u6cd5\u83b7\u53d6\u80a1\u7968\u6570\u636e\uff0c\u7a0b\u5e8f\u9000\u51fa\")\n        exit()\n\n    # \u7ed8\u5236\u5386\u53f2\u4ef7\u683c\n    plot_price_history(close_prices)\n\n    # \u8499\u7279\u5361\u6d1b\u6a21\u62df\n    simulations = monte_carlo_simulations(close_prices, num_simulations, days)\n    var = monte_carlo_var(simulations, confidence_level)\n\n    print(f\"\u5355\u53ea\u80a1\u7968 {stock_code} \u5728 {confidence_level * 100:.0f}% \u7f6e\u4fe1\u6c34\u5e73\u4e0b\uff0c{days} \u5929\u7684 VaR \u4e3a: {var:.2%}\")\n\n    # \u7ed8\u5236\u6a21\u62df\u7ed3\u679c\u4e0eVaR\n    plot_var_results(simulations, var, confidence_level, days)\n    # \u7ed8\u5236K\u7ebf\u56fe\n    plot_kline(stock_code, start_date, end_date)\n<\/code><\/pre>\n","protected":false},"excerpt":{"rendered":"","protected":false},"author":1,"featured_media":0,"comment_status":"closed","ping_status":"open","sticky":false,"template":"","format":"standard","meta":{"footnotes":""},"categories":[2,24],"tags":[],"class_list":["post-5637","post","type-post","status-publish","format-standard","hentry","category-2","category-24"],"_links":{"self":[{"href":"http:\/\/g1n29wqq.ipyingshe.net:5347\/index.php?rest_route=\/wp\/v2\/posts\/5637","targetHints":{"allow":["GET"]}}],"collection":[{"href":"http:\/\/g1n29wqq.ipyingshe.net:5347\/index.php?rest_route=\/wp\/v2\/posts"}],"about":[{"href":"http:\/\/g1n29wqq.ipyingshe.net:5347\/index.php?rest_route=\/wp\/v2\/types\/post"}],"author":[{"embeddable":true,"href":"http:\/\/g1n29wqq.ipyingshe.net:5347\/index.php?rest_route=\/wp\/v2\/users\/1"}],"replies":[{"embeddable":true,"href":"http:\/\/g1n29wqq.ipyingshe.net:5347\/index.php?rest_route=%2Fwp%2Fv2%2Fcomments&post=5637"}],"version-history":[{"count":1,"href":"http:\/\/g1n29wqq.ipyingshe.net:5347\/index.php?rest_route=\/wp\/v2\/posts\/5637\/revisions"}],"predecessor-version":[{"id":5638,"href":"http:\/\/g1n29wqq.ipyingshe.net:5347\/index.php?rest_route=\/wp\/v2\/posts\/5637\/revisions\/5638"}],"wp:attachment":[{"href":"http:\/\/g1n29wqq.ipyingshe.net:5347\/index.php?rest_route=%2Fwp%2Fv2%2Fmedia&parent=5637"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"http:\/\/g1n29wqq.ipyingshe.net:5347\/index.php?rest_route=%2Fwp%2Fv2%2Fcategories&post=5637"},{"taxonomy":"post_tag","embeddable":true,"href":"http:\/\/g1n29wqq.ipyingshe.net:5347\/index.php?rest_route=%2Fwp%2Fv2%2Ftags&post=5637"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}