def stock(ctx, datadir, startdate, enddate, label_asset):
    '''run constant risk model
    '''
    Const.datadir = datadir

    if not enddate:
        yesterday = (datetime.now() - timedelta(days=1))
        enddate = yesterday.strftime("%Y-%m-%d")

    category_stock = [
        'date', 'largecap', 'smallcap', 'rise', 'oscillation', 'decline',
        'growth', 'value'
    ]

    df_pool = pd.read_csv(datapath('fund_pool.csv'),
                          index_col=['category', 'date'],
                          parse_dates=['date'],
                          dtype={'code': str},
                          usecols=['category', 'date', 'code'])
    df = df_pool.loc[category_stock]
    df.index = df.index.droplevel(0)

    df_result = df.groupby(
        level=0, group_keys=False).apply(lambda x: x.drop_duplicates('code'))
    df_result['ratio'] = 1.0
    df_result['ratio'] = df_result['ratio'].groupby(
        level=0).apply(lambda x: np.round(x / len(x), 4))
    df_result.reset_index(inplace=True)
    df_result = DFUtil.pad_sum_to_one(df_result, df_result['date'], 'ratio')
    df_result['risk'] = 1.0
    df_result.set_index(['risk', 'date', 'code'], inplace=True)
    df_result.to_csv(datapath('position-pool-stock.csv'), header=False)

    print df_result['ratio'].groupby(level=(0, 1)).sum()
Exemple #2
0
def test(ctx, datadir, startdate, enddate, label_asset, reshape, markowitz):
    '''run risk management using simple strategy
    '''
    Const.datadir = datadir

    if not enddate:
        yesterday = (datetime.now() - timedelta(days=1))
        enddate = yesterday.strftime("%Y-%m-%d")

    df_nav = pd.read_csv(datapath('../csvdata/000300_nav_2012.csv'),
                         index_col=['date'],
                         parse_dates=['date'])
    #df_nav = pd.read_csv(datapath('dd.csv'),  index_col=['td_date'], parse_dates=['td_date'])

    #df_pos = pd.read_csv(datapath('port_weight.csv'),  index_col=['date'], parse_dates=['date'])

    df_timing = pd.read_csv(datapath('hs_gftd.csv'),
                            index_col=['date'],
                            parse_dates=['date'],
                            usecols=['date', 'trade_types'])
    #df_timing = pd.read_csv(datapath('../csvdata/000300_gftd_result.csv'),  index_col=['date'], parse_dates=['date'], usecols=['date', 'trade_types'])
    df_timing = df_timing.rename(columns={'trade_types': 'sh000300'})

    df = pd.DataFrame({
        'nav':
        df_nav.iloc[:, 0],
        'timing':
        df_timing['sh000300'].reindex(df_nav.index, method='pad')
    })

    risk_mgr = RiskManagement.RiskManagement()
    df_result = risk_mgr.perform('sh000300', df)

    df_result.to_csv(datapath('riskmgr_result.csv'))
def highlowriskasset(lookback, adjust_period):

    #highriskassetdf  = allocationdata.equal_risk_asset_df
    highriskassetdf = pd.read_csv(datapath('equalriskasset.csv'),
                                  index_col='date',
                                  parse_dates=['date'])
    highriskassetdfr = highriskassetdf.pct_change().fillna(0.0)

    lowassetlabel = ['ratebond', 'creditbond']
    #lowriskassetdfr  = allocationdata.label_asset_df
    lowriskassetdfr = pd.read_csv(datapath('labelasset.csv'),
                                  index_col='date',
                                  parse_dates=['date'])
    lowriskassetdfr = lowriskassetdfr[lowassetlabel]
    lowriskassetdfr = lowriskassetdfr.loc[highriskassetdfr.index]

    his_week = lookback  # allocationdata.allocation_lookback
    interval = adjust_period  # allocationdata.allocation_adjust_period

    highdf = highriskasset(highriskassetdfr, his_week, interval)
    lowdf = lowriskasset(lowriskassetdfr, his_week, interval)

    df = pd.concat([highdf, lowdf], axis=1, join_axes=[highdf.index])
    dfr = df.pct_change().fillna(0.0)

    print dfr

    highlowdf = highlowallocation(dfr)
