Example #1
0
 def __is_valid_intrinio_record(self, record: Dict) -> bool:
     fiscal_period: str = record.get(
         AppConsts.INTRINIO_KEY_INC_STMT_FISC_PD)
     return record \
         and not StringUtils.isNullOrWhitespace(record.get(AppConsts.INTRINIO_KEY_INC_STMT_TICKER)) \
         and not StringUtils.isNullOrWhitespace(record.get(AppConsts.INTRINIO_KEY_INC_STMT_NAME)) \
         and not StringUtils.isNullOrWhitespace(fiscal_period) \
         and (fiscal_period.endswith(AppConsts.INTRINIO_PERIOD_SUFFIX_TTM) or fiscal_period.endswith(AppConsts.INTRINIO_PERIOD_SUFFIX_FY))
Example #2
0
 def get_date(datestr: str, fmt: str) -> date:
     if not isinstance(datestr, str) \
             or not isinstance(fmt, str) \
             or StringUtils.isNullOrWhitespace(datestr) \
             or StringUtils.isNullOrWhitespace(fmt):
         return None
     try:
         return datetime.strptime(datestr, fmt)
     except Exception as ex:
         LogUtils.warning('Invalid date inputs={0} {1}'.format(
             datestr, fmt))
         return None
Example #3
0
    def get_all_suggestions(self) -> int:
        error: Exception = None
        try:

            accnt: Account = self.get_account()
            capital: float = NumberUtils.to_floor(
                NumberUtils.to_float(accnt._raw['buying_power']) /
                2)  # 2 to trade everyday

            # Double Bottoms
            req: TradeSuggestionsRequest = TradeSuggestionsRequest()
            req.is_job = True
            req.current_capital = capital
            req.pct_risk_per_trade = 2.5
            req.volume_limit = 0.01
            req.test_limit_symbol = 800
            req.adv_min = AppConsts.ADV_MIN_DFLT
            req.adpv_min = AppConsts.ADPV_MIN_DFLT
            req.strategy_type = AppConsts.STRATEGY_DOUBLE_BOTTOMS
            req.strategy_request = {}
            req.strategy_request['exponential_smoothing_alpha'] = 0.8
            req.strategy_request['exponential_smoothing_max_min_diff'] = 0.7
            req.strategy_request['double_bottoms_diff'] = 1
            LogUtils.debug(StringUtils.to_json(req))
            self.get_suggestions(req)

            # Double Tops
            req: TradeSuggestionsRequest = TradeSuggestionsRequest()
            req.is_job = True
            req.current_capital = capital
            req.pct_risk_per_trade = 2.5
            req.volume_limit = 0.01
            req.test_limit_symbol = 800
            req.adv_min = AppConsts.ADV_MIN_DFLT
            req.adpv_min = AppConsts.ADPV_MIN_DFLT
            req.strategy_type = AppConsts.STRATEGY_DOUBLE_TOPS
            req.strategy_request = {}
            req.strategy_request['exponential_smoothing_alpha'] = 0.8
            req.strategy_request['exponential_smoothing_max_min_diff'] = 0.7
            req.strategy_request['double_tops_diff'] = 1
            LogUtils.debug(StringUtils.to_json(req))
            self.get_suggestions(req)

        except Exception as ex:
            error = ex
        finally:
            self.__email_client.send_html(
                subject=AppConsts.EMAIL_SUBJECT_GET_SUGGESTIONS,
                template_path=AppConsts.TEMPLATE_PATH_GET_SUGGESTIONS,
                model={'errors': [error] if error else []})
            if error:
                LogUtils.error('Get Suggestions Error', error)
            return 1
Example #4
0
 def is_valid_model(self) -> bool:
     return not StringUtils.isNullOrWhitespace(self.strategy_type) \
         and self.pct_risk_per_trade > 0 \
         and self.pct_risk_per_trade <= 100 \
         and self.volume_limit >= 0.01 \
         and self.volume_limit <= 100 \
         and self.test_limit_symbol >= 1
