Back

Explore Courses Blog Tutorials Interview Questions
0 votes
2 views
in Python by (16.4k points)
closed by

This is my First Question Here, Excuse me for my mix-ups I have been perusing Andreas Clenow's Trading Evolved, a Book which is about Backtesting and Finance utilizing Python Here is the Code and blunder that I get

%matplotlib inline

# Import Zipline functions that we need

from zipline import run_algorithm

from zipline.api import order_target_percent, symbol

# Import date and time zone libraries

from datetime import datetime

import pytz

import pandas as pd

# Import visualization

import matplotlib.pyplot as plt

def initialize(context):

    # Which stock to trade

    context.stock = symbol('AAPL')

    

    # Moving average window

    context.index_average_window = 100

    

def handle_data(context, data):

    # Request history for the stock

    equities_hist = data.history(context.stock, "close", 

                                 context.index_average_window, "1d")

    

    # Check if price is above moving average

    if equities_hist[-1] > equities_hist.mean():

        stock_weight = 1.0

    else:

        stock_weight = 0.0

    

    # Place order

    order_target_percent(context.stock, stock_weight)

def analyze(context, perf):

    fig = plt.figure(figsize=(12, 8))

    

    # First chart

    ax = fig.add_subplot(311)

    ax.set_title('Strategy Results')

    ax.semilogy(perf['portfolio_value'], linestyle='-', 

                label='Equity Curve', linewidth=3.0)

    ax.legend()

    ax.grid(False)

    

    # Second chart

    ax = fig.add_subplot(312)

    ax.plot(perf['gross_leverage'], 

            label='Exposure', linestyle='-', linewidth=1.0)

    ax.legend()

    ax.grid(True)

    # Third chart

    ax = fig.add_subplot(313)

    ax.plot(perf['returns'], label='Returns', linestyle='-.', linewidth=1.0)

    ax.legend()

    ax.grid(True)

# Set start and end date

#start_date = datetime(1996, 1, 1, tzinfo=pytz.UTC)

#end_date = datetime(2018, 12, 31, tzinfo=pytz.UTC)

#start_date = pd.to_datetime('1996-1-1', utc=True)

#end_date = pd.to_datetime('2018-12-31', utc=True)

start_date = pd.to_datetime('1996-1-1', utc=True)

end_date = pd.to_datetime('2018-12-31', utc=True)

# Fire off the backtest