def portfolio_detail():
    columns = ('risk', 'date', 'category', 'fund', 'ratio')
    #
    # 中类资产比例和对应基金
    #
    df = portfolio_category()
    print "portfolio_category"

    data = []
    for key, row in df.iterrows():
        # codes2 = filter_by_status(date, codes)
        (risk, date, category) = key
        ratio = row['ratio']
        funds = row['xfund'].split(':')
        data.extend([(risk, date, category, fund, ratio)
                     for (fund, ratio) in split_category_ratio(ratio, funds)])

    df_result = pd.DataFrame(data, columns=columns)
    print "category to fund finish"

    #
    # 过滤掉过小的份额配置
    #
    df_result = df_result[df_result['ratio'] >= 0.009999]
    print "fileout small"
    df_result.to_csv(datapath('tmp-result.csv'), index=False)

    #
    # 过滤掉与上期换手率小于3%
    #
    df_result = DFUtil.filter_by_turnover_rate(df_result, 0.03)
    print "filter_by_turnover_rate"
    df_result.to_csv(datapath('tmp-result2.csv'), index=False)

    #
    # 某天持仓补足100%
    #
    df_result = DFUtil.pad_sum_to_one(df_result,
                                      [df_result['risk'], df_result['date']])
    print "pad_sum_to_one"

    #
    # 计算资产组合净值
    #
    df_result.to_csv(datapath('position-detail.csv'), index=False)
    df_result.replace({
        'category': categories_types()
    }).to_csv(datapath('position-d.csv'), index=False)

    return df_result
def investor_risk_maxdrawdown(ctx, optlist, optstartid, optendid, optmonth,
                              output):
    '''run constant risk model
    '''

    db = database.connection('asset')

    sql = "SELECT is_investor_id, DATE_FORMAT(is_date, '%%Y-%%m') AS is_month,SUM(is_return) as is_return FROM `is_investor_holding` WHERE 1 "
    if optstartid is not None:
        sql += " AND is_investor_id >= '%s' " % optstartid
    if optendid is not None:
        sql += " AND is_investor_id <= '%s' " % optendid
    sql += "GROUP BY is_investor_id, is_month"

    df_result = pd.read_sql(sql, db, index_col=['is_investor_id', 'is_month'])
    df_result = df_result.unstack(1)
    df_result.columns = df_result.columns.droplevel(0)

    if output is not None:
        path = output
    else:
        path = datapath('export-nav.csv')

    df_result.to_csv(path)

    print("export nav to file %s" % (path))
Exemple #6
0
def bond_establish_data():

    indicator_df = pd.read_csv(os.path.normpath(
        datapath('../csvdata/bond_establish_date.csv')),
                               index_col='code',
                               parse_dates=['date'])
    return indicator_df
Exemple #7
0
def fund_position(start_date, end_date):

    positiondf = pd.read_csv(os.path.normpath(
        datapath('../csvdata/fund_position2.csv')),
                             index_col='date',
                             parse_dates=['date'])
    positiondf = positiondf[
        positiondf.index <= datetime.strptime(end_date, '%Y-%m-%d')]
    positiondf = positiondf[
        positiondf.index >= datetime.strptime(start_date, '%Y-%m-%d')]

    codes = []

    for col in positiondf.columns:
        vs = positiondf[col].values
        has = True
        for v in vs:
            try:
                if isnan(v):
                    has = False
            except:
                has = False

        if has:
            codes.append(col)

    positiondf = positiondf[codes]
    return positiondf
Exemple #8
0
def asset_alloc_low_risk_per_day(day, lookback, df_inc=None, columns=None):
    '''perform asset allocation of low risk asset for single day
    '''
    if columns and 'date' not in columns:
        columns.insert(0, 'date')

    # 加载时间轴数据
    index = DBData.trade_date_lookback_index(end_date=day, lookback=lookback)

    # 加载数据
    if df_inc is None:
        df_nav = pd.read_csv(datapath('labelasset.csv'),
                             index_col='date',
                             parse_dates=['date'],
                             usecols=columns)
        df_inc = df_nav.pct_change().fillna(0.0)
    #
    # 根据时间轴进行重采样
    #
    df_inc = df_inc.reindex(index, fill_value=0.0)

    #
    # 基于马克维茨进行资产配置
    #
    risk, returns, ws, sharpe = PF.markowitz_r(df_inc, None)

    sr_result = pd.concat([
        pd.Series(ws, index=df_inc.columns),
        pd.Series((sharpe, risk, returns), index=['sharpe', 'risk', 'return'])
    ])

    return sr_result
Exemple #9
0
def fund_index_data(start_date, end_date, index_code):

    #取开始时间和结束时间的数据
    df = pd.read_csv(os.path.normpath(datapath('../csvdata/fund_value.csv')),
                     index_col='date',
                     parse_dates=['date'])
    df = df[df.index <= datetime.strptime(end_date, '%Y-%m-%d')]
    df = df[df.index >= datetime.strptime(start_date, '%Y-%m-%d')]

    #取基金成立时间指标
    indicator_df = pd.read_csv(os.path.normpath(
        datapath('../csvdata/fund_establish_date.csv')),
                               index_col='code',
                               parse_dates=['date'])
    establish_date_code = set()
    for code in indicator_df.index:
        date = indicator_df['establish_date'][code]
        if date <= datetime.strptime(start_date, '%Y-%m-%d'):
            establish_date_code.add(code)

    cols = df.columns
    fund_cols = []
    for col in cols:

        #有20%的净值是nan,则过滤掉该基金
        vs = df[col]
        n = 0
        for v in vs:
            if isnan(v):
                n = n + 1
        if n > 0.2 * len(vs):
            continue

        if col.find('OF') >= 0 and col in establish_date_code:
            fund_cols.append(col)

    fund_df = df[fund_cols]
    #fund_df_r = df_r[fund_cols]

    index_df = df[index_code]
    #index_df_r = df_r[index_col]

    #print fund_df_r
    #print index_df_r

    return fund_df, index_df
Exemple #10
0
def stockavg(ctx, datadir, optinput, optoutput):
    '''generate final portfolio using simple average strategy (no cost)
    '''
    Const.datadir = datadir
    #
    # 生成配置数据
    #
    output = None
    if optinput is None:
        if os.path.isfile(datapath('riskmgr_position.csv')):
            optinput = datapath('riskmgr_position.csv')
            output = datapath('position-r.csv')
        elif os.path.isfile(datapath('portfolio_position.csv')):
            optinput = datapath('portfolio_position.csv')
            output = datapath('position-v.csv')
        else:
            click.echo(click.style("error: mising position file!",
                                   fg="yellow"))
            return -1

    if optoutput is None:
        if output is None:
            optoutput = datapath('position-v.csv')
        else:
            optoutput = output

    print "convert portfilio position  %s to final position %s" % (optinput,
                                                                   optoutput)
    GeneralizationPosition.portfolio_avg_simple(optinput, optoutput)
Exemple #11
0
def stock_fund_code():

    funddf = pd.read_csv(os.path.normpath(
        datapath('../csvdata/stock_fund_code.csv')),
                         index_col='code')
    codes = []
    for code in funddf.index:
        codes.append(code)
    return codes
Exemple #12
0
def trade(ctx, datadir, output):
    '''generate final portfolio with optimized strategy (cost consider in).  
    '''
    Const.datadir = datadir
    if output is None:
        output = datapath('position-z.csv')
    with (open(output, 'w') if output != '-' else os.fdopen(
            os.dup(sys.stdout.fileno()), 'w')) as out:
        GeneralizationPosition.portfolio_trade(out)
Exemple #13
0
def label_asset_nav(start_date, end_date):
    df_pool = pd.read_csv(datapath('fund_pool.csv'),
                          index_col=['category', 'date', 'code'],
                          parse_dates=['date'])
    df_pool['ratio'] = 1.0

    data = {}
    with click.progressbar(length=len(df_pool.index.levels[0]),
                           label='label nav') as bar:
        for category in df_pool.index.levels[0]:
            #
            # 生成大类的基金仓位配置矩阵
            #
            df_pool_category = df_pool.loc[category, ['ratio']]
            df_position = df_pool_category.groupby(
                level=0).apply(lambda x: x / len(x))
            df_position = df_position.unstack(fill_value=0.0)
            df_position.columns = df_position.columns.droplevel(0)
            #
            # 加载各个基金的日净值数据
            #
            if category in ['GLNC', 'HSCI.HI', 'SP500.SPI']:
                df_nav_fund = DBData.db_index_value_daily(
                    start_date, end_date, df_position.columns)
            else:
                df_nav_fund = DBData.db_fund_value_daily(
                    start_date, end_date, codes=df_position.columns)
            df_inc_fund = df_nav_fund.pct_change().fillna(0.0)
            #
            # 计算组合净值增长率
            #
            df_nav_portfolio = DFUtil.portfolio_nav(df_inc_fund,
                                                    df_position,
                                                    result_col='portfolio')
            df_nav_portfolio.to_csv(
                datapath('category_nav_' + category + '.csv'))

            data[category] = df_nav_portfolio['portfolio']
            bar.update(1)

    df_result = pd.DataFrame(data)
    #df_result.to_csv(datapath('labelasset.csv'))

    return df_result
