Factors can be combined, both with other Factors and with scalar values, via any of the builtin mathematical operators (+, -, *, etc). This makes it easy to write complex expressions that combine multiple Factors. For example, constructing a Factor that computes the average of two other Factors is simply:
>>> f1 = SomeFactor(...)
>>> f2 = SomeOtherFactor(...)
>>> average = (f1 + f2) / 2.0
In this lesson, we will create a pipeline that creates a relative_difference
factor by combining a 10-day average factor and a 30-day average factor.
As usual, let's start with our imports:
from zipline.pipeline import Pipeline, EquityPricing
from zipline.research import run_pipeline
from zipline.pipeline.factors import SimpleMovingAverage
For this example, we need two factors: a 10-day mean close price factor, and a 30-day one:
mean_close_10 = SimpleMovingAverage(inputs=EquityPricing.close, window_length=10)
mean_close_30 = SimpleMovingAverage(inputs=EquityPricing.close, window_length=30)
Then, let's create a percent difference factor by combining our mean_close_30
factor with our mean_close_10
factor.
percent_difference = (mean_close_10 - mean_close_30) / mean_close_30
In this example, percent_difference
is still a Factor
even though it's composed as a combination of more primitive factors. We can add percent_difference
as a column in our pipeline. Let's define make_pipeline
to create a pipeline with percent_difference
as a column (and not the mean close factors):
def make_pipeline():
mean_close_10 = SimpleMovingAverage(inputs=EquityPricing.close, window_length=10)
mean_close_30 = SimpleMovingAverage(inputs=EquityPricing.close, window_length=30)
percent_difference = (mean_close_10 - mean_close_30) / mean_close_30
return Pipeline(
columns={
'percent_difference': percent_difference
}
)
Let's see what the new output looks like:
result = run_pipeline(make_pipeline(), start_date='2015-05-05', end_date='2015-05-05')
result
percent_difference | ||
---|---|---|
date | asset | |
2015-05-05 00:00:00+00:00 | Equity(FIBBG000C2V3D6 [A]) | 0.000209 |
Equity(QI000000004076 [AABA]) | -0.017429 | |
Equity(FIBBG006T1NZ18 [AAC]) | 0.048123 | |
Equity(FIBBG000V2S3P6 [AACG]) | 0.052646 | |
Equity(FIBBG000BDYRW6 [AADR]) | 0.021066 | |
... | ... | |
Equity(FIBBG0001JCK35 [RBSPE]) | NaN | |
Equity(FIBBG0001JCK44 [RBSPG]) | NaN | |
Equity(FIBBG0001JCQT4 [RBSPI]) | NaN | |
Equity(FIBBG007NFXFG8 [UZB]) | 0.003607 | |
Equity(FIBBG0046M31Y3 [WMGIZ]) | -0.016594 |
8292 rows × 1 columns
Next Lesson: Filters