Ejemplo n.º 1
0
def simulateOrders(start_date, end_date, orders_file, start_val):
    # Process orders
    portvals = compute_portvals(start_date, end_date, orders_file, start_val)
    if isinstance(portvals, pd.DataFrame):
        portvals = portvals[portvals.columns[0]]  # if a DataFrame is returned select the first column to get a Series

    # Get portfolio stats
    cum_ret, avg_daily_ret, std_daily_ret, sharpe_ratio = get_portfolio_stats(portvals)

    # Simulate a $SPX-only reference portfolio to get stats
    prices_SPX = get_data(['$SPX'], pd.date_range(start_date, end_date))
    prices_SPX = prices_SPX[['$SPX']]  # remove SPY
    portvals_SPX = get_portfolio_value(prices_SPX, [1.0])
    cum_ret_SPX, avg_daily_ret_SPX, std_daily_ret_SPX, sharpe_ratio_SPX = get_portfolio_stats(portvals_SPX)

    # Compare portfolio against $SPX
    print "Data Range: {} to {}".format(start_date, end_date)
    print
    print "Sharpe Ratio of Fund: {}".format(sharpe_ratio)
    print "Sharpe Ratio of $SPX: {}".format(sharpe_ratio_SPX)
    print
    print "Cumulative Return of Fund: {}".format(cum_ret)
    print "Cumulative Return of $SPX: {}".format(cum_ret_SPX)
    print
    print "Standard Deviation of Fund: {}".format(std_daily_ret)
    print "Standard Deviation of $SPX: {}".format(std_daily_ret_SPX)
    print
    print "Average Daily Return of Fund: {}".format(avg_daily_ret)
    print "Average Daily Return of $SPX: {}".format(avg_daily_ret_SPX)
    print
    print "Final Portfolio Value: {}".format(portvals[-1])

    # Plot computed daily portfolio value
    df_temp = pd.concat([portvals, prices_SPX['$SPX']], keys=['Portfolio', 'SPY'], axis=1)
    plot_normalized_data(df_temp, title="Daily portfolio value")
Ejemplo n.º 2
0
def test_run():
    """Driver function."""
    # Define input parameters
    #start_date = '2011-01-14'
    #end_date = '2011-12-14'
    #orders_file = os.path.join("orders", "orders2.csv")
    #start_date = '2010-05-20'
    #end_date = '2012-06-30'

    #start_date = '2009-01-06'
    #end_date = '2012-06-30'
    start_date = '2009-12-31'
    end_date = '2010-12-31'

    orders_file = os.path.join("orders", "orders.csv")
    start_val = 10000

    print orders_file

    # Process orders
    portvals = compute_portvals(start_date, end_date, orders_file, start_val)
    if isinstance(portvals, pd.DataFrame):
        portvals = portvals[portvals.columns[
            0]]  # if a DataFrame is returned select the first column to get a Series

    # Get portfolio stats
    cum_ret, avg_daily_ret, std_daily_ret, sharpe_ratio = get_portfolio_stats(
        portvals)

    # Simulate a $SPX-only reference portfolio to get stats
    prices_SPX = get_data(['$SPX'], pd.date_range(start_date, end_date))
    prices_SPX = prices_SPX[['$SPX']]  # remove SPY
    portvals_SPX = get_portfolio_value(prices_SPX, [1.0])
    cum_ret_SPX, avg_daily_ret_SPX, std_daily_ret_SPX, sharpe_ratio_SPX = get_portfolio_stats(
        portvals_SPX)

    # Compare portfolio against $SPX
    print "Data Range: {} to {}".format(start_date, end_date)
    print
    print "Sharpe Ratio of Fund: {}".format(sharpe_ratio)
    print "Sharpe Ratio of $SPX: {}".format(sharpe_ratio_SPX)
    print
    print "Cumulative Return of Fund: {}".format(cum_ret)
    print "Cumulative Return of $SPX: {}".format(cum_ret_SPX)
    print
    print "Standard Deviation of Fund: {}".format(std_daily_ret)
    print "Standard Deviation of $SPX: {}".format(std_daily_ret_SPX)
    print
    print "Average Daily Return of Fund: {}".format(avg_daily_ret)
    print "Average Daily Return of $SPX: {}".format(avg_daily_ret_SPX)
    print
    print "Final Portfolio Value: {}".format(portvals[-1])

    # Plot computed daily portfolio value
    df_temp = pd.concat([portvals, prices_SPX['$SPX']],
                        keys=['Portfolio', '$SPX'],
                        axis=1)
    plot_normalized_data(df_temp, title="Daily portfolio value and $SPX")
