Advertisement
Guest User

Untitled

a guest
Mar 19th, 2018
103
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 5.46 KB | None | 0 0
  1. # Code implementing a BestPossibleStrategy object (details below). It should implement testPolicy() which returns
  2. # a trades data frame (see below). The main part of this code should call marketsimcode as necessary to generate the
  3. # plots used in the report.
  4.  
  5. import pandas as pd
  6. import numpy as np
  7. import datetime as dt
  8. import os
  9. from util import get_data, plot_data
  10.  
  11. from marketsimcode import compute_portvals, get_portfolio_stats
  12.  
  13.  
  14. class BestPossibleStrategy(object):
  15.  
  16.     def testPolicy(self, symbol="JPM", sd=dt.datetime(2008, 1, 1), ed=dt.datetime(2009, 12, 31), sv=100000):
  17.         """
  18.        Method given a symbol, a start and end date, and a starting portfolio value, will give you the optimal
  19.        trade strategy.
  20.  
  21.        :param symbol: The stock symbol to act on
  22.        :param sd: A Datetime object that represents the start date.
  23.        :param ed: A Datetime object that represents the end date.
  24.        :param sv: The Start Value of the portfolio.
  25.  
  26.        :returns df_trades: A data frame whose values represent trades for each day. Legal values are
  27.        +1000.0 indicating a BUY of 1000 shares, -1000.0 indicating a SELL of 1000 shares, and 0.0
  28.        indicating NOTHING. Values of +2000 and -2000 for trades are also legal so long as net
  29.        holdings are constrained to -1000, 0, and 1000.
  30.  
  31.        """
  32.         date_range = pd.date_range(sd, ed)
  33.         df = get_data([symbol], date_range)
  34.         df = df.fillna(method='ffill').fillna(method='bfill')
  35.         df_trades = df.copy()
  36.         df_trades["PriceToday"] = np.NaN
  37.         df_trades["PriceTomorrow"] = np.NaN
  38.         df_trades[:] = np.NaN  # make it all nan for now.
  39.         net_holdings = 0
  40.  
  41.         # for each row in the trades (all trading days) compute what should be done by looking
  42.         # into the future (the next day)
  43.         for i in range(0, len(df_trades)-1):
  44.             if df.iloc[i][symbol] < df.iloc[i+1][symbol] and net_holdings == 0:
  45.                 df_trades.iloc[i][symbol] = 1000
  46.                 net_holdings += 1000
  47.                 df_trades.iloc[i]["PriceToday"] = df.iloc[i][symbol]
  48.                 df_trades.iloc[i]["PriceTomorrow"] = df.iloc[i][symbol]
  49.             elif df.iloc[i][symbol] < df.iloc[i+1][symbol] and net_holdings == -1000:
  50.                 df_trades.iloc[i][symbol] = 2000
  51.                 net_holdings += 2000
  52.                 df_trades.iloc[i]["PriceToday"] = df.iloc[i][symbol]
  53.                 df_trades.iloc[i]["PriceTomorrow"] = df.iloc[i+1][symbol]
  54.             elif df.iloc[i][symbol] > df.iloc[i + 1][symbol] and net_holdings == 0:
  55.                 df_trades.iloc[i][symbol] = -1000
  56.                 net_holdings += -1000
  57.                 df_trades.iloc[i]["PriceToday"] = df.iloc[i][symbol]
  58.                 df_trades.iloc[i]["PriceTomorrow"] = df.iloc[i + 1][symbol]
  59.             elif df.iloc[i][symbol] < df.iloc[i + 1][symbol] and net_holdings == 1000:
  60.                 df_trades.iloc[i][symbol] = -2000
  61.                 net_holdings += -2000
  62.                 df_trades.iloc[i]["PriceToday"] = df.iloc[i][symbol]
  63.                 df_trades.iloc[i]["PriceTomorrow"] = df.iloc[i + 1][symbol]
  64.  
  65.         # last day set to remove all holdings
  66.         df_trades.iloc[-1][symbol] = -1 * net_holdings
  67.         df_trades.iloc[-1]["PriceToday"] = df.iloc[i][symbol]
  68.         df_trades.iloc[-1]["PriceTomorrow"] = df.iloc[i + 1][symbol]
  69.  
  70.         # TODO: If there are net holdings fix so all positions are set to 0 on that day.
  71.         # remove the na row.s
  72.         df_trades = df_trades.rename(columns={symbol: 'order'})
  73.         df_trades = df_trades[['order', 'PriceToday', 'PriceTomorrow']]
  74.         # df_trades = df_trades[symbol, "PriceToday", "PriceTomorrow"].to_frame()
  75.         # df_trades = df_trades.to_frame()
  76.         df_trades = df_trades.dropna()
  77.         return df_trades
  78.  
  79.     def generate_benchmark(self, symbol="JPM", sd=dt.datetime(2008, 1, 1), ed=dt.datetime(2009, 12, 31)):
  80.         date_range = pd.date_range(sd, ed)
  81.         symbol = [symbol]
  82.         df = get_data(symbol, date_range)
  83.         # buy 1k shares on day one and return. DO nothing else.
  84.         date = [df.index[0], df.index[len(df.index)-1]]
  85.         order = [1000, -1000]
  86.         benchmark_df = pd.DataFrame(data=order, index=date, columns=['order'])
  87.         return benchmark_df
  88.  
  89.  
  90. def main():
  91.     bps = BestPossibleStrategy()
  92.     bps_orders = bps.testPolicy()
  93.     bps_pv = compute_portvals(orders=bps_orders, start_val=100000, commission=0.0, impact=0.0)
  94.  
  95.     benchmark_orders = bps.generate_benchmark()
  96.     benchmark_pv = compute_portvals(orders=benchmark_orders, start_val=100000,  commission=0.0, impact=0.0)
  97.  
  98.     cr, adr, sddr, sr = get_portfolio_stats(bps_pv)
  99.     bcr, badr, bssdr, bsr = get_portfolio_stats(benchmark_pv)
  100.  
  101.     print "portfolio:             {} ".format("Benchmark")
  102.     print "cumulative return:    {} ".format(bcr)
  103.     print "average daily return: {} ".format(badr)
  104.     print "st.dev daily returns: {} ".format(bssdr)
  105.     print "Sharpe Ratio:         {} ".format(bsr)
  106.     print
  107.     print "portfolio:             {} ".format("BestPossibleStrategy")
  108.     print "cumulative return:    {} ".format(cr)
  109.     print "average daily return: {} ".format(adr)
  110.     print "st.dev daily returns: {} ".format(sddr)
  111.     print "Sharpe Ratio:         {} ".format(sr)
  112.  
  113.     # print out a compare of stats
  114.     print
  115.     # print "Final Portfolio Value: {}".format(bps_pv[-1])
  116.     # print "Final Benchmark Value: {}".format(benchmark_pv[-1])
  117.  
  118.  
  119.  
  120. if __name__ == "__main__":
  121.     main()
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement