def before_ranking(date, ranking_type, before=1): d = utils.to_datetime(date) - utils.relativeterm(before, with_time=True) while not utils.is_weekday(d): d = d - utils.relativeterm(1, with_time=True) d = utils.to_format(d) stocks = Loader.ranking(d, ranking_type) return stocks
def convert_pdf(): title, head_image, article = get_content() if is_weekday(): logger.warning("周末不发版") return "周末不发版" year, month, day = get_now_day() directory = get_today_directory() filename = f'{directory}/{year}{month}{day}.pdf' html = pre.format(title=title, article=article, head_image=head_image) pdfkit.from_string(html, filename, configuration=config, options=options)
def job(): if utils.is_weekday(): logging.info( "*********************************************************************" ) if utils.need_update_data(): logging.info("更新数据") process.run() stocks = utils.get_stocks() m_filter = strategy(end_date=None) results = list(filter(m_filter, stocks)) logging.info('选股结果:{0}'.format(results)) logging.info( "*********************************************************************" )
def simulates(self, strategy_setting, data, start_date, end_date, with_closing=True, ignore_manda=True): self.log("simulating %s %s" % (start_date, end_date)) self.stats = SimulatorStats() args = data["args"] stocks = data["data"] index = data["index"] codes = self.get_targets(args, [], start_date) # シミュレーター準備 combination, simulators = self.create_simulator( args, codes, stocks, start_date, end_date, strategy_setting, ignore_manda) # 日付のリストを取得 dates = self.simulate_dates(codes, stocks, start_date, end_date) self.log("targets: %s" % list(simulators.keys())) capacity = None for step, date in enumerate(dates): # 休日はスキップ if not utils.is_weekday(utils.to_datetime(date)): self.log("%s is not weekday" % date) continue self.log("\n=== [%s] ===" % date) stats = self.stats.create_trade_data() stats["date"] = date binding = sum( list(map(lambda x: x.order_binding(), simulators.values()))) for code in simulators.keys(): # 対象日までのデータの整形 self.log("[%s]" % code) # M&A 適用 simulators = self.manda_by_date(date, code, simulators) simulators[code].capacity = simulators[ code].capacity if capacity is None else capacity simulators[code].binding = binding - simulators[ code].order_binding() # 自分の拘束分はsimulator側で加算するので引いておく simulators[code].simulate_by_date(date, stocks[code], index) capacity = simulators[code].capacity binding += simulators[code].order_binding( ) - simulators[code].unbound stats["unrealized_gain"] = self.sum_stats( simulators, lambda x: x.stats.last_unrealized_gain()) stats["gain"] = self.sum_stats(simulators, lambda x: x.stats.get("gain", 0)) self.stats.append(stats) stats, simulators = self.closing(stats, simulators) self.log( "gain: %s, %s, %s" % (stats["unrealized_gain"], stats["gain"], capacity + binding)) # 手仕舞い if with_closing: simulators = self.force_closing(dates, stocks, simulators) return simulators
def job(): if utils.is_weekday(): #work_flow.process() return TRUE
def job(): if utils.is_weekday(): work_flow.process()
def edit_timeline(self, bucket, intial_location_str, radius): condition = True tries = 0 while True: location_type = np.random.choice(self.buckets[bucket]) print(location_type) response = self.query(intial_location_str, radius, location_type) tries += 1 if len(response['results']) == 0 and tries < 3: continue else: break if len(response['results']) == 0: return {} pruned_results = list( np.random.choice(response['results'], self.places[bucket])) if len(pruned_results) == 0: return {} if self.events[bucket] == 'everyday': for key in self.timeline.keys(): location = np.random.choice( pruned_results)['geometry']['location'] self.timeline[key].append(update_timestamp(location, key)) elif self.events[bucket] == 'weekday': for key in self.timeline.keys(): if is_weekday(key): location = np.random.choice( pruned_results)['geometry']['location'] self.timeline[key].append(update_timestamp(location, key)) else: continue elif self.events[bucket] == 'regular': random_number = np.random.randint(7, 10) chosen_keys = np.random.choice(list(self.timeline.keys()), random_number) for key in chosen_keys: location = np.random.choice( pruned_results)['geometry']['location'] self.timeline[key].append(update_timestamp(location, key)) elif self.events[bucket] == 'occasional': random_number = np.random.randint(4, 7) chosen_keys = np.random.choice(list(self.timeline.keys()), random_number) for key in chosen_keys: location = np.random.choice( pruned_results)['geometry']['location'] self.timeline[key].append(update_timestamp(location, key)) elif self.events[bucket] == 'rare': random_number = np.random.randint(0, 3) chosen_keys = np.random.choice(list(self.timeline.keys()), random_number) for key in chosen_keys: location = np.random.choice( pruned_results)['geometry']['location'] self.timeline[key].append(update_timestamp(location, key)) return np.random.choice(pruned_results)['geometry']['location']
def apply_trace(figure, before, date, code, row, col, rows, cols, layout, options): args = create_args(code) end = date start = utils.to_format( utils.to_datetime(end) - utils.relativeterm(int(before))) simulator_data = strategy.load_simulator_data( args.code, start, end, args, names=["average"] if options["use_multi"] else []) df = simulator_data.middle df = df[df["date"] >= start] df = df.reset_index() # 陽線-> candle.data[1], 陰線 -> candle.data[0] candle = FF.create_candlestick(df["open"], df["high"], df["low"], df["close"], dates=df["date"]) stocks = list(candle.data) figure = add_stats(figure, row, col, stocks, df, []) # ローソク足をグラフに適用 # 日付リスト dates = list(map(lambda x: utils.to_datetime(x), df["date"].astype(str))) rangebreaks = [{ "values": list( filter(lambda x: not utils.is_weekday(x), utils.daterange(dates[0], dates[-1]))) }] # 休日を除外 daterange = [dates[0], dates[-1]] layout_settings = create_layout_settings(options) if options["use_multi"]: setting = layout_settings[0] setting["line"] = [setting["line"][0]] # candle with average layout_settings = [setting] # =================================================================== # layout_settingをもとに各グラフにデータを入れる domain_from = 0 for setting in sorted(layout_settings, key=lambda x: x["to"]): i = row if options["use_multi"] else setting["id"] label_i = ( (col - 1) + (row - 1) * cols) + 1 if options["use_multi"] else setting["id"] # multiの場合同じlegendがいくつも並ぶので最初のだけ有効に showlegend = layout["showlegend"] and row == 1 and col == 1 if options[ "use_multi"] else layout["showlegend"] figure = apply_fig_setting(figure, i, col, df, setting["bar"], mode="bar", showlegend=showlegend) figure = apply_fig_setting(figure, i, col, df, setting["line"], mode="lines", showlegend=showlegend) figure = apply_fig_setting(figure, i, col, df, setting["marker"], mode="markers", showlegend=showlegend) xlabel = "xaxis%s" % label_i layout[xlabel] = { "range": daterange, "rangebreaks": rangebreaks, "scaleanchor": "x1" } if not options["use_multi"]: ylabel = "yaxis%s" % label_i layout[ylabel] = {"domain": [domain_from, setting["to"]]} layout[xlabel]["domain"] = [0.0, 1.0] domain_from = setting["to"] return figure, layout
def simulates(self, strategy_setting, data, start_date, end_date, with_closing=True, ignore_manda=True): self.log(lambda: "simulating %s %s" % (start_date, end_date)) self.stats = SimulatorStats() args = data["args"] stocks = data["data"] index = data["index"] codes = self.get_targets(args, [], start_date) # ファイル読込あり # シミュレーター準備 combination, simulators = self.create_simulator(args, codes, stocks, start_date, end_date, strategy_setting, ignore_manda) # 日付のリストを取得 dates = self.simulate_dates(codes, stocks, start_date, end_date) self.log(lambda: "targets: %s" % list(simulators.keys())) deposit = None for step, date in enumerate(dates): # 休日はスキップ if not utils.is_weekday(utils.to_datetime(date)): self.log(lambda: "%s is not weekday" % date) continue self.log(lambda: "\n=== [%s] ===" % date) stats = self.stats.create_trade_data() stats["date"] = date binding = sum(list(map(lambda x: x.order_binding(), simulators.values()))) # atrを元にhard_limitを設定 atrs = list(map(lambda x: int(stocks[x].middle[stocks[x].middle["date"] <= date]["atr"].iloc[-1]), simulators.keys())) hard_limit = max(atrs) self.log(lambda : "allow_max_loss: %s, hard_limit: %s" % (hard_limit * self.combination_setting.max_position_size * self.simulator_setting.min_unit, hard_limit)) risk = 0 for code in simulators.keys(): # 対象日までのデータの整形 self.log(lambda: "[%s]" % code) # M&A 適用 simulators = self.manda_by_date(date, code, simulators) # hard_limit設定 simulators[code].setting.hard_limit = hard_limit if self.combination_setting.auto_limit else None if self.simulator_setting.use_deposit: simulators[code].update_deposit(simulators[code].deposit if deposit is None else deposit) else: simulators[code].capacity = simulators[code].capacity if deposit is None else deposit simulators[code].binding = binding - simulators[code].order_binding() # 自分の拘束分はsimulator側で加算するので引いておく simulators[code].simulate_by_date(date, stocks[code], index) deposit = simulators[code].deposit if self.simulator_setting.use_deposit else simulators[code].capacity binding += simulators[code].order_binding() - simulators[code].unbound if risk > self.simulator_setting.assets * 0.1 and self.combination_setting.auto_limit: self.log(lambda : " ! clear orders. risk: %s" % (risk)) simulators[code].clear_orders() last_order = simulators[code].stats.last()["new_order"] risk = risk + hard_limit * (0 if last_order is None else last_order.num) * self.simulator_setting.min_unit stats["unrealized_gain"] = self.sum_stats(simulators, lambda x: x.stats.last_unrealized_gain()) stats["gain"] = self.sum_stats(simulators, lambda x: x.stats.get("gain", 0)) self.stats.append(stats) stats, simulators = self.closing(args, stats, simulators) self.log(lambda: "unrealized_gain: %s, gain: %s, total gain: %s, deposit: %s, binding: %s" % (stats["unrealized_gain"], stats["gain"], sum(self.stats.gain()), deposit, binding)) # 手仕舞い if with_closing: simulators = self.force_closing(dates, stocks, simulators) return simulators