Ejemplo n.º 3
0
def test_run():
    """Driver function."""
    # Define input parameters
    start_date = '2011-01-05'
    end_date = '2011-01-20'
    orders_file = os.path.join("", "orders_ML4T-399_train.csv")
    start_val = 1000000

    #TestCase-2 Passing perfectly
    #start_date = '2011-01-10'
    #end_date = '2011-12-20'
    #orders_file = os.path.join("orders", "orders.csv")
    #start_val = 1000000

    #TestCase-3 Passing perfectly
    #start_date = '2011-01-14'
    #end_date = '2011-12-14'
    #orders_file = os.path.join("orders", "orders2.csv")
    #start_val = 1000000

    # Process orders
    portvals = compute_portvals(start_date, end_date, orders_file, start_val)
    if isinstance(portvals, pd.DataFrame):
        portvals = portvals[portvals.columns[0]]  # if a DataFrame is returned select the first column to get a Series
    
    # Get portfolio stats
    cum_ret, avg_daily_ret, std_daily_ret, sharpe_ratio = get_portfolio_stats(portvals)

    # Simulate a $SPX-only reference portfolio to get stats
    prices_SPX = get_data(['$SPX'], pd.date_range(start_date, end_date))
    prices_SPX = prices_SPX[['$SPX']]  # remove SPY
    portvals_SPX = get_portfolio_value(prices_SPX, [1.0])
    cum_ret_SPX, avg_daily_ret_SPX, std_daily_ret_SPX, sharpe_ratio_SPX = get_portfolio_stats(portvals_SPX)

    # Compare portfolio against $SPX
    print "Data Range: {} to {}".format(start_date, end_date)
    print
    print "Sharpe Ratio of Fund: {}".format(sharpe_ratio)
    print "Sharpe Ratio of $SPX: {}".format(sharpe_ratio_SPX)
    print
    print "Cumulative Return of Fund: {}".format(cum_ret)
    print "Cumulative Return of $SPX: {}".format(cum_ret_SPX)
    print
    print "Standard Deviation of Fund: {}".format(std_daily_ret)
    print "Standard Deviation of $SPX: {}".format(std_daily_ret_SPX)
    print
    print "Average Daily Return of Fund: {}".format(avg_daily_ret)
    print "Average Daily Return of $SPX: {}".format(avg_daily_ret_SPX)
    print
    print "Final Portfolio Value: {}".format(portvals[-1])

    # Plot computed daily portfolio value
    df_temp = pd.concat([portvals, prices_SPX['$SPX']], keys=['Portfolio', '$SPX'], axis=1)
    plot_normalized_data(df_temp, title="Daily portfolio value and $SPX")
Ejemplo n.º 4
0
def test_run():
    """Driver function."""
    # Define input parameters
    orders_file = os.path.join("data", "orders.csv")
    start_val = 1000000

    # Process orders
    portvals = compute_portvals(orders_file, start_val)

    start_date = portvals.index[0]
    end_date = portvals.index[-1]

    if isinstance(portvals, pd.DataFrame):
        portvals = portvals[portvals.columns[
            0]]  # if a DataFrame is returned select the first column to get a Series

    # Get portfolio stats
    cum_ret, avg_daily_ret, std_daily_ret, sharpe_ratio = get_portfolio_stats(
        portvals)

    # Simulate a SPY-only reference portfolio to get stats
    prices_SPX = get_data(['SPY'], pd.date_range(start_date, end_date))
    prices_SPX = prices_SPX[['SPY']]  # remove SPY
    portvals_SPX = get_portfolio_value(prices_SPX, [1.0])
    cum_ret_SPX, avg_daily_ret_SPX, std_daily_ret_SPX, sharpe_ratio_SPX = get_portfolio_stats(
        portvals_SPX)

    # Compare portfolio against $SPX
    print "Data Range: {} to {}".format(start_date, end_date)
    print
    print "Sharpe Ratio of Fund: {}".format(sharpe_ratio)
    print "Sharpe Ratio of $SPX: {}".format(sharpe_ratio_SPX)
    print
    print "Cumulative Return of Fund: {}".format(cum_ret)
    print "Cumulative Return of $SPX: {}".format(cum_ret_SPX)
    print
    print "Standard Deviation of Fund: {}".format(std_daily_ret)
    print "Standard Deviation of $SPX: {}".format(std_daily_ret_SPX)
    print
    print "Average Daily Return of Fund: {}".format(avg_daily_ret)
    print "Average Daily Return of $SPX: {}".format(avg_daily_ret_SPX)
    print
    print "Final Portfolio Value: {}".format(portvals[-1])
    print "Final SPY Value: {}".format(portvals_SPX[-1] * start_val)

    # Plot computed daily portfolio value
    df_temp = pd.concat([portvals, prices_SPX['SPY']],
                        keys=['Portfolio', 'SPY'],
                        axis=1)
    plot_normalized_data(df_temp,
                         title="Daily portfolio value",
                         ylabel="Normalized Price")
Ejemplo n.º 5
0
def test_run():
	symbols = ['IBM']
	train_dates = pd.date_range('2008-1-1', '2010-12-31')
	test_dates = pd.date_range('2011-1-1', '2011-12-31')
	training = get_data(symbols, train_dates)
	testing = get_data(symbols, test_dates)
	trainingIBM = training[symbols]
	testingIBM = testing[symbols]

	testing_result = train_model(trainingIBM, testingIBM)
	ax = testing_result[['IBM', 'pred']].plot(title='Predicted market')
	ax.set_xlabel('Date')
	ax.set_ylabel('Price')
	fig = ax.get_figure()
	fig.savefig("output/predicted_market.png")

	generate_orders(testing_result)

	orders_file = os.path.join("orders", "orders.csv")
	start_val = 10000
	# Process orders
	portvals = compute_portvals('2011-1-1', '2011-12-31', orders_file, start_val)
	if isinstance(portvals, pd.DataFrame):
	    portvals = portvals[portvals.columns[0]]  # if a DataFrame is returned select the first column to get a Series
	# print portvals
	# Get portfolio stats
	cum_ret, avg_daily_ret, std_daily_ret, sharpe_ratio = get_portfolio_stats(portvals)
	# Simulate a $SPX-only reference portfolio to get stats
	prices_SPX = get_data(['$SPX'], test_dates)
	prices_SPX = prices_SPX[['$SPX']]  # remove SPY
	portvals_SPX = get_portfolio_value(prices_SPX, [1.0])
	cum_ret_SPX, avg_daily_ret_SPX, std_daily_ret_SPX, sharpe_ratio_SPX = get_portfolio_stats(portvals_SPX)

	print "Data Range: {} to {}".format('2011-1-1', '2011-12-31')
	print
	print "Sharpe Ratio of Fund: {}".format(sharpe_ratio)
	print "Sharpe Ratio of $SPX: {}".format(sharpe_ratio_SPX)
	print
	print "Cumulative Return of Fund: {}".format(cum_ret)
	print "Cumulative Return of $SPX: {}".format(cum_ret_SPX)
	print
	print "Standard Deviation of Fund: {}".format(std_daily_ret)
	print "Standard Deviation of $SPX: {}".format(std_daily_ret_SPX)
	print
	print "Average Daily Return of Fund: {}".format(avg_daily_ret)
	print "Average Daily Return of $SPX: {}".format(avg_daily_ret_SPX)
	print
	print "Final Portfolio Value: {}".format(portvals[-1])

	# Plot computed daily portfolio value
	df_temp = pd.concat([portvals, prices_SPX['$SPX']], keys=['Portfolio', '$SPX'], axis=1)
	plot_normalized_data(df_temp, title="Daily portfolio value and $SPX")
Ejemplo n.º 6
0
def test_run():
    """Driver function."""
    #start_date = '2011-01-05'
    #end_date = '2011-01-20'
    
    #start_date = '2011-01-10'
    #end_date = '2011-12-20'
    
    start_date = '2010-1-1'
    end_date = '2010-12-31'
    
    orders_file = os.path.join("orders", "ml_mc3_p2_IBM_test.csv")
    start_val = 10000

    # Process orders
    portvals = compute_portvals(start_date, end_date, orders_file, start_val)
    if isinstance(portvals, pd.DataFrame):
        portvals = portvals[portvals.columns[0]]  # if a DataFrame is returned select the first column to get a Series
    
    # Get portfolio stats
    cum_ret, avg_daily_ret, std_daily_ret, sharpe_ratio = get_portfolio_stats(portvals)

    # Simulate a SPY-only reference portfolio to get stats
    prices_SPY = get_data(['SPY'], pd.date_range(start_date, end_date))
    prices_SPY = prices_SPY[['SPY']]  # remove SPY
    portvals_SPY = get_portfolio_value(prices_SPY, [1.0])
    cum_ret_SPY, avg_daily_ret_SPY, std_daily_ret_SPY, sharpe_ratio_SPY = get_portfolio_stats(portvals_SPY)

    # Compare portfolio against SPY
    print "Data Range: {} to {}".format(start_date, end_date)
    print
    print "Sharpe Ratio of Fund: {}".format(sharpe_ratio)
    print "Sharpe Ratio of SPY: {}".format(sharpe_ratio_SPY)
    print
    print "Cumulative Return of Fund: {}".format(cum_ret)
    print "Cumulative Return of SPY: {}".format(cum_ret_SPY)
    print
    print "Standard Deviation of Fund: {}".format(std_daily_ret)
    print "Standard Deviation of SPY: {}".format(std_daily_ret_SPY)
    print
    print "Average Daily Return of Fund: {}".format(avg_daily_ret)
    print "Average Daily Return of SPY: {}".format(avg_daily_ret_SPY)
    print
    print "Final Portfolio Value: {}".format(portvals[-1])

    # Plot computed daily portfolio value
    df_temp = pd.concat([portvals, prices_SPY['SPY']], keys=['Portfolio', 'SPY'], axis=1)
    plot_normalized_data(df_temp, title="Daily portfolio value and SPY")
Ejemplo n.º 7
0
def test_run():
    """Driver function."""
    # Define input parameters
    start_date = "2011-01-05"
    end_date = "2011-01-20"
    orders_file = os.path.join("orders", "orders-short.csv")
    start_val = 1000000

    # Process orders
    portvals = compute_portvals(start_date, end_date, orders_file, start_val)
    if isinstance(portvals, pd.DataFrame):
        portvals = portvals[portvals.columns[0]]  # if a DataFrame is returned select the first column to get a Series
    # print portvals
    # Get portfolio stats
    cum_ret, avg_daily_ret, std_daily_ret, sharpe_ratio = get_portfolio_stats(portvals)

    # Simulate a $SPX-only reference portfolio to get stats

    cum_ret_SPX, avg_daily_ret_SPX, std_daily_ret_SPX, sharpe_ratio_SPX = get_portfolio_stats(portvals_SPX)

    # Compare portfolio against $SPX
    print "Data Range: {} to {}".format(start_date, end_date)
    print
    print "Sharpe Ratio of Fund: {}".format(sharpe_ratio)
    print "Sharpe Ratio of $SPX: {}".format(sharpe_ratio_SPX)
    print
    print "Cumulative Return of Fund: {}".format(cum_ret)
    print "Cumulative Return of $SPX: {}".format(cum_ret_SPX)
    print
    print "Standard Deviation of Fund: {}".format(std_daily_ret)
    print "Standard Deviation of $SPX: {}".format(std_daily_ret_SPX)
    print
    print "Average Daily Return of Fund: {}".format(avg_daily_ret)
    print "Average Daily Return of $SPX: {}".format(avg_daily_ret_SPX)
    print
    print "Final Portfolio Value: {}".format(portvals[-1])

    # Plot computed daily portfolio value
    df_temp = pd.concat([portvals, prices_SPX["$SPX"]], keys=["Portfolio", "$SPX"], axis=1)
    plot_normalized_data(df_temp, title="Daily portfolio value and $SPX")
Ejemplo n.º 8
0
def test_run():
    start_date = '2007-12-31'
    end_date = '2009-12-31'
    symbols = ['IBM']
    generate_orders(start_date, end_date, symbols)

    orders_file = os.path.join("orders", "orders.csv")
    start_val = 10000
    # Process orders
    portvals = compute_portvals(start_date, end_date, orders_file, start_val)
    if isinstance(portvals, pd.DataFrame):
        portvals = portvals[portvals.columns[0]]  # if a DataFrame is returned select the first column to get a Series
    # print portvals
    # Get portfolio stats
    cum_ret, avg_daily_ret, std_daily_ret, sharpe_ratio = get_portfolio_stats(portvals)
    # Simulate a $SPX-only reference portfolio to get stats
    prices_SPX = get_data(['$SPX'], pd.date_range(start_date, end_date))
    prices_SPX = prices_SPX[['$SPX']]  # remove SPY
    portvals_SPX = get_portfolio_value(prices_SPX, [1.0])
    cum_ret_SPX, avg_daily_ret_SPX, std_daily_ret_SPX, sharpe_ratio_SPX = get_portfolio_stats(portvals_SPX)

    print "Data Range: {} to {}".format(start_date, end_date)
    print
    print "Sharpe Ratio of Fund: {}".format(sharpe_ratio)
    print "Sharpe Ratio of $SPX: {}".format(sharpe_ratio_SPX)
    print
    print "Cumulative Return of Fund: {}".format(cum_ret)
    print "Cumulative Return of $SPX: {}".format(cum_ret_SPX)
    print
    print "Standard Deviation of Fund: {}".format(std_daily_ret)
    print "Standard Deviation of $SPX: {}".format(std_daily_ret_SPX)
    print
    print "Average Daily Return of Fund: {}".format(avg_daily_ret)
    print "Average Daily Return of $SPX: {}".format(avg_daily_ret_SPX)
    print
    print "Final Portfolio Value: {}".format(portvals[-1])

    # Plot computed daily portfolio value
    df_temp = pd.concat([portvals, prices_SPX['$SPX']], keys=['Portfolio', '$SPX'], axis=1)
    plot_normalized_data(df_temp, title="Daily portfolio value and $SPX")
Ejemplo n.º 9
0
def test_run(start_date, end_date, orders_file, start_val):
    # Process orders
    portvals = compute_portvals(start_date, end_date, orders_file, start_val)
    if isinstance(portvals, pd.DataFrame):
        portvals = portvals[portvals.columns[0]]  # if a DataFrame is returned select the first column to get a Series
    
    # Get portfolio stats
    cum_ret, avg_daily_ret, std_daily_ret, sharpe_ratio = get_portfolio_stats(portvals)

    # Simulate a $SPX-only reference portfolio to get stats
    prices_SPX = get_data(['$SPX'], pd.date_range(start_date, end_date))
    prices_SPX = prices_SPX[['$SPX']]  # remove SPY
    portvals_SPX = get_portfolio_value(prices_SPX, [1.0])
    cum_ret_SPX, avg_daily_ret_SPX, std_daily_ret_SPX, sharpe_ratio_SPX = get_portfolio_stats(portvals_SPX)

    # Compare portfolio against $SPX
    print "Data Range: {} to {}".format(start_date, end_date)
    print
    print "Sharpe Ratio of Fund: {}".format(sharpe_ratio)
    print "Sharpe Ratio of $SPX: {}".format(sharpe_ratio_SPX)
    print
    print "Cumulative Return of Fund: {}".format(cum_ret)
    print "Cumulative Return of $SPX: {}".format(cum_ret_SPX)
    print
    print "Standard Deviation of Fund: {}".format(std_daily_ret)
    print "Standard Deviation of $SPX: {}".format(std_daily_ret_SPX)
    print
    print "Average Daily Return of Fund: {}".format(avg_daily_ret)
    print "Average Daily Return of $SPX: {}".format(avg_daily_ret_SPX)
    print
    print "Final Portfolio Value: {}".format(portvals[-1])
    print
    
    # Plot computed daily portfolio value
    df_temp = pd.concat([portvals, prices_SPX['$SPX']], keys=['Portfolio', '$SPX'], axis=1)
    plot_normalized_data(df_temp, title="Daily portfolio value", ylabel="Normalized Price")
