Package: zipline-tej
InstallationUsed packages and environmentMain package: ZiplinePython 3.8 or above (currently support up to 3.11)Microsoft Windows OS or macOS or LinuxOther Python dependency packages: Pandas, Numpy, Logbook, Exchange-calendars, etc.How to install Zipline Reloaded modified by TEJWe're going to illustrate under anaconda environment, so we suggest usingAnacondaas development environment.Download dependency packages.Windows(zipline-tej.yml)Mac(zipline-tej_mac.yml)Start an Anaconda (base) prompt, create an virtual environment and install the appropriate versions of packages:
(Westronglyrecommand using virtual environment to keep every project independent.)(reason)Windows Users
# change directionary to the folder exists zipline-tej.yml
$ cd <C:\Users\username\Downloads>

# create virtual env
$ conda env create -f zipline-tej.yml

# activate virtual env
$ conda activate zipline-tej
Mac Users
# change directionary to the folder exists zipline-tej_mac.yml
$ cd <C:\Users\username\Downloads>

# create virtual env
$ conda env create -f zipline-tej_mac.yml

# activate virtual env
$ conda activate zipline-tejAlso, if you are familiar with Python enough, you can create a virtual environment without zipline-tej.yml and here's the sample :# create virtual env
$ conda create -n <env_name> python=3.10

# activate virtual env
$ conda activate <env_name>

# download dependency packages
$ pip install zipline-tejWhile encountering environment problems, we provided a consistent and stable environment onDocker hub.For users that using docker, we briefly introduce how to download and use it.First of all, please download and installdocker-desktop.1. Start docker-desktop. (Registration is not must.)

2. Select the "images" on the leftside and search "tej87681088/tquant" and click "Pull".

3. After the image was downloaded, click the "run" icon the enter the optional settings.

3-1. Contaner-name: whatever you want.

3-2. Ports: the port to connect, "8888" is recommended.

3-3. Volumes: the place to store files. (You can create volume first on the left side.)

e.g. created a volume named "data", host path enter "data", container path "/app" is recommended.

4. Select the "Containers" leftside, the click the one which its image name is tej87681088/tquant

5. In its "Logs" would show an url like 
http://127.0.0.1:8888/tree?token=XXXXXXXXXXXXXXXXXXXXXXXXXXXXXX

6. Go to your browser and enter "http://127.0.0.1:<port_you_set_in_step_3-2>/tree?token=XXXXXXXXXXXXXXXXXXXXXXXXXXXXXX"

6-1. If your port is 8888, you can just click the hyperlink.

7. Start develop your strategy!

NOTICE: Next time, we just need to reproduce step4 to step6.Quick startCLI InterfaceThe following code implements a simple buy-and-hold trading algorithm.fromzipline.apiimportorder,record,symboldefinitialize(context):context.asset=symbol("2330")defhandle_data(context,data):order(context.asset,10)record(TSMC=data.current(context.asset,"price"))defanalyze(context=None,results=None):importmatplotlib.pyplotasplt# Plot the portfolio and asset data.ax1=plt.subplot(211)results.portfolio_value.plot(ax=ax1)ax1.set_ylabel("Portfolio value (TWD)")ax2=plt.subplot(212,sharex=ax1)results.TSMC.plot(ax=ax2)ax2.set_ylabel("TSMC price (TWD)")# Show the plot.plt.gcf().set_size_inches(18,8)plt.show()You can then run this algorithm using the Zipline CLI. But first, you need to download some market data with historical prices and trading volumes:Before ingesting data, you have to set some environment variables as follow:# setting TEJAPI_KEY to get permissions loading data
$ set TEJAPI_KEY=<your_key>
$ set TEJAPI_BASE=https://api.tej.com.tw

# setting download ticker
$ set ticker=2330 2317

# setting backtest period
$ set mdate=20200101 20220101Ingest and run backtesting algorithm$ zipline ingest -b tquant
$ zipline run -f buy_and_hold.py  --start 20200101 --end 20220101 -o bah.pickle --no-benchmark --no-treasuryThen, the resulting performance DataFrame is saved as bah.pickle, which you can load and analyze from Python.More useful zipline commandsBefore callingziplinein CLI, be sure that TEJAPI_KEY and TEJAPI_BASE were set.
Usezipline --helpto get more information.For example :
We want to know how to usezipline run, we can run as follow:zipline run --helpUsage: zipline run [OPTIONS]
  Run a backtest for the given algorithm.

