0
0
Close the orders
orders.close()
This code starts by importing the numpy and pandas libraries. Next, it defines a function called initialize. This function is called when the code first starts up. This function sets the context variables asset and timeframe. The next function is called handle_data. This function takes two input parameters, context and data. The first input is the context, which is an Asset object and the second input is the data, which is a Dataframe.
The first thing that handle_data does is get the price data for the asset. This data is stored in the price_history object. The data has been split into 250 consecutive bar counts. Each bar count is stored in a different column in the data. The fields column in the data corresponds to the columns in the price_history object.
The next thing that handle_data does is to calculate the rolling mean and standard deviation. These values are stored in the rolling_mean and rolling_std variables.
After calculating the rolling mean and standard deviation, handle_data calculates the upper and lower bounds. These bounds are stored in the upper_bound and lower_bound variables.
If the current price of the asset is
Library: django
ython
import numpy as np
import pandas as pd
def initialize(context):
context.asset = 'EURUSD'
context.timeframe = 'M1'
def handle_data(context, data):
# Get the price data for the asset
price_history = data.history(context.asset, context.timeframe, bar_count=250, fields='close')
# Calculate the rolling mean and standard deviation
rolling_mean = price_history.mean()
rolling_std = price_history.std()
# Calculate the upper and lower bounds
upper_bound = rolling_mean + 2 * rolling_std
lower_bound = rolling_mean - 2 * rolling_std
# Check if the current price is outside the bounds
if data.current(context.asset, context.timeframe) > upper_bound:
# Sell the asset
order_target(context.asset, 0)
elif data.current(context.asset, context.timeframe) < lower_bound:
# Buy the asset
order_target(context.asset, 1)