Exemple #14
0
def money_value(start_date, end_date):

    #取开始时间和结束时间的数据
    df = pd.read_csv(os.path.normpath(datapath('../csvdata/money_value.csv')),
                     index_col=0,
                     parse_dates=['date'])
    df = df[df.index <= datetime.strptime(end_date, '%Y-%m-%d')]
    df = df[df.index >= datetime.strptime(start_date, '%Y-%m-%d')]

    #print df
    #取基金成立时间指标
    indicator_df = pd.read_csv(os.path.normpath(
        datapath('../csvdata/money_establish_date.csv')),
                               index_col='code',
                               parse_dates=['date'])
    indicator_df = indicator_df.dropna()
    establish_date_code = set()
    for code in indicator_df.index:
        date = indicator_df['establish_date'][code]
        if datetime.strptime(date, '%Y-%m-%d') <= datetime.strptime(
                start_date, '%Y-%m-%d'):
            establish_date_code.add(code)

    cols = df.columns
    fund_cols = []
    for col in cols:

        #有20%的净值是nan,则过滤掉该基金
        vs = df[col].values
        n = 0
        for v in vs:
            if isnan(v):
                n = n + 1
        if n > 0.2 * len(vs):
            continue

        if col.find('OF') >= 0 and col in establish_date_code:
            fund_cols.append(col)

    fund_cols = list(set(fund_cols))

    fund_df = df[fund_cols]

    return fund_df
Exemple #15
0
def label_asset_tag(label_index, lookback=52):
    '''perform fund tagging along label_index.
    '''

    # label_index = pd.DatetimeIndex(['2012-10-26', '2015-09-30', '2016-04-08', '2016-10-14'])

    #
    # 计算每个调仓点的最新配置
    #
    data_stock = {}
    data_bond = {}
    data_money = {}
    data_other = {}
    with click.progressbar(length=len(label_index),
                           label='label asset') as bar:
        for day in label_index:
            data_stock[day] = label_asset_stock_per_day(
                day, lookback, Const.fund_num)
            data_bond[day] = label_asset_bond_per_day(day, lookback,
                                                      Const.fund_num)
            data_money[day] = label_asset_money_per_day(
                day, lookback, Const.fund_num)
            data_other[day] = label_asset_other_per_day(
                day, lookback, Const.fund_num)
            bar.update(1)

    df_stock = pd.concat(data_stock, names=['date', 'category', 'code'])
    df_bond = pd.concat(data_bond, names=['date', 'category', 'code'])
    df_money = pd.concat(data_money, names=['date', 'category', 'code'])
    df_other = pd.concat(data_other, names=['date', 'category', 'code'])

    df_result = pd.concat([df_stock, df_bond, df_money, df_other])
    df_result = df_result.swaplevel(0, 1)
    df_result.sort_index(inplace=True)
    #df_result.to_csv(datapath('fund_pool.csv'))

    #
    # 兼容老版本的基金池
    #
    fund_pool_convert_to_old(df_stock, datapath('stock_fund.csv'))
    fund_pool_convert_to_old(df_bond, datapath('bond_fund.csv'))
    fund_pool_convert_to_old(df_money, datapath('money_fund.csv'))
    fund_pool_convert_to_old(df_other, datapath('other_fund.csv'))
Exemple #16
0
def stockindex():
    df = pd.read_csv(os.path.normpath(datapath('../csvdata/fund_value.csv')),
                     index_col='date',
                     parse_dates=['date'])
    df = df[[
        const.hs300_code, const.largecap_code, const.smallcap_code,
        const.largecapgrowth_code, const.largecapvalue_code,
        const.smallcapvalue_code, const.smallcapgrowth_code, const.zz500_code
    ]]
    return df
def select_other_new(day, df_indicator):
    daystr = day.strftime("%Y-%m-%d")
    categories = ['SP500.SPI', 'GLNC', 'HSCI.HI']

    data = {}
    for category in categories:
        data[category] = df_indicator.loc[[category]]

    df_result = pd.concat(data, names=['category', 'code'])
    df_result.to_csv(datapath('other_pool_' + daystr + '.csv'))

    return df_result
Exemple #18
0
def index_value(start_date, end_date, index_code):

    #取开始时间和结束时间的数据
    df = pd.read_csv(os.path.normpath(datapath('../csvdata/fund_value.csv')),
                     index_col='date',
                     parse_dates=['date'])
    df = df[df.index <= datetime.strptime(end_date, '%Y-%m-%d')]
    df = df[df.index >= datetime.strptime(start_date, '%Y-%m-%d')]

    index_df = df[index_code]

    return index_df
