Home > Enterprise >  What does "context" in "def myFunc(context)" mean in python
What does "context" in "def myFunc(context)" mean in python

Time:06-01

I read a book named Trading Evolved and saw this code, where there are context variables in all 3 functions.

I'm a newbie in Python and don't have a thorough Python knowledge. After searching on Google, Stackoverflow and in Zipline documentation intuitively, I still have several questions regarding the usage of this context variable.

# This ensures that our graphs will be shown properly in the notebook.
%matplotlib inline
# Import Zipline functions that we need
from zipline import run_algorithm
from zipline.api import order_target_percent, symbol
import pandas as pd

# Import date and time zone libraries
from datetime import datetime
import pytz

# Import visualization
import matplotlib.pyplot as plt

As I know it, the 3 functions below works as 3 parameters passed to the zipline function run_algorithm() at the bottom.

But I don't know where these functions get their parameters and what values they return.

I also don't know how the value of context.stock variable assigned in initialize(context) function passes to handle_data(context, data) function.

Any help would be appreciated~

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=(16, 10))

    # 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 = pd.Timestamp('1996-1-1', tz='utc')
end_date = pd.Timestamp('2022-6-1', tz='utc')

# plot theme in dark mode: bmh, classic, fivethirtyeight, ggplot, seaborn
from matplotlib import style
style.use('ggplot')
# 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'
)

CodePudding user response:

"Context" in computer speak just means a place to store the unique information this operation needs. It provides a context for the function to operate. The run_algorithm function must be creating an object to store all the information, and it gets passed to those callback functions to operate on.

CodePudding user response:

How the parameters are used and called is most likely from within the run_algorithm function as it looks like a pure abstraction function which takes a number of sequential functions and executes them one after the other.

Maybe form documentation or if the project is open source you can search from the inside of the project to get better knowledge how these are set.

As you see in the example at your post at the bottom you do not give the specified inputs to each function as you do not call the function but just declare which ones to be used by the run_algorithms function.

  • Related