Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- # Code implementing a BestPossibleStrategy object (details below). It should implement testPolicy() which returns
- # a trades data frame (see below). The main part of this code should call marketsimcode as necessary to generate the
- # plots used in the report.
- import pandas as pd
- import numpy as np
- import datetime as dt
- import os
- from util import get_data, plot_data
- from marketsimcode import compute_portvals, get_portfolio_stats
- class BestPossibleStrategy(object):
- def testPolicy(self, symbol="JPM", sd=dt.datetime(2008, 1, 1), ed=dt.datetime(2009, 12, 31), sv=100000):
- """
- Method given a symbol, a start and end date, and a starting portfolio value, will give you the optimal
- trade strategy.
- :param symbol: The stock symbol to act on
- :param sd: A Datetime object that represents the start date.
- :param ed: A Datetime object that represents the end date.
- :param sv: The Start Value of the portfolio.
- :returns df_trades: A data frame whose values represent trades for each day. Legal values are
- +1000.0 indicating a BUY of 1000 shares, -1000.0 indicating a SELL of 1000 shares, and 0.0
- indicating NOTHING. Values of +2000 and -2000 for trades are also legal so long as net
- holdings are constrained to -1000, 0, and 1000.
- """
- date_range = pd.date_range(sd, ed)
- df = get_data([symbol], date_range)
- df = df.fillna(method='ffill').fillna(method='bfill')
- df_trades = df.copy()
- df_trades["PriceToday"] = np.NaN
- df_trades["PriceTomorrow"] = np.NaN
- df_trades[:] = np.NaN # make it all nan for now.
- net_holdings = 0
- # for each row in the trades (all trading days) compute what should be done by looking
- # into the future (the next day)
- for i in range(0, len(df_trades)-1):
- if df.iloc[i][symbol] < df.iloc[i+1][symbol] and net_holdings == 0:
- df_trades.iloc[i][symbol] = 1000
- net_holdings += 1000
- df_trades.iloc[i]["PriceToday"] = df.iloc[i][symbol]
- df_trades.iloc[i]["PriceTomorrow"] = df.iloc[i][symbol]
- elif df.iloc[i][symbol] < df.iloc[i+1][symbol] and net_holdings == -1000:
- df_trades.iloc[i][symbol] = 2000
- net_holdings += 2000
- df_trades.iloc[i]["PriceToday"] = df.iloc[i][symbol]
- df_trades.iloc[i]["PriceTomorrow"] = df.iloc[i+1][symbol]
- elif df.iloc[i][symbol] > df.iloc[i + 1][symbol] and net_holdings == 0:
- df_trades.iloc[i][symbol] = -1000
- net_holdings += -1000
- df_trades.iloc[i]["PriceToday"] = df.iloc[i][symbol]
- df_trades.iloc[i]["PriceTomorrow"] = df.iloc[i + 1][symbol]
- elif df.iloc[i][symbol] < df.iloc[i + 1][symbol] and net_holdings == 1000:
- df_trades.iloc[i][symbol] = -2000
- net_holdings += -2000
- df_trades.iloc[i]["PriceToday"] = df.iloc[i][symbol]
- df_trades.iloc[i]["PriceTomorrow"] = df.iloc[i + 1][symbol]
- # last day set to remove all holdings
- df_trades.iloc[-1][symbol] = -1 * net_holdings
- df_trades.iloc[-1]["PriceToday"] = df.iloc[i][symbol]
- df_trades.iloc[-1]["PriceTomorrow"] = df.iloc[i + 1][symbol]
- # TODO: If there are net holdings fix so all positions are set to 0 on that day.
- # remove the na row.s
- df_trades = df_trades.rename(columns={symbol: 'order'})
- df_trades = df_trades[['order', 'PriceToday', 'PriceTomorrow']]
- # df_trades = df_trades[symbol, "PriceToday", "PriceTomorrow"].to_frame()
- # df_trades = df_trades.to_frame()
- df_trades = df_trades.dropna()
- return df_trades
- def generate_benchmark(self, symbol="JPM", sd=dt.datetime(2008, 1, 1), ed=dt.datetime(2009, 12, 31)):
- date_range = pd.date_range(sd, ed)
- symbol = [symbol]
- df = get_data(symbol, date_range)
- # buy 1k shares on day one and return. DO nothing else.
- date = [df.index[0], df.index[len(df.index)-1]]
- order = [1000, -1000]
- benchmark_df = pd.DataFrame(data=order, index=date, columns=['order'])
- return benchmark_df
- def main():
- bps = BestPossibleStrategy()
- bps_orders = bps.testPolicy()
- bps_pv = compute_portvals(orders=bps_orders, start_val=100000, commission=0.0, impact=0.0)
- benchmark_orders = bps.generate_benchmark()
- benchmark_pv = compute_portvals(orders=benchmark_orders, start_val=100000, commission=0.0, impact=0.0)
- cr, adr, sddr, sr = get_portfolio_stats(bps_pv)
- bcr, badr, bssdr, bsr = get_portfolio_stats(benchmark_pv)
- print "portfolio: {} ".format("Benchmark")
- print "cumulative return: {} ".format(bcr)
- print "average daily return: {} ".format(badr)
- print "st.dev daily returns: {} ".format(bssdr)
- print "Sharpe Ratio: {} ".format(bsr)
- print
- print "portfolio: {} ".format("BestPossibleStrategy")
- print "cumulative return: {} ".format(cr)
- print "average daily return: {} ".format(adr)
- print "st.dev daily returns: {} ".format(sddr)
- print "Sharpe Ratio: {} ".format(sr)
- # print out a compare of stats
- print
- # print "Final Portfolio Value: {}".format(bps_pv[-1])
- # print "Final Benchmark Value: {}".format(benchmark_pv[-1])
- if __name__ == "__main__":
- main()
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement