Imports & Functions Required For Backtests

  • Zipline Functions
    • from zipline import run_algorithm #needed every time we run a backtest
    • from zipline.api import order_target_percent #ability to place orders in terms of target percent
    • from zipline.api import order_target #ability to place orders in terms of shares
    • from zipline.api import symbol #ability to look at stocks based on ticker
    • from zipline.api import record
    • from zipline.api import set_benchmark
    • from zipline.api import schedule_function
    • from zipline.api import date_rules
    • from zipline.api import time_rules
  • Date and Timezone Libraries
    • from datetime import datetime
    • import pytz
  • Visualization & Analysis
    • import matplotlib.pyplot as plt
    • import pyfolio as pf
  • Backtest Functions
    • Initialize
      • Executed before the backtest starts
      • Sets the parameters
        • context.stock = symbol(‘AAPL’)
        • context.stocks_to_hold = 10
        • context.index_average_window = 100
        • set_benchmark(False)
        • schedule_function(handle_data, date_rules.month_start(), time_rules.market_close()) #Trading once per month
    • Handle_data
      • Rules for when to buy, sell, and how much
    • Analyze
      • Calculates analytics and visualize results
      • PyFolio has various types of built in tear sheets, ‘returns’ is one example
      • Custom analysis can be done by creating pie and bar charts using:
        • Make pie chart for allocations
          • fig, ax1 = plt.subplots(figsize=[12, 10])
          • ax1.pie(df[‘value’], labels=df.index, shadow=True, startangle=90)
          • ax1.axis(‘equal’)
          • ax1.set_title(‘Allocation on {}’.format(day))
          • plt.show()
        • Make bar chart for open PnL
          • fig, ax1 = plt.subplots(figsize=[12, 10])
          • pnl_df = df.drop(‘cash’)
          • ax1.barh( pnl_df.index, pnl_df[‘pnl’], align=’center’, color=’green’, ecolor=’black’)
          • ax1.set_title(‘Open PnL on {}’.format(day))
          • plt.show()

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

Create your website with WordPress.com
Get started
%d bloggers like this: