desc
stringlengths 3
26.7k
| decl
stringlengths 11
7.89k
| bodies
stringlengths 8
553k
|
---|---|---|
'Delete the cookie on the Flask test client.'
| def delete_cookie(self, key, *args, **kwargs):
| server_name = (flask.current_app.config['SERVER_NAME'] or 'localhost')
return self.client.delete_cookie(server_name, key=key, *args, **kwargs)
|
'Set up fixtures for the class.
This methods runs once for the entire class. This test case do not
insert or update any record on the database, so there is no problem
to be run only once for the class.
This way it save some time, instead of populate the test database
each time a test is executed.'
| @classmethod
def setUpClass(cls):
| admin = create_admin()
app = create_app(config='quokka.test_settings', DEBUG=False, test=True, admin_instance=admin)
with app.app_context():
db = list(app.extensions.get('mongoengine').keys())[0]
db.connection.drop_database('quokka_test')
from quokka.utils.populate import Populate
Populate(db)()
cls.app = app
cls.db = db
|
'Create app must be implemented.
It is mandatory for flask_testing test cases. Only returns
the app created in the setUpClass method.'
| def create_app(self):
| return self.app
|
'Add a new entry to the feed. This function can either be called
with a :class:`FeedEntry` or some keyword and positional arguments
that are forwarded to the :class:`FeedEntry` constructor.'
| def add(self, *args, **kwargs):
| if ((len(args) == 1) and (not kwargs) and isinstance(args[0], FeedEntry)):
self.entries.append(args[0])
else:
kwargs['feed_url'] = self.feed_url
self.entries.append(FeedEntry(*args, **kwargs))
|
'Return a generator that yields pieces of XML.'
| def generate(self):
| if (not self.author):
if (False in map((lambda e: bool(e.author)), self.entries)):
self.author = ({'name': 'Unknown author'},)
if (not self.updated):
dates = sorted([entry.updated for entry in self.entries])
self.updated = ((dates and dates[(-1)]) or datetime.utcnow())
(yield u'<?xml version="1.0" encoding="utf-8"?>\n')
(yield u'<feed xmlns="http://www.w3.org/2005/Atom">\n')
(yield (' ' + _make_text_block('title', self.title, self.title_type)))
(yield (u' <id>%s</id>\n' % escape(self.id)))
(yield (u' <updated>%s</updated>\n' % format_iso8601(self.updated)))
if self.url:
(yield (u' <link href="%s" />\n' % escape(self.url)))
if self.feed_url:
(yield (u' <link href="%s" rel="self" />\n' % escape(self.feed_url)))
for link in self.links:
(yield (u' <link %s/>\n' % ''.join((('%s="%s" ' % (k, escape(link[k]))) for k in link))))
for author in self.author:
(yield u' <author>\n')
(yield (u' <name>%s</name>\n' % escape(author['name'])))
if ('uri' in author):
(yield (u' <uri>%s</uri>\n' % escape(author['uri'])))
if ('email' in author):
(yield (' <email>%s</email>\n' % escape(author['email'])))
(yield ' </author>\n')
if self.subtitle:
(yield (' ' + _make_text_block('subtitle', self.subtitle, self.subtitle_type)))
if self.icon:
(yield (u' <icon>%s</icon>\n' % escape(self.icon)))
if self.logo:
(yield (u' <logo>%s</logo>\n' % escape(self.logo)))
if self.rights:
(yield (' ' + _make_text_block('rights', self.rights, self.rights_type)))
(generator_name, generator_url, generator_version) = self.generator
if (generator_name or generator_url or generator_version):
tmp = [u' <generator']
if generator_url:
tmp.append((u' uri="%s"' % escape(generator_url)))
if generator_version:
tmp.append((u' version="%s"' % escape(generator_version)))
tmp.append((u'>%s</generator>\n' % escape(generator_name)))
(yield u''.join(tmp))
for entry in self.entries:
for line in entry.generate():
(yield (u' ' + line))
(yield u'</feed>\n')
|
'Convert the feed into a string.'
| def to_string(self):
| return u''.join(self.generate())
|
'Return a response object for the feed.'
| def get_response(self):
| return BaseResponse(self.to_string(), mimetype='application/atom+xml')
|
'Use the class as WSGI response object.'
| def __call__(self, environ, start_response):
| return self.get_response()(environ, start_response)
|
'Yields pieces of ATOM XML.'
| def generate(self):
| base = ''
if self.xml_base:
base = (' xml:base="%s"' % escape(self.xml_base))
(yield (u'<entry%s>\n' % base))
(yield (u' ' + _make_text_block('title', self.title, self.title_type)))
(yield (u' <id>%s</id>\n' % escape(self.id)))
(yield (u' <updated>%s</updated>\n' % format_iso8601(self.updated)))
if self.published:
(yield (u' <published>%s</published>\n' % format_iso8601(self.published)))
if self.url:
(yield (u' <link href="%s" />\n' % escape(self.url)))
for author in self.author:
(yield u' <author>\n')
(yield (u' <name>%s</name>\n' % escape(author['name'])))
if ('uri' in author):
(yield (u' <uri>%s</uri>\n' % escape(author['uri'])))
if ('email' in author):
(yield (u' <email>%s</email>\n' % escape(author['email'])))
(yield u' </author>\n')
for link in self.links:
(yield (u' <link %s/>\n' % ''.join((('%s="%s" ' % (k, escape(link[k]))) for k in link))))
for category in self.categories:
(yield (u' <category %s/>\n' % ''.join((('%s="%s" ' % (k, escape(category[k]))) for k in category))))
if self.summary:
(yield (u' ' + _make_text_block('summary', self.summary, self.summary_type)))
if self.content:
(yield (u' ' + _make_text_block('content', self.content, self.content_type)))
(yield u'</entry>\n')
|
'Convert the feed item into a unicode object.'
| def to_string(self):
| return u''.join(self.generate())
|
'Construct the network.'
| def setup(self):
| raise NotImplementedError('Must be implemented by the subclass.')
|
'Load network weights.
data_path: The path to the numpy-serialized network weights
session: The current TensorFlow session
ignore_missing: If true, serialized weights for missing layers are ignored.'
| def load(self, data_path, session, ignore_missing=False):
| data_dict = np.load(data_path, encoding='latin1').item()
for op_name in data_dict:
with tf.variable_scope(op_name, reuse=True):
for (param_name, data) in iteritems(data_dict[op_name]):
try:
var = tf.get_variable(param_name)
session.run(var.assign(data))
except ValueError:
if (not ignore_missing):
raise
|
'Set the input(s) for the next operation by replacing the terminal nodes.
The arguments can be either layer names or the actual layers.'
| def feed(self, *args):
| assert (len(args) != 0)
self.terminals = []
for fed_layer in args:
if isinstance(fed_layer, string_types):
try:
fed_layer = self.layers[fed_layer]
except KeyError:
raise KeyError(('Unknown layer name fed: %s' % fed_layer))
self.terminals.append(fed_layer)
return self
|
'Returns the current network output.'
| def get_output(self):
| return self.terminals[(-1)]
|
'Returns an index-suffixed unique name for the given prefix.
This is used for auto-generating layer names based on the type-prefix.'
| def get_unique_name(self, prefix):
| ident = (sum((t.startswith(prefix) for (t, _) in self.layers.items())) + 1)
return ('%s_%d' % (prefix, ident))
|
'Creates a new TensorFlow variable.'
| def make_var(self, name, shape):
| return tf.get_variable(name, shape, trainable=self.trainable)
|
'Verifies that the padding is one of the supported ones.'
| def validate_padding(self, padding):
| assert (padding in ('SAME', 'VALID'))
|
'Instantiate an \'AlignDlib\' object.
:param facePredictor: The path to dlib\'s
:type facePredictor: str'
| def __init__(self, facePredictor):
| assert (facePredictor is not None)
self.detector = dlib.get_frontal_face_detector()
self.predictor = dlib.shape_predictor(facePredictor)
|
'Find all face bounding boxes in an image.
:param rgbImg: RGB image to process. Shape: (height, width, 3)
:type rgbImg: numpy.ndarray
:return: All face bounding boxes in an image.
:rtype: dlib.rectangles'
| def getAllFaceBoundingBoxes(self, rgbImg):
| assert (rgbImg is not None)
try:
return self.detector(rgbImg, 1)
except Exception as e:
print 'Warning: {}'.format(e)
return []
|
'Find the largest face bounding box in an image.
:param rgbImg: RGB image to process. Shape: (height, width, 3)
:type rgbImg: numpy.ndarray
:param skipMulti: Skip image if more than one face detected.
:type skipMulti: bool
:return: The largest face bounding box in an image, or None.
:rtype: dlib.rectangle'
| def getLargestFaceBoundingBox(self, rgbImg, skipMulti=False):
| assert (rgbImg is not None)
faces = self.getAllFaceBoundingBoxes(rgbImg)
if (((not skipMulti) and (len(faces) > 0)) or (len(faces) == 1)):
return max(faces, key=(lambda rect: (rect.width() * rect.height())))
else:
return None
|
'Find the landmarks of a face.
:param rgbImg: RGB image to process. Shape: (height, width, 3)
:type rgbImg: numpy.ndarray
:param bb: Bounding box around the face to find landmarks for.
:type bb: dlib.rectangle
:return: Detected landmark locations.
:rtype: list of (x,y) tuples'
| def findLandmarks(self, rgbImg, bb):
| assert (rgbImg is not None)
assert (bb is not None)
points = self.predictor(rgbImg, bb)
return [(p.x, p.y) for p in points.parts()]
|
'align(imgDim, rgbImg, bb=None, landmarks=None, landmarkIndices=INNER_EYES_AND_BOTTOM_LIP)
Transform and align a face in an image.
:param imgDim: The edge length in pixels of the square the image is resized to.
:type imgDim: int
:param rgbImg: RGB image to process. Shape: (height, width, 3)
:type rgbImg: numpy.ndarray
:param bb: Bounding box around the face to align. \
Defaults to the largest face.
:type bb: dlib.rectangle
:param landmarks: Detected landmark locations. \
Landmarks found on `bb` if not provided.
:type landmarks: list of (x,y) tuples
:param landmarkIndices: The indices to transform to.
:type landmarkIndices: list of ints
:param skipMulti: Skip image if more than one face detected.
:type skipMulti: bool
:param scale: Scale image before cropping to the size given by imgDim.
:type scale: float
:return: The aligned RGB image. Shape: (imgDim, imgDim, 3)
:rtype: numpy.ndarray'
| def align(self, imgDim, rgbImg, bb=None, landmarks=None, landmarkIndices=INNER_EYES_AND_BOTTOM_LIP, skipMulti=False, scale=1.0):
| assert (imgDim is not None)
assert (rgbImg is not None)
assert (landmarkIndices is not None)
if (bb is None):
bb = self.getLargestFaceBoundingBox(rgbImg, skipMulti)
if (bb is None):
return
if (landmarks is None):
landmarks = self.findLandmarks(rgbImg, bb)
npLandmarks = np.float32(landmarks)
npLandmarkIndices = np.array(landmarkIndices)
H = cv2.getAffineTransform(npLandmarks[npLandmarkIndices], (((imgDim * MINMAX_TEMPLATE[npLandmarkIndices]) * scale) + ((imgDim * (1 - scale)) / 2)))
thumbnail = cv2.warpAffine(rgbImg, H, (imgDim, imgDim))
return thumbnail
|
'çç¥åœæ°ïŒå¯¹æ¯æ ¹Barè¿è¡äžæ¬¡ã'
| def on_bar(self):
| if (self.volume == 0):
return
if ((self.position() == 0) and (self.masmall[1] <= self.mabig[1]) and (self.masmall > self.mabig)):
quantity = self.__determine_position()
if (quantity > 0):
price = self.close[0]
self.buy('long', price, quantity, contract=code)
self.buy_price = price
self.num_cont += 1
elif ((self.position() > 0) and (self.masmall < self.mabig)):
price = self.close[0]
self.sell('long', price, self.position())
if (price > self.buy_price):
self.num_win += 1
|
'1) ææ åéåæ°åŒéŽçè¿ç®ã ctx.ma2 - 0
2) ææ åéåæº¯ ctx.ma2[3]
3) ååŒåå€åŒæµè¯'
| def test_case(self):
| (close, open, ma, ma3, tech_operator) = ([], [], [], [], [])
boll = {'upper': [], 'middler': [], 'lower': []}
boll3 = {'upper': [], 'middler': [], 'lower': []}
class DemoStrategy(Strategy, ):
def on_init(self, ctx):
'\xe5\x88\x9d\xe5\xa7\x8b\xe5\x8c\x96\xe6\x95\xb0\xe6\x8d\xae'
ctx.ma = MA(ctx.close, 2)
ctx.boll = BOLL(ctx.close, 2)
def on_symbol(self, ctx):
if (ctx.curbar >= 2):
tech_operator.append(((ctx.ma - 0) == ctx.ma[0]))
ma3.append(ctx.ma[3])
ma.append(ctx.ma[0])
close.append(ctx.close[0])
open.append(ctx.open[0])
boll['upper'].append(float(ctx.boll['upper']))
boll['middler'].append(ctx.boll['middler'][0])
boll['lower'].append(ctx.boll['lower'][0])
boll3['upper'].append(ctx.boll['upper'][3])
boll3['middler'].append(ctx.boll['middler'][3])
boll3['lower'].append(ctx.boll['lower'][3])
assert isinstance(ctx.boll['lower'], NumberSeries)
assert isinstance(ctx.ma, MA)
set_symbols(['BB.TEST-1.Minute'])
add_strategy([DemoStrategy('A1')])
run()
source_ma = talib.SMA(np.asarray(close), 2)
self.assertTrue(all(tech_operator), '\xe6\x8c\x87\xe6\xa0\x87\xe8\xbf\x90\xe7\xae\x97\xe9\x94\x99\xe8\xaf\xaf!')
self.assertFalse((ma[0] == ma[0]), '\xe6\x8c\x87\xe6\xa0\x87NaN\xe5\x80\xbc\xe6\xb5\x8b\xe8\xaf\x95\xe5\xa4\xb1\xe8\xb4\xa5!')
for (source, target) in zip(source_ma[1:], ma[1:]):
self.assertTrue((target == source), '\xe5\x8d\x95\xe5\x80\xbc\xe6\x8c\x87\xe6\xa0\x87\xe8\xae\xa1\xe7\xae\x97\xe6\xb5\x8b\xe8\xaf\x95\xe5\xa4\xb1\xe8\xb4\xa5!')
for (source, target) in zip(ma[1:], ma3[4:]):
self.assertTrue((target == source), '\xe5\x8d\x95\xe5\x80\xbc\xe6\x8c\x87\xe6\xa0\x87\xe5\x9b\x9e\xe6\xba\xaf\xe6\xb5\x8b\xe8\xaf\x95\xe5\xa4\xb1\xe8\xb4\xa5!')
for nan in ma3[:4]:
self.assertFalse((nan == nan), '\xe5\x8d\x95\xe5\x80\xbc\xe6\x8c\x87\xe6\xa0\x87\xe5\x9b\x9e\xe6\xba\xafNaN\xe5\x80\xbc\xe6\xb5\x8b\xe8\xaf\x95\xe5\xa4\xb1\xe8\xb4\xa5!')
logger.info('-- \xe5\x8d\x95\xe5\x80\xbc\xe6\x8c\x87\xe6\xa0\x87\xe6\xb5\x8b\xe8\xaf\x95\xe6\x88\x90\xe5\x8a\x9f --')
(upper, middler, lower) = talib.BBANDS(np.asarray(close), 2, 2, 2)
ta_boll = {'upper': upper, 'middler': middler, 'lower': lower}
for v in ['upper', 'lower', 'middler']:
self.assertFalse((boll[v][0] == boll[v][0]), '\xe5\xa4\x9a\xe5\x80\xbc\xe6\x8c\x87\xe6\xa0\x87NaN\xe5\x80\xbc\xe6\xb5\x8b\xe8\xaf\x95\xe5\xa4\xb1\xe8\xb4\xa5!')
for (source, target) in zip(ta_boll[v][1:], boll[v][1:]):
self.assertTrue((target == source), '\xe5\xa4\x9a\xe5\x80\xbc\xe6\x8c\x87\xe6\xa0\x87\xe8\xae\xa1\xe7\xae\x97\xe6\xb5\x8b\xe8\xaf\x95\xe5\xa4\xb1\xe8\xb4\xa5!')
for nan in boll3[v][:4]:
self.assertFalse((nan == nan), '\xe5\xa4\x9a\xe5\x80\xbc\xe6\x8c\x87\xe6\xa0\x87\xe5\x9b\x9e\xe6\xba\xafNaN\xe5\x80\xbc\xe6\xb5\x8b\xe8\xaf\x95\xe5\xa4\xb1\xe8\xb4\xa5!')
for (source, target) in zip(boll[v][1:], boll3[v][4:]):
self.assertTrue((target == source), '\xe5\xa4\x9a\xe5\x80\xbc\xe6\x8c\x87\xe6\xa0\x87\xe5\x9b\x9e\xe6\xba\xaf\xe6\xb5\x8b\xe8\xaf\x95\xe5\xa4\xb1\xe8\xb4\xa5!')
logger.info('-- \xe5\xa4\x9a\xe5\x80\xbc\xe6\x8c\x87\xe6\xa0\x87\xe6\xb5\x8b\xe8\xaf\x95\xe6\x88\x90\xe5\x8a\x9f --')
logger.info('***** \xe6\x8c\x87\xe6\xa0\x87\xe6\xb5\x8b\xe8\xaf\x95\xe6\x88\x90\xe5\x8a\x9f *****\n')
|
'æµè¯ïŒon_bar, on_symbol, on_exit çè¿è¡é¢æ¬¡ïŒæ°æ®åçç¥éåçç²ç²åºŠæµè¯;
ctx.prontract, ctx.strategy'
| def test_case(self):
| on_exit = {'strategy': []}
on_bar = {'strategy': []}
on_symbol = {'combination': set(), 'step_num': 0}
class DemoStrategy(Strategy, ):
def on_init(self, ctx):
'\xe5\x88\x9d\xe5\xa7\x8b\xe5\x8c\x96\xe6\x95\xb0\xe6\x8d\xae'
return
def on_symbol(self, ctx):
on_symbol['combination'].add((str(ctx.pcontract), ctx.strategy))
on_symbol['step_num'] += 1
def on_bar(self, ctx):
on_bar['strategy'].append(ctx.strategy)
def on_exit(self, ctx):
on_exit['strategy'].append(ctx.strategy)
set_symbols(['BB.TEST-1.Minute', 'AA.TEST-1.Minute'])
add_strategy([DemoStrategy('A1'), DemoStrategy('A2')])
add_strategy([DemoStrategy('B1'), DemoStrategy('B2')])
run()
fname = os.path.join(os.getcwd(), 'data', '1MINUTE', 'TEST', 'BB.csv')
blen = len(pd.read_csv(fname))
fname = os.path.join(os.getcwd(), 'data', '1MINUTE', 'TEST', 'AA.csv')
alen = len(pd.read_csv(fname))
sample = set([('BB.TEST-1.MINUTE', 'A1'), ('BB.TEST-1.MINUTE', 'A2'), ('AA.TEST-1.MINUTE', 'A1'), ('AA.TEST-1.MINUTE', 'A2'), ('BB.TEST-1.MINUTE', 'B1'), ('BB.TEST-1.MINUTE', 'B2'), ('AA.TEST-1.MINUTE', 'B1'), ('AA.TEST-1.MINUTE', 'B2')])
self.assertTrue(((alen > 0) and (blen > 0)))
self.assertTrue((on_symbol['combination'] == sample), 'on_symbol\xe6\xb5\x8b\xe8\xaf\x95\xe5\xa4\xb1\xe8\xb4\xa5!')
self.assertTrue((on_symbol['step_num'] == ((alen * 4) + (blen * 4))), 'on_symbol\xe6\xb5\x8b\xe8\xaf\x95\xe5\xa4\xb1\xe8\xb4\xa5!')
self.assertTrue(((['A1', 'A2', 'B1', 'B2'] * max(blen, alen)) == on_bar['strategy']), 'on_bar\xe6\xb5\x8b\xe8\xaf\x95\xe5\xa4\xb1\xe8\xb4\xa5\xef\xbc\x81')
self.assertTrue((['A1', 'A2', 'B1', 'B2'] == on_exit['strategy']), 'on_exit\xe6\xb5\x8b\xe8\xaf\x95\xe5\xa4\xb1\xe8\xb4\xa5\xef\xbc\x81')
logger.info('-- \xe7\xad\x96\xe7\x95\xa5on_xxx\xe4\xb8\xbb\xe5\x87\xbd\xe6\x95\xb0\xe6\xb5\x8b\xe8\xaf\x95\xe6\x88\x90\xe5\x8a\x9f --')
|
'1) å¯å¹³ä»äœãctx.pos()
2) profile.all_holdings æ¯æ ¹baræ¶çæ¶éŽçä»·æ Œæ®åã
3) éœå€Žä¹°åãctx.buy, ctx.sell'
| def test_case(self):
| (t_cashes0, t_cashes1) = ([], [])
t_ocashes0 = []
t_oequity0 = []
t_equity0 = []
class DemoStrategy1(Strategy, ):
' \xe9\x99\x90\xe4\xbb\xb7\xe5\x8f\xaa\xe4\xb9\xb0\xe5\xa4\x9a\xe5\xa4\xb4\xe4\xbb\x93\xe4\xbd\x8d\xe7\x9a\x84\xe7\xad\x96\xe7\x95\xa5 '
def on_init(self, ctx):
'\xe5\x88\x9d\xe5\xa7\x8b\xe5\x8c\x96\xe6\x95\xb0\xe6\x8d\xae'
pass
def on_bar(self, ctx):
curtime = ctx.datetime[0].time()
if (curtime in [bt1, bt2, bt3]):
ctx.buy(ctx.close, 1)
elif (curtime == st1):
assert ((ctx.pos() == 3) and '\xe6\x8c\x81\xe4\xbb\x93\xe6\xb5\x8b\xe8\xaf\x95\xe5\xa4\xb1\xe8\xb4\xa5\xef\xbc\x81')
ctx.sell(ctx.close, 2)
elif (curtime == st2):
assert ((ctx.pos() == 1) and '\xe6\x8c\x81\xe4\xbb\x93\xe6\xb5\x8b\xe8\xaf\x95\xe5\xa4\xb1\xe8\xb4\xa5\xef\xbc\x81')
ctx.sell(ctx.close, 1)
t_ocashes0.append(ctx.cash())
t_oequity0.append(ctx.equity())
t_cashes0.append(ctx.test_cash())
t_equity0.append(ctx.test_equity())
class DemoStrategy2(Strategy, ):
' \xe9\x99\x90\xe4\xbb\xb7\xe4\xb9\xb0\xe5\xa4\x9a\xe5\x8d\x96\xe7\xa9\xba\xe7\x9a\x84\xe7\xad\x96\xe7\x95\xa5 '
def on_init(self, ctx):
'\xe5\x88\x9d\xe5\xa7\x8b\xe5\x8c\x96\xe6\x95\xb0\xe6\x8d\xae'
pass
def on_bar(self, ctx):
curtime = ctx.datetime[0].time()
if (curtime in [bt1, bt2, bt3]):
ctx.buy(ctx.close, 1)
ctx.short(ctx.close, 2)
elif (curtime == st1):
assert ((ctx.pos() == 3) and '\xe9\xbb\x98\xe8\xae\xa4\xe6\x8c\x81\xe4\xbb\x93\xe6\x9f\xa5\xe8\xaf\xa2\xe6\xb5\x8b\xe8\xaf\x95\xe5\xa4\xb1\xe8\xb4\xa5\xef\xbc\x81')
ctx.sell(ctx.close, 2)
assert ((ctx.pos('short') == 6) and '\xe6\x8c\x81\xe4\xbb\x93\xe6\xb5\x8b\xe8\xaf\x95\xe5\xa4\xb1\xe8\xb4\xa5\xef\xbc\x81')
ctx.cover(ctx.close, 4)
elif (curtime == st2):
assert ((ctx.pos('long') == 1) and '\xe6\x8c\x81\xe4\xbb\x93\xe6\xb5\x8b\xe8\xaf\x95\xe5\xa4\xb1\xe8\xb4\xa5\xef\xbc\x81')
ctx.sell(ctx.close, 1)
assert ((ctx.pos('short') == 2) and '\xe6\x8c\x81\xe4\xbb\x93\xe6\xb5\x8b\xe8\xaf\x95\xe5\xa4\xb1\xe8\xb4\xa5\xef\xbc\x81')
ctx.cover(ctx.close, 2)
t_cashes1.append(ctx.test_cash())
class DemoStrategy3(Strategy, ):
' \xe6\xb5\x8b\xe8\xaf\x95\xe5\xb9\xb3\xe4\xbb\x93\xe6\x9c\xaa\xe6\x88\x90\xe4\xba\xa4\xe6\x97\xb6\xe7\x9a\x84\xe6\x8c\x81\xe4\xbb\x93\xef\xbc\x8c\xe6\x92\xa4\xe5\x8d\x95\xe5\x90\x8e\xe7\x9a\x84\xe6\x8c\x81\xe4\xbb\x93\xef\xbc\x8c\xe6\x92\xa4\xe5\x8d\x95\xe3\x80\x82 '
def on_init(self, ctx):
'\xe5\x88\x9d\xe5\xa7\x8b\xe5\x8c\x96\xe6\x95\xb0\xe6\x8d\xae'
pass
def on_bar(self, ctx):
if (ctx.curbar == 1):
ctx.short(138, 1)
ctx.short(138, 1)
ctx.buy(ctx.close, 1)
elif (ctx.curbar == 3):
assert (len(ctx.open_orders) == 2)
ctx.cancel(ctx.open_orders[0])
assert ((len(ctx.open_orders) == 2) and '\xe6\x92\xa4\xe5\x8d\x95\xe6\xb5\x8b\xe8\xaf\x95\xe5\xa4\xb1\xe8\xb4\xa5')
elif (ctx.curbar == 4):
assert ((len(ctx.open_orders) == 1) and '\xe6\x92\xa4\xe5\x8d\x95\xe6\xb5\x8b\xe8\xaf\x95\xe5\xa4\xb1\xe8\xb4\xa5\xef\xbc\x81')
elif (ctx.curbar == 5):
assert (ctx.pos() == 1)
ctx.sell(300, 1)
elif (ctx.curbar == 7):
assert ((ctx.pos() == 0) and '\xe6\x8c\x81\xe4\xbb\x93\xe6\xb5\x8b\xe8\xaf\x95\xe5\xa4\xb1\xe8\xb4\xa5!')
assert ((len(ctx.open_orders) == 2) and '\xe6\x92\xa4\xe5\x8d\x95\xe6\xb5\x8b\xe8\xaf\x95\xe5\xa4\xb1\xe8\xb4\xa5\xef\xbc\x81')
order = list(filter((lambda x: (x.side == TradeSide.PING)), ctx.open_orders))[0]
ctx.cancel(order)
elif (ctx.curbar == 8):
assert ((len(ctx.open_orders) == 1) and '\xe6\x92\xa4\xe5\x8d\x95\xe6\xb5\x8b\xe8\xaf\x95\xe5\xa4\xb1\xe8\xb4\xa5\xef\xbc\x81')
assert ((ctx.pos() == 1) and '\xe6\x8c\x81\xe4\xbb\x93\xe6\xb5\x8b\xe8\xaf\x95\xe5\xa4\xb1\xe8\xb4\xa5!')
if ((ctx.curbar > 1) and (ctx.datetime[0].date() != ctx.datetime[1].date())):
assert ((len(ctx.open_orders) == 0) and '\xe9\x9a\x94\xe5\xa4\x9c\xe8\xae\xa2\xe5\x8d\x95\xe6\xb8\x85\xe7\xa9\xba\xe6\xb5\x8b\xe8\xaf\x95\xe5\xa4\xb1\xe8\xb4\xa5')
set_symbols(['future.TEST-1.Minute'])
profile = add_strategy([DemoStrategy1('A1'), DemoStrategy2('A2'), DemoStrategy3('A3')], {'capital': capital, 'ratio': [0.3, 0.3, 0.4]})
run()
all_holdings = profile.all_holdings()
all_holdings0 = profile.all_holdings(0)
all_holdings1 = profile.all_holdings(1)
all_holdings2 = profile.all_holdings(2)
self.assertTrue(((len(source) > 0) and (len(source) == len(all_holdings))), '\xe6\xa8\xa1\xe6\x8b\x9f\xe5\x99\xa8\xe6\xb5\x8b\xe8\xaf\x95\xe5\xa4\xb1\xe8\xb4\xa5\xef\xbc\x81')
lmg = Contract.long_margin_ratio('future.TEST')
multi = Contract.volume_multiple('future.TEST')
smg = Contract.short_margin_ratio('future.TEST')
(s_equity0, s_cashes0, s_oequity0, s_ocashes0, dts) = buy_closed_curbar1(source, (capital * 0.3), lmg, multi)
for i in range(len(dts)):
self.assertAlmostEqual(t_equity0[i], s_equity0[i])
self.assertAlmostEqual(t_oequity0[i], s_oequity0[i])
self.assertAlmostEqual(t_ocashes0[i], s_ocashes0[i])
self.assertAlmostEqual(t_cashes0[i], s_cashes0[i])
for (i, hd) in enumerate(all_holdings0):
self.assertAlmostEqual(hd['equity'], s_equity0[i])
self.assertAlmostEqual(hd['cash'], s_cashes0[i])
self.assertTrue((hd['datetime'] == dts[i]), 'all_holdings\xe6\x8e\xa5\xe5\x8f\xa3\xe6\xb5\x8b\xe8\xaf\x95\xe5\xa4\xb1\xe8\xb4\xa5\xef\xbc\x81')
for i in range(0, (len(t_cashes0) - 1)):
self.assertAlmostEqual(t_cashes0[i], s_cashes0[i])
(e0, c0, dts) = buy_closed_curbar(source, ((capital * 0.3) / 2), lmg, multi)
(e1, c1, dts) = holdings_short_maked_curbar(source, ((capital * 0.3) / 2), smg, multi)
s_equity1 = [(x + y) for (x, y) in zip(e0, e1)]
s_cashes1 = [(x + y) for (x, y) in zip(c0, c1)]
self.assertTrue((len(t_cashes1) == len(s_cashes1)), 'cash\xe6\x8e\xa5\xe5\x8f\xa3\xe6\xb5\x8b\xe8\xaf\x95\xe5\xa4\xb1\xe8\xb4\xa5\xef\xbc\x81')
for (i, hd) in enumerate(profile.all_holdings(1)):
self.assertTrue((hd['datetime'] == dts[i]), 'all_holdings\xe6\x8e\xa5\xe5\x8f\xa3\xe6\xb5\x8b\xe8\xaf\x95\xe5\xa4\xb1\xe8\xb4\xa5\xef\xbc\x81')
self.assertAlmostEqual(hd['equity'], s_equity1[i])
for i in range(0, (len(t_cashes1) - 1)):
self.assertAlmostEqual(t_cashes1[i], s_cashes1[i])
for i in range(0, len(profile.all_holdings())):
hd = all_holdings[i]
hd0 = all_holdings0[i]
hd1 = all_holdings1[i]
hd2 = all_holdings2[i]
self.assertTrue((hd['cash'] == ((hd0['cash'] + hd1['cash']) + hd2['cash'])), 'all_holdings\xe6\x8e\xa5\xe5\x8f\xa3\xe6\xb5\x8b\xe8\xaf\x95\xe5\xa4\xb1\xe8\xb4\xa5\xef\xbc\x81')
self.assertTrue((hd['commission'] == ((hd0['commission'] + hd1['commission']) + hd2['commission'])), 'all_holdings\xe6\x8e\xa5\xe5\x8f\xa3\xe6\xb5\x8b\xe8\xaf\x95\xe5\xa4\xb1\xe8\xb4\xa5\xef\xbc\x81')
self.assertTrue((hd['equity'] == ((hd0['equity'] + hd1['equity']) + hd2['equity'])), 'all_holdings\xe6\x8e\xa5\xe5\x8f\xa3\xe6\xb5\x8b\xe8\xaf\x95\xe5\xa4\xb1\xe8\xb4\xa5\xef\xbc\x81')
hd0 = profile.holding(0)
hd1 = profile.holding(1)
hd2 = profile.holding(2)
hd = profile.holding()
self.assertTrue((((hd0['equity'] + hd1['equity']) + hd2['equity']) == hd['equity']), 'holdings\xe6\x8e\xa5\xe5\x8f\xa3\xe6\xb5\x8b\xe8\xaf\x95\xe5\xa4\xb1\xe8\xb4\xa5\xef\xbc\x81')
self.assertTrue((((hd0['cash'] + hd1['cash']) + hd2['cash']) == hd['cash']), 'holdings\xe6\x8e\xa5\xe5\x8f\xa3\xe6\xb5\x8b\xe8\xaf\x95\xe5\xa4\xb1\xe8\xb4\xa5\xef\xbc\x81')
self.assertTrue((((hd0['commission'] + hd1['commission']) + hd2['commission']) == hd['commission']), 'holdings\xe6\x8e\xa5\xe5\x8f\xa3\xe6\xb5\x8b\xe8\xaf\x95\xe5\xa4\xb1\xe8\xb4\xa5\xef\xbc\x81')
self.assertTrue((((hd0['history_profit'] + hd1['history_profit']) + hd2['history_profit']) == hd['history_profit']), 'holdings\xe6\x8e\xa5\xe5\x8f\xa3\xe6\xb5\x8b\xe8\xaf\x95\xe5\xa4\xb1\xe8\xb4\xa5\xef\xbc\x81')
hd0last = profile.all_holdings(0)[(-1)]
self.assertTrue((hd0last['equity'] == hd0['equity']), 'holdings\xe6\x8e\xa5\xe5\x8f\xa3\xe6\xb5\x8b\xe8\xaf\x95\xe5\xa4\xb1\xe8\xb4\xa5\xef\xbc\x81')
self.assertTrue((hd0last['cash'] == hd0['cash']), 'holdings\xe6\x8e\xa5\xe5\x8f\xa3\xe6\xb5\x8b\xe8\xaf\x95\xe5\xa4\xb1\xe8\xb4\xa5\xef\xbc\x81')
self.assertTrue((hd0last['commission'] == hd0['commission']), 'holdings\xe6\x8e\xa5\xe5\x8f\xa3\xe6\xb5\x8b\xe8\xaf\x95\xe5\xa4\xb1\xe8\xb4\xa5\xef\xbc\x81')
self.assertTrue(((len(profile.all_holdings()) == len(s_equity0)) and (len(s_equity0) > 0)), 'holdings\xe6\x8e\xa5\xe5\x8f\xa3\xe6\xb5\x8b\xe8\xaf\x95\xe5\xa4\xb1\xe8\xb4\xa5\xef\xbc\x81')
|
''
| def test_case2(self):
| (buy_entries, sell_entries) = ([], [])
(short_entries, cover_entries) = ([], [])
(cashes0, cashes1, cashes2) = ([], [], [])
class DemoStrategyBuy(Strategy, ):
' \xe5\x8f\xaa\xe5\xbc\x80\xe5\xa4\x9a\xe5\xa4\xb4\xe4\xbb\x93\xe4\xbd\x8d\xe7\x9a\x84\xe7\xad\x96\xe7\x95\xa5 '
def on_init(self, ctx):
'\xe5\x88\x9d\xe5\xa7\x8b\xe5\x8c\x96\xe6\x95\xb0\xe6\x8d\xae'
pass
def on_bar(self, ctx):
if (ctx.datetime[0] in buy_entries):
ctx.buy((ctx.low - OFFSET), 1)
elif ((ctx.pos() > 0) and (ctx.datetime[0].time() == st1)):
ctx.sell(ctx.close, ctx.pos())
cashes0.append(ctx.test_cash())
class DemoStrategyShort(Strategy, ):
' \xe5\x8f\xaa\xe5\xbc\x80\xe7\xa9\xba\xe5\xa4\xb4\xe4\xbb\x93\xe4\xbd\x8d\xe7\x9a\x84\xe7\xad\x96\xe7\x95\xa5 '
def on_init(self, ctx):
'\xe5\x88\x9d\xe5\xa7\x8b\xe5\x8c\x96\xe6\x95\xb0\xe6\x8d\xae'
pass
def on_bar(self, ctx):
if (ctx.datetime[0] in short_entries):
ctx.short((ctx.high + OFFSET), 1)
elif ((ctx.pos('short') > 0) and (ctx.datetime[0].time() == st1)):
ctx.cover(ctx.close, ctx.pos('short'))
cashes1.append(ctx.test_cash())
class DemoStrategySell(Strategy, ):
' \xe5\x8f\xaa\xe5\xbc\x80\xe5\xa4\x9a\xe5\xa4\xb4\xe4\xbb\x93\xe4\xbd\x8d\xe7\x9a\x84\xe7\xad\x96\xe7\x95\xa5 '
def on_init(self, ctx):
'\xe5\x88\x9d\xe5\xa7\x8b\xe5\x8c\x96\xe6\x95\xb0\xe6\x8d\xae'
pass
def on_bar(self, ctx):
if (ctx.datetime[0].time() == bt1):
ctx.buy(ctx.close, 1)
elif ((ctx.pos('long') > 0) and (ctx.datetime[0] in sell_entries)):
ctx.sell((ctx.high + OFFSET), ctx.pos())
elif ((ctx.pos('long') > 0) and (ctx.datetime[0].time() == st3)):
ctx.sell(ctx.close, ctx.pos())
cashes2.append(ctx.test_cash())
class DemoStrategyCover(Strategy, ):
def on_init(self, ctx):
'\xe5\x88\x9d\xe5\xa7\x8b\xe5\x8c\x96\xe6\x95\xb0\xe6\x8d\xae'
pass
def on_bar(self, ctx):
if (ctx.datetime[0].time() == bt1):
ctx.short(ctx.close, 1)
elif ((ctx.pos('short') > 0) and (ctx.datetime[0] in cover_entries)):
ctx.cover((ctx.low - OFFSET), ctx.pos('short'))
elif ((ctx.pos('short') > 0) and (ctx.datetime[0].time() == st3)):
ctx.cover(ctx.close, ctx.pos('short'))
set_symbols(['future.TEST-1.Minute'])
profile = add_strategy([DemoStrategyBuy('B1'), DemoStrategySell('B2'), DemoStrategyShort('B3'), DemoStrategyCover('B4')], {'capital': capital, 'ratio': [0.25, 0.25, 0.25, 0.25]})
(buy_entries, sell_entries, short_entries, cover_entries) = entries_maked_nextbar(source)
run()
lmg = Contract.long_margin_ratio('future.TEST')
multi = Contract.volume_multiple('future.TEST')
smg = Contract.short_margin_ratio('future.TEST')
(target, cashes, dts) = holdings_buy_maked_nextbar(source, buy_entries, (capital / 4), lmg, multi)
self.assertTrue(((len(profile.all_holdings(0)) == len(target)) and (len(target) > 0)), '\xe6\xa8\xa1\xe6\x8b\x9f\xe5\x99\xa8\xe6\xb5\x8b\xe8\xaf\x95\xe5\xa4\xb1\xe8\xb4\xa5\xef\xbc\x81')
for (i, hd) in enumerate(profile.all_holdings(0)):
self.assertTrue((hd['datetime'] == dts[i]), '\xe6\xa8\xa1\xe6\x8b\x9f\xe5\x99\xa8\xe6\xb5\x8b\xe8\xaf\x95\xe5\xa4\xb1\xe8\xb4\xa5\xef\xbc\x81')
self.assertAlmostEqual(hd['equity'], target[i])
for i in range(0, (len(cashes0) - 1)):
self.assertAlmostEqual(cashes0[i], cashes[i])
(target, cashes, dts) = holdings_short_maked_nextbar(source, short_entries, (capital / 4), smg, multi)
self.assertTrue(((len(profile.all_holdings(2)) == len(target)) and (len(target) > 0)), '\xe6\xa8\xa1\xe6\x8b\x9f\xe5\x99\xa8\xe6\xb5\x8b\xe8\xaf\x95\xe5\xa4\xb1\xe8\xb4\xa5\xef\xbc\x81')
for (i, hd) in enumerate(profile.all_holdings(2)):
self.assertTrue((hd['datetime'] == dts[i]), '\xe6\xa8\xa1\xe6\x8b\x9f\xe5\x99\xa8\xe6\xb5\x8b\xe8\xaf\x95\xe5\xa4\xb1\xe8\xb4\xa5\xef\xbc\x81')
self.assertAlmostEqual(hd['equity'], target[i])
for i in range(0, (len(cashes1) - 1)):
self.assertAlmostEqual(cashes1[i], cashes[i])
(target, cashes, dts) = holdings_sell_maked_nextbar(source, sell_entries, (capital / 4), lmg, multi)
self.assertTrue(((len(profile.all_holdings(1)) == len(target)) and (len(target) > 0)), '\xe6\xa8\xa1\xe6\x8b\x9f\xe5\x99\xa8\xe6\xb5\x8b\xe8\xaf\x95\xe5\xa4\xb1\xe8\xb4\xa5\xef\xbc\x81')
for (i, hd) in enumerate(profile.all_holdings(1)):
self.assertTrue((hd['datetime'] == dts[i]), '\xe6\xa8\xa1\xe6\x8b\x9f\xe5\x99\xa8\xe6\xb5\x8b\xe8\xaf\x95\xe5\xa4\xb1\xe8\xb4\xa5\xef\xbc\x81')
self.assertAlmostEqual(hd['equity'], target[i])
self.assertAlmostEqual(hd['cash'], cashes[i])
for i in range(0, (len(cashes2) - 1)):
self.assertAlmostEqual(cashes2[i], cashes[i])
(target, cashes, dts) = holdings_cover_maked_nextbar(source, cover_entries, (capital / 4), smg, multi)
self.assertTrue(((len(profile.all_holdings(3)) == len(target)) and (len(target) > 0)), '\xe6\xa8\xa1\xe6\x8b\x9f\xe5\x99\xa8\xe6\xb5\x8b\xe8\xaf\x95\xe5\xa4\xb1\xe8\xb4\xa5\xef\xbc\x81')
for (i, hd) in enumerate(profile.all_holdings(3)):
self.assertTrue((hd['datetime'] == dts[i]), '\xe6\xa8\xa1\xe6\x8b\x9f\xe5\x99\xa8\xe6\xb5\x8b\xe8\xaf\x95\xe5\xa4\xb1\xe8\xb4\xa5\xef\xbc\x81')
self.assertAlmostEqual(hd['equity'], target[i])
self.assertAlmostEqual(hd['cash'], cashes[i])
return
|
''
| def test_case4(self):
| cashes0 = []
class DemoStrategy(Strategy, ):
def on_init(self, ctx):
'\xe5\x88\x9d\xe5\xa7\x8b\xe5\x8c\x96\xe6\x95\xb0\xe6\x8d\xae'
pass
def on_bar(self, ctx):
curtime = ctx.datetime[0].time()
if (curtime in [bt1, bt2, bt3]):
ctx.buy(0, 1)
ctx.short(0, 2)
elif (curtime == st1):
assert ((ctx.pos('long') == 3) and '\xe6\x8c\x81\xe4\xbb\x93\xe6\xb5\x8b\xe8\xaf\x95\xe5\xa4\xb1\xe8\xb4\xa5\xef\xbc\x81')
ctx.sell(0, 2)
assert ((ctx.pos('short') == 6) and '\xe6\x8c\x81\xe4\xbb\x93\xe6\xb5\x8b\xe8\xaf\x95\xe5\xa4\xb1\xe8\xb4\xa5\xef\xbc\x81')
ctx.cover(0, 4)
elif (curtime == st2):
assert ((ctx.pos('long') == 1) and '\xe6\x8c\x81\xe4\xbb\x93\xe6\xb5\x8b\xe8\xaf\x95\xe5\xa4\xb1\xe8\xb4\xa5\xef\xbc\x81')
ctx.sell(0, 1)
assert ((ctx.pos('short') == 2) and '\xe6\x8c\x81\xe4\xbb\x93\xe6\xb5\x8b\xe8\xaf\x95\xe5\xa4\xb1\xe8\xb4\xa5\xef\xbc\x81')
ctx.cover(0, 2)
cashes0.append(ctx.test_cash())
set_symbols(['future.TEST-1.Minute'])
profile = add_strategy([DemoStrategy('C1')], {'capital': capital})
run()
lmg = Contract.long_margin_ratio('future.TEST')
multi = Contract.volume_multiple('future.TEST')
smg = Contract.short_margin_ratio('future.TEST')
(target, cashes, dts) = holdings_buy_short_maked_market(source, capital, lmg, smg, multi)
self.assertTrue((len(cashes0) == len(cashes)), 'cash\xe6\x8e\xa5\xe5\x8f\xa3\xe6\xb5\x8b\xe8\xaf\x95\xe5\xa4\xb1\xe8\xb4\xa5\xef\xbc\x81')
for (i, hd) in enumerate(profile.all_holdings()):
self.assertTrue((hd['datetime'] == dts[i]), '\xe6\xa8\xa1\xe6\x8b\x9f\xe5\x99\xa8\xe6\xb5\x8b\xe8\xaf\x95\xe5\xa4\xb1\xe8\xb4\xa5\xef\xbc\x81')
self.assertAlmostEqual(hd['equity'], target[i])
for i in range(0, (len(cashes0) - 1)):
self.assertAlmostEqual(cashes0[i], cashes[i])
|
''
| def test_case5(self):
| cashes0 = []
class DemoStrategy(Strategy, ):
def on_init(self, ctx):
'\xe5\x88\x9d\xe5\xa7\x8b\xe5\x8c\x96\xe6\x95\xb0\xe6\x8d\xae'
pass
def on_bar(self, ctx):
curtime = ctx.datetime[0].time()
if (curtime in [bt1, bt2, bt3]):
ctx.buy(ctx.close, 1)
ctx.short(ctx['future2.TEST-1.Minute'].close, 2, 'future2.TEST')
elif (curtime == st1):
for pos in ctx.all_positions():
if (str(pos.contract) == 'FUTURE.TEST'):
assert (pos.quantity == 3)
assert (pos.closable == 3)
assert (pos.direction == Direction.LONG)
else:
assert (pos.quantity == 6)
assert (pos.closable == 6)
assert (pos.direction == Direction.SHORT)
assert ((ctx.pos('long', 'future.TEST') == 3) and '\xe6\x8c\x81\xe4\xbb\x93\xe6\xb5\x8b\xe8\xaf\x95\xe5\xa4\xb1\xe8\xb4\xa5\xef\xbc\x81')
ctx.sell(ctx.close, 2)
assert ((ctx.pos('short', 'future2.TEST') == 6) and '\xe6\x8c\x81\xe4\xbb\x93\xe6\xb5\x8b\xe8\xaf\x95\xe5\xa4\xb1\xe8\xb4\xa5\xef\xbc\x81')
ctx.cover(ctx['future2.TEST-1.Minute'].close, 4, 'future2.TEST')
elif (curtime == st2):
assert ((ctx.pos('long', 'future.TEST') == 1) and '\xe8\xb7\xa8\xe5\x90\x88\xe7\xba\xa6\xe6\x8c\x81\xe4\xbb\x93\xe6\xb5\x8b\xe8\xaf\x95\xe5\xa4\xb1\xe8\xb4\xa5\xef\xbc\x81')
ctx.sell(ctx.close, 1, 'future.TEST')
assert ((ctx.pos('short', 'future2.TEST') == 2) and '\xe6\x8c\x81\xe4\xbb\x93\xe6\xb5\x8b\xe8\xaf\x95\xe5\xa4\xb1\xe8\xb4\xa5\xef\xbc\x81')
ctx.cover(ctx['future2.TEST-1.Minute'].close, 2, 'future2.TEST')
cashes0.append(ctx.test_cash())
set_symbols(['future.TEST-1.Minute', 'future2.TEST-1.Minute'])
profile = add_strategy([DemoStrategy('D1')], {'capital': capital})
run()
fname = os.path.join(os.getcwd(), 'data', '1MINUTE', 'TEST', 'FUTURE2.csv')
source2 = pd.read_csv(fname, parse_dates=True, index_col=0)
lmg = Contract.long_margin_ratio('future.TEST')
multi = Contract.volume_multiple('future.TEST')
(target1, cashes1, dts) = buy_closed_curbar(source, (capital / 2), lmg, multi)
multi = Contract.volume_multiple('future2.TEST')
smg = Contract.short_margin_ratio('future2.TEST')
(target2, cashes2, dts) = holdings_short_maked_curbar(source2, (capital / 2), smg, multi)
target = [(x + y) for (x, y) in zip(target1, target2)]
cashes = [(x + y) for (x, y) in zip(cashes1, cashes2)]
self.assertTrue((len(cashes0) == len(cashes)), 'cash\xe6\x8e\xa5\xe5\x8f\xa3\xe6\xb5\x8b\xe8\xaf\x95\xe5\xa4\xb1\xe8\xb4\xa5\xef\xbc\x81')
for i in range(0, (len(cashes0) - 1)):
self.assertAlmostEqual(cashes0[i], cashes[i])
for (i, hd) in enumerate(profile.all_holdings()):
self.assertTrue((hd['datetime'] == dts[i]), 'all_holdings\xe6\x8e\xa5\xe5\x8f\xa3\xe6\xb5\x8b\xe8\xaf\x95\xe5\xa4\xb1\xe8\xb4\xa5\xef\xbc\x81')
self.assertAlmostEqual(hd['equity'], target[i])
|
''
| def on_init(self, ctx):
| ctx.ma10 = MA(ctx.close, 10, 'ma10', 'y', 2)
ctx.ma20 = MA(ctx.close, 20, 'ma20', 'b', 2)
|
''
| def on_init(self, ctx):
| ctx.ma5 = MA(ctx.close, 5, 'ma5', 'y', 2)
ctx.ma10 = MA(ctx.close, 10, 'ma10', 'black', 2)
|
''
| def on_init(self, ctx):
| ctx.ma100 = MA(ctx.close, 100, 'ma100', 'y', 2)
ctx.ma200 = MA(ctx.close, 200, 'ma200', 'b', 2)
ctx.boll = BOLL(ctx.close, 20)
ctx.ma2 = NumberSeries()
|
''
| def on_init(self, ctx):
| ctx.ma50 = MA(ctx.close, 50, 'ma50', 'y', 2)
ctx.ma100 = MA(ctx.close, 100, 'ma100', 'black', 2)
|
''
| def on_init(self, ctx):
| ctx.ma10 = MA(ctx.close, 10, 'ma10', 'y', 2)
ctx.ma20 = MA(ctx.close, 20, 'ma20', 'b', 2)
|
''
| def on_init(self, ctx):
| ctx.ma5 = MA(ctx.close, 5, 'ma5', 'y', 2)
ctx.ma30 = MA(ctx.close, 30, 'ma30', 'black', 2)
|
''
| def on_init(self, ctx):
| ctx.ma10 = MA(ctx.close, 10, 'ma10', 'y', 1)
ctx.ma20 = MA(ctx.close, 20, 'ma20', 'b', 1)
ctx.dt = DateTimeSeries()
ctx.month_price = NumberSeries()
|
''
| def on_init(self, ctx):
| ctx.ma50 = MA(ctx.close, 50, 'ma50', 'y', 2)
ctx.ma100 = MA(ctx.close, 100, 'ma100', 'black', 2)
|
''
| def run_strategy(self, name):
| return
|
''
| def get_technicals(self):
| from quantdigger.technicals import get_techs
return get_techs()
|
'docstring for load_pcontract'
| def show_data(self, strpcontract):
| return self.gate.sync_call('show_data', {'pcontract': strpcontract})
|
'docstring for get_data'
| def get_pcontract(self, pcontract):
| pass
|
''
| def run_strategy(self, name):
| return
|
''
| def get_technicals(self):
| return
|
'docstring for plo'
| def plot(self):
| six.print_('plot')
|
''
| def add_technical(self, ith, technical):
| return
|
''
| def run_strategy(self, name):
| return
|
''
| def get_technicals(self):
| return
|
''
| def get_strategies(self):
| return
|
'Returns:
pd.DataFrame'
| def get_contracts(self):
| fname = os.path.join(self._root, 'CONTRACTS.csv')
df = pd.read_csv(fname)
df.index = ((df['code'] + '.') + df['exchange'])
df.index = map((lambda x: x.upper()), df.index)
return df
|
'Args:
tbdata (dict): {\'datetime\', \'open\', \'close\',
\'high\', \'low\', \'volume\'}
pcontract (PContract): åšæå纊'
| def import_bars(self, tbdata, pcontract):
| strpcon = str(pcontract).upper()
(contract, period) = tuple(strpcon.split('-'))
(code, exch) = tuple(contract.split('.'))
period = period.replace('.', '')
try:
os.makedirs(os.path.join(self._root, period, exch))
except OSError:
pass
fname = os.path.join(self._root, period, exch, (code + '.csv'))
df = pd.DataFrame(tbdata)
df.to_csv(fname, columns=['datetime', 'open', 'close', 'high', 'low', 'volume'], index=False)
|
'Args:
data (dict): {key, code, exchange, name, spell,
long_margin_ratio, short_margin_ratio, price_tick, volume_multiple}'
| def import_contracts(self, data):
| fname = os.path.join(self._root, 'CONTRACTS.csv')
df = pd.DataFrame(data)
df.to_csv(fname, columns=['code', 'exchange', 'name', 'spell', 'long_margin_ratio', 'short_margin_ratio', 'price_tick', 'volume_multiple'], index=False)
|
'Returns:
pd.DataFrame.'
| def get_contracts(self):
| self._cursor.execute('select * from contract')
data = self._cursor.fetchall()
data = zip(*data)
df = pd.DataFrame({'code': data[1], 'exchange': data[2], 'name': data[3], 'spell': data[4], 'long_margin_ratio': data[5], 'short_margin_ratio': data[6], 'price_tick': data[7], 'volume_multiple': data[8]}, index=data[0])
return df
|
'Args:
tbdata (dict): {\'datetime\', \'open\', \'close\',
\'high\', \'low\', \'volume\'}
pcontract (PContract): åšæå纊'
| def import_bars(self, tbdata, pcontract):
| strpcon = str(pcontract).upper()
data = []
(ids, utimes) = ([], [])
strdt = strpcon.split('-')[1].upper()
tbname = strpcon.split('-')[0].split('.')
tbname = '_'.join([tbname[1], tbname[0]])
for dt in tbdata['datetime']:
(id, utime) = datautil.encode2id(strdt, dt)
ids.append(id)
utimes.append(utime)
data = zip(ids, utimes, tbdata['open'], tbdata['close'], tbdata['high'], tbdata['low'], tbdata['volume'])
try:
self._cursor.execute('CREATE TABLE {tb}\n (id int primary key,\n datetime timestamp,\n open real,\n close real,\n high real,\n low real,\n volume int)'.format(tb=tbname))
self._db.commit()
except sqlite3.OperationalError:
pass
finally:
sql = ('INSERT INTO %s VALUES (?,?,?,?,?,?,?)' % tbname)
self._cursor.executemany(sql, data)
self._db.commit()
|
'Args:
data (dict): {key, code, exchange, name, spell,
long_margin_ratio, short_margin_ratio, price_tick, volume_multiple}'
| def import_contracts(self, data):
| tbname = 'contract'
data['key'] = map((lambda x: x.upper()), data['key'])
data = zip(data['key'], data['code'], data['exchange'], data['name'], data['spell'], data['long_margin_ratio'], data['short_margin_ratio'], data['price_tick'], data['volume_multiple'])
sql = 'CREATE TABLE {tb}\n (key text primary key,\n code text not null,\n exchange text not null,\n name text not null,\n spell text not null,\n long_margin_ratio real not null,\n short_margin_ratio real not null,\n price_tick real not null,\n volume_multiple real not null\n )'.format(tb=tbname)
self._cursor.execute(sql)
sql = ('INSERT INTO %s VALUES (?,?,?,?,?,?,?,?,?)' % tbname)
self._cursor.executemany(sql, data)
self._db.commit()
|
''
| def rolling_forward(self):
| self.curbar += 1
if (self.curbar == self._max_length):
return (False, self.curbar)
else:
return (True, self.curbar)
|
''
| def __init__(self, profile, n=10, intraday=False):
| self.fig = plt.figure(facecolor='white')
self.fig.canvas.set_window_title('future data analyze')
self.nbar = n
self.cursors = []
self.data = process_data(n, intraday, self.get_tradeinfo(profile), profile.data())
self.axes = []
self.rax = plt.axes([0, 0.5, 0.08, 0.15])
self.radio = RadioButtons(self.rax, ('scatter', 'summary', 'summary2', 'entry', 'exit', 'simple'), active=0)
self.update('scatter')
self.radio.on_clicked(self.update)
summary(self.data)
|
'docstring for fname'
| def get_tradeinfo(self, profile):
| entry_datetime = []
exit_datetime = []
entry_price = []
exit_price = []
islong = []
for deal in profile.deals():
entry_datetime.append(deal.open_datetime)
exit_datetime.append(deal.close_datetime)
entry_price.append(deal.open_price)
exit_price.append(deal.close_price)
v = (True if (deal.direction == 1) else False)
islong.append(v)
tradeinfo = pd.DataFrame({'entry_price': entry_price, 'exit_datetime': exit_datetime, 'exit_price': exit_price, 'islong': islong}, index=entry_datetime)
return tradeinfo
|
'Return the label for time x at position pos'
| def __call__(self, x, pos=0):
| ind = int(round(x))
if ((ind >= len(self.dates)) or (ind < 0)):
return ''
return self.dates[ind].strftime(self.fmt)
|
'docstring for on_motion'
| def on_pick(self, event):
| six.print_('888888')
six.print_(str(event.mouseevent.xdata))
|
'docstring for on_motion'
| def on_move(self, event):
| if isinstance(event.xdata, np.float64):
i = (int(event.xdata) / 1)
if (self.pre_x != i):
six.print_(self.data.index[i])
six.print_(self.data[i])
c = ((pd.to_datetime(self.data.index[i]).strftime('%Y-%m-%d %H:%M:%S') + '\n') + 'hh')
self.fig.axes[2].set_xlabel(c)
self.pre_x = i
|
''
| def _rolling_algo(self, data, n, i):
| raise NotImplementedError
|
'åéåè¿è¡, ç»æå¿
é¡»èµåŒç»self.valuesã
Args:
data (np.ndarray): æ°æ®
n (int): æ¶éŽçªå£å€§å°'
| def _vector_algo(self, data, n):
| raise NotImplementedError
|
''
| def compute(self):
| if (not hasattr(self, '_args')):
raise Exception('\xe6\xaf\x8f\xe4\xb8\xaa\xe6\x8c\x87\xe6\xa0\x87\xe9\x83\xbd\xe5\xbf\x85\xe9\xa1\xbb\xe6\x9c\x89_args\xe5\xb1\x9e\xe6\x80\xa7\xef\xbc\x8c\xe4\xbb\xa3\xe8\xa1\xa8\xe6\x8c\x87\xe6\xa0\x87\xe8\xae\xa1\xe7\xae\x97\xe7\x9a\x84\xe5\x8f\x82\xe6\x95\xb0\xef\xbc\x81')
self.data = self._args[0]
self._vector_algo(*tuple(self._args))
if (not hasattr(self, 'values')):
raise Exception('\xe6\xaf\x8f\xe4\xb8\xaa\xe6\x8c\x87\xe6\xa0\x87\xe9\x83\xbd\xe5\xbf\x85\xe9\xa1\xbb\xe6\x9c\x89value\xe5\xb1\x9e\xe6\x80\xa7\xef\xbc\x8c\xe4\xbb\xa3\xe8\xa1\xa8\xe6\x8c\x87\xe6\xa0\x87\xe8\xae\xa1\xe7\xae\x97\xe7\xbb\x93\xe6\x9e\x9c\xef\xbc\x81')
if isinstance(self.values, dict):
self.series = OrderedDict()
for (key, value) in six.iteritems(self.values):
self.series[key] = series.NumberSeries(value, self.name, self, float('nan'))
for (key, value) in six.iteritems(self.series):
setattr(self, key, value)
self.is_multiple = True
else:
self.series = [series.NumberSeries(self.values, self.name, self, float('nan'))]
self.is_multiple = False
self._init_bound()
|
'计ç®äžäžªå溯åŒ, 被Serieså»¶è¿è°çšã
Args:
cache_index (int): çŒå玢åŒ
rolling_index (int): åæº¯çŽ¢åŒ'
| def compute_element(self, cache_index, rolling_index):
| pass
|
''
| def __size__(self):
| if self.is_multiple:
return len(self.series.itervalues().next())
return len(self.series[0])
|
'data (NumberSeries/np.ndarray/list)'
| @tech_init
def __init__(self, data, n, name='MA', style='y', lw=1):
| super(MA, self).__init__(name)
self._args = [ndarray(data), n]
|
''
| def _rolling_algo(self, data, n, i):
| return (talib.SMA(data, n)[i],)
|
'åéåè¿è¡, ç»æå¿
é¡»èµåŒç»self.valuesã
Args:
data (np.ndarray): æ°æ®
n (int): æ¶éŽçªå£å€§å°'
| def _vector_algo(self, data, n):
| self.values = talib.SMA(data, n)
|
'ç»åŸïŒåæ°å¯ç±UIè°æŽã'
| def plot(self, widget):
| self.widget = widget
self.plot_line(self.values, self.style, lw=self.lw)
|
''
| def _rolling_algo(self, data, n, a1, a2, i):
| (upper, middle, lower) = talib.BBANDS(data, n, a1, a2)
return (upper[i], middle[i], lower[i])
|
''
| def _vector_algo(self, data, n, a1, a2):
| (u, m, l) = talib.BBANDS(data, n, a1, a2)
self.values = {'upper': u, 'middler': m, 'lower': l}
|
'ç»åŸïŒåæ°å¯ç±UIè°æŽã'
| def plot(self, widget):
| self.widget = widget
self.plot_line(self.values['upper'], self.styles[0], lw=self.lw)
self.plot_line(self.values['middler'], self.styles[1], lw=self.lw)
self.plot_line(self.values['lower'], self.styles[2], lw=self.lw)
|
'Args:
*args (tuple): [_xdata], ydata, style
**kwargs (dict): lw, ms'
| def plot_line(self, *args, **kwargs):
| lw = kwargs.get('lw', 1)
ms = kwargs.get('ms', 10)
if (len(args[0]) > 0):
if (len(args) == 2):
ydata = args[0]
style = args[1]
if isinstance(self.widget, Axes):
self.ax_widget.plot_line(self.widget, ydata, style, lw, ms)
else:
self.qt_widget.plot_line(self.widget, ydata, style, lw, ms)
elif (len(args) == 3):
_xdata = args[0]
ydata = args[1]
style = args[2]
if isinstance(self.widget, Axes):
self.ax_widget.plot_line_withx(self.widget, _xdata, ydata, style, lw, ms)
else:
self.qt_widget.plot_line_withx(self.widget, _xdata, ydata, style, lw, ms)
|
''
| def plot(self, widget):
| raise NotImplementedError
|
'åºå®çºµåæ èåŽãåŠRSIææ ã
:ivar y_range: çºµåæ èåŽã
:vartype y_range: list'
| def stick_yrange(self, y_range):
| self._lower = y_range
self._upper = y_range
|
'å¯è§åºå[w_left, w_right]ç§»åšæ¶åéæ°è®¡ç®çºµåæ èåŽã'
| def y_interval(self, w_left, w_right):
| if (len(self._upper) == 2):
return (max(self._upper), min(self._lower))
try:
if self._xdata:
(w_left, w_right) = sub_interval(w_left, w_right, self._xdata)
except ValueError:
return ((-1000000), 1000000)
else:
ymax = np.max(self._upper[w_left:w_right])
ymin = np.min(self._lower[w_left:w_right])
return (ymax, ymin)
|
'Represent the open, close as a bar line and high low range as a
vertical line.
ax : an Axes instance to plot to
width : the bar width in points
colorup : the color of the lines where close >= open
colordown : the color of the lines where close < open
alpha : bar transparency
return value is lineCollection, barCollection'
| def __init__(self, data, tracker, name='candle', width=0.6, colorup='r', colordown='g', lc='k', alpha=1):
| self.data = data
self.name = name
self.width = width
self.colorup = colorup
self.colordown = colordown
self.lc = lc
self.alpha = alpha
self.lineCollection = []
self.barCollection = []
|
'Create a slider from *valmin* to *valmax* in axes *ax*
*valinit*
The slider initial position
*label*
The slider label
*valfmt*
Used to format the slider value
*closedmin* and *closedmax*
Indicate whether the slider interval is closed
*slidermin* and *slidermax*
Used to constrain the value of this slider to the values
of other sliders.
additional kwargs are passed on to ``self.poly`` which is the
:class:`matplotlib.patches.Rectangle` which draws the slider
knob. See the :class:`matplotlib.patches.Rectangle` documentation
valid property names (e.g., *facecolor*, *edgecolor*, *alpha*, ...)'
| def __init__(self, ax, name, label, valmin, valmax, valinit=0.5, width=1, valfmt='%1.2f', time_index=None, closedmin=True, closedmax=True, slidermin=None, slidermax=None, drag_enabled=True, **kwargs):
| AxesWidget.__init__(self, ax)
self.label = ax.text((-0.02), 0.5, label, transform=ax.transAxes, verticalalignment='center', horizontalalignment='right')
self.valtext = None
self.poly = None
self.reinit(valmin, valmax, valinit, width, valfmt, time_index, **kwargs)
self.name = name
self.cnt = 0
self.closedmin = closedmin
self.closedmax = closedmax
self.slidermin = slidermin
self.slidermax = slidermax
self.drag_active = False
self.drag_enabled = drag_enabled
self.observers = {}
ax.set_yticks([])
ax.set_navigate(False)
self._connect()
|
'docstring for timess'
| def _value_format(self, x):
| ind = int(round(x))
if ((ind >= len(self._index)) or (ind < 0)):
return ''
return self._index[ind].strftime(self._fmt)
self._slider = Slider(0, (self._data_length - 1), (self._data_length - 1), (self._data_length / 50), '%d', self._data.index)
|
'[valmin, valmax]'
| def reinit(self, valmin, valmax, valinit=0.5, width=1, valfmt='%1.2f', time_index=None, **kwargs):
| self.ax.set_xticks(self._xticks_to_display(valmax))
self._index = time_index
self.valmin = valmin
self.valmax = valmax
self.val = valinit
self.valinit = valinit
self.width = width
self.valfmt = valfmt
self._fmt = slider_strtime_format((time_index[1] - time_index[0]))
self.ax.set_xlim((valmin, valmax))
self._data_length = valmax
if self.valtext:
self.valtext.remove()
if self.poly:
self.poly.remove()
self.poly = self.ax.axvspan((valmax - (self.width / 2)), (valmax + (self.width / 2)), 0, 1, **kwargs)
self.valtext = self.ax.text(1.005, 0.5, self._value_format(valinit), transform=self.ax.transAxes, verticalalignment='center', horizontalalignment='left')
|
'When the slider value is changed, call *func* with the new
slider position
A connection id is returned which can be used to disconnect'
| def add_observer(self, obj):
| self.observers[obj.name] = obj
|
'remove the observer with connection id *cid*'
| def remove_observer(self, cid):
| try:
del self.observers[cid]
except KeyError:
pass
|
'reset the slider to the initial value if needed'
| def reset(self):
| if (self.val != self.valinit):
self._set_val(self.valinit)
|
'update the slider position'
| def on_event(self, event):
| if self.ignore(event):
return
if (event.button != 1):
return
if ((event.name == 'button_press_event') and (event.inaxes == self.ax)):
self.drag_active = True
event.canvas.grab_mouse(self.ax)
if (not self.drag_active):
return
elif ((event.name == 'button_press_event') and (event.inaxes != self.ax)):
self.drag_active = False
event.canvas.release_mouse(self.ax)
return
elif ((event.name == 'button_release_event') and (event.inaxes == self.ax)):
self.drag_active = False
event.canvas.release_mouse(self.ax)
self._update_observer(event)
return
self._update(event.xdata)
self._update_observer(event)
|
''
| def _update_observer(self, event):
| for (name, obj) in six.iteritems(self.observers):
try:
obj.on_slider(self.val, event)
except Exception as e:
six.print_(e)
|
'Create a slider from *valmin* to *valmax* in axes *ax*'
| def __init__(self, ax, name, wdlength, min_wdlength):
| AxesWidget.__init__(self, ax)
self.name = name
self.wdlength = wdlength
self.min_wdlength = min_wdlength
self.voffset = 0
self.connect()
self.plotters = {}
self.cnt = 0
self.observers = {}
|
'æ·»å å¹¶ç»å¶, äžå
讞éåçplotter'
| def add_plotter(self, plotter, twinx):
| if (plotter.name in self.plotters):
raise
if (not self.plotters):
twinx = False
if twinx:
twaxes = self.ax.twinx()
plotter.plot(twaxes)
plotter.ax = twaxes
plotter.twinx = True
else:
plotter.plot(self.ax)
plotter.ax = self.ax
plotter.twinx = False
self.plotters[plotter.name] = plotter
|
'update the slider position'
| def _update(self, event):
| self.update(event.xdata)
|
'When the slider value is changed, call *func* with the new
slider position
A connection id is returned which can be used to disconnect'
| def add_observer(self, obj):
| self.observers[obj.name] = obj
|
'remove the observer with connection id *cid*'
| def disconnect(self, cid):
| try:
del self.observers[cid]
except KeyError:
pass
|
'Args:
fig (Figure): matplotlibç»åŸå®¹åšã
data (DataFrame): [open, close, high, low]æ°æ®è¡šã'
| def __init__(self, fig, data, left=0.1, bottom=0.05, width=0.85, height=0.9, parent=None):
| self.name = 'MultiWidgets'
self._fig = fig
self._subwidgets = {}
self._cursor = None
self._cursor_axes_index = {}
self._hoffset = 1
(self._left, self._width) = (left, width)
(self._bottom, self._height) = (bottom, height)
self._slider_height = 0.1
self._bigger_picture_height = 0.3
self._all_axes = []
self.load_data(data)
self._cursor_axes = {}
|
''
| def draw_widgets(self):
| self._w_left = (self._data_length - self._w_width)
self._w_right = self._data_length
self._reset_auxiliary_widgets()
self._update_widgets()
|
'Args:
ith_subwidget (int.): åçªå£åºå·ã
widget (AxesWidget): æ§ä»¶ã
Returns:
AxesWidget. widget'
| def add_widget(self, ith_subwidget, widget, ymain=False, connect_slider=False):
| for plotter in six.itervalues(widget.plotters):
if plotter.twinx:
plotter.ax.format_coord = self._format_coord
self.axes.append(plotter.ax)
self._cursor = MultiCursor(self._fig.canvas, list(self._cursor_axes.values()), color='r', lw=2, horizOn=False, vertOn=True)
self._subwidgets[ith_subwidget] = widget
if connect_slider:
self._slider.add_observer(widget)
return widget
|
''
| def on_slider(self, val, event):
| if (event.name == 'button_press_event'):
self._bigger_picture.set_zorder(1000)
self._slider_cursor = MultiCursor(self._fig.canvas, [self._slider_ax, self._bigger_picture], color='y', lw=2, horizOn=False, vertOn=True)
log.debug('on_press_event')
elif (event.name == 'button_release_event'):
self._bigger_picture.set_zorder(0)
del self._slider_cursor
log.debug('on_release_event')
elif (event.name == 'motion_notify_event'):
pass
self._w_left = int(val)
self._w_right = (self._w_left + self._w_width)
if (self._w_right >= self._data_length):
self._w_right = ((self._data_length - 1) + self._hoffset)
self._w_left = (self._w_right - self._w_width)
self._update_widgets()
|
''
| def _clear(self):
| return
|
'matplotlibä¿¡å·è¿æ¥ã'
| def _connect(self):
| self.cidpress = self._fig.canvas.mpl_connect('button_press_event', self.on_press)
self.cidrelease = self._fig.canvas.mpl_connect('button_release_event', self.on_release)
self.cidmotion = self._fig.canvas.mpl_connect('motion_notify_event', self.on_motion)
self._fig.canvas.mpl_connect('axes_enter_event', self.on_enter_axes)
self._fig.canvas.mpl_connect('axes_leave_event', self.on_leave_axes)
self._fig.canvas.mpl_connect('key_release_event', self.on_keyrelease)
|
''
| def _update_widgets(self):
| self.axes[0].set_xlim((int(self._w_left), int(self._w_right)))
self._set_ylim(int(self._w_left), int(self._w_right))
self._fig.canvas.draw()
|
'讟眮åœåæŸç€ºçªå£çy蜎èåŽã'
| def _set_ylim(self, w_left, w_right):
| for subwidget in six.itervalues(self._subwidgets):
subwidget.set_ylim(w_left, w_right)
|
''
| def _format_coord(self, x, y):
| index = x
f = (x % 1)
index = ((x - f) if (f < 0.5) else min(((x - f) + 1), (len(self._data['open']) - 1)))
delta = (self._data.index[1] - self._data.index[0])
fmt = slider_strtime_format(delta)
index = int(index)
return ('[dt=%s o=%.2f c=%.2f h=%.2f l=%.2f]' % (self._data.index[index].strftime(fmt), self._data['open'][index], self._data['close'][index], self._data['high'][index], self._data['low'][index]))
|
'Return the label for time x at position pos'
| def __call__(self, x, pos=0):
| ind = int(round(x))
if ((ind >= len(self.dates)) or (ind < 0)):
return ''
return self.dates[ind].strftime(self.fmt)
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.