Last active
June 26, 2019 00:44
-
-
Save sshariff01/2339ca10e9f335e65e626c5f57e6e660 to your computer and use it in GitHub Desktop.
ML4T - Project 5
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
"""MC2-P1: Market simulator. | |
Copyright 2018, Georgia Institute of Technology (Georgia Tech) | |
Atlanta, Georgia 30332 | |
All Rights Reserved | |
Template code for CS 4646/7646 | |
Georgia Tech asserts copyright ownership of this template and all derivative | |
works, including solutions to the projects assigned in this course. Students | |
and other users of this template code are advised not to share it with others | |
or to make it available on publicly viewable websites including repositories | |
such as github and gitlab. This copyright statement should not be removed | |
or edited. | |
We do grant permission to share solutions privately with non-students such | |
as potential employers. However, sharing with other current or future | |
students of CS 7646 is prohibited and subject to being investigated as a | |
GT honor code violation. | |
-----do not edit anything above this line--- | |
Student Name: Shoabe Shariff | |
GT User ID: sshariff3 | |
GT ID: 903272097 | |
""" | |
import pandas as pd | |
import numpy as np | |
import datetime as dt | |
import os | |
from util import get_data, plot_data | |
import pdb | |
def author(): | |
return 'sshariff3' | |
def compute_portvals(orders_file = "./orders/orders-test.csv", start_val = 1000000, commission=9.95, impact=0.005): | |
# this is the function the autograder will call to test your code | |
# NOTE: orders_file may be a string, or it may be a file object. Your | |
# code should work correctly with either input | |
# TODO: Your code here | |
orders = pd.read_csv(orders_file, index_col='Date', parse_dates=True, usecols=['Date', 'Symbol', 'Order', 'Shares'], na_values=['nan']) | |
orders = orders.sort_index() | |
symbols = np.unique(orders['Symbol'].values).tolist() | |
start_date = orders.index[0] | |
end_date = orders.index[-1] | |
adjusted_close_prices = get_data(symbols, pd.date_range(start_date, end_date)) | |
adjusted_close_prices.index.name = 'Date' | |
adjusted_close_prices['PORTFOLIO'] = 0 | |
portfolio = dict.fromkeys(symbols, 0) | |
portfolio['CASH'] = start_val | |
return adjusted_close_prices.apply(lambda x: calculate_portfolio_value(x, orders, portfolio, commission, impact), axis=1, raw=False) | |
def calculate_portfolio_value(prices, orders_all, portfolio, commission, impact): | |
if prices.name in orders_all.index: | |
orders_for_the_day = orders_all.loc[orders_all.index == prices.name, ['Symbol', 'Shares', 'Order']] | |
orders_for_the_day.apply(lambda x: update_portfolio(x, prices, portfolio, commission, impact), axis=1, raw=False) | |
prices['PORTFOLIO'] = portfolio['CASH'] # Initialize to cash holdings amount | |
for sym in portfolio.keys(): | |
if sym == 'CASH': | |
continue | |
num_shares_in_portfolio = portfolio[sym] | |
prices['PORTFOLIO'] = prices['PORTFOLIO'] + num_shares_in_portfolio * prices[sym] | |
return prices['PORTFOLIO'] | |
def update_portfolio(order, prices, portfolio, commission, impact): | |
purchase_symbol = order['Symbol'] | |
stock_price = prices[purchase_symbol] | |
trade_num_shares = order['Shares'] | |
# Update Portfolio Shares and Cash Holdings | |
if order['Order'] == 'BUY': | |
portfolio[purchase_symbol] = portfolio[purchase_symbol] + trade_num_shares | |
# Apply market impact - Price goes up by impact prior to purchase | |
stock_price = stock_price * (1 + impact) | |
portfolio['CASH'] = portfolio['CASH'] - trade_num_shares * stock_price | |
else: | |
portfolio[purchase_symbol] = portfolio[purchase_symbol] - trade_num_shares | |
# Apply market impact - Price goes down by impact prior to sell | |
stock_price = stock_price * (1 - impact) | |
portfolio['CASH'] = portfolio['CASH'] + trade_num_shares * stock_price | |
# Apply commission - To be applied on every transaction, regardless of BUY or SELL | |
portfolio['CASH'] = portfolio['CASH'] - commission | |
def test_code(): | |
# this is a helper function you can use to test your code | |
# note that during autograding his function will not be called. | |
# Define input parameters | |
of = "./orders/orders2.csv" | |
sv = 1000000 | |
# Process orders | |
portvals = compute_portvals(orders_file = of, start_val = sv) | |
if isinstance(portvals, pd.DataFrame): | |
portvals = portvals[portvals.columns[0]] # just get the first column | |
else: | |
"warning, code did not return a DataFrame" | |
# Get portfolio stats | |
# Here we just fake the data. you should use your code from previous assignments. | |
start_date = dt.datetime(2008,1,1) | |
end_date = dt.datetime(2008,6,1) | |
cum_ret, avg_daily_ret, std_daily_ret, sharpe_ratio = [0.2,0.01,0.02,1.5] | |
cum_ret_SPY, avg_daily_ret_SPY, std_daily_ret_SPY, sharpe_ratio_SPY = [0.2,0.01,0.02,1.5] | |
# Compare portfolio against $SPX | |
print "Date Range: {} to {}".format(start_date, end_date) | |
print "Sharpe Ratio of Fund: {}".format(sharpe_ratio) | |
print "Sharpe Ratio of SPY : {}".format(sharpe_ratio_SPY) | |
print "Cumulative Return of Fund: {}".format(cum_ret) | |
print "Cumulative Return of SPY : {}".format(cum_ret_SPY) | |
print "Standard Deviation of Fund: {}".format(std_daily_ret) | |
print "Standard Deviation of SPY : {}".format(std_daily_ret_SPY) | |
print "Average Daily Return of Fund: {}".format(avg_daily_ret) | |
print "Average Daily Return of SPY : {}".format(avg_daily_ret_SPY) | |
print "Final Portfolio Value: {}".format(portvals[-1]) | |
if __name__ == "__main__": | |
compute_portvals() | |
# test_code() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment