zipline run_pipeline and positional arguments - python

I'm using Zipline-1.1.1, Python3.4.6 to create a dynamic stock selector as follows:
from zipline.pipeline import Pipeline, engine
from zipline.pipeline.factors import AverageDollarVolume, Returns
def make_pipeline():
dollar_volume = AverageDollarVolume(window_length=1)
high_dollar_volume = dollar_volume.percentile_between(N, 100)
recent_returns = Returns(window_length=N, mask=high_dollar_volume)
low_returns = recent_returns.percentile_between(0, n)
high_returns = recent_returns.percentile_between(N, 100)
pipe_columns = {
'low_returns': low_returns,
'high_returns': high_returns,
'recent_returns': recent_returns,
'dollar_volume': dollar_volume
}
pipe_screen = (low_returns | high_returns)
pipe = Pipeline(columns=pipe_columns, screen=pipe_screen)
return pipe
I initialize a pipeline object with:
my_pipe = make_pipeline()
But when I try to populate the Pipeline, it fails with:
result = engine.PipelineEngine.run_pipeline(my_pipe, '2017-07-10', '2017-07-11')
Traceback (most recent call last):
File "<input>", line 1, in <module>
result = engine.PipelineEngine.run_pipeline(my_pipe, '2017-07-10', '2017-07-11')
TypeError: run_pipeline() missing 1 required positional argument: 'end_date'
I can't figure out what is wrong, any help is much appreciated.

If I understand correctly, you're using this library.
As far as I can see from that code, to be able to use run_pipeline method you have to instantiate on of pipeline engines before, e.g. SimplePipelineEngine. You need that because PipelineEngine is a class, even abstract class, not an object.
So you have to create an object of SimplePipelineEngine class and then call run_pipeline on it. You can do it this way:
your_engine = SimplePipelineEngine(get_loader=your_loader, calendar=your_calendar, asset_finder=your_asset_finder)
your_eninge.run_pipeline(my_pipe, '2017-07-10', '2017-07-11')
Of course you have to create your_loader etc. first.
Here is example of SimplePipelineEngine usage. I hope it will help.

Related

PyFMI multiple inputs in Master simulation

I am trying to simulate two FMUs with the one having inputs as CSV files by using the Master. What I have tried is the following:
from pyfmi import load_fmu
from pyfmi import Master
import pandas as pd
electricity_network = load_fmu(r"C:\Users\kosmy\Pandapower_Reduced.fmu")
pv = load_fmu(r"C:\Users\kosmy\Photovoltaics.Model.PVandWeather_simple.fmu")
load_file = r"C:\Users\kosmy\load_prof_sec_res.csv"
load = pd.read_csv(load_file)
models = [electricity_network, pv]
connections = [(pv, "P_MW", electricity_network, "P_pv1"),
(pv, "P_MW", electricity_network, "P_pv2")]
master_simulator = Master(models, connections)
input_object = [((electricity_network, 'P_load1'), load),
((electricity_network, 'P_load2'), load)]
res = master_simulator.simulate(final_time = 86400, input = input_object)
I am getting the following error:
Traceback (most recent call last):
File "C:\Users\kosmy\run_csv_pyfmi.py", line 29, in <module>
res = master_simulator.simulate(final_time = 86400, input = input_object)
File "src\pyfmi\master.pyx", line 1474, in pyfmi.master.Master.simulate
File "src\pyfmi\master.pyx", line 1369, in pyfmi.master.Master.specify_external_input
TypeError: tuple indices must be integers or slices, not tuple
Apparently, I do not give the correct format to the input, but I have not found an example demonstrating the correct format when using the Master.
Does anyone know how can I use the input in this case?
def load(t):
return 10, math.cos(t)
input_object = ([(electricity_network, 'P_load1'),(electricity_network, 'P_load2')],load)
another option is
data = np.transpose(np.vstack((t,u,v)))
input_object = (['InputVarI','InputVarP'],data)
error while creating a 2-tuple as input for model.simulate() of fmu model with pyfmi

Python - Creating an instance of a module, getting an error

I am creating a universal text field that can be used in many python turtle projects. I am trying to create an instance of it but I get this error:
>>> import TextField
>>> tf = TextField('None', False)
Traceback (most recent call last):
File "<pyshell#1>", line 1, in <module>
tf = TextField('None', False)
TypeError: 'module' object is not callable
>>>
What in a module causes this type of error? I completely wrote this module and I'm getting an error creating an instance of it :( ... What do I need in this module to make it 'callable'? I have tried adding a def __call__(self): but that doesn't affect the problem at all, nor create any errors.
Here is the beginning of the script where the problem is most likely happening:
# Created by SUPERMECHM500 # repl.it
# Edited by cdlane # stackoverflow.com
class TextField:
TextFieldBorderColor = '#0019fc'
TextFieldBGColor = '#000000'
TextFieldTextColor = '#ffffff'
ShiftedDigits = {
'1':'!',
'2':'#',
'3':'#',
'4':'$',
'5':'%',
'6':'^',
'7':'&',
'8':'*',
'9':'(',
'0':')'
}
def __init__(self, command, CanBeEmpty): # Ex. textField = TextField('Execute()', True)
self.CmdOnEnter = command
self.turtle = Turtle()
self.CanBeEmpty = CanBeEmpty
self.turtle.speed('fastest')
self.inp = []
self.FullOutput = ""
self.TextSeparation = 7
self.s = self.TextSeparation
self.key_shiftL = False
......
The module is not the class. If your class TextField is in a module called TextField, then it is referred to as TextField.TextField.
Or change your import to
from TextField import TextField

Visibility of python class attributes

I am fairly new to Python, and trying to write a wrapper class around some Quantlib swap objects. Problem is that I am trying to call the Qualtlib Schedule object using attributes that have been either passed to the constructor or calculated in the constructor. Problem is when I run the code as such;
import swapleg as sl
Leg1 = sl.SwapLeg("Fix","AUD",ql.Date(26, 9, 2018),ql.Date(26, 9, 2028),ql.Monthly)
print(Leg1.EffectiveDate)
Leg1.showSchedule()
I get the following error
Traceback (most recent call last):
September 26th, 2018
.......
AttributeError: type object 'SwapLeg' has no attribute 'EffectiveDate'
The code is listed - the object Leg1 gets instantiated, and the EffectiveDate does get set. My issue is that when the showSchedule call the Quantlib call ql.Schedule, it loses visibility to the EffectiveDate, even though I am looking it with self.EffectiveDate. Clearly I am missing something here. Any help would be appreciated.
import QuantLib as ql
class SwapLeg:
def __init__(self,LegType,CCY,EffectiveDate=None,TerminationDate=None,Tenor=None,Rate=None,Spread=None):
self.LegType=LegType
self.CCY=CCY
self.Tenor=Tenor
if EffectiveDate is None:
self.EffectiveDate = ql.Settings.instance().evaluationDate
else:
self.EffectiveDate =EffectiveDate
......
def _LegSchedule(self):
ls = ql.Schedule( self.EffectiveDate,
self.TerminationDate,
self.Tenor,
self.Calendar,
self.businessDayConvention,
self.businessDayConvention,
self.GenRule,
self.EndOfMonth,
self.FirstDate,
self.NextToLastDate)
return ls
#classmethod
def showSchedule(self):
for i, d in enumerate(self._LegSchedule(self)):
print("{0} {1}".format(i+1,d))

Python unittesting initiate values