Ejemplo n.º 10
0
def test_run():
    """Driver function."""

    # Define input parameters
    start_date = '2007-12-31'
    end_date = '2009-12-31'
    stock_symbol = ["IBM"]

    #initial cash for the strategy
    start_val = 10000

    #Get stock quotation
    dates = pd.date_range(start_date, end_date)
    stock_prices = get_data(stock_symbol, dates)

    #Get bollinger indicator and trading signals
    bollinger = bollinger_indicator(stock_prices[stock_symbol[0]])
    trading_signal = bollinger_strategy(bollinger)

    #Get orders and save to csv order file
    orders = generate_trades(stock_symbol[0], start_val, bollinger,
                             trading_signal)
    orders_file = os.path.join("orders", "bollinger.csv")
    orders.to_csv(orders_file, index=False)

    #Plot strategy
    plot_bollinger_strategy(bollinger, trading_signal)

    #Measure performance of strategy
    #Process orders
    portvals = marketsim.compute_portvals(start_date, end_date, orders_file,
                                          start_val)
    portvals = portvals["_VALUE"]

    # Get portfolio stats
    cum_ret, avg_daily_ret, std_daily_ret, sharpe_ratio = get_portfolio_stats(
        portvals)

    # Simulate a $SPX-only reference portfolio to get stats
    prices_SPX = get_data(['^GSPC'], pd.date_range(start_date, end_date))
    prices_SPX = prices_SPX[['^GSPC']]  # remove SPY
    portvals_SPX = get_portfolio_value(prices_SPX, [1.0])
    cum_ret_SPX, avg_daily_ret_SPX, std_daily_ret_SPX, sharpe_ratio_SPX = get_portfolio_stats(
        portvals_SPX)

    # Compare portfolio against $SPX
    print "Data Range: {} to {}".format(start_date, end_date)
    print
    print "Sharpe Ratio of Fund: {}".format(sharpe_ratio)
    print "Sharpe Ratio of $SPX: {}".format(sharpe_ratio_SPX)
    print
    print "Cumulative Return of Fund: {}".format(cum_ret)
    print "Cumulative Return of $SPX: {}".format(cum_ret_SPX)
    print
    print "Standard Deviation of Fund: {}".format(std_daily_ret)
    print "Standard Deviation of $SPX: {}".format(std_daily_ret_SPX)
    print
    print "Average Daily Return of Fund: {}".format(avg_daily_ret)
    print "Average Daily Return of $SPX: {}".format(avg_daily_ret_SPX)
    print
    print "Final Portfolio Value: {}".format(portvals[-1])

    # Plot computed daily portfolio value
    df_temp = pd.concat([portvals, prices_SPX['^GSPC']],
                        keys=['Portfolio', '^GSPC'],
                        axis=1)
    plot_normalized_data(df_temp, title="Daily portfolio value and $SPX")
Ejemplo n.º 11
0
def test_run():
    """Driver function."""
    #plot1.1
    symbol = ['ML4t-399']
    start_date = '2008-01-01'
    end_date = '2009-12-30'
    df_data = wrap_up(symbol, start_date, end_date)
    sell_dates, buy_dates, end_dates = trading_dates(df_data, symbol[0])

    df_data['predY'] = df_data['price'] * (df_data['predY'] + 1)
    df_data['trainY'] = df_data['price'] * (df_data['Y'] + 1)
    plot = df_data.plot(y=['trainY', 'predY', 'price'],
                        color=['green', 'red', 'blue'])
    plt.title('Training Y/Price/Predicted Y plot for ML4T-399')
    plt.legend(loc=1)
    plt.show()

    #plot 1.2
    symbol = ['IBM']
    start_date = '2008-01-01'
    end_date = '2009-12-30'
    df_data = wrap_up(symbol, start_date, end_date)
    sell_dates, buy_dates, end_dates = trading_dates(df_data, symbol[0])

    df_data['predY'] = df_data['price'] * (df_data['predY'] + 1)
    df_data['trainY'] = df_data['price'] * (df_data['Y'] + 1)
    plot = df_data.plot(y=['trainY', 'predY', 'price'],
                        color=['green', 'red', 'blue'])
    plt.title('Training Y/Price/Predicted Y plot for IBM')
    plt.show()

    #plot 2 in
    symbol = ['ML4t-399']
    start_date = '2008-01-01'
    end_date = '2009-12-30'
    df_data = wrap_up(symbol, start_date, end_date)
    sell_dates, buy_dates, end_dates = trading_dates(df_data, symbol[0])
    df_data['predY'] = df_data['price'] * (df_data['predY'] + 1)
    df_data['trainY'] = df_data['price'] * (df_data['Y'] + 1)

    plot = df_data.plot(y=['trainY', 'predY', 'price'],
                        color=['yellow', 'blue', 'purple'])
    ymin, ymax = plot.get_ylim()
    plot.vlines(x=sell_dates, ymin=ymin, ymax=ymax - 1, color='r')
    plot.vlines(x=buy_dates, ymin=ymin, ymax=ymax - 1, color='g')
    plot.vlines(x=end_dates, ymin=ymin, ymax=ymax - 1, color='black')
    plt.title('Sine Data In Sample Entries/Exits')
    plt.legend(loc=1)
    plt.show()

    #plot 3 in
    start_val = 10000
    orders_file = os.path.join("orders", "orders_mc3_p2.csv")
    portvals = compute_portvals(start_date, end_date, orders_file, start_val)

    if isinstance(portvals, pd.DataFrame):
        portvals = portvals[portvals.columns[
            0]]  # if a DataFrame is returned select the first column to get a Series
    print portvals
    # Get portfolio stats
    cum_ret, avg_daily_ret, std_daily_ret, sharpe_ratio = get_portfolio_stats(
        portvals)

    # Simulate a $SPX-only reference portfolio to get stats
    prices_SPX = get_data(['$SPX'], pd.date_range(start_date, end_date))
    prices_SPX = prices_SPX[['$SPX']]  # remove SPY
    portvals_SPX = get_portfolio_value(prices_SPX, [1.0])
    cum_ret_SPX, avg_daily_ret_SPX, std_daily_ret_SPX, sharpe_ratio_SPX = get_portfolio_stats(
        portvals_SPX)

    #Compare portfolio against $SPX
    print "Data Range: {} to {}".format(start_date, end_date)
    print
    print "Sharpe Ratio of Fund: {}".format(sharpe_ratio)
    print "Sharpe Ratio of $SPX: {}".format(sharpe_ratio_SPX)
    print
    print "Cumulative Return of Fund: {}".format(cum_ret)
    print "Cumulative Return of $SPX: {}".format(cum_ret_SPX)
    print
    print "Standard Deviation of Fund: {}".format(std_daily_ret)
    print "Standard Deviation of $SPX: {}".format(std_daily_ret_SPX)
    print
    print "Average Daily Return of Fund: {}".format(avg_daily_ret)
    print "Average Daily Return of $SPX: {}".format(avg_daily_ret_SPX)
    print
    print "Final Portfolio Value: {}".format(portvals[-1])

    #Plot computed daily portfolio value
    df_temp = pd.concat([portvals, prices_SPX['$SPX']],
                        keys=['Portfolio', '$SPX'],
                        axis=1)
    plot_normalized_data(df_temp, title="Daily portfolio value and $SPX")

    #plot 4 out
    symbol = ['ML4t-399']
    start_date = '2008-01-01'
    end_date = '2009-12-30'
    df_data = wrap_up(symbol, start_date, end_date, out=True)
    sell_dates, buy_dates, end_dates = trading_dates(df_data, symbol[0])

    df_data['predY'] = df_data['price'] * (df_data['predY'] + 1)
    df_data['Y'] = df_data['price'] * (df_data['Y'] + 1)
    plot = df_data.plot(y=['Y', 'predY', 'price'])

    ymin, ymax = plot.get_ylim()
    plot.vlines(x=sell_dates, ymin=ymin, ymax=ymax - 1, color='r')
    plot.vlines(x=buy_dates, ymin=ymin, ymax=ymax - 1, color='g')
    plot.vlines(x=end_dates, ymin=ymin, ymax=ymax - 1, color='black')
    plt.title('Sine Data Out of Sample Entries/Exits')
    plt.show()

    #plot 5 out
    start_date = '2010-01-01'
    end_date = '2010-12-30'
    start_val = 100000
    orders_file = os.path.join("orders", "orders_mc3_p2.csv")
    portvals = compute_portvals(start_date, end_date, orders_file, start_val)

    if isinstance(portvals, pd.DataFrame):
        portvals = portvals[portvals.columns[
            0]]  # if a DataFrame is returned select the first column to get a Series
    print portvals
    # Get portfolio stats
    cum_ret, avg_daily_ret, std_daily_ret, sharpe_ratio = get_portfolio_stats(
        portvals)

    # Simulate a $SPX-only reference portfolio to get stats
    prices_SPX = get_data(['$SPX'], pd.date_range(start_date, end_date))
    prices_SPX = prices_SPX[['$SPX']]  # remove SPY
    portvals_SPX = get_portfolio_value(prices_SPX, [1.0])
    cum_ret_SPX, avg_daily_ret_SPX, std_daily_ret_SPX, sharpe_ratio_SPX = get_portfolio_stats(
        portvals_SPX)

    #Compare portfolio against $SPX
    print "Data Range: {} to {}".format(start_date, end_date)
    print
    print "Sharpe Ratio of Fund: {}".format(sharpe_ratio)
    print "Sharpe Ratio of $SPX: {}".format(sharpe_ratio_SPX)
    print
    print "Cumulative Return of Fund: {}".format(cum_ret)
    print "Cumulative Return of $SPX: {}".format(cum_ret_SPX)
    print
    print "Standard Deviation of Fund: {}".format(std_daily_ret)
    print "Standard Deviation of $SPX: {}".format(std_daily_ret_SPX)
    print
    print "Average Daily Return of Fund: {}".format(avg_daily_ret)
    print "Average Daily Return of $SPX: {}".format(avg_daily_ret_SPX)
    print
    print "Final Portfolio Value: {}".format(portvals[-1])

    #Plot computed daily portfolio value
    df_temp = pd.concat([portvals, prices_SPX['$SPX']],
                        keys=['Portfolio', '$SPX'],
                        axis=1)
    plot_normalized_data(df_temp, title="Daily portfolio value and $SPX")

    #plot 6 in
    symbol = ['IBM']
    start_date = '2008-01-01'
    end_date = '2009-12-30'
    df_data = wrap_up(symbol, start_date, end_date)
    sell_dates, buy_dates, end_dates = trading_dates(df_data, symbol[0])
    df_data['predY'] = df_data['price'] * (df_data['predY'] + 1)
    df_data['trainY'] = df_data['price'] * (df_data['Y'] + 1)
    plot = df_data.plot(y=['trainY', 'predY', 'price'])
    ymin, ymax = plot.get_ylim()
    plot.vlines(x=sell_dates, ymin=ymin, ymax=ymax - 1, color='r')
    plot.vlines(x=buy_dates, ymin=ymin, ymax=ymax - 1, color='g')
    plot.vlines(x=end_dates, ymin=ymin, ymax=ymax - 1, color='black')
    plt.title('IBM Data In Sample Entries/Exits')
    plt.show()
    ##
    #plot 7 in
    start_val = 10000
    orders_file = os.path.join("orders", "orders_mc3_p2.csv")
    portvals = compute_portvals(start_date, end_date, orders_file, start_val)

    if isinstance(portvals, pd.DataFrame):
        portvals = portvals[portvals.columns[
            0]]  # if a DataFrame is returned select the first column to get a Series
    print portvals
    # Get portfolio stats
    cum_ret, avg_daily_ret, std_daily_ret, sharpe_ratio = get_portfolio_stats(
        portvals)

    # Simulate a $SPX-only reference portfolio to get stats
    prices_SPX = get_data(['$SPX'], pd.date_range(start_date, end_date))
    prices_SPX = prices_SPX[['$SPX']]  # remove SPY
    portvals_SPX = get_portfolio_value(prices_SPX, [1.0])
    cum_ret_SPX, avg_daily_ret_SPX, std_daily_ret_SPX, sharpe_ratio_SPX = get_portfolio_stats(
        portvals_SPX)

    #Compare portfolio against $SPX
    print "Data Range: {} to {}".format(start_date, end_date)
    print
    print "Sharpe Ratio of Fund: {}".format(sharpe_ratio)
    print "Sharpe Ratio of $SPX: {}".format(sharpe_ratio_SPX)
    print
    print "Cumulative Return of Fund: {}".format(cum_ret)
    print "Cumulative Return of $SPX: {}".format(cum_ret_SPX)
    print
    print "Standard Deviation of Fund: {}".format(std_daily_ret)
    print "Standard Deviation of $SPX: {}".format(std_daily_ret_SPX)
    print
    print "Average Daily Return of Fund: {}".format(avg_daily_ret)
    print "Average Daily Return of $SPX: {}".format(avg_daily_ret_SPX)
    print
    print "Final Portfolio Value: {}".format(portvals[-1])

    #Plot computed daily portfolio value
    df_temp = pd.concat([portvals, prices_SPX['$SPX']],
                        keys=['Portfolio', '$SPX'],
                        axis=1)
    plot_normalized_data(df_temp, title="Daily portfolio value and $SPX")
    ##

    #plot 8 out
    symbol = ['IBM']
    start_date = '2008-01-01'
    end_date = '2009-12-31'
    df_data = wrap_up(symbol, start_date, end_date, out=True)
    sell_dates, buy_dates, end_dates = trading_dates(df_data, symbol[0])
    df_data['predY'] = df_data['price'] * (df_data['predY'] + 1)
    df_data['Y'] = df_data['price'] * (df_data['Y'] + 1)
    plot = df_data.plot(y=['Y', 'predY', 'price'])
    ymin, ymax = plot.get_ylim()
    plot.vlines(x=sell_dates, ymin=ymin, ymax=ymax - 1, color='r')
    plot.vlines(x=buy_dates, ymin=ymin, ymax=ymax - 1, color='g')
    plot.vlines(x=end_dates, ymin=ymin, ymax=ymax - 1, color='black')
    plt.title('IBM Data Out Sample Entries/Exits')
    plt.show()

    #
    #plot 9 out
    start_date = '2010-01-01'
    end_date = '2010-12-31'
    start_val = 100000
    orders_file = os.path.join("orders", "orders_mc3_p2.csv")
    portvals = compute_portvals(start_date, end_date, orders_file, start_val)

    if isinstance(portvals, pd.DataFrame):
        portvals = portvals[portvals.columns[
            0]]  # if a DataFrame is returned select the first column to get a Series
    print portvals
    # Get portfolio stats
    cum_ret, avg_daily_ret, std_daily_ret, sharpe_ratio = get_portfolio_stats(
        portvals)

    # Simulate a $SPX-only reference portfolio to get stats
    prices_SPX = get_data(['$SPX'], pd.date_range(start_date, end_date))
    prices_SPX = prices_SPX[['$SPX']]  # remove SPY
    portvals_SPX = get_portfolio_value(prices_SPX, [1.0])
    cum_ret_SPX, avg_daily_ret_SPX, std_daily_ret_SPX, sharpe_ratio_SPX = get_portfolio_stats(
        portvals_SPX)

    #Compare portfolio against $SPX
    print "Data Range: {} to {}".format(start_date, end_date)
    print
    print "Sharpe Ratio of Fund: {}".format(sharpe_ratio)
    print "Sharpe Ratio of $SPX: {}".format(sharpe_ratio_SPX)
    print
    print "Cumulative Return of Fund: {}".format(cum_ret)
    print "Cumulative Return of $SPX: {}".format(cum_ret_SPX)
    print
    print "Standard Deviation of Fund: {}".format(std_daily_ret)
    print "Standard Deviation of $SPX: {}".format(std_daily_ret_SPX)
    print
    print "Average Daily Return of Fund: {}".format(avg_daily_ret)
    print "Average Daily Return of $SPX: {}".format(avg_daily_ret_SPX)
    print
    print "Final Portfolio Value: {}".format(portvals[-1])

    #Plot computed daily portfolio value
    df_temp = pd.concat([portvals, prices_SPX['$SPX']],
                        keys=['Portfolio', '$SPX'],
                        axis=1)
    plot_normalized_data(df_temp, title="Daily portfolio value and $SPX")
Ejemplo n.º 12
0
def test_run():
    """Driver function."""
    global trades_df
    # Define Date Parameters
    start_date = '2007-12-31'
    end_date = '2009-12-31'
    dates = pd.date_range(start_date, end_date)
    # Set Starting Cash Value
    start_val = 10000
    # Set Starting Symbols
    symbols = ['IBM']
    # Set up Prices DataFrame
    df = get_data(symbols, dates)
    # IBM rolling_mean (rolling mean)
    rolling_mean_IBM = get_rolling_mean(df['IBM'], window=20)
    # IBM rolling standard deviation
    rolling_std_IBM = get_rolling_std(df['IBM'], window=20)
    # Upper and Lower Bollinger Bands
    upper_band, lower_band = get_bollinger_bands(rolling_mean_IBM,
                                                 rolling_std_IBM)
    # Plot raw SPY values, rolling mean and Bollinger Bands
    ax = df['IBM'].plot(title="Bollinger Bands", label='IBM')
    rolling_mean_IBM.plot(label='SMA', ax=ax, color='y')
    upper_band.plot(label='Upper Band', ax=ax, color='c')
    lower_band.plot(label='Lower Band', ax=ax, color='c')
    # Get short entries/exits
    get_shorts(upper_band, rolling_mean_IBM, df)
    # Get long entries/exits
    get_longs(lower_band, rolling_mean_IBM, df)

    # Process orders
    trades_df = trades_df.sort('Date')
    portvals = compute_portvals(start_date, end_date, trades_df, start_val)
    if isinstance(portvals, pd.DataFrame):
        portvals = portvals[portvals.columns[
            0]]  # if a DataFrame is returned select the first column to get a Series

    # Get portfolio stats
    cum_ret, avg_daily_ret, std_daily_ret, sharpe_ratio = get_portfolio_stats(
        portvals)

    # Simulate a $SPX-only reference portfolio to get stats
    prices_SPX = get_data(['$SPX'], pd.date_range(start_date, end_date))
    prices_SPX = prices_SPX[['$SPX']]  # remove SPY
    portvals_SPX = get_portfolio_value(prices_SPX, [1.0])
    cum_ret_SPX, avg_daily_ret_SPX, std_daily_ret_SPX, sharpe_ratio_SPX = get_portfolio_stats(
        portvals_SPX)

    # Compare portfolio against $SPX
    print "Data Range: {} to {}".format(start_date, end_date)
    print
    print "Sharpe Ratio of Fund: {}".format(sharpe_ratio)
    print "Sharpe Ratio of $SPX: {}".format(sharpe_ratio_SPX)
    print
    print "Cumulative Return of Fund: {}".format(cum_ret)
    print "Cumulative Return of $SPX: {}".format(cum_ret_SPX)
    print
    print "Standard Deviation of Fund: {}".format(std_daily_ret)
    print "Standard Deviation of $SPX: {}".format(std_daily_ret_SPX)
    print
    print "Average Daily Return of Fund: {}".format(avg_daily_ret)
    print "Average Daily Return of $SPX: {}".format(avg_daily_ret_SPX)
    print
    print "Final Portfolio Value: {}".format(portvals[-1])

    # Plot 1
    ax.set_xlabel("Date")
    ax.set_ylabel("Price")
    ax.legend(loc='upper left')
    plt.show()

    # Plot 2
    df_temp = pd.concat([portvals, prices_SPX['$SPX']],
                        keys=['Portfolio', '$SPX'],
                        axis=1)
    plot_normalized_data(df_temp, title="Daily portfolio value and $SPX")
