Esempio n. 1
0
def test_case(of, sd, ed, ret, avg, std, sharp, fin, sv=1000000):
    portvals = compute_portvals(orders_file=of, start_val=sv)

    if not isinstance(portvals, pd.DataFrame):
        print "Test FAILED portvals not a pd.DataFrame, type: {}".format(
            type(portvals))
        return
    else:
        portvals = portvals[portvals.columns[0]]  # just get the first column

    cr, adr, sddr, sr = compute_portfolio_stats(portvals)
    act = [cr, adr, sddr, sr, portvals[-1]]
    ex = [ret, avg, std, sharp, fin]

    if pd.Timestamp(sd) != portvals.index[0]:
        print "Test FAILED start-date: {}, expected: {}, actual: {}".format(
            of, sd, portvals.index[0])
        return
    if pd.Timestamp(ed) != portvals.index[-1]:
        print "Test FAILED end-date: {}, expected: {}, actual: {}".format(
            of, ed, portvals.index[-1])
        return
    if np.allclose(ex, act):
        print "Test PASSED: {}".format(of)
    else:
        print "Test FAILED: {}, expected: {}, actual: {}".format(of, ex, act)
def optimize_portfolio(sd=dt.datetime(2008,1,1), ed=dt.datetime(2009,1,1),
    syms=['GOOG','AAPL','GLD','XOM'], gen_plot=False):

    # Read in adjusted closing prices for given symbols, date range
    dates = pd.date_range(sd, ed)
    prices_all = get_data(syms, dates)  # automatically adds SPY
    prices = prices_all[syms]  # only portfolio symbols
    prices_SPY = prices_all['SPY']  # only SPY, for comparison later

    # find the allocations for the optimal portfolio
    # note that the values here ARE NOT meant to be correct for a test case
    sv = 1000000
    rfr = 0.0
    sf = 252.0
    allocs = find_optimal_allocations(prices, sv, rfr, sf) # add code here to find the allocations
    port_val = analysis.get_portfolio_value(prices,allocs,sv)
    cr, adr, sddr, sr = analysis.compute_portfolio_stats(port_val, rfr, sf)

    # Compare daily portfolio value with SPY using a normalized plot
    if gen_plot:
        # add code to plot here
        df_temp = pd.concat([port_val, prices_SPY], keys=['Portfolio', 'SPY'], axis=1)
        pass

    return allocs, cr, adr, sddr, sr
Esempio n. 3
0
def sharpe_maximizer(allocs, prices):
    """Optimization function to be passed to the optimizer.
    
    Parameters
    ----------
        prices: daily prices for each stock in portfolio
        allocs: Allocation for each portfolio component
    
    Returns
    -------
        sharpe_ratio: Negative sharpe ratio so the minimizer finds the maximum
    
    """
    #Get portfolio statistics
    cum_ret, avg_daily_ret, std_daily_ret, sharpe_ratio = compute_portfolio_stats(
        prices, allocs)

    return -sharpe_ratio
Esempio n. 4
0
def optimize_portfolio(sd, ed, syms, gen_plot):
    """

    :param sd: dt.datetime
    :param ed: dt.datetime
    :param syms: list of strings
    :param gen_plot: boolean
    :return: tuple (allocs, cr, adr, sddr, sr)
    """
    n = len(syms)

    dates = pd.date_range(sd, ed)
    prices_all = get_data(syms, dates)
    prices = prices_all[syms]
    prices_SPY = prices_all['SPY']

    prices = prices.ffill()
    prices = prices.bfill()

    normed = prices / prices.iloc[0]

    x0 = np.ones(n) / n

    bounds = [(0.0, 1.0) for i in range(n)]
    constraints = ({'type': 'eq', 'fun': lambda x: 1 - np.sum(x)})

    allocs = minimize(f, x0, args=(normed, 0.0, 252.0), method='SLSQP', bounds=bounds,
                      constraints=constraints).x

    alloced = normed * allocs
    port_val = alloced.sum(axis=1)

    cr, adr, sddr, sr = compute_portfolio_stats(port_val=port_val)

    if gen_plot:
        df_temp = pd.concat([port_val, prices_SPY], keys=['Portfolio', 'SPY'], axis=1)
        df_temp = df_temp / df_temp.iloc[0]
        plot_data(df_temp, "Daily Portfolio Value and SPY")

    return allocs, cr, adr, sddr, sr
Esempio n. 5
0
def optimize_portfolio(sd=dt.datetime(2008, 1, 1),
                       ed=dt.datetime(2009, 1, 1),
                       syms=['GOOG', 'AAPL', 'GLD', 'XOM'],
                       gen_plot=False):
    """Simulate and optimize portfolio allocations."""
    # Read in adjusted closing prices for given symbols, date range
    dates = pd.date_range(sd, ed)
    prices_all = get_data(syms, dates)  # automatically adds SPY
    prices = prices_all[syms]  # only portfolio symbols
    prices_SPY = prices_all['SPY']  # only SPY, for comparison later

    # Get optimal allocations for sharpe ration and tehn compute portfolio stats - THE DIFFERENCE FROM MC1_P1
    allocs = find_optimal_allocations(prices)
    allocs = allocs / np.sum(
        allocs)  # normalize allocations, if they don't sum to 1.0

    # Get daily portfolio value (already normalized since we use default start_val=1.0)
    port_val = compute_portfolio_value(prices, allocs)

    # Get portfolio statistics (note: std_daily_ret = volatility)
    cum_ret, avg_daily_ret, std_daily_ret, sharpe_ratio = compute_portfolio_stats(
        prices, allocs)

    # Print statistics
    print "Start Date:", start_date
    print "End Date:", end_date
    print "Symbols:", symbols
    print "Optimal allocations:", allocs
    print "Sharpe Ratio:", sharpe_ratio
    print "Volatility (stdev of daily returns):", std_daily_ret
    print "Average Daily Return:", avg_daily_ret
    print "Cumulative Return:", cum_ret

    # Compare daily portfolio value with normalized SPY
    df_temp = pd.concat([port_val, prices_all['SPY']],
                        keys=['Portfolio', 'SPY'],
                        axis=1)
    plot_normalized_data(df_temp, "Daily portfolio value and SPY")

    return allocs, cum_ret, avg_daily_ret, std_daily_ret, sharpe_ratio
def optimize_portfolio(sd=dt.datetime(2008,1,1), ed=dt.datetime(2009,1,1), \
    syms=['GOOG','AAPL','GLD','XOM'], gen_plot=False):

    # Read in adjusted closing prices for given symbols, date range
    dates = pd.date_range(sd, ed)
    prices_all = get_data(syms, dates)  # automatically adds SPY
    prices = prices_all[syms]  # only portfolio symbols
    prices_SPY = prices_all['SPY']  # only SPY, for comparison later
    sv = 1000000

    # find the allocations for the optimal portfolio
    # note that the values here ARE NOT meant to be correct for a test case

    guess = []
    for symbols in syms:
        guess.append(1.0 / len(syms))

    bounds = []
    for symbols in syms:
        bounds.append((0.0, 1.0))

    constraints = ({'type': 'eq', 'fun': lambda x: 1.0 - np.sum(x)})
    res = spo.minimize(volatility,
                       guess,
                       args=(prices, syms),
                       bounds=bounds,
                       constraints=constraints)
    allocs = res.x

    ############################################################################################################
    # CODE FROM analysis.py
    ############################################################################################################

    # normalized data in "normalized_prices" dataframe
    normalized_prices = prices.copy()
    #print normalized_prices[0:11]

    for symbol in normalized_prices:
        normalized_prices[symbol] = (normalized_prices[symbol]) / (
            prices.at[prices.first_valid_index(), symbol])

    # normalize the SPY prices
    normalized_prices_SPY = prices_SPY.copy()  # normalized SPY for comparison
    normalized_prices_SPY = (normalized_prices_SPY) / prices_SPY[0]

    # Get daily portfolio value
    allocs_prices = normalized_prices.copy()
    i = 0
    # multiply by allocation
    for symbols in prices:
        allocs_prices[symbols] = normalized_prices[symbols] * allocs[i]
        i = i + 1

    # multiply by sv to get pos_val (position value)
    pos_val = allocs_prices.copy()
    for symbols in pos_val:
        pos_val[symbols] = pos_val[symbols] * sv

    # get daily portfolio value
    port_val = pd.DataFrame
    port_val = allocs_prices.sum(axis=1)

    # Get portfolio statistics (note: std_avg_daily_ret = volatility)
    cr, adr, sddr, sr = compute_portfolio_stats(port_val,
                                                allocs,
                                                rfr=0.0,
                                                sf=252.0)

    # Compare daily portfolio value with SPY using a normalized plot
    if gen_plot:
        # add code to plot here
        df_temp = pd.concat([port_val, normalized_prices_SPY],
                            keys=['Portfolio', 'SPY'],
                            axis=1)
        plot_data(df_temp)
        pass

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

    return allocs, cr, adr, sddr, sr