def portfolio_simple():
    columns = ('risk', 'date', 'fund', 'ratio')
    #
    # 中类资产比例和对应基金
    #
    df = portfolio_category()
    print "portfolio_category"

    data = []
    for key, row in df.iterrows():
        # codes2 = filter_by_status(date, codes)
        (risk, date, _ph) = key
        ratio = row['ratio']
        funds = row['xfund'].split(':')
        data.extend([(risk, date, fund, ratio)
                     for (fund, ratio) in split_category_ratio(ratio, funds)])

    df2 = pd.DataFrame(data, columns=columns)
    print "category to fund finish"
    #
    # 根据基金代码合并配置比例
    #
    df_result = df2.groupby(['risk', 'date', 'fund']).sum()
    df_result.reset_index(inplace=True)
    print "sum funds"

    #
    # 过滤掉过小的份额配置
    #
    df_result = df_result[df_result['ratio'] >= 0.009999]
    print "fileout small"

    #
    # 过滤掉与上期换手率小于3%
    #
    df_result = filter_by_turnover_rate(df_result, 0.03)
    print "filter_by_turnover_rate"

    #
    # 某天持仓补足100%
    #
    df_result = pad_sum_to_one(df_result)
    print "pad_sum_to_one"

    #
    # 计算资产组合净值
    #
    df_result.to_csv(datapath('position-s.csv'), header=False)

    return df_result
def select_money_new(day, df_indicator, limit=1):
    daystr = day.strftime("%Y-%m-%d")
    # df = df_label.merge(df_indicator, left_index=True, right_index=True)
    categories = ['money']

    data = {}
    for category in categories:
        data[category] = df_indicator.sort_values(by='sharpe',
                                                  ascending=False)[:limit]

    df_result = pd.concat(data, names=['category', 'code'])
    df_result.to_csv(datapath('money_pool_' + daystr + '.csv'))

    return df_result
def highlowriskasset(lookback, adjust_period):

    #highriskassetdf  = allocationdata.equal_risk_asset_df
    highriskassetdf = pd.read_csv(datapath('equalriskasset.csv'),
                                  index_col='date',
                                  parse_dates=['date'])
    highriskassetdfr = highriskassetdf.pct_change().fillna(0.0)

    lowassetlabel = ['ratebond', 'creditbond']
    #lowriskassetdfr  = allocationdata.label_asset_df
    lowriskassetdfr = pd.read_csv(datapath('labelasset.csv'),
                                  index_col='date',
                                  parse_dates=['date'])
    lowriskassetdfr = lowriskassetdfr[lowassetlabel]
    lowriskassetdfr = lowriskassetdfr.loc[highriskassetdfr.index]

    his_week = lookback
    interval = adjust_period

    highdf = highriskasset(allocationdata, highriskassetdfr, his_week,
                           interval)
    lowdf = lowriskasset(allocationdata, lowriskassetdfr, his_week, interval)

    df = pd.concat([highdf, lowdf], axis=1, join_axes=[highdf.index])
    dfr = df.pct_change().fillna(0.0)

    highlowdf = highlowallocation(allocationdata, dfr, his_week, interval)

    print "sharpe : ", FundIndicator.portfolio_sharpe(
        highlowdf['highlow_risk_asset'].values)
    print "annual_return : ", FundIndicator.portfolio_return(
        highlowdf['highlow_risk_asset'].values)
    print "maxdrawdown : ", FundIndicator.portfolio_maxdrawdown(
        highlowdf['highlow_risk_asset'].values)

    highlowdf.to_csv(datapath('highlowrisk_net_value.csv'))
def select_bond_new(day, df_label, df_indicator, limit=5):
    daystr = day.strftime("%Y-%m-%d")
    # df = df_label.merge(df_indicator, left_index=True, right_index=True)
    categories = ['ratebond', 'creditbond', 'convertiblebond']

    data = {}
    for category in categories:
        index_codes = df_label[df_label[category] == 1].index
        df_tmp = df_indicator.loc[index_codes]
        data[category] = df_tmp.sort_values(by='jensen',
                                            ascending=False)[0:limit]

    df_result = pd.concat(data, names=['category', 'code'])
    df_result.to_csv(datapath('bond_pool_' + daystr + '.csv'))

    return df_result
def highlowallocation(dfr):

    #print dfr

    dates = dfr.index

    portfolio_vs = [[1, 1, 1, 1, 1, 1, 1, 1, 1, 1]]
    portfolio_dates = []
    portfolio_dates.append(dates[0])

    print 'risk rank'
    for i in range(1, len(dates)):

        d = dates[i]

        high_risk_asset_r = dfr.loc[d, 'high_risk_asset']
        low_risk_asset_r = dfr.loc[d, 'low_risk_asset']

        print d,
        risk_vs = []
        for j in range(1, 11):
            high_w = (j - 1) * 1.0 / 9
            low_w = 1 - high_w
            last_risk_vs = portfolio_vs[-1]
            v = last_risk_vs[j - 1] * (1 + high_risk_asset_r * high_w +
                                       low_risk_asset_r * low_w)
            risk_vs.append(v)
            print v,
        print

        portfolio_vs.append(risk_vs)
        portfolio_dates.append(d)

    cols = []
    for i in range(0, 10):
        cols.append(str(i + 1))
    portfolio_df = pd.DataFrame(portfolio_vs,
                                index=portfolio_dates,
                                columns=cols)
    portfolio_df.index.name = 'date'
    portfolio_df.to_csv(datapath('risk_portfolio.csv'))

    # allocationdata.riskhighlowriskasset = portfolio_df
    return portfolio_df
def select_money(funddf):

    day = funddf.index.max()
    daystr = day.strftime("%Y-%m-%d")

    fund_sharpe = fi.fund_sharp_annual(funddf)
    print fund_sharpe
    df = pd.DataFrame(fund_sharpe, columns=['code', 'sharpe'])
    df.set_index('code', inplace=True)
    df.to_csv(datapath('money_indicator_' + daystr + '.csv'))

    codes = []
    tag = {}
    tag['money'] = fund_sharpe[0][0]
    codes.append(fund_sharpe[0][0])
    #tag['sharpe2'] = fund_sharpe[1][0]
    #codes.append(fund_sharpe[0][0])

    return codes, tag
def portfolio_trade(out):
    df = pd.read_csv(datapath('gposition.csv'),
                     index_col=['risk', 'date', 'category'],
                     parse_dates=['date'])

    lines = []
    data = []
    for key, row in df.iterrows():
        # codes2 = filter_by_status(date, codes)
        (risk, date, category) = key
        ratio = row['ratio']
        funds = row['xfund']
        lines.append("%s,%.1f,%s,%.4f,%s" %
                     (date.strftime("%Y-%m-%d"), risk, category, ratio, funds))
    #
    # 调用晓彬的代码
    #
    positions = GeneralizationTrade.init(lines)
    positions = clean_min(positions)
    positions = clean_same(positions)

    for record in positions:
        risk, date, code, ratio = record
        out.write("%s,%s,%06s,%.4f\n" % (risk, date, code, ratio))
def highriskasset(dfr, his_week, interval):

    if 'HSCI.HI' in dfr.columns:
        dfr = dfr.drop('HSCI.HI', axis=1)

    if 'oscillation' in dfr.columns:
        dfr = dfr.drop('oscillation', axis=1)

    #interval = 26

    result_dates = []
    result_datas = []

    position_dates = []
    position_datas = []

    dates = dfr.index

    portfolio_vs = [1]
    result_dates.append(dates[his_week - 1])

    fund_values = {}
    fund_codes = []

    for i in range(his_week + 1, len(dates)):

        if (i - his_week - 1) % interval == 0:

            start_date = dates[i - his_week].strftime('%Y-%m-%d')
            end_date = dates[i - 1].strftime('%Y-%m-%d')

            allocation_dfr = dfr[
                dfr.index <= datetime.strptime(end_date, '%Y-%m-%d').date()]
            allocation_dfr = allocation_dfr[
                allocation_dfr.index >= datetime.strptime(
                    start_date, '%Y-%m-%d').date()]

            uplimit = [1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 0.3, 0.3]
            downlimit = [0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0]

            #risk, returns, ws, sharpe = PF.markowitz_r(allocation_dfr, None)
            risk, returns, ws, sharpe = PF.markowitz_r_spe(
                allocation_dfr, [downlimit, uplimit])
            #risk, returns, ws, sharpe = PF.markowitz_r(allocation_dfr, None)
            fund_codes = allocation_dfr.columns

            #for n in range(0, len(fund_codes)):
            #    ws[n] = 1.0 / len(fund_codes)

            last_pv = portfolio_vs[-1]
            fund_values = {}
            for n in range(0, len(fund_codes)):
                fund_values[n] = [last_pv * ws[n]]

            position_dates.append(end_date)
            position_datas.append(ws)

        pv = 0
        d = dates[i]
        for n in range(0, len(fund_codes)):
            vs = fund_values[n]
            code = fund_codes[n]
            fund_last_v = vs[-1]
            fund_last_v = fund_last_v + fund_last_v * dfr.loc[d, code]
            vs.append(fund_last_v)
            pv = pv + vs[-1]
        portfolio_vs.append(pv)
        result_dates.append(d)

        print d, pv

    result_datas = portfolio_vs
    result_df = pd.DataFrame(result_datas,
                             index=result_dates,
                             columns=['high_risk_asset'])

    result_df.index.name = 'date'
    result_df.to_csv(datapath('highriskasset.csv'))

    highriskposition_df = pd.DataFrame(position_datas,
                                       index=position_dates,
                                       columns=dfr.columns)
    highriskposition_df.index.name = 'date'
    highriskposition_df.to_csv(datapath('highriskposition.csv'))

    #allocationdata.high_risk_position_df = highriskposition_df
    #allocationdata.high_risk_asset_df     = result_df

    return result_df
