def markowitz_r_spe_bl(funddfr, P, eta, alpha, bounds):

    rf = Const.rf

    final_risk = 0
    final_return = 0
    final_ws = []
    final_ws = list(1.0 * np.ones(len(funddfr.columns)) / len(funddfr.columns))
    final_sharp = -np.inf
    final_codes = []

    codes = funddfr.columns
    return_rate = []
    for code in codes:
        return_rate.append(funddfr[code].values)

    if eta.size == 0:
        risks, returns, ws = fin.efficient_frontier_spe(return_rate, bounds)
    else:
        risks, returns, ws = fin.efficient_frontier_spe_bl(
            return_rate, P, eta, alpha, bounds)

    for j in range(0, len(risks)):
        if risks[j] == 0:
            continue
        sharp = (returns[j] - rf) / risks[j]
        if sharp > final_sharp:
            final_risk = risks[j]
            final_return = returns[j]
            final_ws = ws[j]
            final_sharp = sharp

    return final_risk, final_return, final_ws, final_sharp
Exemple #2
0
def draw(where=None,
         order=None,
         sort=None,
         draw_candle_stick=True,
         draw_roi=True,
         draw_share_holder=True,
         save_fig=False):
    global stock_index
    global stock_tuple_list

    if save_fig:
        delete_figure_files()

    stock_tuple_list = Financial.select(where, order, sort)

    index = -1
    for stock_tuple in stock_tuple_list:
        index = index + 1

        stock = Financial.Stock(stock_tuple)
        if stock is None:
            continue

        if not Financial.check_out(stock):
            continue

        print(stock.to_string())

        Financial.write_to_file(stock)

        draw_stock_data(stock,
                        draw_candle_stick=draw_candle_stick,
                        draw_roi=draw_roi,
                        draw_share_holder=draw_share_holder,
                        save_fig=save_fig)
def main():
    Init.initialize()
    Financial.download()
    Financial.analyze()

    Draw.draw(where="1", order="roi", sort="DESC", draw_candle_stick=True, draw_roi=False, draw_share_holder=False,
              save_fig=True)
    def markowitz_r_spe_bl(self, funddfr, P, eta, alpha, bounds):

        final_risk = 0
        final_return = 0
        final_ws = []
        final_ws = list(1.0 * np.ones(len(funddfr.columns)) / len(funddfr.columns))
        final_sharpe = -np.inf
        final_codes = []

        codes = funddfr.columns
        return_rate = []
        for code in codes:
            return_rate.append(funddfr[code].values)

        if eta.size == 0:
            risk, ret, ws = fin.efficient_frontier_spe(return_rate, bounds)
        else:
            risk, ret, ws = fin.efficient_frontier_spe_bl(return_rate, P, eta, alpha, bounds)

        for j in range(len(risk)):
            if risks[j] == 0:
                continue
            sharpe = (ret[j] - Const.rf) / risk[j]
            if sharpe > final_sharp:
                final_risk = risk[j]
                final_return = ret[j]
                final_ws = ws[j]
                final_sharpe = sharpe

        # final_res = np.append(final_ws, np.array([final_risk, final_ret, final_sharpe]))

        return final_ws
Exemple #5
0
def MainMenu():
    fin = False
    Menu()
    while fin==False:
      
        opcion = input(":> ")
        if opcion == "testconaz":
            AzureDatabaseSelect("Usuarios")
        elif opcion == "sysinfo":
            sys.SystemInformation()
        elif opcion == "finance":
            finance.Menu()
        elif opcion.startswith("echo"):
            echo(opcion)
        elif opcion == "help" or opcion == "/?":
            print("Comandos disponibles:\n  testconaz, sysinfo, finance, echo, scan, cls/clear, exit/99")
        elif opcion == "exit" or opcion == "99":
            fin = True
            exit()
        elif opcion == "scan":
            print("Llamada a scan aquí")
        elif input == "":
            print("No se ha encontrado ninguna orden")
        elif opcion == "cls" or opcion=="clear":
            if platform.system() == "Windows":
                os.system("cls")
            else:
                os.system("clear")
        else:
            print("Comando no reconocido. Ejecute help o /? para ver los comandos disponibles")
