Beispiel #1
0
def monthly(funds):
    """
    @summary Computes monthly returns centered around 0
    @param funds: A time series containing daily fund values
    @return an array of monthly returns
    """
    funds2 = []
    last_last_month = -1
    years = qsdateutil.getYears(funds)
    for year in years:
        months = qsdateutil.getMonths(funds, year)
        for month in months:
            last_this_month = qsdateutil.getLastDay(funds, year, month)
            if last_last_month == -1 :
                last_last_month=qsdateutil.getFirstDay(funds, year, month)
            if type(funds).__name__=='TimeSeries':
                funds2.append(funds[last_this_month]/funds[last_last_month]-1)
            else:
                funds2.append(funds.xs(last_this_month)/funds.xs(last_last_month)-1)
            last_last_month = last_this_month
    return(funds2)
Beispiel #2
0
def average_monthly(funds):
    """
    @summary Computes average monthly returns centered around 0
    @param funds: A time series containing daily fund values
    @return an array of average monthly returns
    """
    rets = daily(funds)
    ret_i = 0
    years = qsdateutil.getYears(funds)
    averages = []
    for year in years:
        months = qsdateutil.getMonths(funds, year)
        for month in months:
            avg = 0
            count = 0
            days = qsdateutil.getDays(funds, year, month)
            for day in days:
                avg += rets[ret_i]
                ret_i += 1
                count += 1
            averages.append(float(avg) / count)
    return (averages)
def average_monthly(funds):
    """
    @summary Computes average monthly returns centered around 0
    @param funds: A time series containing daily fund values
    @return an array of average monthly returns
    """
    rets = daily(funds)
    ret_i = 0
    years = qsdateutil.getYears(funds)
    averages = []
    for year in years:
        months = qsdateutil.getMonths(funds, year)
        for month in months:
            avg = 0
            count = 0
            days = qsdateutil.getDays(funds, year, month)
            for day in days:
                avg += rets[ret_i]
                ret_i += 1
                count += 1
            averages.append(float(avg) / count)
    return(averages)    
