1
0
Fork 0

Finish project 5 marketsim successfully

master
Felix Martin 2020-10-10 09:48:08 -04:00
parent cb72af1781
commit cb9ae77ddc
2 changed files with 33 additions and 33 deletions

View File

@ -26,10 +26,6 @@ GT ID: 1337 (replace with your GT ID)
""" """
import pandas as pd import pandas as pd
import numpy as np
import datetime as dt
import os
import sys
from util import get_data, plot_data from util import get_data, plot_data
from optimize_something.optimization import calculate_stats from optimize_something.optimization import calculate_stats
@ -76,25 +72,26 @@ def get_portfolio_value(holding, prices):
return value return value
def handle_orders(orders, holding, adj_closing_prices): def handle_order(date, order, holding, prices, commission, impact):
"""Process the orders.""" """Process the order."""
for date, order in orders.iterrows(): symbol, order, shares = order
symbol, order, shares = order adj_closing_price = prices[symbol]
adj_closing_price = adj_closing_prices[symbol] cost = shares * adj_closing_price
cost = shares * adj_closing_price # Charge commission and deduct impact penalty
if order == "BUY": holding['cash'] -= (commission + impact * adj_closing_price * shares)
# print(f"Buy {shares:6} of {symbol:4} on {date}") if order == "BUY":
holding['cash'] -= cost # print(f"Buy {shares:6} of {symbol:4} on {date}")
holding[symbol] += shares holding['cash'] -= cost
elif order == "SELL": holding[symbol] += shares
# print(f"Sell {shares:6} of {symbol:4} on {date}") elif order == "SELL":
holding['cash'] += cost # print(f"Sell {shares:6} of {symbol:4} on {date}")
holding[symbol] -= shares holding['cash'] += cost
else: holding[symbol] -= shares
raise Exception("Unexpected order type.") else:
raise Exception("Unexpected order type.")
def compute_portvals(orders_file="./orders/orders-01.csv", start_val=1000000, commission=9.95, impact=0.005): def compute_portvals(orders_file, start_val=1000000, commission=9.95, impact=0.005):
orders = read_orders(orders_file) orders = read_orders(orders_file)
start_date, end_date, symbols = get_order_book_info(orders) start_date, end_date, symbols = get_order_book_info(orders)
@ -106,22 +103,17 @@ def compute_portvals(orders_file="./orders/orders-01.csv", start_val=1000000, co
holding = {s: 0 for s in symbols} holding = {s: 0 for s in symbols}
holding['cash'] = start_val holding['cash'] = start_val
orders_processed = 0 # Iterate over all trading days that are in the (inclusive) range of the
# order book dates. This implicitly ignores orders placed on non-trading
# days.
for date, values in prices.iterrows(): for date, values in prices.iterrows():
if date in orders.index: # Process orders for that day.
current_orders = orders.loc[date:date] for date, order in orders.loc[date:date].iterrows():
orders_processed += current_orders.shape[0] handle_order(date, order, holding, values, commission, impact)
handle_orders(current_orders, holding, values)
# Compute portfolio value at the end of day. # Compute portfolio value at the end of day.
values['Portval'] = get_portfolio_value(holding, values) values['Portval'] = get_portfolio_value(holding, values)
# Make sure we have processed all orders. If there was an order on a return prices[['Portval']]
# non-trading day we would currently not handle it.
assert(orders.shape[0] == orders_processed)
portvals = prices[['Portval']]
return portvals
def test_code(): def test_code():
@ -129,6 +121,7 @@ def test_code():
sv = 1000000 sv = 1000000
portvals = compute_portvals(orders_file=of, start_val=sv) portvals = compute_portvals(orders_file=of, start_val=sv)
if isinstance(portvals, pd.DataFrame): if isinstance(portvals, pd.DataFrame):
portvals = portvals[portvals.columns[0]] # just get the first column portvals = portvals[portvals.columns[0]] # just get the first column
else: else:
@ -161,5 +154,9 @@ def test_code():
print(f"Final Portfolio Value: {portvals[-1]}") print(f"Final Portfolio Value: {portvals[-1]}")
def author():
return 'felixm'
if __name__ == "__main__": if __name__ == "__main__":
test_code() test_code()

View File

@ -0,0 +1,3 @@
Date,Symbol,Order,Shares
2011-01-05,AAPL,BUY,1500
2011-01-20,AAPL,SELL,1500
1 Date Symbol Order Shares
2 2011-01-05 AAPL BUY 1500
3 2011-01-20 AAPL SELL 1500