Ejemplo n.º 13
0
def test_run():
    """Driver function."""
    
    # Define input parameters
    start_date = '2007-12-31'
    end_date = '2009-12-31'
    stock_symbol = ["IBM"]
       
    #initial cash for the strategy
    start_val = 10000
    
    #Get stock quotation
    dates =  pd.date_range(start_date, end_date)
    stock_prices = get_data(stock_symbol, dates)
    
    #Get bollinger indicator and trading signals    
    bollinger = bollinger_indicator(stock_prices[ stock_symbol[0] ])    
    trading_signal = bollinger_strategy( bollinger )

    #Get orders and save to csv order file
    orders = generate_trades(stock_symbol[0], start_val, bollinger, trading_signal)
    orders_file = os.path.join("orders", "bollinger.csv")    
    orders.to_csv(orders_file, index=False)
    
    #Plot strategy
    plot_bollinger_strategy( bollinger, trading_signal )
    
    #Measure performance of strategy
    #Process orders
    portvals = marketsim.compute_portvals(start_date, end_date, orders_file, start_val)
    portvals = portvals[ "_VALUE" ]
    
    # Get portfolio stats
    cum_ret, avg_daily_ret, std_daily_ret, sharpe_ratio = get_portfolio_stats(portvals)

    # Simulate a $SPX-only reference portfolio to get stats
    prices_SPX = get_data(['^GSPC'], pd.date_range(start_date, end_date))
    prices_SPX = prices_SPX[['^GSPC']]  # remove SPY
    portvals_SPX = get_portfolio_value(prices_SPX, [1.0])
    cum_ret_SPX, avg_daily_ret_SPX, std_daily_ret_SPX, sharpe_ratio_SPX = get_portfolio_stats(portvals_SPX)

    # Compare portfolio against $SPX
    print "Data Range: {} to {}".format(start_date, end_date)
    print
    print "Sharpe Ratio of Fund: {}".format(sharpe_ratio)
    print "Sharpe Ratio of $SPX: {}".format(sharpe_ratio_SPX)
    print
    print "Cumulative Return of Fund: {}".format(cum_ret)
    print "Cumulative Return of $SPX: {}".format(cum_ret_SPX)
    print
    print "Standard Deviation of Fund: {}".format(std_daily_ret)
    print "Standard Deviation of $SPX: {}".format(std_daily_ret_SPX)
    print
    print "Average Daily Return of Fund: {}".format(avg_daily_ret)
    print "Average Daily Return of $SPX: {}".format(avg_daily_ret_SPX)
    print
    print "Final Portfolio Value: {}".format(portvals[-1])

    # Plot computed daily portfolio value
    df_temp = pd.concat([portvals, prices_SPX['^GSPC']], keys=['Portfolio', '^GSPC'], axis=1)
    plot_normalized_data(df_temp, title="Daily portfolio value and $SPX")