def fund_maxsemivariance(funddf):


    fundsemivariance = {}
    
    funddfr = funddf.pct_change().fillna(0.0)

    codes = funddfr.columns

    for code in codes:

        rs = []    
        for r in funddfr[code].values:
            if not isnan(r):
                rs.append(r)
        max_semivariance = 0

        for i in range(5, len(rs) + 1):
            semivariance = fin.semivariance(rs[0 : i])
            if semivariance > max_semivariance:
                    max_semivariance = semivariance

        fundsemivariance[code] = max_semivariance
    
    return fundsemivariance
Exemple #7
0
def fund_sharp_annual(funddf):

    fundsharp = {}

    funddfr = funddf.pct_change().fillna(0.0)

    codes = funddfr.columns

    for code in codes:
        rs = []
        for r in funddfr[code].values:
            rs.append(r)

        #if code == '000165':
        #print rs

        fundsharp[code] = fin.sharp_annual(rs, Const.rf)

    x = fundsharp
    sorted_x = sorted(x.iteritems(), key=lambda x: x[1], reverse=True)
    sorted_sharp = sorted_x

    result = []
    for i in range(0, len(sorted_sharp)):
        result.append(sorted_sharp[i])

    return result
def markowitz_r(funddfr, bounds):

    rf = const.rf

    final_risk = 0
    final_return = 0
    final_ws = []
    final_sharp = -10000000000000000000000000.0
    final_codes = []

    codes = funddfr.columns

    return_rate = []

    for code in codes:
        return_rate.append(funddfr[code].values)

    risks, returns, ws = fin.efficient_frontier(return_rate, bounds)

    for j in range(0, len(risks)):
        sharp = (returns[j] - rf) / risks[j]
        if sharp > final_sharp:
            final_risk = risks[j]
            final_return = returns[j]
            final_ws = ws[j]
            final_sharp = sharp

    return final_risk, final_return, final_ws, final_sharp
Exemple #9
0
def sortinofilter(funddf, rf, ratio):


    funddfr = funddf.pct_change().fillna(0.0)
    indexdfr = funddf.pct_change().fillna(0.0)

    sortino = {}
    cols = funddfr.columns
    for col in cols:
        p = []
        rs = funddfr[col].values
        for i in range(0, len(rs)):
            if isnan(rs[i]):
                continue
            else:
                p.append(rs[i])

        sortino[col] = fin.sortino(p, rf)


    x = sortino
    sorted_x = sorted(x.iteritems(), key=lambda x : x[1], reverse=True)
    sorted_sortino = sorted_x


    result = []
    for i in range(0, (int)(len(sorted_sortino) * ratio)):
        result.append(sorted_sortino[i])


    return result
def indexallocation(indexdf):

    indexdfr = indexdf.pct_change()

    indexdfr = indexdfr.fillna(0.0)

    codes = indexdfr.columns

    return_rate = []
    for code in codes:
        return_rate.append(indexdfr[code].values)

    #print return_rate
    risks, returns, ws = fin.efficient_frontier_index(return_rate)

    rf = const.rf

    final_risk = 0
    final_return = 0
    final_ws = []
    final_sharp = -1000

    for i in range(0, len(risks)):

        sharp = (returns[i] - rf) / risks[i]

        if sharp > final_sharp:

            final_risk = risks[i]
            final_return = returns[i]
            final_ws = ws[i]
            final_sharp = sharp

    return final_risk, final_return, final_ws, final_sharp
Exemple #11
0
def hmmeasure(funddf, indexdf):


    rf = const.rf
    
    funddfr = funddf.pct_change()
        indexdfr = indexdf.pct_change()

        hm = {}
        cols = funddfr.columns
        for col in cols:
                p = []
                m = []
                rs = funddfr[col].values
                #print col, rs
                indexrs = indexdfr.values
                for i in range(0, len(rs)):
                        if isnan(rs[i]):
                                continue
                        else:
                                p.append(rs[i])
                                m.append(indexrs[i][0])

                #print p
                hm[col] = fin.hm(p, m, rf)
Exemple #12
0
def fund_jensen(funddf, indexdf):

    rf = 0.03 / 52

    funddfr = funddf.pct_change().fillna(0.0)
    indexdfr = indexdf.pct_change().fillna(0.0)

    jensen = {}
    cols = funddfr.columns
    for col in cols:
        p = []
        m = []
        rs = funddfr[col].values
        #print col, rs
        indexrs = indexdfr.values
        for i in range(0, len(rs)):
            if isnan(rs[i]):
                continue
            else:
                p.append(rs[i])
                m.append(indexrs[i])

        jensen[col] = fin.jensen(p, m, rf)

    x = jensen
    sorted_x = sorted(x.iteritems(), key=lambda x: x[1], reverse=True)
    sorted_measure = sorted_x

    return sorted_measure
Exemple #13
0
def jensenfilter(funddf, indexdf, rf, ratio):

    funddfr = funddf.pct_change().fillna(0.0)
    indexdfr = indexdf.pct_change().fillna(0.0)


    jensen = {}
    cols = funddfr.columns
    for col in cols:
        p = []
        m = []
        rs = funddfr[col].values
        #print col, rs
        indexrs = indexdfr.values
        for i in range(0, len(rs)):
            if isnan(rs[i]):
                continue
            else:
                p.append(rs[i])
                m.append(indexrs[i])


        jensen[col] = fin.jensen(p, m, rf)


    x = jensen
    sorted_x = sorted(x.iteritems(), key=lambda x : x[1], reverse=True)
    sorted_jensen = sorted_x

    result = []
    for i in range(0, (int)(len(sorted_jensen) * ratio)):
        result.append(sorted_jensen[i])

    return result
Exemple #14
0
def fund_sharp(funddf):

    fundsharp = {}

    funddfr = funddf.pct_change().fillna(0.0)

    codes = funddfr.columns

    for code in codes:
        rs = []
        for r in funddfr[code].values:
            if not isnan(r):
                rs.append(r)

        fundsharp[code] = fin.sharp(rs, const.rf)

    x = fundsharp
    sorted_x = sorted(x.iteritems(), key=lambda x: x[1], reverse=True)
    sorted_sharp = sorted_x

    result = []
    for i in range(0, len(sorted_sharp)):
        result.append(sorted_sharp[i])

    return result
 def setFinancialInfo(self):
     # set global vars
     Financial._interval_ = Financial.Interval.allYears
     # crawl financial info
     financialObjs = Financial.MultiFinancialInfo(self.shareKey)
     financialObjs.crawl()
     # set financial info
     self.FinancialInfo = financialObjs.results
     return
    def calc_ev_ret(self, df_inc, ev_cov, P, eta, alpha):

        if eta.size == 0:
            ev_ret = df_inc.mean().values
        else:
            initialvalue = np.mean(df_inc.T.values, axis=1)
            ev_ret = fin.black_litterman(initialvalue, ev_cov, P, eta, alpha).reshape(-1)

        return ev_ret
def pool_by_corr_jensen(pool, day, lookback, limit):

    index = base_trade_dates.trade_date_lookback_index(end_date=day, lookback=lookback)

    start_date = index.min().strftime("%Y-%m-%d")
    end_date = day.strftime("%Y-%m-%d")


    ra_index_id = pool['ra_index_id']
    pool_id     = pool['id']
    df_nav_index = base_ra_index_nav.index_value(start_date, end_date, ra_index_id)
    #df_nav_index.index.name = str(df_nav_index.index.name)
    df_nav_index.columns = df_nav_index.columns.astype(str)
    if len(df_nav_index.index) == 0:
        return []
    pool_codes   = asset_ra_pool_sample.load(pool_id)['ra_fund_code'].values

    df_nav_fund  = base_ra_fund_nav.load_daily(start_date, end_date, codes = pool_codes)
    if len(df_nav_fund) == 0:
        return []

    df_nav_fund  = df_nav_fund.reindex(pd.date_range(df_nav_index.index[0], df_nav_index.index[-1]))
    df_nav_fund  = df_nav_fund.fillna(method = 'pad')
    df_nav_fund  = df_nav_fund.dropna(axis = 1)
    df_nav_fund  = df_nav_fund.loc[df_nav_index.index]
    fund_index_df = pd.concat([df_nav_index, df_nav_fund], axis = 1, join_axes = [df_nav_index.index])


    fund_index_corr_df = fund_index_df.pct_change().fillna(0.0).corr().fillna(0.0)

    corr = fund_index_corr_df[ra_index_id][1:]
    corr = corr.sort_values(ascending = False)

    code_jensen = {}
    for code in df_nav_fund.columns:
        jensen = fin.jensen(df_nav_fund[code].pct_change().fillna(0.0), df_nav_index[ra_index_id].pct_change().fillna(0.0) ,Const.rf)
        code_jensen.setdefault(code, jensen)


    if len(code_jensen) == 0:
        logger.info('No FUND')
        return None
    else:
        final_codes = []
        x = code_jensen
        sorted_x = sorted(iter(x.items()), key=lambda x : x[1], reverse=True)
        corr_threshold = np.percentile(corr.values, 80)
        corr_threshold = 0.7 if corr_threshold <= 0.7 else corr_threshold
        corr_threshold = 0.9 if corr_threshold >= 0.9 else corr_threshold
        for i in range(0, len(sorted_x)):
            code, jensen = sorted_x[i]
            if corr[code] >= corr_threshold:
                final_codes.append(code)

        final_codes = final_codes[0 : limit]
        return final_codes