Example #5
0
 def get_files(file_path: str, is_full: bool = False) -> List[str]:
     if StringUtils.isNullOrWhitespace(file_path):
         return []
     path: str = os.path.join(os.getcwd(), file_path)
     if is_full:
         return [os.path.join(path, f) for f in os.listdir(path)]
     return os.listdir(path)
Example #6
0
 def parse_as_list(file_path: str) -> List[List[str]]:
     try:
         LogUtils.debug('START')
         if StringUtils.isNullOrWhitespace(file_path):
             return []
         with open(file_path) as f:
             return list(csv.reader(f)) if f else []
     finally:
         LogUtils.debug('END')
Example #7
0
 def __get_quarter(self, fiscal_period: str) -> int:
     if StringUtils.isNullOrWhitespace(fiscal_period):
         return None
     if fiscal_period.endswith(AppConsts.INTRINIO_PERIOD_SUFFIX_FY):
         return 4
     return NumberUtils.to_int(
         fiscal_period.replace(AppConsts.INTRINIO_PERIOD_PREFIX,
                               '').replace(
                                   AppConsts.INTRINIO_PERIOD_SUFFIX_TTM,
                                   ''))
Example #8
0
    def cancel_order(self, order_id: str) -> None:
        try:

            LogUtils.debug('Submit request = {0}'.format(order_id))

            self.__api.cancel_order(order_id)

        except Exception as ex:
            LogUtils.error(
                'Submit Error for {0}'.format(StringUtils.to_json(order)), ex)
            raise ex
Example #9
0
 def __get_caller() -> Tuple[str, str, int]:
     frame: FrameType = inspect.currentframe()
     frame = frame.f_back if frame else frame
     caller: Tuple[str, str,
                   int] = ('(unknown file)', '(unknown function)', 0)
     while hasattr(frame, "f_code"):
         co: CodeType = frame.f_code
         if StringUtils.are_eq(co.co_filename, __file__):
             frame = frame.f_back
             continue
         caller = (FileUtils.get_base_name(co.co_filename), co.co_name,
                   frame.f_lineno)
         break
     return caller
Example #10
0
 def is_valid_model(self) -> bool:
     return not StringUtils.isNullOrWhitespace(self.strategy_type) \
         and self.start_capital > 0 \
         and self.pct_risk_per_trade > 0 \
         and self.pct_risk_per_trade <= 100 \
         and self.portfolio_max > 0 \
         and self.date_from_obj \
         and self.date_from_obj >= AppConsts.MIN_DATE \
         and self.date_to_obj \
         and self.date_to_obj >= AppConsts.MIN_DATE \
         and self.date_from_obj < self.date_to_obj \
         and self.slippage >= 0 \
         and self.volume_limit >= 0.01 \
         and self.volume_limit <= 100 \
         and self.test_limit_symbol >= 1
Example #11
0
def handle(ex: Exception) -> str:
    response: ResponseModel = ResponseModel()
    try:
        LogUtils.error('Handle error', ex)

        msg: str = str(ex)
        response.http_status_code = http.HTTPStatus.INTERNAL_SERVER_ERROR
        response.error_message = msg if msg else 'Error'
        if isinstance(ex, BadRequestException):
            response.http_status_code = http.HTTPStatus.BAD_REQUEST
        if isinstance(ex, NotFoundException):
            response.http_status_code = http.HTTPStatus.NOT_FOUND
        if isinstance(ex, DbConnectionException):
            response.http_status_code = http.HTTPStatus.INTERNAL_SERVER_ERROR
    except Exception as e:
        response.http_status_code = http.HTTPStatus.INTERNAL_SERVER_ERROR
        response.error_message = 'Error'
    return StringUtils.to_json(response)
Example #12
0
 def import_from_csv_companynames(self) -> str:
     file: str = FileUtils.get_file(AppConsts.INCOME_STMT_FILE)
     records: List[Dict] = CsvUtils.parse_as_dict(file)
     curr_symbol: str = ''
     for record in records:
         symbol: str = record.get(AppConsts.INTRINIO_KEY_INC_STMT_TICKER)
         company_name: str = record.get(
             AppConsts.INTRINIO_KEY_INC_STMT_NAME)
         if symbol == curr_symbol or StringUtils.isNullOrWhitespace(
                 company_name):
             continue
         curr_symbol = symbol
         org_symbol: SM = self.__stock_service.get_symbol(
             curr_symbol, AppConsts.INSTRUMENT_STOCK)
         if not org_symbol:
             continue
         LogUtils.debug('Updating {0}.'.format(company_name))
         org_symbol.name = company_name
         BaseService._update()
     return "1"
Example #13
0
 def get_wo_ext(file_path: str) -> str:
     if StringUtils.isNullOrWhitespace(file_path):
         return ''
     split: Tuple[str] = os.path.splitext(file_path)
     return split[0] if split else ''
Example #14
0
def get_symbols(instrument: str) -> str:
    return StringUtils.to_json(
        ResponseModel(__stock_service.get_symbols(instrument)))
Example #15
0
def close_positions() -> str:
    return StringUtils.to_json(ResponseModel(
        __trade_service.close_positions()))
Example #16
0
def sync_orders() -> str:
    return StringUtils.to_json(ResponseModel(__trade_service.sync_orders()))
Example #17
0
def get_all_suggestions() -> str:
    return StringUtils.to_json(
        ResponseModel(__trade_service.get_all_suggestions()))
Example #18
0
def get_sample_prices_for_charts() -> str:
    req: CR = ModelUtils.get_obj(CR(), request.get_json())
    return StringUtils.to_json(
        ResponseModel(__stock_service.get_sample_prices_for_charts(req)))
Example #19
0
 def get_file(file_path: str) -> str:
     if StringUtils.isNullOrWhitespace(file_path):
         return ''
     return os.path.join(os.getcwd(), file_path)
Example #20
0
def get_key_info(symbol: str) -> str:
    return StringUtils.to_json(
        ResponseModel(__trade_service.get_key_info(symbol)))
Example #21
0
def get_account() -> str:
    return StringUtils.to_json(ResponseModel(__trade_service.get_account()))
Example #22
0
def run() -> str:
    req: BackTestRunRequest = ModelUtils.get_obj(BackTestRunRequest(),
                                                 request.get_json())
    return StringUtils.to_json(ResponseModel(__back_test_service.run(req)))
Example #23
0
def update_symbol() -> str:
    req: SymbolMaster = ModelUtils.get_obj(SymbolMaster(), request.get_json())
    return StringUtils.to_json(
        ResponseModel(__stock_service.update_symbol(req)))
Example #24
0
def get_sp500_mismatches(is_missing: str) -> str:
    return StringUtils.to_json(
        ResponseModel(
            __stock_service.get_sp500_mismatches(is_missing == 'True')))
Example #25
0
 def get_base_name(file_path: str) -> str:
     if StringUtils.isNullOrWhitespace(file_path):
         return ''
     return os.path.basename(file_path)
Example #26
0
def get_trade_orders() -> str:
    req: GetTradeOrdersRequest = ModelUtils.get_obj(GetTradeOrdersRequest(),
                                                    request.get_json())
    return StringUtils.to_json(
        ResponseModel(__trade_service.get_trade_orders(req)))
Example #27
0
 def get_symbol(self, symbol: str, instrument: str) -> SM:
     if StringUtils.isNullOrWhitespace(symbol):
         return None
     symbol = symbol.strip().upper()
     return BaseService._get_first(
         SM, [SM.symbol == symbol, SM.instrument == instrument])
Example #28
0
def get_suggestions() -> str:
    req: TradeSuggestionsRequest = ModelUtils.get_obj(
        TradeSuggestionsRequest(), request.get_json())
    return StringUtils.to_json(
        ResponseModel(__trade_service.get_suggestions(req)))
Example #29
0
def import_prices() -> str:
    return StringUtils.to_json(ResponseModel(__import_service.import_prices()))
Example #30
0
def delete_old_prices() -> str:
    return StringUtils.to_json(
        ResponseModel(__stock_service.delete_old_prices()))