Skip to content
- 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()
Like this:
Like Loading...
Related