Beispiel #4
0
def print_html(fund_ts, benchmark, name, lf_dividend_rets=0.0, original="",
    s_fund_name="Fund", s_original_name="Original", d_trading_params="", d_hedge_params="",
    s_comments="", directory=False, leverage=False, s_leverage_name="Leverage",commissions=0, slippage=0,
    borrowcost=0, ostream=sys.stdout, i_start_cash=1000000):
    """
    @summary prints stats of a provided fund and benchmark
    @param fund_ts: fund value in pandas timeseries
    @param benchmark: benchmark symbol to compare fund to
    @param name: name to associate with the fund in the report
    @param directory: parameter to specify printing to a directory
    @param leverage: time series to plot with report
    @param commissions: value to print with report
    @param slippage: value to print with report
    @param ostream: stream to print stats to, defaults to stdout
    """

    #Set locale for currency conversions
    locale.setlocale(locale.LC_ALL, '')

    #make names length independent for alignment
    s_formatted_original_name="%15s" % s_original_name
    s_formatted_fund_name = "%15s" % s_fund_name

    fund_ts=fund_ts.fillna(method='pad')
    if directory != False :
        if not path.exists(directory):
            makedirs(directory)

        sfile = path.join(directory, "report-%s.html" % name )
        splot = "plot-%s.png" % name
        splot_dir =  path.join(directory, splot)
        ostream = open(sfile, "wb")
        print "writing to ", sfile

        if type(original)==type("str"):
            if type(leverage)!=type(False):
                print_plot(fund_ts, benchmark, name, splot_dir, lf_dividend_rets, leverage=leverage, i_start_cash = i_start_cash, s_leverage_name=s_leverage_name)
            else:
                print_plot(fund_ts, benchmark, name, splot_dir, lf_dividend_rets, i_start_cash = i_start_cash)
        else:
            if type(leverage)!=type(False):
                print_plot([fund_ts, original], benchmark, name, splot_dir, s_original_name, lf_dividend_rets, leverage=leverage, i_start_cash = i_start_cash, s_leverage_name=s_leverage_name)
            else:
                print_plot([fund_ts, original], benchmark, name, splot_dir, s_original_name, lf_dividend_rets, i_start_cash = i_start_cash)

    print_header(ostream,name)
    start_date = fund_ts.index[0].strftime("%m/%d/%Y")
    end_date = fund_ts.index[-1].strftime("%m/%d/%Y")
    ostream.write("Performance Summary for "\
     + str(path.basename(name)) + " Backtest\n")
    ostream.write("For the dates " + str(start_date) + " to "\
                                       + str(end_date) + "")

    #paramater section
    if d_trading_params!="":
        ostream.write("\n\nTrading Paramaters\n\n")
        for var in d_trading_params:
            print_line(var, d_trading_params[var],ostream=ostream)
    if d_hedge_params!="":
        ostream.write("\nHedging Paramaters\n\n")
        if type(d_hedge_params['Weight of Hedge']) == type(float):
            d_hedge_params['Weight of Hedge'] = str(int(d_hedge_params['Weight of Hedge']*100)) + '%'
        for var in d_hedge_params:
            print_line(var, d_hedge_params[var],ostream=ostream)

    #comment section
    if s_comments!="":
        ostream.write("\nComments\n\n%s" % s_comments)


    if directory != False :
        ostream.write("\n\n<img src="+splot+" width=600 />\n\n")

    mult = i_start_cash/fund_ts.values[0]


    timeofday = dt.timedelta(hours = 16)
    timestamps = du.getNYSEdays(fund_ts.index[0], fund_ts.index[-1], timeofday)
    dataobj =de.DataAccess('Yahoo')
    years = du.getYears(fund_ts)
    benchmark_close = dataobj.get_data(timestamps, benchmark, ["close"])
    benchmark_close=benchmark_close[0]
    for bench_sym in benchmark:
        benchmark_close[bench_sym]=benchmark_close[bench_sym].fillna(method='pad')

    if type(lf_dividend_rets) != type(0.0):
        for i,sym in enumerate(benchmark):
            benchmark_close[sym] = _dividend_rets_funds(benchmark_close[sym], lf_dividend_rets[i])

    ostream.write("Resulting Values in $ with an initial investment of "+ locale.currency(int(round(i_start_cash)), grouping=True) + "\n")

    print_line(s_formatted_fund_name+" Resulting Value",(locale.currency(int(round(fund_ts.values[-1]*mult)), grouping=True)),i_spacing=3, ostream=ostream)

    if type(original)!=type("str"):
        mult3 = i_start_cash / original.values[0]
        print_line(s_formatted_original_name +" Resulting Value",(locale.currency(int(round(original.values[-1]*mult3)), grouping=True)),i_spacing=3, ostream=ostream)

    for bench_sym in benchmark:
        mult2=i_start_cash/benchmark_close[bench_sym].values[0]
        print_line(bench_sym+" Resulting Value",locale.currency(int(round(benchmark_close[bench_sym].values[-1]*mult2)), grouping=True),i_spacing=3, ostream=ostream)

    ostream.write("\n")

    if len(years) > 1:
        print_line(s_formatted_fund_name+" Sharpe Ratio","%10.3f" % fu.get_sharpe_ratio(fund_ts.values)[0],i_spacing=4, ostream=ostream)
        if type(original)!=type("str"):
            print_line(s_formatted_original_name+" Sharpe Ratio","%10.3f" % fu.get_sharpe_ratio(original.values)[0],i_spacing=4, ostream=ostream)

        for bench_sym in benchmark:
            print_line(bench_sym+" Sharpe Ratio","%10.3f" % fu.get_sharpe_ratio(benchmark_close[bench_sym].values)[0],i_spacing=4,ostream=ostream)
        ostream.write("\n")

    ostream.write("Transaction Costs\n")
    print_line("Total Commissions"," %15s, %10.2f%%" % (locale.currency(int(round(commissions)), grouping=True), \
                                                  float((round(commissions)*100)/(fund_ts.values[-1]*mult))), i_spacing=4, ostream=ostream)

    print_line("Total Slippage"," %15s, %10.2f%%" % (locale.currency(int(round(slippage)), grouping=True), \
                                                     float((round(slippage)*100)/(fund_ts.values[-1]*mult))), i_spacing=4, ostream=ostream)

    print_line("Total Short Borrowing Cost"," %15s, %10.2f%%" % (locale.currency(int(round(borrowcost)), grouping=True), \
                                                     float((round(borrowcost)*100)/(fund_ts.values[-1]*mult))), i_spacing=4, ostream=ostream)

    print_line("Total Costs"," %15s, %10.2f%%" % (locale.currency(int(round(borrowcost+slippage+commissions)), grouping=True), \
                                  float((round(borrowcost+slippage+commissions)*100)/(fund_ts.values[-1]*mult))), i_spacing=4, ostream=ostream)

    ostream.write("\n")

    print_line(s_formatted_fund_name+" Std Dev of Returns",get_std_dev(fund_ts),i_spacing=8, ostream=ostream)

    if type(original)!=type("str"):
        print_line(s_formatted_original_name+" Std Dev of Returns", get_std_dev(original), i_spacing=8, ostream=ostream)

    for bench_sym in benchmark:
        print_line(bench_sym+" Std Dev of Returns", get_std_dev(benchmark_close[bench_sym]), i_spacing=8, ostream=ostream)

    ostream.write("\n")


    for bench_sym in benchmark:
        print_benchmark_coer(fund_ts, benchmark_close[bench_sym], str(bench_sym), ostream)
    ostream.write("\n")

    ostream.write("\nYearly Performance Metrics")
    print_years(years, ostream)

    s_line=""
    for f_token in get_annual_return(fund_ts, years):
        s_line+=" %+8.2f%%" % f_token
    print_line(s_formatted_fund_name+" Annualized Return", s_line, i_spacing=4, ostream=ostream)
    lf_vals=[get_annual_return(fund_ts, years)]
    ls_labels=[name]

    if type(original)!=type("str"):
        s_line=""
        for f_token in get_annual_return(original, years):
            s_line+=" %+8.2f%%" % f_token
        print_line(s_formatted_original_name+" Annualized Return", s_line, i_spacing=4, ostream=ostream)
        lf_vals.append(get_annual_return(original, years))
        ls_labels.append(s_original_name)

    for bench_sym in benchmark:
        s_line=""
        for f_token in get_annual_return(benchmark_close[bench_sym], years):
            s_line+=" %+8.2f%%" % f_token
        print_line(bench_sym+" Annualized Return", s_line, i_spacing=4, ostream=ostream)
        lf_vals.append(get_annual_return(benchmark_close[bench_sym], years))
        ls_labels.append(bench_sym)

    print lf_vals
    print ls_labels
    ls_year_labels=[]
    for i in range(0,len(years)):
        ls_year_labels.append(str(years[i]))
    print_bar_chart(lf_vals, ls_labels, ls_year_labels, directory+"/annual_rets.png")

    print_years(years, ostream)

    print_line(s_formatted_fund_name+" Winning Days",get_winning_days(fund_ts, years), i_spacing=4, ostream=ostream)


    if type(original)!=type("str"):
        print_line(s_formatted_original_name+" Winning Days",get_winning_days(original, years), i_spacing=4, ostream=ostream)


    for bench_sym in benchmark:
        print_line(bench_sym+" Winning Days",get_winning_days(benchmark_close[bench_sym], years), i_spacing=4, ostream=ostream)


    print_years(years, ostream)

    print_line(s_formatted_fund_name+" Max Draw Down",get_max_draw_down(fund_ts, years), i_spacing=4, ostream=ostream)

    if type(original)!=type("str"):
        print_line(s_formatted_original_name+" Max Draw Down",get_max_draw_down(original, years), i_spacing=4, ostream=ostream)


    for bench_sym in benchmark:
        print_line(bench_sym+" Max Draw Down",get_max_draw_down(benchmark_close[bench_sym], years), i_spacing=4, ostream=ostream)


    print_years(years, ostream)


    print_line(s_formatted_fund_name+" Daily Sharpe Ratio",get_daily_sharpe(fund_ts, years), i_spacing=4, ostream=ostream)


    if type(original)!=type("str"):
        print_line(s_formatted_original_name+" Daily Sharpe Ratio",get_daily_sharpe(original, years), i_spacing=4, ostream=ostream)

    for bench_sym in benchmark:
        print_line(bench_sym+" Daily Sharpe Ratio",get_daily_sharpe(benchmark_close[bench_sym], years), i_spacing=4, ostream=ostream)


    print_years(years, ostream)

    print_line(s_formatted_fund_name+" Daily Sortino Ratio",get_daily_sortino(fund_ts, years), i_spacing=4, ostream=ostream)

    if type(original)!=type("str"):
        print_line(s_formatted_original_name+" Daily Sortino Ratio",get_daily_sortino(original, years), i_spacing=4, ostream=ostream)


    for bench_sym in benchmark:
        print_line(bench_sym+" Daily Sortino Ratio",get_daily_sortino(benchmark_close[bench_sym], years), i_spacing=4, ostream=ostream)


    ostream.write("\n\n\nCorrelation and Beta with DJ Industries for the Fund ")

    print_industry_coer(fund_ts,ostream)

    ostream.write("\n\nCorrelation and Beta with Other Indices for the Fund ")

    print_other_coer(fund_ts,ostream)

    ostream.write("\n\n\nMonthly Returns for the Fund %\n")

    print_monthly_returns(fund_ts, years, ostream)
    print_footer(ostream)
def print_stats(fund_ts, benchmark, name, lf_dividend_rets=0.0, original="",s_fund_name="Fund",
    s_original_name="Original", d_trading_params="", d_hedge_params="", s_comments="", directory = False,
    leverage = False, s_leverage_name="Leverage", commissions = 0, slippage = 0, borrowcost = 0, ostream = sys.stdout, 
    i_start_cash=1000000, ts_turnover="False"):
    """
    @summary prints stats of a provided fund and benchmark
    @param fund_ts: fund value in pandas timeseries
    @param benchmark: benchmark symbol to compare fund to
    @param name: name to associate with the fund in the report
    @param directory: parameter to specify printing to a directory
    @param leverage: time series to plot with report
    @param commissions: value to print with report
    @param slippage: value to print with report
    @param ostream: stream to print stats to, defaults to stdout
    """

    #Set locale for currency conversions
    locale.setlocale(locale.LC_ALL, '')

    if original != "" and type(original) != type([]):
        original = [original]
        if type(s_original_name) != type([]):
            s_original_name = [s_original_name]

    #make names length independent for alignment
    s_formatted_original_name = []
    for name_temp in s_original_name:
        s_formatted_original_name.append("%15s" % name_temp)
    s_formatted_fund_name = "%15s" % s_fund_name

    fund_ts=fund_ts.fillna(method='pad')
    fund_ts=fund_ts.fillna(method='bfill')
    fund_ts=fund_ts.fillna(1.0)
    if directory != False :
        if not path.exists(directory):
            makedirs(directory)

        sfile = path.join(directory, "report-%s.html" % name )
        splot = "plot-%s.png" % name
        splot_dir =  path.join(directory, splot)
        ostream = open(sfile, "wb")
        ostream.write("<pre>")
        print("writing to ", sfile)

        if type(original)==type("str"):
            if type(leverage)!=type(False):
                print_plot(fund_ts, benchmark, name, splot_dir, lf_dividend_rets, leverage=leverage, i_start_cash = i_start_cash, s_leverage_name=s_leverage_name)
            else:
                print_plot(fund_ts, benchmark, name, splot_dir, lf_dividend_rets, i_start_cash = i_start_cash)
        else:
            if type(leverage)!=type(False):
                print_plot([fund_ts, original], benchmark, name, splot_dir, s_original_name, lf_dividend_rets,
                             leverage=leverage, i_start_cash = i_start_cash, s_leverage_name=s_leverage_name)
            else:
                print_plot([fund_ts, original], benchmark, name, splot_dir, s_original_name, lf_dividend_rets, i_start_cash = i_start_cash)

    start_date = fund_ts.index[0].strftime("%m/%d/%Y")
    end_date = fund_ts.index[-1].strftime("%m/%d/%Y")
    ostream.write("Performance Summary for "\
	 + str(path.basename(name)) + " Backtest\n")
    ostream.write("For the dates " + str(start_date) + " to "\
                                       + str(end_date) + "")

    #paramater section
    if d_trading_params!="":
        ostream.write("\n\nTrading Paramaters\n\n")
        for var in d_trading_params:
            print_line(var, d_trading_params[var],ostream=ostream)
    if d_hedge_params!="":
        ostream.write("\nHedging Paramaters\n\n")
        if type(d_hedge_params['Weight of Hedge']) == type(float):
            d_hedge_params['Weight of Hedge'] = str(int(d_hedge_params['Weight of Hedge']*100)) + '%'
        for var in d_hedge_params:
            print_line(var, d_hedge_params[var],ostream=ostream)

    #comment section
    if s_comments!="":
        ostream.write("\nComments\n\n%s" % s_comments)


    if directory != False :
        ostream.write("\n\n<img src="+splot+" width=700 />\n\n")

    mult = i_start_cash/fund_ts.values[0]


    timeofday = dt.timedelta(hours = 16)
    timestamps = du.getNYSEdays(fund_ts.index[0], fund_ts.index[-1], timeofday)
    dataobj =de.DataAccess('Yahoo')
    years = du.getYears(fund_ts)
    benchmark_close = dataobj.get_data(timestamps, benchmark, ["close"], \
                                                     verbose = False)[0]
    for bench_sym in benchmark:
        benchmark_close[bench_sym]=benchmark_close[bench_sym].fillna(method='pad')
        benchmark_close[bench_sym]=benchmark_close[bench_sym].fillna(method='bfill')
        benchmark_close[bench_sym]=benchmark_close[bench_sym].fillna(1.0)

    if type(lf_dividend_rets) != type(0.0):
        for i,sym in enumerate(benchmark):
            benchmark_close[sym] = _dividend_rets_funds(benchmark_close[sym], lf_dividend_rets[i])

    ostream.write("Resulting Values in $ with an initial investment of "+ locale.currency(int(round(i_start_cash)), grouping=True) + "\n")

    print_line(s_formatted_fund_name+" Resulting Value"," %15s, %10.2f%%" % (locale.currency(int(round(fund_ts.values[-1]*mult)), grouping=True), \
                                                     float(100*((fund_ts.values[-1]/fund_ts.values[0])-1))), i_spacing=4, ostream=ostream)

    # if type(original)!=type("str"):
    #     mult3 = i_start_cash / original.values[0]
    #     # print_line(s_formatted_original_name +" Resulting Value",(locale.currency(int(round(original.values[-1]*mult3)), grouping=True)),i_spacing=3, ostream=ostream)
    #     print_line(s_formatted_original_name+" Resulting Value"," %15s, %10.2f%%" % (locale.currency(int(round(original.values[-1]*mult3)), grouping=True), \
    #                                                  float(100*((original.values[-1]/original.values[0])-1))), i_spacing=4, ostream=ostream)

    if type(original)!=type("str"):
        for i in range(len(original)):
            mult3 = i_start_cash / original[i].values[0]
            # print_line(s_formatted_original_name +" Resulting Value",(locale.currency(int(round(original[i].values[-1]*mult3)), grouping=True)),i_spacing=3, ostream=ostream)
            print_line(s_formatted_original_name[i]+" Resulting Value"," %15s, %10.2f%%" % (locale.currency(int(round(original[i].values[-1]*mult3)), grouping=True), \
                                                     float(100*((original[i].values[-1]/original[i].values[0])-1))), i_spacing=4, ostream=ostream)

    for bench_sym in benchmark:
        mult2= i_start_cash / benchmark_close[bench_sym].values[0]
        # print_line(bench_sym+" Resulting Value",locale.currency(int(round(benchmark_close[bench_sym].values[-1]*mult2)), grouping=True),i_spacing=3, ostream=ostream)
        print_line(bench_sym+" Resulting Value"," %15s, %10.2f%%" % (locale.currency(int(round(benchmark_close[bench_sym].values[-1]*mult2)), grouping=True), \
                                                     float(100*((benchmark_close[bench_sym].values[-1]/benchmark_close[bench_sym].values[0])-1))), i_spacing=4, ostream=ostream)

    ostream.write("\n")

    # if len(years) > 1:
    print_line(s_formatted_fund_name+" Sharpe Ratio","%10.3f" % fu.get_sharpe_ratio(fund_ts.values)[0],i_spacing=4, ostream=ostream)
    if type(original)!=type("str"):
        for i in range(len(original)):
            print_line(s_formatted_original_name[i]+" Sharpe Ratio","%10.3f" % fu.get_sharpe_ratio(original[i].values)[0],i_spacing=4, ostream=ostream)

    for bench_sym in benchmark:
        print_line(bench_sym+" Sharpe Ratio","%10.3f" % fu.get_sharpe_ratio(benchmark_close[bench_sym].values)[0],i_spacing=4,ostream=ostream)
    ostream.write("\n")


    # KS - Similarity
    # ks, p = ks_statistic(fund_ts);
    # if ks!= -1 and p!= -1:
    #     if ks < p:
    #         ostream.write("\nThe last three month's returns are consistent with previous performance (KS = %2.5f, p = %2.5f) \n\n"% (ks, p))
    #     else:
    #         ostream.write("\nThe last three month's returns are NOT CONSISTENT with previous performance (KS = %2.5f, p = %2.5f) \n\n"% (ks, p))


    ostream.write("Transaction Costs\n")
    print_line("Total Commissions"," %15s, %10.2f%%" % (locale.currency(int(round(commissions)), grouping=True), \
                                                  float((round(commissions)*100)/(fund_ts.values[-1]*mult))), i_spacing=4, ostream=ostream)

    print_line("Total Slippage"," %15s, %10.2f%%" % (locale.currency(int(round(slippage)), grouping=True), \
                                                     float((round(slippage)*100)/(fund_ts.values[-1]*mult))), i_spacing=4, ostream=ostream)

    print_line("Total Short Borrowing Cost"," %15s, %10.2f%%" % (locale.currency(int(round(borrowcost)), grouping=True), \
                                                     float((round(borrowcost)*100)/(fund_ts.values[-1]*mult))), i_spacing=4, ostream=ostream)

    print_line("Total Costs"," %15s, %10.2f%%" % (locale.currency(int(round(borrowcost+slippage+commissions)), grouping=True), \
                                  float((round(borrowcost+slippage+commissions)*100)/(fund_ts.values[-1]*mult))), i_spacing=4, ostream=ostream)

    ostream.write("\n")

    print_line(s_formatted_fund_name+" Std Dev of Returns",get_std_dev(fund_ts),i_spacing=8, ostream=ostream)

    if type(original)!=type("str"):
        for i in range(len(original)):
            print_line(s_formatted_original_name[i]+" Std Dev of Returns", get_std_dev(original[i]), i_spacing=8, ostream=ostream)

    for bench_sym in benchmark:
        print_line(bench_sym+" Std Dev of Returns", get_std_dev(benchmark_close[bench_sym]), i_spacing=8, ostream=ostream)

    ostream.write("\n")


    for bench_sym in benchmark:
        print_benchmark_coer(fund_ts, benchmark_close[bench_sym], str(bench_sym), ostream)
    ostream.write("\n")

    ostream.write("\nYearly Performance Metrics")
    print_years(years, ostream)


    s_line=""
    for f_token in get_annual_return(fund_ts, years):
        s_line+=" %+8.2f%%" % f_token
    print_line(s_formatted_fund_name+" Annualized Return",s_line, i_spacing=4, ostream=ostream)


    if type(original)!=type("str"):
        for i in range(len(original)):
            s_line=""
            for f_token in get_annual_return(original[i], years):
                s_line+=" %+8.2f%%" % f_token
            print_line(s_formatted_original_name[i]+" Annualized Return", s_line, i_spacing=4, ostream=ostream)

    for bench_sym in benchmark:
        s_line=""
        for f_token in get_annual_return(benchmark_close[bench_sym], years):
            s_line+=" %+8.2f%%" % f_token
        print_line(bench_sym+" Annualized Return", s_line, i_spacing=4, ostream=ostream)

    print_years(years, ostream)

    print_line(s_formatted_fund_name+" Winning Days",get_winning_days(fund_ts, years), i_spacing=4, ostream=ostream)


    if type(original)!=type("str"):
        for i in range(len(original)):
            print_line(s_formatted_original_name[i]+" Winning Days",get_winning_days(original[i], years), i_spacing=4, ostream=ostream)


    for bench_sym in benchmark:
        print_line(bench_sym+" Winning Days",get_winning_days(benchmark_close[bench_sym], years), i_spacing=4, ostream=ostream)


    print_years(years, ostream)

    print_line(s_formatted_fund_name+" Max Draw Down",get_max_draw_down(fund_ts, years), i_spacing=4, ostream=ostream)

    if type(original)!=type("str"):
        for i in range(len(original)):
            print_line(s_formatted_original_name[i]+" Max Draw Down",get_max_draw_down(original[i], years), i_spacing=4, ostream=ostream)


    for bench_sym in benchmark:
        print_line(bench_sym+" Max Draw Down",get_max_draw_down(benchmark_close[bench_sym], years), i_spacing=4, ostream=ostream)


    print_years(years, ostream)


    print_line(s_formatted_fund_name+" Daily Sharpe Ratio",get_daily_sharpe(fund_ts, years), i_spacing=4, ostream=ostream)


    if type(original)!=type("str"):
        for i in range(len(original)):
            print_line(s_formatted_original_name[i]+" Daily Sharpe Ratio",get_daily_sharpe(original[i], years), i_spacing=4, ostream=ostream)

    for bench_sym in benchmark:
        print_line(bench_sym+" Daily Sharpe Ratio",get_daily_sharpe(benchmark_close[bench_sym], years), i_spacing=4, ostream=ostream)


    print_years(years, ostream)

    print_line(s_formatted_fund_name+" Daily Sortino Ratio",get_daily_sortino(fund_ts, years), i_spacing=4, ostream=ostream)

    if type(original)!=type("str"):
        for i in range(len(original)):
            print_line(s_formatted_original_name[i]+" Daily Sortino Ratio",get_daily_sortino(original[i], years), i_spacing=4, ostream=ostream)


    for bench_sym in benchmark:
        print_line(bench_sym+" Daily Sortino Ratio",get_daily_sortino(benchmark_close[bench_sym], years), i_spacing=4, ostream=ostream)


    ostream.write("\n\n\nCorrelation and Beta with DJ Industries for the Fund ")

    print_industry_coer(fund_ts,ostream)

    ostream.write("\n\nCorrelation and Beta with Other Indices for the Fund ")

    print_other_coer(fund_ts,ostream)

    ostream.write("\n\n\nMonthly Returns for the Fund %\n")

    print_monthly_returns(fund_ts, years, ostream)

    if type(ts_turnover) != type("False"):
        ostream.write("\n\nMonthly Turnover for the fund\n")
        print_monthly_turnover(fund_ts, years, ts_turnover, ostream)

    ostream.write("\n\n3 Month Kolmogorov-Smirnov 2-Sample Similarity Test\n")

    print_monthly_ks(fund_ts, years, ostream)

    ks, p = ks_statistic(fund_ts);
    if ks!= -1 and p!= -1:
        ostream.write("\nResults for the Similarity Test over last 3 months : (KS = %2.5f, p = %2.5f) \n\n"% (ks, p))

    if directory != False:
        ostream.write("</pre>")
Beispiel #6
0
def reportFunctionality(funds, symbols,filename=sys.stdout):
	if(len(symbols)!=0):
		funds2=runOther(funds,symbols)
		arg2=1
	else:
		arg2=0

	if(filename==sys.stdout):
		html_file=sys.stdout
	else:
		html_file = open(filename,"w")
	
	#top
	html_file.write("<HTML>\n")
	html_file.write("<HEAD>\n")	
	html_file.write("<TITLE>QSTK Generated Report from "+readableDate(funds.index[0])+" to "+readableDate(funds.index[-1])+"</TITLE>\n")
	html_file.write("</HEAD>\n\n")
	html_file.write("<BODY><CENTER>\n\n")
	
	years=du.getYears(funds)

	html_file.write("<H2>Performance Summary for "+sys.argv[1]+"</H2>\n")
	html_file.write("For the dates "+readableDate(funds.index[0])+" to "+readableDate(funds.index[-1])+"\n")


	html_file.write("<H3>Yearly Performance Metrics</H3>\n")


	html_file.write("<TABLE CELLPADDING=10>\n")
	html_file.write("<TR><TH></TH>\n")
	for year in years:
		html_file.write("<TH>"+str(year)+"</TH>\n")
	html_file.write("</TR>\n")

	#yearly return
	html_file.write("<TR>\n")
	html_file.write("<TH>Annualized Return:</TH>\n")
	for year in years:
		retur=getYearReturn(funds,year)
		html_file.write("<TD>\n")
		print >>html_file, "%.2f\n" % (retur*100) 
		html_file.write("%</TD>\n")
	html_file.write("</TR>\n")

	#yearly winning days
	html_file.write("<TR>\n")
	html_file.write("<TH>Winning Days:</TH>\n")
	for year in years:
		# change to compare to inputs - ratio=tsu.getYearRatio(funds,year)
		if(arg2!=0):
			win=getWinningDays(funds,funds2,year)
			html_file.write("<TD>\n")
			print >>html_file, "%.2f\n" % (win*100)
			html_file.write("%</TD>\n")
		else:
			html_file.write("<TD>No comparison.</TD>\n")
	html_file.write("</TR>\n")

	#max draw down
	html_file.write("<TR>\n")
	html_file.write("<TH>Max Draw Down:</TH>\n")
	for year in years:
		drop=getYearMaxDrop(funds,year)
		html_file.write("<TD>\n")
		print >>html_file, "%.2f" % (drop*100)
		html_file.write("%</TD>\n")
	html_file.write("</TR>\n")

	#yearly sharpe ratio using daily rets
	html_file.write("<TR>\n")
	html_file.write("<TH>Daily Sharpe Ratio:</TH>\n")
	for year in years:
		ratio=tsu.getYearRatio(funds,year)
		html_file.write("<TD>\n")
		print >>html_file, "%.2f\n" % ratio
		html_file.write("</TD>\n")
	html_file.write("</TR>\n")


	#yearly sharpe ratio using monthly rets
	html_file.write("<TR>\n")
	html_file.write("<TH>Monthly Sharpe Ratio:</TH>\n")
	for year in years:
		ratio=getYearRatioUsingMonth(funds,year)
		html_file.write("<TD>\n")
		print >>html_file, "%.2f\n" % ratio
		html_file.write("</TD>\n")
	html_file.write("</TR>\n")
	
	html_file.write("</TABLE>\n")
	html_file.write("<BR/>\n\n")

	vals=funds.values;
	vals2=np.append(vals,funds2.values,2)


	df=DataMatrix(index=funds.index,data=funds.values, columns=['fund'])
	df2=DataMatrix(index=funds2.index,data=funds2.values,columns=['other'])
	df['other']=df2['other']

	corrcoef=numpy.corrcoef(funds.values[0:-1],funds2.values)
	html_file.write("<H3>Correlation=")
	print >>html_file, "%.2f\n" % corrcoef[0][1]
	html_file.write("<H3>\n")
	html_file.write("<BR/>\n\n")


	#montly returns
	mrets=tsu.monthly(funds)
	html_file.write("<H2>Monthly Returns</H2>\n")
	html_file.write("<TABLE CELLPADDING=10>\n")
	html_file.write("<TR>\n")
	html_file.write("<TH></TH>\n")
	month_names=du.getMonthNames()
	for name in month_names:
		html_file.write("<TH>"+str(name)+"</TH>\n")
	html_file.write("</TR>\n")

	i=0
	for year in years:
		html_file.write("<TR>\n")
		html_file.write("<TH>"+str(year)+"</TH>\n")
		months=du.getMonths(funds,year)
		for month in months:
			html_file.write("<TD>\n")
			print >>html_file, "%.2f\n" % (mrets[i]*100)
			html_file.write("%</TD>\n")
			i+=1
		html_file.write("</TR>\n")
	html_file.write("</TABLE>\n")
	html_file.write("<BR/>\n\n")

	#fund value graph
	fundlist=[];
	fundlist.append(funds)
	fundlist.append(funds2)
	converter.fundsToPNG(fundlist,'funds.png')
	html_file.write("<IMG SRC=\'./funds.png\'/>\n")
	html_file.write("<BR/>\n\n")
	
	#end
	html_file.write("</CENTER></BODY>\n\n")
	html_file.write("</HTML>")