Options:
  -f, --algofile FILENAME         The file that contains the algorithm to run.
  -t, --algotext TEXT             The algorithm script to run.
  -D, --define TEXT               Define a name to be bound in the namespace
                                  before executing the algotext. For example
                                  '-Dname=value'. The value may be any python
                                  expression. These are evaluated in order so
                                  they may refer to previously defined names.
  --data-frequency [daily|minute]
                                  The data frequency of the simulation.
                                  [default: daily]
  --capital-base FLOAT            The starting capital for the simulation.
                                  [default: 10000000.0]
  -b, --bundle BUNDLE-NAME        The data bundle to use for the simulation.
                                  [default: tquant]
  --bundle-timestamp TIMESTAMP    The date to lookup data on or before.
                                  [default: <current-time>]
  -bf, --benchmark-file FILE      The csv file that contains the benchmark
                                  returns
  --benchmark-symbol TEXT         The symbol of the instrument to be used as a
                                  benchmark (should exist in the ingested
                                  bundle)
  --benchmark-sid INTEGER         The sid of the instrument to be used as a
                                  benchmark (should exist in the ingested
                                  bundle)
  --no-benchmark                  If passed, use a benchmark of zero returns.
  -bf, --treasury-file FILE       The csv file that contains the treasury
                                  returns
  --treasury-symbol TEXT          The symbol of the instrument to be used as a
                                  treasury (should exist in the ingested
                                  bundle)
  --treasury-sid INTEGER          The sid of the instrument to be used as a
                                  treasury (should exist in the ingested
                                  bundle)
  --no-treasury                   If passed, use a treasury of zero returns.
  -s, --start DATE                The start date of the simulation.
  -e, --end DATE                  The end date of the simulation.
  -o, --output FILENAME           The location to write the perf data. If this
                                  is '-' the perf will be written to stdout.
                                  [default: -]
  --trading-calendar TRADING-CALENDAR
                                  The calendar you want to use e.g. TEJ_XTAI.
                                  TEJ_XTAI is the default.
  --print-algo / --no-print-algo  Print the algorithm to stdout.
  --metrics-set TEXT              The metrics set to use. New metrics sets may
                                  be registered in your extension.py.
  --blotter TEXT                  The blotter to use.  [default: default]
  --help                          Show this message and exit.New add tickers$ zipline add -t "<ticker_wants_to_add>"If tickers are more than 1 ticker, split them apart by " " or ","  or ";".For more detail usezipline add --help.Display bundle-info$ zipline bundle-infoTo show what the tickers are there in newest bundle.For more detail usezipline bundle-info --help.Switch bundleBefore using switch, usezipline bundlesto get the timestamp of each folder.$ zipline switch -t "<The_timestamp_of_the_folder_want_to_use>"Due to zipline only using the newest foler, switch can make previous folder become newest.For more detail usezipline switch --help.Update bundle$ zipline updateTo update the bundle information to newest date.For more detail usezipline update --help.Jupyter NotebookChange Anaconda kernelSince we've downloaded package "nb_conda_kernels", we should be able to change kernel in jupyter notebook.How to new a notebook using specific kernel(1) Open anaconda prompt(2) Enter the command as follow :# First one can be ignore if already in environment of zipline-tej
