{"id":552,"date":"2024-07-02T08:52:00","date_gmt":"2024-07-02T00:52:00","guid":{"rendered":"http:\/\/123.60.176.65\/?p=552"},"modified":"2024-07-02T08:52:00","modified_gmt":"2024-07-02T00:52:00","slug":"ai%e9%a1%be%e9%97%ae%e6%8a%95%e8%b5%84%e4%b9%8b%e9%ab%98%e7%ba%a7%e7%ad%96%e7%95%a5%e4%ba%8c%ef%bc%9a%e5%bd%bc%e5%be%97%e6%9e%97%e5%a5%87%e7%9a%84peg%ef%bc%88%e5%bb%ba%e8%ae%ae%e6%94%b6%e8%97%8f","status":"publish","type":"post","link":"https:\/\/laoyulaoyu.com\/index.php\/2024\/07\/02\/ai%e9%a1%be%e9%97%ae%e6%8a%95%e8%b5%84%e4%b9%8b%e9%ab%98%e7%ba%a7%e7%ad%96%e7%95%a5%e4%ba%8c%ef%bc%9a%e5%bd%bc%e5%be%97%e6%9e%97%e5%a5%87%e7%9a%84peg%ef%bc%88%e5%bb%ba%e8%ae%ae%e6%94%b6%e8%97%8f\/","title":{"rendered":"AI\u987e\u6295\u9ad8\u7ea7\u7b56\u7565\u4e4b\u4e8c\uff1a\u5f7c\u5f97\u6797\u5947\u7684PEG\uff08\u5efa\u8bae\u6536\u85cf\uff09"},"content":{"rendered":"\n<figure class=\"wp-block-image size-full\"><img decoding=\"async\" src=\"http:\/\/123.60.176.65\/wp-content\/uploads\/2024\/06\/b999a9014c086e0609c2f7180c087bf40ad1cb7f.png\" alt=\"\" class=\"wp-image-559\"\/><\/figure>\n\n\n\n<blockquote class=\"wp-block-quote is-layout-flow wp-block-quote-is-layout-flow\">\n<pre class=\"wp-block-verse\"><strong>\u5199\u5728\u524d\u9762\u7684\u8bdd\uff1a<\/strong>\u5f7c\u5f97\u00b7\u6797\u5947\u662f\u4e00\u4f4d\u975e\u5e38\u6210\u529f\u7684\u6295\u8d44\u8005\u548c\u524d\u9ea6\u54f2\u4f26\u57fa\u91d1\u7684\u57fa\u91d1\u7ecf\u7406\uff0c\u4ed6\u63d0\u51fa\u4e86\u4e00\u79cd\u88ab\u5e7f\u6cdb\u91c7\u7528\u7684\u4ef7\u503c\u9009\u80a1\u7b56\u7565\uff0c\u5373\u4f7f\u7528\u5e02\u76c8\u7387\u76f8\u5bf9\u76c8\u5229\u589e\u957f\u7387\uff08PEG\uff09\u4f5c\u4e3a\u8861\u91cf\u80a1\u7968\u4ef7\u503c\u7684\u4e3b\u8981\u6307\u6807\u3002<mark style=\"background-color:rgba(0, 0, 0, 0)\" class=\"has-inline-color has-vivid-cyan-blue-color\">PEG\u6bd4\u7387\u662f\u4e00\u79cd\u53d7\u5230\u6295\u8d44\u8005\u559c\u7231\u7684\u6307\u6807<\/mark>\uff0c\u56e0\u4e3a\u5b83\u8bd5\u56fe\u901a\u8fc7\u8003\u8651\u516c\u53f8\u7684\u589e\u957f\u6765\u63d0\u4f9b\u6bd4\u4f20\u7edf\u5e02\u76c8\u7387\uff08PE\uff09\u66f4\u5168\u9762\u7684\u80a1\u7968\u4f30\u503c\u65b9\u6cd5\u3002<\/pre>\n<\/blockquote>\n\n\n\n<h2 class=\"wp-block-heading\">\u7b56\u7565\u540d\u79f0: \u5f7c\u5f97\u6797\u5947PEG\u4ef7\u503c\u9009\u80a1\u7b56\u7565<\/h2>\n\n\n\n<p><strong>\u7b56\u7565\u601d\u8def:<\/strong><\/p>\n\n\n\n<p>1.\u9009\u62e9<mark style=\"background-color:rgba(0, 0, 0, 0)\" class=\"has-inline-color has-vivid-cyan-blue-color\">PEG &lt; 0.5<\/mark>, \u5373\u7a33\u5b9a\u6210\u957f\u4e14\u4ef7\u503c\u88ab\u4f4e\u4f30\u7684\u80a1\u7968\uff0c\u5176\u4e2d<mark style=\"background-color:rgba(0, 0, 0, 0)\" class=\"has-inline-color has-vivid-cyan-blue-color\">PEG = PE \/ growth_rate<\/mark><\/p>\n\n\n\n<p>2.\u4f7f\u7528ES\u98ce\u9669\u5e73\u4ef7\u914d\u6743<\/p>\n\n\n\n<p>3.\u6839\u636e\u7ec4\u5408\u7684\u65e5\u5185\u6ce2\u52a8\u5c0f\u4e8e3%\u7684\u6761\u4ef6, \u4e0e\u8d27\u5e01\u57fa\u91d1\u7ec4\u5408\u914d\u8d44<\/p>\n\n\n\n<p>4.\u6700\u5927\u6301\u4ed35\u53ea\u80a1\u7968\u548c1\u53ea\u8d27\u5e01\u57fa\u91d1, \u4f18\u5148\u4e70\u5165\u5e02\u503c\u5c0f\u7684, 15\u5929\u8c03\u4ed3\u4e00\u6b21<\/p>\n\n\n\n<p>5.\u5254\u9664\u4e86\u5468\u671f\u6027\u548c\u9879\u76ee\u7c7b\u884c\u4e1a(\u8be5\u90e8\u5206\u5bf9\u6539\u5584\u56de\u64a4\u6709\u660e\u663e\u7684\u6548\u679c)<\/p>\n\n\n\n<h2 class=\"wp-block-heading\">\u7b97\u6cd5\u4ee3\u7801\u5982\u4e0b\uff1a<\/h2>\n\n\n\n<pre class=\"wp-block-code\"><code>import pandas as pd\nimport numpy as np\nimport datetime as dt\n\ndef init(context):\n    # \u5f53\u524d\u6301\u4ed3\u6570\uff1a0\n    context.num = 0\n    # \u6700\u5927\u6301\u4ed3\u80a1\u7968\u6570\uff1a5\n    context.stock_max_num = 5\n    \n    # \u6bcf\u53ea\u80a1\u7968\u7684\u6700\u5927\u98ce\u9669\u655e\u53e3\n    context.risk_limit = 0.03 \/ context.stock_max_num\n    \n    # \u5df2\u6301\u4ed3\u5929\u6570\uff1a0\u5929\n    # \u6301\u4ed3\u5468\u671f\uff1a15\u5929\n    context.hold_days, context.hold_cycle = 0, 15\n    \n    # \u8ba1\u7b97ES\u7684\u7f6e\u4fe1\u5ea6\n    context.confidenceLevel = 0.05\n    # \u8ba1\u7b97ES\u7684\u5386\u53f2\u56de\u6d4b\u957f\u5ea6\n    context.lag = 180\n    \n    # \u6bcf\u4e2a\u4ea4\u6613\u65e509:31\u8fd0\u884c\n    run_daily(func=fun_main, reference_security='000001.SZ')\n\n    \n######################  \u4e3b\u51fd\u6570 \ndef fun_main(context, bar_dict):\n    flag = fun_needRebalance(context)\n    \n    if flag:\n        last_date = get_last_datetime().strftime('%Y%m%d')\n        universe = list(get_all_securities('stock', date = last_date).index)\n        # stock_list = universe\n        stock_list = fun_unpaused(universe,bar_dict)\n        stock_list = fun_remove_new(stock_list, 60)\n        stock_list = fun_remove_periodic_industry(stock_list, last_date)\n        \n\n        line = '###############' + str(last_date) + ': ' + str(len(universe)) + ' \/ ' + str(len(stock_list))\n        print(line)\n\n        # \u8ba1\u7b97\u5355\u5b63\u5ea6\u589e\u957f\u7387\n        df_growth = fun_cal_growth_rate(bar_dict, stock_list, last_date)\n\n        # \u8ba1\u7b97PEG\n        df_all = fun_cal_PEG(bar_dict, df_growth.copy(), last_date)\n\n        # \u9009\u80a1\n        buy_list = fun_get_buy_list(context, bar_dict, df_all.copy(), context.stock_max_num, last_date)\n\n        # \u8ba1\u7b97\u80a1\u7968\u6743\u91cd\n        stock_weight = fun_cal_stock_weight(buy_list, context.lag, context.confidenceLevel, last_date, 'ES')\n        print('stock_weight: ')\n        print(stock_weight)\n        \n        bond_weight = {'511880.OF': 1.0}\n        \n        # \u8ba1\u7b97\u6700\u7ec8\u6743\u91cd\uff08\u8003\u8651\u7ec4\u5408\u98ce\u9669 + \u503a\u5238\uff09\n        trade_ratio = fun_cal_position(context, bar_dict, stock_weight, bond_weight)\n        \n        print('trade_ratio: ')\n        print(trade_ratio)\n        \n        # \u4e0b\u5355\n        fun_do_trade(context, bar_dict, trade_ratio)\n\n    context.num = len(context.portfolio.stock_account.positions)\n\n\ndef handle_bar(context,bar_dict):\n    pass\n\n\n#### 1.\u5224\u65ad\u662f\u5426\u8c03\u4ed3\u51fd\u6570 #########################################\ndef fun_needRebalance(context):\n    # \u6761\u4ef61: \u6301\u4ed3\u80a1\u6570\u4e3a0\u65f6\uff0c\u91cd\u65b0\u8c03\u4ed3\n    if context.num == 0:\n        context.hold_days = 0\n        return True\n    \n    # \u6761\u4ef62\uff1a\u6301\u4ed3\u5230\u8c03\u4ed3\u5468\u671f\u65f6\uff0c\u91cd\u65b0\u8c03\u4ed3\n    elif context.hold_days == context.hold_cycle:\n        context.hold_days = 0\n        return True\n    \n    else:\n        context.hold_days += 1\n        return False\n\n\n#### 2.\u5254\u9664\u505c\u724c\u80a1\u7968\u51fd\u6570 #########################################\ndef fun_unpaused(_stock_list,bar_dict):\n    return &#91;stock for stock in _stock_list if not bar_dict&#91;stock].is_paused] \n    \n\n#### 3.\u5254\u9664\u4e0a\u5e02\u4e0d\u523060\u5929\u7684\u65b0\u80a1 ###################################\ndef fun_remove_new(_stock_list, days):\n    deltaDate = get_datetime() - dt.timedelta(days)\n    \n    stock_list = &#91;]\n    for stock in _stock_list:\n        if get_security_info(stock).start_date &lt; deltaDate:\n            stock_list.append(stock)\n    \n    return stock_list\n    \n\n#### 4.\u5254\u9664\u5468\u671f\u6027\u884c\u4e1a ###########################################\ndef fun_remove_periodic_industry(stock_list, last_date):\n    \n    periodic_industry = &#91;#'T0101', # \u79cd\u690d\u4e1a\u4e0e\u6797\u4e1a\n                         #'T0102', # \u517b\u6b96\u4e1a\n                         #'T0103', # \u519c\u4ea7\u54c1\u52a0\u5de5\n                         #'T0104', # \u519c\u4e1a\u670d\u52a1\n        \n                         'T0201', # \u7164\u70ad\u5f00\u91c7\n                         'T0202', # \u77f3\u6cb9\u77ff\u4e1a\u5f00\u91c7\n                         'T0203', # \u91c7\u6398\u670d\u52a1\n                         'T0301', # \u57fa\u7840\u5316\u5b66\n                         'T0302', # \u5316\u5b66\u5236\u54c1\n                         'T0303', # \u5316\u5de5\u65b0\u6750\u6599\n                         'T0304', # \u5316\u5de5\u5408\u6210\u6750\u6599\n                         'T0401', # \u94a2\u94c1\n                         'T0501', # \u6709\u8272\u51b6\u70bc\u52a0\u5de5\n                         'T0502', # \u65b0\u6750\u6599\n        \n                         'T0601', # \u5efa\u7b51\u6750\u6599\n                         'T0602', # \u5efa\u7b51\u88c5\u9970\n                         'T0701', # \u901a\u7528\u8bbe\u5907\n                         'T0702', # \u4e13\u7528\u8bbe\u5907\n                         'T0703', # \u4eea\u5668\u4eea\u8868\n                         'T0704', # \u7535\u6c14\u8bbe\u5907\n                         #'T0801', # \u534a\u5bfc\u4f53\u53ca\u5143\u4ef6\n                         #'T0802', # \u5149\u5b66\u5149\u7535\u5b50\n                         #'T0803', # \u5176\u4ed6\u7535\u5b50\n                         #'T0804', # \u7535\u5b50\u5236\u9020\n                         'T0901', # \u6c7d\u8f66\u6574\u8f66\n                         'T0902', # \u6c7d\u8f66\u96f6\u90e8\u4ef6\n                         'T0903', # \u975e\u6c7d\u8f66\u4ea4\u8fd0\n                         'T0904', # \u4ea4\u8fd0\u8bbe\u5907\u670d\u52a1\n                         #'T1001', # \u901a\u4fe1\u8bbe\u5907\n                         #'T1002', # \u8ba1\u7b97\u673a\u8bbe\u5907\n                         'T1101', # \u767d\u8272\u5bb6\u7535\n                         'T1102', # \u89c6\u542c\u5668\u6750\n                         #'T1201', # \u996e\u6599\u5236\u9020\n                         #'T1202', # \u98df\u54c1\u52a0\u5de5\u5236\u9020\n                         #'T1301', # \u9632\u6b62\u5236\u9020\n                         #'T1302', # \u670d\u88c5\u5bb6\u7eba\n                         #'T1401', # \u9020\u7eb8\n                         #'T1402', # \u5305\u88c5\u5370\u5237\n                         #'T1403', # \u5bb6\u7528\u8f7b\u5de5\n                         #'T1501', # \u5316\u5b66\u5236\u836f\n                         #'T1502', # \u4e2d\u836f\n                         #'T1503', # \u751f\u7269\u5236\u54c1\n                         #'T1504', # \u533b\u836f\u5546\u4e1a\n                         #'T1505', # \u533b\u7597\u5668\u68b0\u670d\u52a1\n                         'T1601', # \u7535\u529b\n                         'T1602', # \u71c3\u6c14\u6c34\u52a1\n                         'T1603', # \u73af\u4fdd\u5de5\u7a0b\n                         'T1701', # \u6e2f\u53e3\u822a\u8fd0\n                         'T1702', # \u516c\u8def\u94c1\u8def\u8fd0\u8f93\n                         #'T1703', # \u516c\u4ea4\n                         #'T1704', # \u673a\u573a\u822a\u8fd0\n                         #'T1705', # \u7269\u6d41\n                         'T1801', # \u623f\u5730\u4ea7\u5f00\u53d1\n                         'T1802', # \u56ed\u533a\u5f00\u53d1\n        \n                         'T1901', # \u94f6\u884c\n                         'T1902', # \u4fdd\u9669\u53ca\u5176\u4ed6\n                         'T1903', # \u8bc1\u5238\n                         #'T2001', # \u96f6\u552e\n                         'T2002', # \u8d38\u6613\n                         #'T2101', # \u666f\u70b9\u53ca\u65c5\u6e38\n                         #'T2102', # \u9152\u5e97\u53ca\u9910\u996e\n                         #'T2201', # \u901a\u4fe1\u670d\u52a1\n                         #'T2202', # \u8ba1\u7b97\u673a\u5e94\u7528\n                         #'T2203', # \u4f20\u5a92\n                         #'T2301', # \u7efc\u5408\n                         #'T2401'  # \u56fd\u9632\u519b\u5de5\n                         ]\n    \n    for industry in periodic_industry:\n        stocks = get_industry_stocks(industry, last_date)\n        stock_list = list(set(stock_list).difference(set(stocks)))\n    \n    return stock_list\n\n\n#### 5.\u8ba1\u7b97\u5355\u5b63\u5ea6\u589e\u957f\u7387\u51fd\u6570 ####################################################\ndef fun_cal_growth_rate(bar_dict, stock_list, last_date):\n    \n    # \u8ba1\u7b97\u5355\u5b63\u5ea6\u51c0\u6536\u76ca\u51fd\u6570\n    def fun_get_quarterly_net_profit(current_quarter, last_quarter, stock_list):\n        q = query(income.symbol,\n                  income.net_profit\n                 ).filter(income.symbol.in_(stock_list))\n\n        # \u5f53\u5b63\u5ea6\u7d2f\u8ba1\u51c0\u5229\u6da6\n        df1 = get_fundamentals(q, statDate = current_quarter)\n        df1.columns = &#91;'symbol', 'total_net_profit']\n\n        # \u4e0a\u5b63\u5ea6\u7d2f\u8ba1\u51c0\u5229\u6da6\n        df2 = get_fundamentals(q, statDate = last_quarter)\n        df2.columns = &#91;'symbol', 'last_total_net_profit']\n\n        df = pd.merge(df1, df2, on='symbol')\n\n        # \u5f53\u524d\u5355\u5b63\u5ea6\u51c0\u5229\u6da6\n        df&#91;'quarterly_net_profit'] = df&#91;'total_net_profit'] - df&#91;'last_total_net_profit']\n\n        del df&#91;'total_net_profit']\n        del df&#91;'last_total_net_profit']\n\n        return df\n    \n    ########## \u83b7\u53d6\u8d22\u62a5\u5b63\u5ea6\u65e5\u671f \n    q = query(income.symbol, \n              income.stat_date\n             ).filter(income.symbol.in_(stock_list))\n\n    df = get_fundamentals(q, date = last_date)\n    \n    df = df.sort_values(&#91;'income_stat_date'], ascending=False)\n    \n    last_statDate = df.iloc&#91;0,1]\n    \n    # \u5254\u9664\u672a\u6309\u65f6\u516c\u5e03\u62a5\u8868\u7684\u516c\u53f8\uff0c\u907f\u514d\u672a\u6765\u51fd\u6570\n    df&#91;df&#91;'income_stat_date'] != last_statDate] = None\n    df = df.dropna()\n    stock_list = list(df&#91;'income_symbol'].values)\n\n    the_year = int(str(last_statDate)&#91;0:4])\n    the_month = str(last_statDate)&#91;5:7]\n\n    ########## \u83b7\u53d6\u8d22\u62a5\u5355\u5b63\u5ea6\u51c0\u5229\u6da6\u589e\u957f\u7387\n    '''\n    quarter_1:  \u5f53\u5b63\u5ea6\n    quarter_2:  \u4e0a\u5b63\u5ea6\n    quarter_3:  \u540c\u6bd4\u4e0a\u5b63\u5ea6\n    quarter_4:  \u53bb\u5e74\u4e0a\u5b63\u5ea6\n    '''\n\n    if the_month == '03':\n        # \u56e0\u4e3a\u4e00\u5b63\u5ea6\u7684\u62a5\u8868\u662f\u5355\u5b63\u5ea6\u8868\uff0c\u6240\u4ee5\u9700\u8981\u5355\u72ec\u5904\u7406\n        quarter_1 = str(the_year)     + 'q1'\n        quarter_3 = str(the_year - 1) + 'q1'\n\n        q = query(income.symbol,\n              income.net_profit\n             ).filter(income.symbol.in_(stock_list))\n\n        df1 = get_fundamentals(q, statDate = quarter_1)\n        df1.columns = &#91;'symbol', 'current_net_profit']\n\n        df2 = get_fundamentals(q, statDate = quarter_3)\n        df2.columns = &#91;'symbol', 'last_net_profit']\n\n    else:\n        if the_month == '12':\n            quarter_1 = str(the_year)     + 'q4'\n            quarter_2 = str(the_year)     + 'q3'\n            quarter_3 = str(the_year - 1) + 'q4'\n            quarter_4 = str(the_year - 1) + 'q3'\n\n        elif the_month == '09':\n            quarter_1 = str(the_year)     + 'q3'\n            quarter_2 = str(the_year)     + 'q2'\n            quarter_3 = str(the_year - 1) + 'q3'\n            quarter_4 = str(the_year - 1) + 'q2'\n\n        elif the_month == '06':\n            quarter_1 = str(the_year)     + 'q2'\n            quarter_2 = str(the_year)     + 'q1'\n            quarter_3 = str(the_year - 1) + 'q2'\n            quarter_4 = str(the_year - 1) + 'q1'\n\n        else:\n            print('There is something wrong with the stat_date.')\n\n        # \u8ba1\u7b97\u5f53\u671f\u5355\u5b63\u5ea6\u51c0\u5229\u6da6\n        df1 = fun_get_quarterly_net_profit(quarter_1, quarter_2, stock_list)\n        df1.columns = &#91;'symbol', 'current_net_profit']\n\n        # \u8ba1\u7b97\u540c\u6bd4\u4e0a\u671f\u5355\u5b63\u5ea6\u51c0\u5229\u6da6\n        df2 = fun_get_quarterly_net_profit(quarter_3, quarter_4, stock_list)\n        df2.columns = &#91;'symbol', 'last_net_profit']\n\n\n    df_growth = pd.merge(df1, df2, on='symbol')\n    # \u589e\u957f\u7387\u5355\u4f4d\u4e3a%\n    df_growth&#91;'growth_rate'] = (df_growth&#91;'current_net_profit'] \/ df_growth&#91;'last_net_profit'] - 1) * 100\n\n    return df_growth\n\n\n#### 6.\u8ba1\u7b97PEG\u51fd\u6570 ############################################################\ndef fun_cal_PEG(bar_dict, df_growth, last_date):\n    stock_list = stock_list = list(df_growth&#91;'symbol'].values)\n    \n    q = query(valuation.symbol,\n              valuation.pe_ttm,\n             ).filter(valuation.symbol.in_(stock_list))\n\n    df_pe = get_fundamentals(q, date = last_date)\n    df_pe.columns = &#91;'symbol', 'pe_ttm']\n    \n    # \u5254\u9664PE\u503c\u4e3a\u8d1f\u7684\u80a1\u7968\n    df_pe&#91;df_pe&#91;'pe_ttm'] &lt; 0] = None\n    df_pe = df_pe.dropna()\n    \n    # \u4f7f\u7528\u4e2d\u4f4d\u6570\u53bb\u6781\u503c\u6cd5\n    df_pe = winsorize(df_pe, 'pe_ttm')\n    df_pe = df_pe.dropna()\n    \n    # \u5f7c\u5f97\u6797\u5947\u7684\u6587\u7ae0\u4e2d\u63d0\u5230\uff1a\u589e\u957f\u7387&gt;50\u7684\u516c\u53f8\uff0c\u9ad8\u589e\u957f\u4e0d\u53ef\u6301\u7eed\n    df_growth&#91;df_growth&#91;'growth_rate'] &gt; 50] = None\n    # \u5254\u9664\u589e\u957f\u7387\u4e3a\u8d1f\u7684\u516c\u53f8\n    df_growth&#91;df_growth&#91;'growth_rate'] &lt;= 0] = None\n\n    df_growth = df_growth.dropna()\n\n    del df_growth&#91;'current_net_profit']\n    del df_growth&#91;'last_net_profit']\n\n    df_all = pd.merge(df_pe, df_growth, on='symbol')\n\n    df_all&#91;'PEG'] = df_all&#91;'pe_ttm'] \/ df_all&#91;'growth_rate']\n    \n    return df_all\n\n\n#### 7.\u6839\u636ePEG\u9009\u80a1\u51fd\u6570 ###########################################################\ndef fun_get_buy_list(context, bar_dict, df_all, n, last_date):\n    \n    # \u83b7\u53d6\u80a1\u7968\u5e02\u503c\u4fe1\u606f\u51fd\u6570\n    def fun_get_market_cap(df_selected, last_date):\n        stock_list = list(df_selected&#91;'symbol'].values)\n    \n        # \u83b7\u53d6\u80a1\u7968\u5e02\u503c\n        q = query(valuation.symbol,\n                  valuation.market_cap\n                 ).filter(valuation.symbol.in_(stock_list))\n\n        df_cap = get_fundamentals(q, date = last_date)\n        df_cap.columns = &#91;'symbol', 'market_cap']\n\n        df_selected = pd.merge(df_selected, df_cap, on = 'symbol')\n        df_selected = df_selected.sort_values(&#91;'market_cap'], ascending = True)\n        df_selected = df_selected.reset_index()\n        \n        del df_selected&#91;'index']\n        \n        return df_selected\n        \n        \n    # PEG \u9700\u5c0f\u4e8e 0.5\n    df_selected = df_all&#91;df_all&#91;'PEG'] &lt; 0.5].copy()\n    \n    # \u589e\u6dfb\u80a1\u7968\u7684\u5e02\u503c\u4fe1\u606f\u5230df_selected\n    df_selected = fun_get_market_cap(df_selected.copy(), last_date)\n    \n    # \u83b7\u5f97\u5907\u9009\u80a1\u7968\u5217\u8868\n    if len(df_selected) &gt;= n:\n        buy_list = list(df_selected&#91;'symbol']&#91;:n].values)\n        \n        for i in range(n):\n            print(str(df_selected&#91;'symbol']&#91;i]) + ', PEG = ' + str(df_selected&#91;'PEG']&#91;i]))\n    \n    else:\n        print('\u65b0\u80a1\u4ec5\uff1a ' + str(len(df_selected)))\n        buy_list = list(df_selected&#91;'symbol'].values)\n        \n        for i in range(len(df_selected)):\n            print(str(df_selected&#91;'symbol']&#91;i]) + ', PEG = ' + str(df_selected&#91;'PEG']&#91;i]))\n        \n        old_stock_list = list(context.portfolio.stock_account.positions.keys())\n        \n        if '511880.OF' in old_stock_list:\n            old_stock_list.remove('511880.OF')\n        \n        if len(old_stock_list) &gt; 0:\n        \n            df_growth_old = fun_cal_growth_rate(bar_dict, old_stock_list, last_date)\n\n            df_all_old = fun_cal_PEG(bar_dict, df_growth_old.copy(), last_date)\n\n            df_selected_old = df_all_old&#91;df_all_old&#91;'PEG'] &lt; 1.0].copy()\n\n            df_selected_old = fun_get_market_cap(df_selected_old.copy(), last_date)\n\n            old_stock_list = list(df_selected_old&#91;'symbol'].values)\n\n            i = len(buy_list)\n            for stock in old_stock_list:\n                if i &lt; n:\n                    buy_list.append(stock)\n                    print(str(stock) + ', PEG = ' + str(df_selected_old.loc&#91;df_selected_old&#91;'symbol'] == stock, 'PEG'].values))\n                    i += 1\n                else:\n                    break\n        \n        \n    return buy_list\n\n\n#### 8.\u8ba1\u7b97\u80a1\u7968\u4ed3\u4f4d ##############################################################\ndef fun_cal_stock_weight(stock_list, lag, alpha, last_date, flag=None):\n    \n    # \u8ba1\u7b97\u4e2a\u80a1ES\u98ce\u9669\n    def fun_cal_stockES(stock, lag, alpha, last_date):\n        \n        if lag * alpha &lt; 3: \n            print('The size of lag is too small for the given confidence level.')\n        \n        prices = get_price(stock, start_date=None, end_date=last_date, fre_step='1d', fields=&#91;'close'], skip_paused=False, fq='pre', bar_count=lag, is_panel=0)\n\n        dailyReturns = prices.pct_change().dropna()\n        dailyReturns_sort = dailyReturns.sort_values(&#91;'close'], ascending=True)\n\n        num = round((lag-1) * alpha)\n        ES = dailyReturns_sort&#91;'close']&#91;:num].sum() \/ num\n\n        return ES\n    \n    # ES\u98ce\u9669\u5e73\u4ef7\u914d\u80a1\n    if flag == 'ES':\n        stock_position = {}\n        total_position = 0\n        for stock in stock_list:\n            risk = fun_cal_stockES(stock, lag, alpha, last_date)\n            stock_position&#91;stock] = 1.0 \/ risk\n            total_position += stock_position&#91;stock]\n\n        stock_real_position = {}\n        for stock in stock_list:\n            stock_real_position&#91;stock] = stock_position&#91;stock] \/ total_position\n    \n    # \u7b49\u6743\u91cd\u914d\u80a1\n    else:\n        stock_real_position = {}\n        for stock in stock_list:\n            stock_real_position&#91;stock] = 1.0 \/ len(stock_list)\n\n    return stock_real_position\n\n\n#### 9.\u8ba1\u7b97\u52a0\u5165\u8d27\u5e01\u57fa\u91d1\u540e\u7684\u8d44\u4ea7\u914d\u7f6e ##################################################\ndef fun_cal_position(context, bar_dict, stock_weight, bond_weight, position_ratio = 1.0):\n    \n    # \u8ba1\u7b97\u7ec4\u5408\u6536\u76ca\n    def fun_get_portfolio_daily_return(bar_dict, stock_weight, lag=180):\n        \n        last_date = get_last_datetime().strftime('%Y%m%d')\n        stock_list = list(stock_weight.keys())\n        \n        df = pd.DataFrame()\n        for stock in stock_list:\n            prices = get_price(stock, start_date=None, end_date=last_date, fre_step='1d', fields=&#91;'close'], skip_paused=False, fq='pre', bar_count=lag, is_panel=0)\n            df&#91;stock] = prices&#91;'close']\n        \n        df = df.pct_change().dropna()\n        \n        df&#91;'portfolio_returns'] = 0\n        for stock in stock_list:\n            df&#91;'portfolio_returns'] += df&#91;stock] * stock_weight&#91;stock]\n            del df&#91;stock]\n            \n        df = df.sort_values(&#91;'portfolio_returns'], ascending = True)\n        \n        return df\n    \n    # \u8ba1\u7b97\u7ec4\u5408ES\u503c\n    def fun_get_portfolio_ES(dailyReturns, alpha):\n        \n        lag = len(dailyReturns)\n        \n        num = round(lag * alpha)\n        \n        ES = - (dailyReturns&#91;'portfolio_returns']&#91;:num].sum() \/ num)\n        \n        if ES &lt; 0:\n            ES = 0\n        \n        print('ES: ' + str(ES))\n        \n        return ES\n    \n    # \u8ba1\u7b97\u7ec4\u5408VaR\u503c\n    def fun_get_portfolio_VaR(dailyReturns, alpha):\n        \n        z_score = {0.05: 1.65,\n                   0.04: 1.75,\n                   0.01: 2.33,\n                   0.0001: 3.7}\n        \n        VaR = - (dailyReturns&#91;'portfolio_returns'].mean() - z_score&#91;alpha] * dailyReturns&#91;'portfolio_returns'].std())\n        \n        if VaR &lt; 0:\n            VaR = 0\n        \n        print('VaR: ' + str(VaR))\n        \n        return VaR\n        \n    # \u8ba1\u7b97\u80a1\u7968\u7ec4\u5408\u5728\u7ed9\u5b9a\u98ce\u9669\u635f\u5931\u7684\u60c5\u51b5\u4e0b\u6700\u5927\u6301\u4ed3\u91d1\u989d    \n    def fun_get_equity_value(bar_dict, stock_weight, risk_money, max_risk_money, alpha, position_ratio):\n        \n        # \u8ba1\u7b97\u7ec4\u5408\u6bcf\u65e5\u6536\u76ca\n        df_daily_returns = fun_get_portfolio_daily_return(bar_dict, stock_weight)\n        \n        # \u8ba1\u7b97\u7ec4\u5408ES\u503c\n        portfolio_ES = fun_get_portfolio_ES(df_daily_returns.copy(), alpha)\n        \n        # \u8ba1\u7b97\u7ec4\u5408VaR\u503c\n        portfolio_VaR = fun_get_portfolio_VaR(df_daily_returns.copy(), alpha)\n        \n        # \u7ec4\u5408ES\u548cVaR\u98ce\u9669\u5747\u4e3a0\n        if (portfolio_ES) == 0 and (portfolio_VaR) == 0:\n            equity_value = context.positions_value * position_ratio\n            print('\u7ec4\u5408\u98ce\u9669\u8bc4\u4f30\u4e3a0\uff0c \u8bf7\u68c0\u67e5\u6570\u636e\u3002')\n            return equity_value\n        \n        if portfolio_ES == 0:\n            print('ES = 0')\n            equity_value = risk_money \/ portfolio_VaR\n        \n        elif portfolio_VaR == 0:\n            print('VaR = 0')\n            equity_value = max_risk_money \/ portfolio_ES\n            \n        else:\n            equity_value = min(risk_money \/ portfolio_VaR, max_risk_money \/ portfolio_ES)\n    \n        \n        return equity_value\n        \n    \n    stock_num = len(stock_weight)\n    \n    risk_money = context.portfolio.portfolio_value * stock_num * context.risk_limit * position_ratio\n    max_risk_money = risk_money * 1.5\n    \n    # \u80a1\u7968\u7ec4\u5408\u5728\u7ed9\u5b9a\u98ce\u9669\u635f\u5931\u7684\u60c5\u51b5\u4e0b\uff0c\u6700\u5927\u6301\u4ed3\u91d1\u989d\n    stock_value = 0\n    if stock_weight:\n        stock_value = fun_get_equity_value(bar_dict, stock_weight, risk_money, max_risk_money, context.confidenceLevel, position_ratio)\n        \n    stock_ratio = 0    # \u80a1\u7968\u6301\u4ed3\u6bd4\u4f8b\n    bond_ratio = 0     # \u503a\u5238\u6301\u4ed3\u6bd4\u4f8b\n    \n    total_value = context.portfolio.portfolio_value * position_ratio    # \u6700\u5927\u6301\u4ed3\u91d1\u989d\uff08\u5305\u62ec\u80a1\u7968\u548c\u503a\u5238\uff09\n    \n    if stock_value &gt; total_value:\n        bond_ratio = 0\n        stock_ratio = 1.0 * position_ratio\n    else:\n        stock_ratio = (stock_value \/ total_value) * position_ratio\n        bond_ratio = (1 - (stock_value \/ total_value)) * position_ratio\n    \n    print('stock_value: ' + str(stock_value))\n    print('total_value: ' + str(total_value))\n    \n    trade_ratio = {}\n    for stock in stock_weight:\n        if stock in trade_ratio:\n            trade_ratio&#91;stock] += round((stock_weight&#91;stock] * stock_ratio), 3)\n        else:\n            trade_ratio&#91;stock] = round((stock_weight&#91;stock] * stock_ratio), 3)\n    \n    for stock in bond_weight:\n        if stock in trade_ratio:\n            trade_ratio&#91;stock] += round((bond_weight&#91;stock] * bond_ratio), 3)\n        else:\n            trade_ratio&#91;stock] = round((bond_weight&#91;stock] * bond_ratio), 3)\n    \n    return trade_ratio\n\n    \n#### 10.\u6839\u636e\u6307\u5b9a\u7684\u4ed3\u4f4d\u4e0b\u5355 #############################################################\ndef fun_do_trade(context, bar_dict, stock_position):\n    \n    for stock in list(context.portfolio.stock_account.positions.keys()):\n        if stock not in stock_position:\n            order_target_percent(stock, 0)\n        else:\n            order_target_percent(stock, stock_position&#91;stock])\n    \n    for stock in stock_position:\n        if stock not in list(context.portfolio.stock_account.positions.keys()):\n            order_target_percent(stock, stock_position&#91;stock])\n    \n    print('\u5f53\u524d\u6301\u4ed3: ')\n    print(list(context.portfolio.stock_account.positions.keys()))\n            \n    \n#### 11.\u4e2d\u4f4d\u6570\u53bb\u6781\u503c\u51fd\u6570 ################################################################\ndef winsorize(df, factor, n=20):\n    '''\n    df\u4e3abar_dictFrame\u6570\u636e\n    factor\u4e3a\u9700\u8981\u53bb\u6781\u503c\u7684\u5217\u540d\u79f0\n    n \u4e3a\u5224\u65ad\u6781\u503c\u4e0a\u4e0b\u8fb9\u754c\u7684\u5e38\u6570\n    '''\n    # \u63d0\u53d6\u8be5\u5217\u7684\u6570\u636e\n    ls_raw = np.array(df&#91;factor].values)\n    # \u6392\u5e8f\n    ls_raw.sort(axis = 0)\n    # \u83b7\u53d6\u4e2d\u4f4d\u6570\n    D_M = np.median(ls_raw)\n    \n    # \u8ba1\u7b97\u79bb\u5dee\u503c\n    ls_deviation = abs(ls_raw - D_M)\n    # \u6392\u5e8f\n    ls_deviation.sort(axis = 0)\n    # \u83b7\u53d6\u79bb\u5dee\u4e2d\u4f4d\u6570\n    D_MAD = np.median(ls_deviation)\n    \n    # \u5c06\u5927\u4e8e\u4e2d\u4f4d\u6570n\u500d\u79bb\u5dee\u4e2d\u4f4d\u6570\u7684\u503c\u8d4b\u4e3aNaN\n    df.loc&#91;df&#91;factor] &gt;= D_M + n * D_MAD, factor] = None\n    # \u5c06\u5c0f\u4e8e\u4e2d\u4f4d\u6570n\u500d\u79bb\u5dee\u4e2d\u4f4d\u6570\u7684\u503c\u8d4b\u4e3aNaN\n    df.loc&#91;df&#91;factor] &lt;= D_M - n * D_MAD, factor] = None\n    \n    return df<\/code><\/pre>\n\n\n\n<hr class=\"wp-block-separator has-alpha-channel-opacity\"\/>\n\n\n\n<p class=\"has-text-align-center has-cyan-bluish-gray-color has-text-color has-link-color wp-elements-bd402b7c146898dcf3d05749282e5860\"><strong>\u672c\u6587\u5185\u5bb9\u4ec5\u4ec5\u662f\u6280\u672f\u63a2\u8ba8\u548c\u5b66\u4e60\uff0c\u5e76\u4e0d\u6784\u6210\u4efb\u4f55\u6295\u8d44\u5efa\u8bae\u3002<\/strong><\/p>\n","protected":false},"excerpt":{"rendered":"<p>\u5199\u5728\u524d\u9762\u7684\u8bdd\uff1a\u5f7c\u5f97\u00b7\u6797\u5947\u662f\u4e00\u4f4d\u975e\u5e38\u6210\u529f\u7684\u6295\u8d44\u8005\u548c\u524d&#8230;<\/p>\n<div class=\"more-link-wrapper\"><a class=\"more-link\" href=\"https:\/\/laoyulaoyu.com\/index.php\/2024\/07\/02\/ai%e9%a1%be%e9%97%ae%e6%8a%95%e8%b5%84%e4%b9%8b%e9%ab%98%e7%ba%a7%e7%ad%96%e7%95%a5%e4%ba%8c%ef%bc%9a%e5%bd%bc%e5%be%97%e6%9e%97%e5%a5%87%e7%9a%84peg%ef%bc%88%e5%bb%ba%e8%ae%ae%e6%94%b6%e8%97%8f\/\">Continue reading<span class=\"screen-reader-text\">AI\u987e\u6295\u9ad8\u7ea7\u7b56\u7565\u4e4b\u4e8c\uff1a\u5f7c\u5f97\u6797\u5947\u7684PEG\uff08\u5efa\u8bae\u6536\u85cf\uff09<\/span><\/a><\/div>\n","protected":false},"author":1,"featured_media":0,"comment_status":"open","ping_status":"closed","sticky":false,"template":"","format":"standard","meta":{"footnotes":""},"categories":[2],"tags":[4],"class_list":["post-552","post","type-post","status-publish","format-standard","hentry","category-aiinvest","tag-ai","entry"],"_links":{"self":[{"href":"https:\/\/laoyulaoyu.com\/index.php\/wp-json\/wp\/v2\/posts\/552","targetHints":{"allow":["GET"]}}],"collection":[{"href":"https:\/\/laoyulaoyu.com\/index.php\/wp-json\/wp\/v2\/posts"}],"about":[{"href":"https:\/\/laoyulaoyu.com\/index.php\/wp-json\/wp\/v2\/types\/post"}],"author":[{"embeddable":true,"href":"https:\/\/laoyulaoyu.com\/index.php\/wp-json\/wp\/v2\/users\/1"}],"replies":[{"embeddable":true,"href":"https:\/\/laoyulaoyu.com\/index.php\/wp-json\/wp\/v2\/comments?post=552"}],"version-history":[{"count":0,"href":"https:\/\/laoyulaoyu.com\/index.php\/wp-json\/wp\/v2\/posts\/552\/revisions"}],"wp:attachment":[{"href":"https:\/\/laoyulaoyu.com\/index.php\/wp-json\/wp\/v2\/media?parent=552"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/laoyulaoyu.com\/index.php\/wp-json\/wp\/v2\/categories?post=552"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/laoyulaoyu.com\/index.php\/wp-json\/wp\/v2\/tags?post=552"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}