def markowitz_bl_fixrisk(df_inc, P, eta, alpha, bound, target_risk):

    w0 = [1 / len(df_inc.columns)] * len(df_inc.columns)

    bnds = [(bound[i]['lower'], bound[i]['upper']) for i in range(len(bound))]
    ret = df_inc.mean().values
    vol = df_inc.cov().values

    initialvalue = np.mean(df_inc.T.values, axis=1)
    expected_return = fin.black_litterman(initialvalue, vol, P, eta, alpha)
    ret = expected_return.reshape(-1)

    asset_sum1_limit = 0.0
    sum1_limit_assets = []
    for asset in range(len(bound)):
        if bound[asset]['sum1'] != 0.0:
            sum1_limit_assets.append(asset)
            asset_sum1_limit = bound[asset]['sum1']

    cons = [
        {
            'type': 'eq',
            'fun': lambda x: np.sum(x) - 1.0
        },
        {
            'type': 'ineq',
            'fun': lambda x: target_risk - np.sqrt(np.dot(x, np.dot(vol, x)))
        },
    ]
    if asset_sum1_limit > 0.0:
        cons.append({
            'type':
            'ineq',
            'fun':
            lambda x: asset_sum1_limit - np.sum(x[sum1_limit_assets])
        })
    cons = tuple(cons)

    res = scipy.optimize.minimize(risk_budget_objective,
                                  w0,
                                  args=[ret, vol, target_risk],
                                  method='SLSQP',
                                  bounds=bnds,
                                  constraints=cons,
                                  options={
                                      'disp': False,
                                      'eps': 1e-3
                                  })

    final_risk = np.sqrt(np.dot(res.x, np.dot(vol, res.x)))
    final_return = np.dot(res.x, ret)
    final_ws = res.x
    final_sharp = (final_return - Const.rf) / final_risk

    return final_risk, final_return, final_ws, final_sharp
def strategicallocation(delta, weq, V, tau, P, Q):

    P = np.array(P)
    Q = np.array(Q)

    tauV = tau * V

    Omega = np.dot(np.dot(P, tauV), P.T) * np.eye(Q.shape[0])

    res = fin.black_litterman(delta, weq, V, tau, P, Q, Omega)

    return re
Exemple #20
0
def ppwfilter(funddf, indexdf, rf, ratio):


    length = len(funddf.index)

    '''
    tran_index = []
    for i in range(0, length):
        if i % 4 == 0:
            tran_index.append(i)

    funddf = funddf.iloc[tran_index]
    funddfr = funddf.pct_change()

    indexdf = indexdf.iloc[tran_index]
    indexdfr = indexdf.pct_change()
    '''


    funddfr = funddf.pct_change().fillna(0.0)
    indexdfr = indexdf.pct_change().fillna(0.0)

    ppw = {}
    cols = funddfr.columns
    for col in cols:
        p = []
        m = []
        rs = funddfr[col].values
        indexrs = indexdfr.values
        for i in range(0, len(rs)):
            if isnan(rs[i]):
                continue
            else:
                p.append(rs[i] - rf)
                m.append(indexrs[i] - rf)


        ppw[col] = fin.ppw(p, m)


    x = ppw
    sorted_x = sorted(x.iteritems(), key=lambda x : x[1], reverse=True)
    sorted_ppw = sorted_x


    result = []
    for i in range(0, (int)(len(sorted_ppw) * ratio)):
        result.append(sorted_ppw[i])

    #print result
    return result
Exemple #21
0
def fund_semivariance(funddf):

    fundsemivariance = {}

    funddfr = funddf.pct_change().fillna(0.0)

    codes = funddfr.columns

    for code in codes:
        rs = []
        for r in funddfr[code].values:
            if not isnan(r):
                rs.append(r)

        fundsemivariance[code] = fin.semivariance(rs)

    return fundsemivariance
def markowitz(funddf, bounds, d):

    rf = const.rf
    funddfr = funddf.pct_change()
    funddfr = funddfr.fillna(0.0)

    final_risk = 0
    final_return = 0
    final_ws = []
    final_sharp = -10000000000000000000000000.0
    final_codes = []

    codes = funddfr.columns

    return_rate = []

    for code in codes:
        return_rate.append(funddfr[code].values)

    risks, returns, ws = fin.efficient_frontier(return_rate, bounds)

    for j in range(0, len(risks)):
        sharp = (returns[j] - rf) / risks[j]
        if sharp > final_sharp:
            final_risk = risks[j]
            final_return = returns[j]
            final_ws = ws[j]
            final_sharp = sharp

    f_str = '%s, %f, %f, %f, %f, %f, %f, %f, %f, %f, %f, %f, %f, %f, %f, %f, %f, %f\n'
    f = open('./tmp/ef_' + d + '.csv', 'w')
    f.write(
        'date, risk, return, largecap, smallcap, rise, oscillation, decline ,growth ,value, ratebond, creditbond, convertiblebond, money1, money2, SP500.SPI, SPGSGCTR.SPI, HSCI.HI\n'
    )
    #for j in range(0, len(risks)):
    #    f.write(f_str % (d,risks[j], returns[j], ws[j][0], ws[j][1], ws[j][2], ws[j][3], ws[j][4], ws[j][5], ws[j][6], ws[j][7], ws[j][8], ws[j][9], ws[j][10], ws[j][11], ws[j][12], ws[j][13], ws[j][14] ))

    f.flush()
    f.close()

    return final_risk, final_return, final_ws, final_sharp
def ppwmeasure(funddf, indexdf, rf):


    length = len(funddf.index)

    '''
    tran_index = []
    for i in range(0, length):
        if i % 4 == 0:
            tran_index.append(i)

    funddf = funddf.iloc[tran_index]
    funddfr = funddf.pct_change()

    indexdf = indexdf.iloc[tran_index]
    indexdfr = indexdf.pct_change()
    '''

    funddfr = funddf.pct_change().fillna(0.0)
    indexdfr = indexdf.pct_change().fillna(0.0)


    ppw = {}
    cols = funddfr.columns
    for col in cols:
        p = []
        m = []
        rs = funddfr[col].values
        indexrs = indexdfr.values
        for i in range(0, len(rs)):
            if isnan(rs[i]):
                continue
            else:
                p.append(rs[i] - rf)
                m.append(indexrs[i] - rf)
        #print p
        #print m

        ppw[col] = fin.ppw(p, m)

    return ppw
def sortinomeasure(funddf, rf):

    funddfr = funddf.pct_change().fillna(0.0)
    indexdfr = funddf.pct_change().fillna(0.0)

    sortino = {}
    cols = funddfr.columns
    for col in cols:
        p = []
        rs = funddfr[col].values
        for i in range(0, len(rs)):
            if isnan(rs[i]):
                continue
            else:
                p.append(rs[i])
        sortino_value = fin.sortino(p, rf)
        #if np.isinf(sortino_value):
        #    continue
        sortino[col] = sortino_value

    return sortino
def technicallocation(funddf, fund_rank):

    rf = const.rf

    funddfr = funddf.pct_change()

    funddfr = funddfr.fillna(0.0)

    final_risk = 0
    final_return = 0
    final_ws = []
    final_sharp = -10000000000000000.0
    final_codes = []

    for i in range(2, min(11, len(fund_rank))):

        codes = fund_rank[0:i]
        dfr = funddfr[codes]

        #dfr.fillna(0.0)

        return_rate = []
        for code in codes:
            return_rate.append(dfr[code].values)

        #print return_rate
        risks, returns, ws = fin.efficient_frontier_fund(return_rate)

        for j in range(0, len(risks)):

            sharp = (returns[j] - rf) / risks[j]
            if sharp > final_sharp:

                final_risk = risks[i]
                final_return = returns[i]
                final_ws = ws[i]
                final_sharp = sharp

    return final_risk, final_return, final_ws, final_sharp
def jensenmeasure(funddf, indexdf, rf):

    funddfr = funddf.pct_change().fillna(0.0)
    indexdfr = indexdf.pct_change().fillna(0.0)

    jensen = {}
    cols = funddfr.columns
    for col in cols:
        p = []
        m = []
        rs = funddfr[col].values
        #print col, rs
        indexrs = indexdfr.values
        for i in range(0, len(rs)):
            if isnan(rs[i]):
                continue
            else:
                p.append(rs[i])
                m.append(indexrs[i])

        jensen[col] = fin.jensen(p, m, rf)

    return jensen
indexrs = []
for i in range(1, len(indexvs)):
    indexrs.append(indexvs[i] / indexvs[i-1] - 1)
    


rf = 0.025 / 52
jensen = {}
sortino = {}
for code in fundrs.keys():
    rs = fundrs[code]

    if len(rs) < len(indexrs):
        continue

    jensen[code] = fin.jensen(rs, indexrs, rf)
    sortino[code] = fin.sortino(rs, rf)
    #print jensen[codes[i]]
    #print sortino[codes[i]]

#print jensen
#print sortino
#print dates


x = jensen
sorted_x = sorted(x.iteritems(), key=lambda x : x[1], reverse=True) 
sorted_jensen = sorted_x