$ conda activate zipline-tej 
# start a jupyter notebook
$ jupyter notebook(3) Start a notebook and select Python[conda env:zipline-tej](4)(Optional) If you have already written a notebook, you can open it and  change kernel by clicking the "Kernel" in menu and "Change kernel" to select the specfic kernel.Set environment variables TEJAPI_KEY, ticker and mdate* ticker would be your target ticker symbol, and it should be a string. If there're more than one ticker needed, use " ", "," or ";" to split them apart.* mdate refers the begin date and end date, use " ", "," or ";" to split them apart.In[1]:importosos.environ['TEJAPI_KEY']=<your_key>os.environ['ticker']='2330 2317'os.environ['mdate']='20200101 20220101'Call ingest to download data to ~\.ziplineIn[2]:!ziplineingest-btquant[Out]:Mergingdailyequityfiles:[YYYY-MM-DDHH:mm:ss.ssssss]INFO:zipline.data.bundles.core:Ingestingtquant.Design the backtesting strategyIn[3]:fromzipline.apiimportorder,record,symboldefinitialize(context):context.asset=symbol("2330")defhandle_data(context,data):order(context.asset,10)record(TSMC=data.current(context.asset,"price"))defanalyze(context=None,results=None):importmatplotlib.pyplotasplt# Plot the portfolio and asset data.ax1=plt.subplot(211)results.portfolio_value.plot(ax=ax1)ax1.set_ylabel("Portfolio value (TWD)")ax2=plt.subplot(212,sharex=ax1)results.TSMC.plot(ax=ax2)ax2.set_ylabel("TSMC price (TWD)")# Show the plot.plt.gcf().set_size_inches(18,8)plt.show()Run backtesting algorithm and plotIn[4]:fromziplineimportrun_algorithmimportpandasaspdfromzipline.utils.calendar_utilsimportget_calendartrading_calendar=get_calendar('TEJ_XTAI')start=pd.Timestamp('20200103',tz='utc')end=pd.Timestamp('20211230',tz='utc')result=run_algorithm(start=start,end=end,initialize=initialize,capital_base=1000000,handle_data=handle_data,bundle='tquant',trading_calendar=trading_calendar,analyze=analyze,data_frequency='daily')[Out]:Show trading processIn[5]:result[Out]:period_openperiod_closestarting_valueending_valuestarting_cashending_cashportfolio_valuelongs_countshorts_countlong_value...treasury_period_returntrading_daysperiod_labelalgo_volatilitybenchmark_period_returnbenchmark_volatilityalgorithm_period_returnalphabetasharpe2020-01-03 05:30:00+00:002020-01-03 01:01:00+00:002020-01-03 05:30:00+00:000.00.01.000000e+061.000000e+061.000000e+06000.0...0.012020-01NaN0.0NaN0.000000NoneNoneNaN2020-01-06 05:30:00+00:002020-01-06 01:01:00+00:002020-01-06 05:30:00+00:000.03320.01.000000e+069.966783e+059.999983e+05103320.0...0.022020-010.0000190.00.0-0.000002NoneNone-11.2249722020-01-07 05:30:00+00:002020-01-07 01:01:00+00:002020-01-07 05:30:00+00:003320.06590.09.966783e+059.933817e+059.999717e+05106590.0...0.032020-010.0002370.00.0-0.000028NoneNone-10.0385142020-01-08 05:30:00+00:002020-01-08 01:01:00+00:002020-01-08 05:30:00+00:006590.09885.09.933817e+059.900850e+059.999700e+05109885.0...0.042020-010.0002030.00.0-0.000030NoneNone-9.2981282020-01-09 05:30:00+00:002020-01-09 01:01:00+00:002020-01-09 05:30:00+00:009885.013500.09.900850e+059.867083e+051.000208e+061013500.0...0.052020-010.0017540.00.00.000208NoneNone5.986418..................................................................2021-12-24 05:30:00+00:002021-12-24 01:01:00+00:002021-12-24 05:30:00+00:002920920.02917320.0-1.308854e+06-1.314897e+061.602423e+06102917320.0...0.04842021-120.2327910.00.00.602423NoneNone1.1707432021-12-27 05:30:00+00:002021-12-27 01:01:00+00:002021-12-27 05:30:00+00:002917320.02933040.0-1.314897e+06-1.320960e+061.612080e+06102933040.0...0.04852021-120.2325770.00.00.612080NoneNone1.1828642021-12-28 05:30:00+00:002021-12-28 01:01:00+00:002021-12-28 05:30:00+00:002933040.02982750.0-1.320960e+06-1.327113e+061.655637e+06102982750.0...0.04862021-120.2330860.00.00.655637NoneNone1.2379582021-12-29 05:30:00+00:002021-12-29 01:01:00+00:002021-12-29 05:30:00+00:002982750.02993760.0-1.327113e+06-1.333276e+061.660484e+06102993760.0...0.04872021-120.2328500.00.00.660484NoneNone1.2431762021-12-30 05:30:00+00:002021-12-30 01:01:00+00:002021-12-30 05:30:00+00:002993760.02995050.0-1.333276e+06-1.339430e+061.655620e+06102995050.0...0.04882021-120.2326290.00.00.655620NoneNone1.235305488 rows × 38 columnsMore Zipline TutorialsFor moretutorialsSuggestionsTo get TEJAPI_KEY(link)TEJ Official Website