Sorry if this question is stupid. I created an unittest class which needs to take given inputs and outputs from outside. Thus, I guess these values should be initiated. However, I met some errors in the following code:
CODE:
import unittest
from StringIO import StringIO
##########Inputs and outputs from outside#######
a=[1,2]
b=[2,3]
out=[3,4]
####################################
def func1(a,b):
return a+b
class MyTestCase(unittest.TestCase):
def __init__(self,a,b,out):
self.a=a
self.b=b
self.out=out
def testMsed(self):
for i in range(self.tot_iter):
print i
fun = func1(self.a[i],self.b[i])
value = self.out[i]
testFailureMessage = "Test of function name: %s iteration: %i expected: %i != calculated: %i" % ("func1",i,value,fun)
self.assertEqual(round(fun,3),round(value,3),testFailureMessage)
if __name__ == '__main__':
f = MyTestCase(a,b,out)
from pprint import pprint
stream = StringIO()
runner = unittest.TextTestRunner(stream=stream, verbosity=2)
result = runner.run(unittest.makeSuite(MyTestCase(a,b,out)))
print 'Tests run', result.testsRun
However, I got the following error
Traceback (most recent call last):
File "C:testing.py", line 33, in <module>
result = runner.run(unittest.makeSuite(MyTestCase(a,b,out)))
File "C:\Python27\lib\unittest\loader.py", line 310, in makeSuite
return _makeLoader(prefix, sortUsing, suiteClass).loadTestsFromTestCase(testCaseClass)
File "C:\Python27\lib\unittest\loader.py", line 50, in loadTestsFromTestCase
if issubclass(testCaseClass, suite.TestSuite):
TypeError: issubclass() arg 1 must be a class
Can anyone give me some suggestions? Thanks!
The root of the problem is this line,
result = runner.run(unittest.makeSuite(MyTestCase(a,b,out)))
unittest.makeSuite expects a class, not an instance of a class. So just MyTestCase, not MyTestCase(a, b, out). This means that you can't pass parameters to your test case in the manner you are attempting to. You should probably move the code from init to a setUp function. Either access a, b, and out as globals inside setUp or take a look at this link for information regarding passing parameters to a unit test.
By the way, here is the source file within python where the problem originated. Might be informative to read.

Variable not the same type in two different functions

I have two functions which print into an excel file. THe only input is the file name. Here is the code:
#excelpy
import excelpy
#Tinker
from Tkinter import *
from tkSimpleDialog import *
from tkFileDialog import *
Function Mode1
def Mode1(full_name):
print full_name
print type(full_name)
testwbook = excelpy.workbook(full_name)
testwbook.show()
testwbook.set_cell((1,1),'TEST1', fontColor='red')
testwbook.set_range(2,1,['Number','Name'])
m1 = testwbook.save(full_name)
testwbook.close()
return m1
Function Mode2
def Mode2(full_name):
print full_name
print type(full_name)
testwbook = excelpy.workbook(full_name)
testwbook.show()
testwbook.set_cell((1,1),'TEST2', fontColor='red')
testwbook.set_range(2,1,['Number','Name'])
m2 = testwbook.save(full_name)
testwbook.close()
return m2
Main
root = Tk()
d = str(asksaveasfilename(parent=root,filetypes=[('Excel','*.xls')],title="Save report as..."))
d = d + '.xls'
d = d.replace('/','\\')
root.destroy()
Mode1(d)
Mode2(d)
And once in a while I get the following error:
Traceback (most recent call last):
File "T:\TEST\testpy.py", line 2035, in <module>
Mode2(d)
File ""T:\TEST\testpy.py"", line 1381, in Mode2
print type(full_name)
TypeError: 'str' object is not callable
Any idea why is this happening? How can I prevent it?
The only function call in the line you get the error is a call to the built-in function type(), so the only explanation for your error message is that you overwrote the built-in name type by a global name type pointing to a string object. Try adding
print type
before
print type(full_name)
It looks like somewhere you're setting a (global) variable named type to a string, thus overwriting the built-in type function.
Try searching your code for type = to see what turns up.
Understandably, Python would then throw that exception when you tried to call type (strings can't be "called").

Categories

Resources