x = sortino
Exemple #28
0
def draw_stock_data(stock,
                    draw_candle_stick=True,
                    draw_roi=True,
                    draw_share_holder=True,
                    period=Constants.MONTH,
                    save_fig=False):
    # read and reformat data

    stock_data_dict = pandas.read_csv(
        Financial.get_stock_data_file_name(stock),
        parse_dates=True,
        index_col=0)
    stock_data_dict.reset_index(inplace=True)
    stock_data_dict['date'] = mdates.date2num(stock_data_dict['date'])

    # setup moving average models

    x = stock_data_dict['date']
    roi = stock_data_dict['roi']

    #
    # EMA_1_span = 7
    # EMA_1 = stock_data['Close'].ewm(span=EMA_1_span, min_periods=EMA_1_span).mean()
    #
    # EMA_2_span = 30
    # EMA_2 = stock_data['Close'].ewm(span=EMA_2_span, min_periods=EMA_2_span).mean()
    #
    # SMA_2_span = EMA_2_span
    # SMA_2 = stock_data['Close'].rolling(window=SMA_2_span, center=False).mean()
    #
    # MACD = EMA_1 - EMA_2

    financial_data_file_name = Financial.get_financial_data_file_name(stock)
    if not os.path.exists(financial_data_file_name):
        print(financial_data_file_name + " not exist, return")
        return

    financial_data_dict = pandas.read_csv(
        Financial.get_financial_data_file_name(stock),
        parse_dates=True,
        index_col=0)
    financial_data_dict.reset_index(inplace=True)
    financial_data_dict['date'] = mdates.date2num(financial_data_dict['date'])

    x1 = financial_data_dict['date']
    roe = financial_data_dict['roe']
    book_value_per_share = financial_data_dict['book_value_per_share']
    net_profit_per_share = financial_data_dict['net_profit_per_share'] * 10
    cash_flow_per_share = financial_data_dict['cash_flow_per_share']

    total_current_assets = financial_data_dict['total_current_assets']
    total_assets = financial_data_dict['total_assets']
    total_long_term_liabilities = financial_data_dict[
        'total_long_term_liabilities']
    main_business_income = financial_data_dict['main_business_income']
    financial_expenses = financial_data_dict['financial_expenses']
    net_profit = financial_data_dict['net_profit']
    # roe = financial_data_dict['roe']

    share_bonus_file_name = Financial.get_share_bonus_file_name(stock)
    if not os.path.exists(share_bonus_file_name):
        print(share_bonus_file_name + " not exist, return")
        return

    share_bonus_dict = pandas.read_csv(share_bonus_file_name,
                                       parse_dates=True,
                                       index_col=0)
    share_bonus_dict.reset_index(inplace=True)
    share_bonus_dict['date'] = mdates.date2num(share_bonus_dict['date'])

    x2 = share_bonus_dict['date']
    dividend = share_bonus_dict['dividend']

    if draw_share_holder:
        share_holder_file_name = Financial.get_share_holder_file_name(stock)
        if not os.path.exists(share_holder_file_name):
            print(share_holder_file_name + " not exist, return")
            return

        share_holder_dict = pandas.read_csv(share_holder_file_name,
                                            parse_dates=True,
                                            index_col=0)
        share_holder_dict.reset_index(inplace=True)
        share_holder_dict['date'] = mdates.date2num(share_holder_dict['date'])

        x3 = share_holder_dict['date']
        holder_number = share_holder_dict['number']
        share_ratio = share_holder_dict['ratio']

    # plot

    fig, (ax1, ax3) = plt.subplots(2, sharex=True, figsize=(10, 12))

    # plot candlestick, SAM, EMA in subplot_1
    if draw_candle_stick:
        candlestick_ohlc(ax1,
                         stock_data_dict.values,
                         width=0.5,
                         colorup='r',
                         colordown='g')
        # p1 = ax.plot(x, EMA_1, label='EMA(' + str(EMA_1_span) + ')')
        # p2 = ax.plot(x, EMA_2, label='EMA(' + str(EMA_2_span) + ')')
        # p3 = ax.plot(x, SMA_2, label='SMA(' + str(SMA_2_span) + ')')

    ax1.step(x1, roe, label='Roe')
    ax1.step(x1, cash_flow_per_share, label='CashFlowPerShare')
    ax1.step(x1, net_profit_per_share, label='NetProfitPerShare')
    ax1.step(x1, book_value_per_share, label='BookValuePerShare')
    ax1.step(x2, dividend, label='Dividend')

    if draw_roi:
        ax1.step(x, roi, label='ROI')

    if draw_share_holder:
        ax1.step(x3, holder_number, label='HolderNumber')
        ax1.step(x3, share_ratio, label='ShareRatio')

    ax1.xaxis.set_major_formatter(mdates.DateFormatter('%Y-%m-%d'))
    ax1.xaxis.set_major_locator(mdates.MonthLocator([1, 4, 7, 10]))
    ax1.xaxis.set_major_formatter(mdates.DateFormatter("%b '%y"))
    ax1.set_ylabel('Price', fontsize=16)
    ax1.legend()

    # plot volume in subplot_2
    # ax2.bar(x, stock_data_dict['volume'])
    # ax2.set_ylabel('volume', fontsize=16)

    # plot MACD in subplot_3
    # ax3.plot(x, MACD, label='MACD (' + 'EMA(' + str(EMA_1_span) + '), ' + 'EMA(' + str(EMA_2_span) + '))')

    # ax3.plot(x1, total_current_assets, label='TotalCurrentAssets')
    # ax3.plot(x1, total_assets, label='TotalAssets')
    ax3.plot(x1, total_long_term_liabilities, label='TotalLongTermLiabilities')
    ax3.plot(x1, main_business_income, label='MainBusinessIncome')
    ax3.plot(x1, financial_expenses, label='FinancialExpenses')
    ax3.plot(x1, net_profit, label='NetProfit')
    # ax3.plot(x1, roe, label='ROE')

    ax3.axhline(0, color='gray', linestyle='--')
    ax3.set_xlabel('date')
    ax3.set_ylabel('MACD', fontsize=16)
    ax3.legend()

    # # Pandas 无法显示中文问题 解决方案##
    plt.rcParams['font.sans-serif'] = ['SimHei']  # 用来正常显示中文标签
    plt.rcParams['axes.unicode_minus'] = False  # 用来正常显示负号

    plt.title(stock.to_string())

    if save_fig:
        fig.savefig(Constants.DATA_FIGURE_PATH + stock.get_name())
        plt.close(fig)
    else:
        plt.show()