def lowriskasset(dfr, his_week, interval):

    #interval = 26

    result_dates = []
    result_datas = []

    position_dates = []
    position_datas = []

    dates = dfr.index

    portfolio_vs = [1]
    result_dates.append(dates[his_week - 1])

    fund_values = {}
    fund_codes = []

    for i in range(his_week + 1, len(dates)):

        if (i - his_week - 1) % interval == 0:

            start_date = dates[i - his_week].strftime('%Y-%m-%d')
            end_date = dates[i - 1].strftime('%Y-%m-%d')

            allocation_dfr = dfr[
                dfr.index <= datetime.strptime(end_date, '%Y-%m-%d').date()]
            allocation_dfr = allocation_dfr[
                allocation_dfr.index >= datetime.strptime(
                    start_date, '%Y-%m-%d').date()]

            risk, returns, ws, sharpe = PF.markowitz_r(allocation_dfr, None)
            fund_codes = allocation_dfr.columns

            #for n in range(0, len(fund_codes)):
            #    ws[n] = 1.0 / len(fund_codes)

            last_pv = portfolio_vs[-1]
            fund_values = {}
            for n in range(0, len(fund_codes)):
                fund_values[n] = [last_pv * ws[n]]

            position_dates.append(end_date)
            position_datas.append(ws)

        pv = 0
        d = dates[i]
        for n in range(0, len(fund_codes)):
            vs = fund_values[n]
            code = fund_codes[n]
            fund_last_v = vs[-1]
            fund_last_v = fund_last_v + fund_last_v * dfr.loc[d, code]
            vs.append(fund_last_v)
            pv = pv + vs[-1]
        portfolio_vs.append(pv)
        result_dates.append(d)

        #print d , pv

    result_datas = portfolio_vs
    result_df = pd.DataFrame(result_datas,
                             index=result_dates,
                             columns=['low_risk_asset'])

    result_df.index.name = 'date'
    result_df.to_csv(datapath('lowriskasset.csv'))

    lowriskposition_df = pd.DataFrame(position_datas,
                                      index=position_dates,
                                      columns=dfr.columns)
    lowriskposition_df.index.name = 'date'
    lowriskposition_df.to_csv(datapath('lowriskposition.csv'))

    #allocationdata.low_risk_position_df = lowriskposition_df
    #allocationdata.low_risk_asset_df    = result_df

    return result_df
    #print "sharpe : ", FundIndicator.portfolio_sharpe(highlowdf['highlow_risk_asset'].values)
    #print "annual_return : ", FundIndicator.portfolio_return(highlowdf['highlow_risk_asset'].values)
    #print "maxdrawdown : ", FundIndicator.portfolio_maxdrawdown(highlowdf['highlow_risk_asset'].values)

    #highlowdf.to_csv(datapath('highlowrisk_net_value.csv'))
    #print "sharpe : ", fi.portfolio_sharpe(highdf['high_risk_asset'].values)
    #print "annual_return : ", fi.portfolio_return(highdf['high_risk_asset'].values)
    #print "maxdrawdown : ", fi.portfolio_maxdrawdown(highdf['high_risk_asset'].values)

    #print lowriskassetdfr


if __name__ == '__main__':

    highriskassetdf = pd.read_csv(datapath('equalriskasset.csv'),
                                  index_col='date',
                                  parse_dates=['date'])
    highriskassetdfr = highriskassetdf.pct_change().fillna(0.0)

    lowassetlabel = ['ratebond', 'creditbond']
    lowriskassetdfr = pd.read_csv(datapath('labelasset.csv'),
                                  index_col='date',
                                  parse_dates=['date'])
    lowriskassetdfr = lowriskassetdfr[lowassetlabel]
    lowriskassetdfr = lowriskassetdfr.loc[highriskassetdfr.index]

    his_week = 26
    interval = 26

    highdf = highriskasset(highriskassetdfr, his_week, interval)