results = run_algorithm(

    start=start_date, 

    end=end_date, 

    initialize=initialize, 

    analyze=analyze, 

    handle_data=handle_data, 

    capital_base=10000, 

    data_frequency = 'daily', bundle='quandl' 

Look at the error which I've received:

NoBenchmark Traceback (most recent call last) _RunAlgoError: No benchmark_spec was provided, and zipline.api.set_benchmark was not called in initialize.

Thanks in advance.

closed

4 Answers

0 votes
by (25.7k points)
selected by
 
Best answer

The error message indicates that there is no benchmark specified for the backtest, and the zipline.api.set_benchmark function was not called in the initialize function.

To fix this error, you can set a benchmark for your backtest by calling the set_benchmark function in the initialize function. The benchmark can be any valid identifier for a security or index.

Here's an updated version of your code that sets the benchmark to the S&P 500 index:

%matplotlib inline

from zipline import run_algorithm

from zipline.api import order_target_percent, symbol, set_benchmark

from datetime import datetime

import pytz

import pandas as pd

import matplotlib.pyplot as plt

def initialize(context):

    context.stock = symbol('AAPL')

    context.index_average_window = 100

    set_benchmark(symbol('^GSPC'))  # Set benchmark to S&P 500 index

def handle_data(context, data):

    equities_hist = data.history(context.stock, "close", context.index_average_window, "1d")

    if equities_hist[-1] > equities_hist.mean():

        stock_weight = 1.0

    else:

        stock_weight = 0.0

    order_target_percent(context.stock, stock_weight)

def analyze(context, perf):

    fig = plt.figure(figsize=(12, 8))

    ax = fig.add_subplot(311)

    ax.set_title('Strategy Results')

    ax.semilogy(perf['portfolio_value'], linestyle='-', label='Equity Curve', linewidth=3.0)

    ax.legend()

    ax.grid(False)

    ax = fig.add_subplot(312)

    ax.plot(perf['gross_leverage'], label='Exposure', linestyle='-', linewidth=1.0)

    ax.legend()

    ax.grid(True)

    ax = fig.add_subplot(313)

    ax.plot(perf['returns'], label='Returns', linestyle='-.', linewidth=1.0)

    ax.legend()

    ax.grid(True)

start_date = pd.to_datetime('1996-1-1', utc=True)

end_date = pd.to_datetime('2018-12-31', utc=True)

results = run_algorithm(

    start=start_date,

    end=end_date,

    initialize=initialize,

    analyze=analyze,

    handle_data=handle_data,

    capital_base=10000,

    data_frequency='daily',

    bundle='quandl'

)

By calling set_benchmark(symbol('^GSPC')), the benchmark is set to the S&P 500 index, represented by the symbol ^GSPC. You can modify the benchmark to any other valid symbol or index you want to use.

0 votes
by (26.4k points)

Try the below code:

def initialize(context):

    # Which stock to trade

    context.stock = symbol('AAPL')

    

    # Moving average window

    context.index_average_window = 100

    set_benchmark(False)

Interested to learn python in detail? Come and Join the python course.

0 votes
by (15.4k points)
The error message is indicating that there is no benchmark specified for the backtest, and the initialize function did not include a call to zipline.api.set_benchmark.

To resolve this issue, you need to set a benchmark for your backtest by including the set_benchmark function within the initialize function. This function allows you to specify a benchmark, such as a security or index, against which you can compare the performance of your trading strategy.

Here is an updated version of your code that addresses this error:

%matplotlib inline

from zipline import run_algorithm

from zipline.api import order_target_percent, symbol, set_benchmark

from datetime import datetime

import pytz

import pandas as pd

import matplotlib.pyplot as plt

def initialize(context):

    context.stock = symbol('AAPL')

    context.index_average_window = 100

    set_benchmark(symbol('^GSPC'))  # Set benchmark to S&P 500 index

def handle_data(context, data):

    equities_hist = data.history(context.stock, "close", context.index_average_window, "1d")

   if equities_hist[-1] > equities_hist.mean():

        stock_weight = 1.0

    else:

        stock_weight = 0.0

    order_target_percent(context.stock, stock_weight)

def analyze(context, perf):

    fig = plt.figure(figsize=(12, 8))

    ax = fig.add_subplot(311)

    ax.set_title('Strategy Results')

    ax.semilogy(perf['portfolio_value'], linestyle='-', label='Equity Curve', linewidth=3.0)

    ax.legend()

    ax.grid(False)

    ax = fig.add_subplot(312)

    ax.plot(perf['gross_leverage'], label='Exposure', linestyle='-', linewidth=1.0)

    ax.legend()

    ax.grid(True)

    ax = fig.add_subplot(313)

    ax.plot(perf['returns'], label='Returns', linestyle='-.', linewidth=1.0)

    ax.legend()

    ax.grid(True)

start_date = pd.to_datetime('1996-1-1', utc=True)

end_date = pd.to_datetime('2018-12-31', utc=True)

results = run_algorithm(

    start=start_date,

    end=end_date,

    initialize=initialize,

    analyze=analyze,

    handle_data=handle_data,

    capital_base=10000,

    data_frequency='daily',

    bundle='quandl'

)

By adding the line set_benchmark(symbol('^GSPC')) inside the initialize function, you specify that the benchmark for the backtest is the S&P 500 index, represented by the symbol ^GSPC. You can modify the benchmark symbol according to your preference.
0 votes
by (19k points)

Here is the correct code for your question:

%matplotlib inline

from zipline import run_algorithm

from zipline.api import order_target_percent, symbol, set_benchmark

from datetime import datetime

import pytz

import pandas as pd

import matplotlib.pyplot as plt

def initialize(context):

    context.stock = symbol('AAPL')

    context.index_average_window = 100

    set_benchmark(symbol('^GSPC'))  # Set benchmark to S&P 500 index

def handle_data(context, data):

    equities_hist = data.history(context.stock, "close", context.index_average_window, "1d")

    if equities_hist[-1] > equities_hist.mean():

        stock_weight = 1.0

    else:

        stock_weight = 0.0

    order_target_percent(context.stock, stock_weight)

def analyze(context, perf):

    fig = plt.figure(figsize=(12, 8))

    ax = fig.add_subplot(311)

    ax.set_title('Strategy Results')

    ax.semilogy(perf['portfolio_value'], linestyle='-', label='Equity Curve', linewidth=3.0)

    ax.legend()

    ax.grid(False)

    ax = fig.add_subplot(312)

    ax.plot(perf['gross_leverage'], label='Exposure', linestyle='-', linewidth=1.0)

    ax.legend()

    ax.grid(True)

    ax = fig.add_subplot(313)

    ax.plot(perf['returns'], label='Returns', linestyle='-.', linewidth=1.0)

    ax.legend()

    ax.grid(True)

start_date = pd.to_datetime('1996-1-1', utc=True)

end_date = pd.to_datetime('2018-12-31', utc=True)

results = run_algorithm(

    start=start_date,

    end=end_date,

    initialize=initialize,

    analyze=analyze,

    handle_data=handle_data,

    capital_base=10000,

    data_frequency='daily',

    bundle='quandl'

)

Related questions

0 votes
1 answer
0 votes
1 answer
0 votes
1 answer
asked Feb 6, 2023 in Others by neelimakv (32.5k points)
0 votes
1 answer
asked Feb 6, 2023 in Others by Nandini V (32.9k points)

Browse Categories

...