return_rate = []
dapan = df['dapan'].values
xiaopan = df['xiaopan'].values

dapanrs = []
xiaopanrs = []
for i in range(1, len(dapan)):
    dapanrs.append(dapan[i] / dapan[i - 1] - 1)
for i in range(1, len(xiaopan)):
    xiaopanrs.append(xiaopan[i] / xiaopan[i - 1] - 1)

return_rate.append(dapanrs)
return_rate.append(xiaopanrs)

risks, returns, portfolios = fin.efficient_frontier(return_rate)

rf = 0.025 / 52
n = 0
sharp = (returns[0] - rf) / risks[0]
for i in range(0, len(returns)):
    s = (returns[i] - rf) / risks[i]
    if s > sharp:
        sharp = s
        n = i

###########################################################################

#print 'sharp : ', sharp, 'return : ', returns[n], 'risk : ', risks[n], 'portfolio : ', portfolios[n]
#print 'annual return : ', returns[n] * 52
def asset_allocation(start_date, end_date, largecap_fund, smallcap_fund, P, Q):
    #########################################################################

    delta = 2.5
    tau = 0.05

    ps = []
    for p in P:
        ps.append(np.array(p))

    P = np.array(ps)

    qs = []
    for q in Q:
        qs.append(np.array(q))

    Q = np.array(qs)

    indexdf = data.index_value(start_date, end_date,
                               [const.largecap_code, const.smallcap_code])

    indexdfr = indexdf.pct_change().fillna(0.0)

    indexrs = []
    for code in indexdfr.columns:
        indexrs.append(indexdfr[code].values)

    #print indexdfr

    sigma = np.cov(indexrs)

    #print type(sigma)
    #print sigma
    #print np.cov(indexrs)
    #print indexdfr

    weq = np.array([0.5, 0.5])
    tauV = tau * sigma
    Omega = np.dot(np.dot(P, tauV), P.T) * np.eye(Q.shape[0])
    er, ws, lmbda = fin.black_litterman(delta, weq, sigma, tau, P, Q, Omega)

    sum = 0
    for w in ws:
        sum = sum + w
    for i in range(0, len(ws)):
        ws[i] = 1.0 * ws[i] / sum

    #print er
    indexws = ws
    #print indexws
    #largecap_fund, smallcap_fund = largesmallcapfunds(fund_tags)

    #print largecap_fund
    #risk, returns, ws, sharp = markowitz(
    #print smallcap_fund

    funddf = data.fund_value(start_date, end_date)

    bounds = boundlimit(len(largecap_fund))

    risk, returns, ws, sharp = markowitz(funddf[largecap_fund], bounds)

    largecap_fund_w = {}
    for i in range(0, len(largecap_fund)):
        code = largecap_fund[i]
        largecap_fund_w[code] = ws[i] * indexws[0]

    bounds = boundlimit(len(smallcap_fund))
    risk, returns, ws, sharp = markowitz(funddf[smallcap_fund], bounds)

    smallcap_fund_w = {}
    for i in range(0, len(smallcap_fund)):
        code = smallcap_fund[i]
        smallcap_fund_w[code] = ws[i] * indexws[1]
    '''    
    #平均分配            
    largecap_fund_w = {}
    for code in largecap_fund:
        largecap_fund_w[code] = 1.0 / len(largecap_fund) * indexws[0]

    
    smallcap_fund_w = {}
    for code in smallcap_fund:
        smallcap_fund_w[code] = 1.0 / len(smallcap_fund) * indexws[1]
    '''

    fundws = {}
    for code in largecap_fund:
        w = fundws.setdefault(code, 0)
        fundws[code] = w + largecap_fund_w[code]
    for code in smallcap_fund:
        w = fundws.setdefault(code, 0)
        fundws[code] = w + smallcap_fund_w[code]

#######################################################################

#print largecap
#print smallcap
#print risefitness
#print declinefitness
#print oscillafitness
#print growthfitness
#print valuefitness
#print

    fund_codes = []
    ws = []
    for k, v in fundws.items():
        fund_codes.append(k)
        ws.append(v)

    #for code in largecap:

    return fund_codes, ws