def optimize_portfolio(start_date, end_date, symbols): """Simulate and optimize portfolio allocations.""" # Read in adjusted closing prices for given symbols, date range dates = pd.date_range(start_date, end_date) prices_all = get_data(symbols, dates) # automatically adds SPY prices = prices_all[symbols] # only portfolio symbols prices_SPY = prices_all['SPY'] # only SPY, for comparison later # Get optimal allocations 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 = get_portfolio_value(prices, allocs) # Get portfolio statistics (note: std_daily_ret = volatility) cum_ret, avg_daily_ret, std_daily_ret, sharpe_ratio = get_portfolio_stats(port_val) # 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 normed_SPY = prices_SPY / prices_SPY.ix[0, :] df_temp = pd.concat([port_val, normed_SPY], keys=['Portfolio', 'SPY'], axis=1) plot_data(df_temp, title="Daily Portfolio Value and SPY")
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")
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")
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")
def test_run(): """Driver function.""" # Define input parameters start_date = '2014-06-26' end_date = '2015-11-03' orders_file = os.path.join("orders", "myorder_.csv") start_val = 10000 # Process orders portvals = compute_portvals(start_date, end_date, orders_file, start_val) print portvals['2015-08-10':'2015-10-10'] portvals_order=portvals/portvals.ix[0] portvals_order=portvals_order.rename(columns={"cash":'Portfolio'}) ax=portvals_order.plot(title="Daily Portfolio Value",label='Portfolio',color='g') if isinstance(portvals, pd.DataFrame): portvals = portvals[portvals.columns[0]] cum_ret, avg_daily_ret, std_daily_ret, sharpe_ratio = get_portfolio_stats(portvals) dates=pd.date_range(start_date, end_date) df_SPY = pd.DataFrame(index=dates) df_temp = pd.read_csv("data/SPY.csv", index_col='Date', parse_dates=True, usecols=['Date', 'Adj Close'], na_values=['nan']) df_temp = df_temp.rename(columns={'Adj Close': 'SPY'}) df_SPY = df_SPY.join(df_temp) df_SPY = df_SPY.dropna(subset=["SPY"]) df_SPY = df_SPY[['SPY']] portvals_SPY = get_portfolio_value(df_SPY, [1.0]) portvals_SPY.plot(label='SPY',ax=ax,color='r') ax.legend(loc='lower left') cum_ret_SPY, avg_daily_ret_SPY, std_daily_ret_SPY, sharpe_ratio_SPY = get_portfolio_stats(portvals_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]) plt.show()
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")
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")
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")
def test_run(): """Driver function.""" # Define input parameters start_date = '2011-01-10' end_date = '2011-12-20' orders_file = os.path.join("orders", "orders.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])
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")
def apply_market_simmulator(symbol, start_date, end_date, filename, start_val, chartName='backtesting.png', title="Data Out Sample Backtest"): # Process orders dates = pd.date_range(start_date, end_date) prices_all = get_data([symbol], dates) # automatically adds SPY prices = prices_all[symbol] # only portfolio symbols SPY_prices = prices_all['SPY'] portvals = compute_portvals(start_date, end_date, filename, 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 df_portfolio = pd.DataFrame(SPY_prices) df_portfolio['Portfolio'] = 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_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 $SPX 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_normalized_data(df_portfolio, chartName, title)
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")
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")
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")
def my_strategy_IBM(prices, predicted_prices, start_date, end_date, file, titl): ax = prices.plot(title=titl, label="price") orders = [] red_flag = 0 green_flag = 0 counter = 0 for index, row in prices.iterrows(): change = predicted_prices["Predicted Y"].ix[index] - prices["Price"].ix[index] p_change = (change / prices["Price"].ix[index]) * 100.0 if p_change > 1.0 and green_flag == 0 and red_flag == 0: plt.axvline(index, color="green") orders.append([index.strftime("%Y-%m-%d"), "IBM", "BUY", 100]) green_flag = 1 elif p_change < -1.0 and red_flag == 0 and green_flag == 0: plt.axvline(index, color="red") orders.append([index.strftime("%Y-%m-%d"), "IBM", "SELL", 100]) red_flag = 1 if counter == 5: plt.axvline(index, color="black") if red_flag == 1: orders.append([index.strftime("%Y-%m-%d"), "IBM", "BUY", 100]) red_flag = 0 elif green_flag == 1: orders.append([index.strftime("%Y-%m-%d"), "IBM", "SELL", 100]) green_flag = 0 counter = 0 elif red_flag == 1 or green_flag == 1: counter += 1 orders_file = os.path.join("orders", file + ".csv") with open(orders_file, "w") as file: wr = csv.writer(file) wr.writerow(["Date", "Symbol", "Order", "Shares"]) wr.writerows(orders) start_val = 10000 portfolio, portfolio_SPY = compute_portvals(start_date, end_date, orders_file, start_val) df_temp = pd.concat([portfolio, portfolio_SPY], axis=1) bx = df_temp.plot(title="Daily Portfolio value " + titl) bx.set_xlabel("Date") bx.set_ylabel("Normalized Price") port_vals = portfolio[portfolio.columns[0]] cum_ret, avg_daily_ret, std_daily_ret, sharpe_ratio = get_portfolio_stats(port_vals) # Simulate a $SPX-only reference portfolio to get stats portvals_SPY = get_portfolio_value(portfolio_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 $SPX 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(port_vals[-1])
def build_MACD(symbols, start_date, end_date, n_fast, n_slow, start_val): dates = pd.date_range(start_date, end_date) prices_all = get_data([symbols], dates) # automatically adds SPY prices = prices_all[symbols] # only portfolio symbols SPY_prices = prices_all['SPY'] ema_fast = pd.ewma(prices, span=n_fast, min_periods=n_slow - 1) ema_slow = pd.ewma(prices, span=n_slow, min_periods=n_slow - 1) macd = ema_fast - ema_slow macd_signal = pd.ewma(macd, span=9, min_periods=8) macd_hist = macd - macd_signal macd_df = pd.DataFrame(macd, columns=['MACD']) macd_df['Signal'] = macd_signal macd_df.dropna() plot_macd_strategy(macd_df, macd_hist, prices, symbols) # Process orders portvals = compute_portvals(start_date, end_date, filename, 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 df_portfolio = pd.DataFrame(SPY_prices) df_portfolio['Bollinger Strategy'] = compute_portvals( start_date, end_date, 'orders.txt', start_val) df_portfolio['MACD'] = 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_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 $SPX 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_normalized_data(df_portfolio)
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")
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")
def build_bollinger_band(symbols, start_date, end_date, window, start_val): dates = pd.date_range(start_date, end_date) prices_all = get_data([symbols], dates) # automatically adds SPY prices = prices_all[symbols] # only portfolio symbols port_sma = pd.rolling_mean(prices, window) port_sma_std = pd.rolling_std(prices, window) upper_band = port_sma + 2*port_sma_std lower_band = port_sma - 2*port_sma_std SPY_prices = prices_all['SPY'] SPY_sma = pd.rolling_mean(SPY_prices, window) SPY_sma_std = pd.rolling_std(SPY_prices, window) SPY_upper_band = SPY_sma + 2*SPY_sma_std SPY_lower_band = SPY_sma - 2*SPY_sma_std bollinger_df = pd.DataFrame(prices) bollinger_df['SMA'] = port_sma bollinger_df['Upper Band'] = upper_band bollinger_df['Lower Band'] = lower_band bollinger_df.plot(title="IBM Bollinger Band") plt.savefig("IBM_Bollinger.png") SPY_bollinger_df = pd.DataFrame(SPY_prices) SPY_bollinger_df['SPY-SMA'] = SPY_sma SPY_bollinger_df['SPY-Upper Band'] = SPY_upper_band SPY_bollinger_df['SPY-Lower Band'] = SPY_lower_band SPY_bollinger_df.plot(title="SPY Bollinger Band") plt.savefig("SPY_Bollinger.png") plot_bollinger_data(bollinger_df, SPY_bollinger_df, symbols, window) # Process orders portvals = compute_portvals(start_date, end_date, filename, 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 df_portfolio = pd.DataFrame(SPY_prices) #df_portfolio['Bollinger Strategy'] = compute_portvals(start_date, end_date, 'orders.txt', start_val) df_portfolio['My Strategy'] = 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_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 $SPX 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_normalized_data(df_portfolio)
def min_sharpe_ratio(allocs, prices): '''Returns the sharpe ratio of the portfolio with weights.''' port_val = get_portfolio_value(prices, allocs, start_val=1) sharpe = get_portfolio_stats(port_val)[3] return -sharpe