Advertisement
Guest User

Untitled

a guest
Apr 26th, 2018
144
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 1.81 KB | None | 0 0
  1. from zipline.api import order_value, record, symbol
  2. import matplotlib.pyplot as plt
  3.  
  4. def initialize(context):
  5.     context.i = 0
  6.     context.asset = symbol('AAPL')
  7.  
  8.  
  9. def handle_data(context, data):
  10.     # Skip first 300 days to get full windows
  11.     context.i += 1
  12.     if context.i < 300:
  13.         return
  14.  
  15.     # Compute averages
  16.     # data.history() has to be called with the same params
  17.     # from above and returns a pandas dataframe.
  18.     short_mavg = data.history(context.asset, 'price', bar_count=100, frequency="1d").mean()
  19.     long_mavg = data.history(context.asset, 'price', bar_count=300, frequency="1d").mean()
  20.     volume = data.current(context.asset, 'volume')
  21.     if(75 > volume):
  22.         order_value(context.asset, 10000)
  23.     if(274 > 206):
  24.         order_value(context.asset, -10000)
  25.  
  26.  
  27.     # Save values for later inspection
  28.     record(AAPL=data.current(context.asset, 'price'),
  29.            short_mavg=short_mavg,
  30.            long_mavg=long_mavg)
  31.  
  32.  
  33. def analyze(context, perf):
  34.     print(perf.sortino)
  35.     print(perf.portfolio_value)
  36.     fig = plt.figure()
  37.     ax1 = fig.add_subplot(211)
  38.     perf.portfolio_value.plot(ax=ax1)
  39.     ax1.set_ylabel('portfolio value in $')
  40.  
  41.     ax2 = fig.add_subplot(212)
  42.     perf['AAPL'].plot(ax=ax2)
  43.     perf[['short_mavg', 'long_mavg']].plot(ax=ax2)
  44.  
  45.     perf_trans = perf.ix[[t != [] for t in perf.transactions]]
  46.     buys = perf_trans.ix[[t[0]['amount'] > 0 for t in perf_trans.transactions]]
  47.     sells = perf_trans.ix[
  48.         [t[0]['amount'] < 0 for t in perf_trans.transactions]]
  49.     ax2.plot(buys.index, perf.short_mavg.ix[buys.index],
  50.              '^', markersize=10, color='m')
  51.     ax2.plot(sells.index, perf.short_mavg.ix[sells.index],
  52.              'v', markersize=10, color='k')
  53.     ax2.set_ylabel('price in $')
  54.     plt.legend(loc=0)
  55.     plt.show()
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement