{"id":5633,"date":"2025-05-23T10:33:50","date_gmt":"2025-05-23T02:33:50","guid":{"rendered":"http:\/\/cnliutz.pgrm.cc\/?p=5633"},"modified":"2025-05-23T10:33:52","modified_gmt":"2025-05-23T02:33:52","slug":"python%e5%8d%95%e5%8f%aa%e8%82%a1%e7%a5%a8%e8%92%99%e7%89%b9%e5%8d%a1%e6%b4%9b%e9%a3%8e%e9%99%a9%e8%ae%a1%e7%ae%97%e5%8f%8a%e7%bb%98%e5%9b%be%e6%96%b9%e6%b3%95","status":"publish","type":"post","link":"http:\/\/g1n29wqq.ipyingshe.net:5347\/?p=5633","title":{"rendered":"python\u5355\u53ea\u80a1\u7968\u8499\u7279\u5361\u6d1b\u98ce\u9669\u8ba1\u7b97\u53ca\u7ed8\u56fe\u65b9\u6cd5"},"content":{"rendered":"\n<pre class=\"wp-block-code\"><code>import akshare as ak\nimport numpy as np\nimport pandas as pd\nimport matplotlib.pyplot as plt\nimport seaborn as sns\nimport time\n\n# \u5b57\u4f53\u8bbe\u7f6e\nplt.rcParams&#91;\"font.family\"] = &#91;\"simkai.ttf\", \"Microsoft YaHei\", \"SimHei\"]\ntry:\n    import matplotlib.font_manager as fm\n    font = fm.FontProperties(fname=r\"C:\\Windows\\Fonts\\msyh.ttc\")\n    plt.rcParams&#91;\"font.family\"] = font.get_name()\nexcept Exception:\n    plt.rcParams&#91;\"font.family\"] = &#91;\"SimHei\", \"simkai.ttf\"]\n\nfrom requests.exceptions import ConnectionError, Timeout, TooManyRedirects\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 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    \"\"\"\u7ed8\u5236\u5386\u53f2\u4ef7\u683c\u8d70\u52bf\"\"\"\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 = 1000\n    days = 1\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\n<\/code><\/pre>\n\n\n\n<figure class=\"wp-block-gallery has-nested-images columns-default is-cropped wp-block-gallery-1 is-layout-flex wp-block-gallery-is-layout-flex\">\n<figure class=\"wp-block-image size-large\"><img loading=\"lazy\" decoding=\"async\" width=\"1000\" height=\"400\" data-id=\"5634\" src=\"http:\/\/cnliutz.pgrm.cc\/wp-content\/uploads\/2025\/05\/Figure_1.png\" alt=\"\" class=\"wp-image-5634\" srcset=\"http:\/\/g1n29wqq.ipyingshe.net:5347\/wp-content\/uploads\/2025\/05\/Figure_1.png 1000w, http:\/\/g1n29wqq.ipyingshe.net:5347\/wp-content\/uploads\/2025\/05\/Figure_1-300x120.png 300w, http:\/\/g1n29wqq.ipyingshe.net:5347\/wp-content\/uploads\/2025\/05\/Figure_1-768x307.png 768w\" sizes=\"auto, (max-width: 1000px) 100vw, 1000px\" \/><\/figure>\n\n\n\n<figure class=\"wp-block-image size-large\"><img loading=\"lazy\" decoding=\"async\" width=\"1000\" height=\"600\" data-id=\"5635\" src=\"http:\/\/cnliutz.pgrm.cc\/wp-content\/uploads\/2025\/05\/Figure_2.png\" alt=\"\" class=\"wp-image-5635\" srcset=\"http:\/\/g1n29wqq.ipyingshe.net:5347\/wp-content\/uploads\/2025\/05\/Figure_2.png 1000w, http:\/\/g1n29wqq.ipyingshe.net:5347\/wp-content\/uploads\/2025\/05\/Figure_2-300x180.png 300w, http:\/\/g1n29wqq.ipyingshe.net:5347\/wp-content\/uploads\/2025\/05\/Figure_2-768x461.png 768w\" sizes=\"auto, (max-width: 1000px) 100vw, 1000px\" \/><\/figure>\n<\/figure>\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-5633","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\/5633","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=5633"}],"version-history":[{"count":1,"href":"http:\/\/g1n29wqq.ipyingshe.net:5347\/index.php?rest_route=\/wp\/v2\/posts\/5633\/revisions"}],"predecessor-version":[{"id":5636,"href":"http:\/\/g1n29wqq.ipyingshe.net:5347\/index.php?rest_route=\/wp\/v2\/posts\/5633\/revisions\/5636"}],"wp:attachment":[{"href":"http:\/\/g1n29wqq.ipyingshe.net:5347\/index.php?rest_route=%2Fwp%2Fv2%2Fmedia&parent=5633"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"http:\/\/g1n29wqq.ipyingshe.net:5347\/index.php?rest_route=%2Fwp%2Fv2%2Fcategories&post=5633"},{"taxonomy":"post_tag","embeddable":true,"href":"http:\/\/g1n29wqq.ipyingshe.net:5347\/index.php?rest_route=%2Fwp%2Fv2%2Ftags&post=5633"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}