def equalriskasset():


    rf = 0.03 / 52


    #ratio_df         = allocationdata.equal_risk_asset_ratio_df
    ratio_df         = pd.read_csv(datapath('equalriskassetratio.csv'), index_col = 'date', parse_dates = ['date'] )
    ratio_dates      = ratio_df.index
    start_date = ratio_dates[0]


    #dfr              = allocationdata.label_asset_df
    dfr              = pd.read_csv(datapath('labelasset.csv'), index_col = 'date', parse_dates = ['date'] )
    dfr              = dfr.pct_change()[dfr.index >= start_date]

    dates = dfr.index
    ratio_dates = ratio_df.index

    #assetlabels  = ['largecap','smallcap','rise','oscillation','decline','growth','value','convertiblebond','SP500.SPI','GLNC','HSCI.HI']

    assetlabels  = ['largecap','smallcap','rise','oscillation','decline','growth','value','convertiblebond','SP500.SPI','GLNC','HSCI.HI']
    asset_values = {}
    asset_combination = {}
    asset_ratio  = {}


    for asset in assetlabels:

        asset_values.setdefault(asset, [1.0])
        asset_ratio.setdefault(asset, 0)
        asset_combination.setdefault(asset, [[0.0, 0,0]])


    result_dates = []
    result_datas  = []

    ii = range(0, len(dates))
    with click.progressbar(length=len(ii), label='update nav for reshaped assets') as bar:
        for i in ii:
            bar.update(1)

            d = dates[i]
            for asset in assetlabels:

                cvs = asset_combination[asset]
                last_cvs = cvs[-1]
                current_cvs = [last_cvs[0] * (1 + dfr.loc[d, asset]), last_cvs[1] * (1 + rf)]
                #current_cvs = [last_cvs[0] * (1 + dfr.loc[d, asset]), last_cvs[1]]
                cvs.append(current_cvs)
                vs = asset_values[asset]
                if current_cvs[0] + current_cvs[1] == 0:
                    continue
                else:
                    vs.append(current_cvs[0] + current_cvs[1])


                '''
                vs = asset_values[asset]
                last_v = vs[-1]
                current_v = last_v + last_v * dfr.loc[d, asset] * asset_ratio[asset]
                vs.append(current_v)
                '''


            if d in ratio_dates:
                for asset in assetlabels:
                    asset_ratio[asset] = ratio_df.loc[d, asset]
                    vs = asset_values[asset]
                    cvs = asset_combination[asset]
                    cvs.append( [vs[-1] * asset_ratio[asset], vs[-1] * (1 - asset_ratio[asset])] )


            #asset_vs = [asset_values['largecap'][-1], asset_values['smallcap'][-1], asset_values['rise'][-1],
            #            asset_values['oscillation'][-1], asset_values['decline'][-1], asset_values['growth'][-1], \
            #            asset_values['value'][-1], asset_values['convertiblebond'][-1], asset_values['SP500.SPI'][-1], \
            #            asset_values['GLNC'][-1], asset_values['HSCI.HI'][-1]]
            #result_datas.append(asset_vs)
            #result_dates.append(d)

            asset_vs = [asset_values['largecap'][-1], asset_values['smallcap'][-1], asset_values['rise'][-1],
                        asset_values['oscillation'][-1], asset_values['decline'][-1], asset_values['growth'][-1], \
                        asset_values['value'][-1], asset_values['SP500.SPI'][-1], \
                        asset_values['GLNC'][-1], asset_values['HSCI.HI'][-1]]
            result_datas.append(asset_vs)
            result_dates.append(d)


            logger.debug("%s %.6f %.6f %.6f %.6f %.6f %.6f %.6f %.6f %.6f %.6f %.6f", \
                        d.strftime("%Y-%m-%d"), asset_values['largecap'][-1], asset_values['smallcap'][-1], asset_values['rise'][-1], \
                        asset_values['oscillation'][-1], asset_values['decline'][-1], asset_values['growth'][-1], \
                        asset_values['value'][-1], asset_values['convertiblebond'][-1], asset_values['SP500.SPI'][-1], \
                        asset_values['GLNC'][-1], asset_values['HSCI.HI'][-1])


            if d in ratio_dates:
                for asset in assetlabels:
                    asset_ratio[asset] = ratio_df.loc[d, asset]


    new_assetlabels  = ['largecap','smallcap','rise','oscillation','decline','growth','value','SP500.SPI','GLNC','HSCI.HI']
    result_df = pd.DataFrame(result_datas, index=result_dates, columns=new_assetlabels)

    result_df.index.name = 'date'
    result_df.to_csv(datapath('equalriskasset.csv'))
Exemple #30
0
#coding=utf8

import os
import string
import pandas as pd
import numpy as np
import fundindicator
from datetime import datetime
import portfolio as pf
import fundindicator as fi

from Const import datapath

dfr = pd.read_csv(datapath('labelasset.csv'),
                  index_col='date',
                  parse_dates=['date'])
dates = dfr.index

his_week = 13
interval = 13

result_dates = []
result_datas = []

position_dates = []
position_datas = []

portfolio_vs = [1]
result_dates.append(dates[his_week])

fund_values = {}