text stringlengths 185 73.3k | repo stringlengths 7 100 | path stringlengths 4 146 | language stringclasses 7
values | hash stringlengths 16 16 | score float64 7 8.5 | stars int64 0 237k |
|---|---|---|---|---|---|---|
# -*- coding: utf-8 -*-
#
# Copyright (c) 2017 Willem van Ketwich
#
# This module is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# T... | devopscorner/demo | ansible/roles/amazon-aws/amazon-aws/plugins/module_utils/cloudfront_facts.py | .py | 99f80f9bf04ccd26 | 7.3 | 3 |
#
# Copyright 2017 Michael De La Rue | Ansible
#
# This file is part of Ansible
#
# Ansible is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later ver... | devopscorner/demo | ansible/roles/amazon-aws/amazon-aws/plugins/module_utils/core.py | .py | 902eea1c213d664c | 7.3 | 3 |
# Copyright (c) 2017 Ansible Project
# GNU General Public License v3.0+ (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt)
from __future__ import (absolute_import, division, print_function)
__metaclass__ = type
import re
try:
import botocore
except ImportError:
pass
from ansible.module_utils._text im... | devopscorner/demo | ansible/roles/amazon-aws/amazon-aws/plugins/module_utils/iam.py | .py | 0d0f188188df4a05 | 7.3 | 3 |
# Copyright: (c) 2018, Aaron Haaf <aabonh@gmail.com>
# GNU General Public License v3.0+ (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt)
from __future__ import (absolute_import, division, print_function)
__metaclass__ = type
import datetime
import hashlib
import hmac
import operator
try:
from boto3 impo... | devopscorner/demo | ansible/roles/amazon-aws/amazon-aws/plugins/module_utils/urls.py | .py | 089b532522cfff20 | 7.3 | 3 |
# Copyright (c) 2017 Will Thames
#
# This code is part of Ansible, but is an independent component.
# This particular file snippet, and this file snippet only, is BSD licensed.
# Modules you write using this snippet, which is embedded dynamically by Ansible
# still belong to the author of the module, and may assign the... | devopscorner/demo | ansible/roles/amazon-aws/amazon-aws/plugins/module_utils/waf.py | .py | 643bc1da71db0c08 | 7.3 | 3 |
#! /usr/bin/env python
# -*- coding: utf-8 -*-
import clr
import glob
import re
import sys
import json
import os
import shutil
import ctypes
import codecs
from datetime import datetime, timedelta
from System import Environment
from collections import defaultdict
from System.Collections.Generic import List
clr.AddRefe... | Bim4Everyone/HVACExtension | ОВиВК.tab/Задания СС(СППЗ).panel/Задание.stack/lib/low_voltage_task_class_lib.py | .py | 2daca28974a9b29c | 7 | 0 |
#! /usr/bin/env python
# -*- coding: utf-8 -*-
from tarfile import TUEXEC
import clr
clr.AddReference("RevitAPI")
clr.AddReference("RevitAPIUI")
clr.AddReference("dosymep.Revit.dll")
clr.AddReference("dosymep.Bim4Everyone.dll")
import dosymep
import re
import glob
import os
from low_voltage_task_class_lib import Jso... | Bim4Everyone/HVACExtension | ОВиВК.tab/Задания СС(СППЗ).panel/Задание.stack/Обновить задание.pushbutton/script.py | .py | 9b540c6d37f271e0 | 7 | 0 |
#! /usr/bin/env python
# -*- coding: utf-8 -*-
import clr
import glob
import re
import sys
import json
import os
import ctypes
import codecs
from datetime import datetime, timedelta
from System import Environment
from collections import defaultdict
from System.Collections.Generic import List
clr.AddReference("RevitAP... | Bim4Everyone/HVACExtension | ОВиВК.tab/Расчеты.panel/Импорт расчета.pushbutton/lib/JsonOperatorLib.py | .py | f1fc209dced915de | 7 | 0 |
"""This example shows how to use the reporter module to receive attribute changes from device.
To run this example, you need to have a device connected to your computer.
Run the example with `poetry run python examples/ble_reporting_example.py [device_name]`.
"""
import datetime
import logging
import sys
import time
... | aidee-health/embody-ble | examples/ble_reporting_example.py | .py | 254497201af92e62 | 7 | 0 |
"""This example shows how to use the reporter module to receive attribute changes from device.
To run this example, you need to have a device connected to your computer.
Run the example with `poetry run python examples/reporting_example.py [device_name]`.
"""
import logging
import sys
import time
from embodyble.embo... | aidee-health/embody-ble | examples/reporting_example.py | .py | d5869ce22d403184 | 7 | 0 |
"""Listener interfaces that can be subscribed to by clients."""
from abc import ABC
from abc import abstractmethod
from enum import StrEnum
from typing import NotRequired
from typing import TypedDict
from embodycodec import codec
class ConnectionInfo(TypedDict):
"""Connection diagnostic information."""
con... | aidee-health/embody-ble | src/embodyble/listeners.py | .py | aaf573f2520d6d5d | 7 | 0 |
"""Logging utilities for the embodyble library."""
import logging
LIBRARY_LOGGER_NAME = "embodyble"
def get_logger(name: str | None = None) -> logging.Logger:
"""Get a logger for the library."""
if name:
return logging.getLogger(f"{LIBRARY_LOGGER_NAME}.{name}")
return logging.getLogger(LIBRARY_... | aidee-health/embody-ble | src/embodyble/logging.py | .py | b925574db5d3642f | 7 | 0 |
"""Utilities for using embody-ble"""
import io
import logging
import threading
import time
from collections.abc import Callable
from embodycodec import codec
from embodycodec import types
from embodyble.embodyble import EmbodyBle
from embodyble.listeners import ResponseMessageListener
logger = logging.getLogger(__... | aidee-health/embody-ble | src/embodyble/utils.py | .py | ae0e6041de01d8f7 | 7 | 0 |
"""Shared pytest fixtures for embody-ble tests."""
import asyncio
from unittest.mock import AsyncMock
from unittest.mock import Mock
import pytest
from bleak.backends.characteristic import BleakGATTCharacteristic
from embodycodec import attributes
from embodycodec import codec
from embodyserial import embodyserial
fr... | aidee-health/embody-ble | tests/conftest.py | .py | 26f604a80419caf3 | 7.5 | 0 |
"""Test logging behavior for the embodyble library."""
import io
import logging
from contextlib import redirect_stderr
from contextlib import redirect_stdout
import embodyble # noqa: F401
from embodyble.logging import configure_library_logging
from embodyble.logging import get_logger
def test_library_silent_by_def... | aidee-health/embody-ble | tests/test_logging.py | .py | bd8694aeaa250dfd | 7.5 | 0 |
"""Test cases for the reporting module."""
import queue
from datetime import UTC
from datetime import datetime
from unittest.mock import Mock
import pytest
from embodycodec import attributes
from embodycodec import codec
from embodyble.reporting import AttributeChangedListener
from embodyble.reporting import Attribu... | aidee-health/embody-ble | tests/test_reporting.py | .py | 0afae2eb427f3d9a | 7.5 | 0 |
import logging
from datetime import datetime
from typing import Dict, List
from apps.workspaces.models import Workspace
from fyle_accounting_mappings.models import ExpenseAttribute
logger = logging.getLogger(__name__)
logger.level = logging.INFO
class Base:
"""The base class for all API classes."""
def __... | fylein/fyle-integrations-platform-connector | fyle_integrations_platform_connector/apis/base.py | .py | ff682ca25f86cc04 | 7 | 0 |
from .base import Base
import logging
from datetime import datetime, timezone
logger = logging.getLogger(__name__)
logger.level = logging.INFO
class Categories(Base):
"""Class for Categories APIs."""
def __init__(self):
Base.__init__(self, attribute_type='CATEGORY')
def sync(self, sync_after: d... | fylein/fyle-integrations-platform-connector | fyle_integrations_platform_connector/apis/categories.py | .py | 0036bd98d4cea7d9 | 7 | 0 |
import logging
from datetime import datetime, timezone
from .base import Base
logger = logging.getLogger(__name__)
logger.level = logging.INFO
class CostCenters(Base):
"""Class for Cost Centers APIs."""
def __init__(self):
Base.__init__(self, attribute_type='COST_CENTER', query_params={'is_enabled':... | fylein/fyle-integrations-platform-connector | fyle_integrations_platform_connector/apis/cost_centers.py | .py | 2e4190dbfffddf19 | 7 | 0 |
from datetime import datetime
from .base import Base
class Employees(Base):
"""Class for Employees APIs."""
def __init__(self):
Base.__init__(self, attribute_type='EMPLOYEE', query_params={'is_enabled': 'eq.true'})
def get_employee_by_email(self, email: str):
"""
Get employee by ... | fylein/fyle-integrations-platform-connector | fyle_integrations_platform_connector/apis/employees.py | .py | fa580e9a1f980ea7 | 7 | 0 |
import logging
from dateutil import parser
from datetime import datetime
from typing import List, Dict
from text_unidecode import unidecode
from .base import Base
logger = logging.getLogger(__name__)
logger.level = logging.INFO
class Expenses(Base):
"""Class for Expenses APIs."""
def get(self, source_acco... | fylein/fyle-integrations-platform-connector | fyle_integrations_platform_connector/apis/expenses.py | .py | e972873a638f0a14 | 7 | 0 |
from typing import List
import base64
import requests
from .base import Base
class Files(Base):
"""
Class for File API
"""
def get_as_base64(self, url):
return base64.b64encode(requests.get(url).content).decode('ascii')
def bulk_generate_file_urls(self, data: List[dict]) -> List[dict]:
... | fylein/fyle-integrations-platform-connector | fyle_integrations_platform_connector/apis/files.py | .py | 3abb49732c240fd7 | 7 | 0 |
from datetime import datetime, timezone
import logging
from .base import Base
from typing import List
logger = logging.getLogger(__name__)
logger.level = logging.INFO
class Merchants(Base):
"""
Class for Merchants API
"""
def __init__(self):
Base.__init__(self, attribute_type='MERCHANT', que... | fylein/fyle-integrations-platform-connector | fyle_integrations_platform_connector/apis/merchants.py | .py | 9f79341ca75684a6 | 7 | 0 |
from .base import Base
from apps.fyle.models import Reimbursement
class Reimbursements(Base):
"""Class for Reimbursements APIs."""
def __construct_query_params(self) -> dict:
"""
Constructs the query params for the API call.
:return: dict
"""
last_synced_record = Reim... | fylein/fyle-integrations-platform-connector | fyle_integrations_platform_connector/apis/reimbursements.py | .py | d16b118819b2bb45 | 7 | 0 |
import logging
import os
from collections.abc import Iterator
from datetime import datetime
from fyle.platform import Platform
from fyle.platform.exceptions import ExpiredTokenError, InvalidTokenError
from apps.workspaces.models import FyleCredential, FeatureConfig
from fyle_accounting_mappings.models import FyleSync... | fylein/fyle-integrations-platform-connector | fyle_integrations_platform_connector/fyle_integrations_platform_connector.py | .py | 0faf164aa0cad79d | 7 | 0 |
import logging
from datetime import timedelta
from django.utils import timezone
from apps.workspaces.models import FyleCredential
logger = logging.getLogger(__name__)
logger.level = logging.INFO
ACCESS_TOKEN_EXPIRY_MINUTES = 30
def is_access_token_valid(fyle_credentials: FyleCredential) -> bool:
"""
Check... | fylein/fyle-integrations-platform-connector | fyle_integrations_platform_connector/token_manager.py | .py | fb7b5413cf7110e7 | 7 | 0 |
# ---
# jupyter:
# jupytext:
# formats: py:percent
# text_representation:
# extension: .py
# format_name: percent
# format_version: '1.3'
# jupytext_version: 1.15.2
# kernelspec:
# display_name: ssb-fagfunksjoner
# language: python
# name: ssb-fagfunksjoner
# ---
# %%
im... | statisticsnorway/ssb-fagfunksjoner | demos/all_combos_demo.py | .py | 6e6b5595669b4e9a | 7.39 | 5 |
"""Nox sessions."""
import os
import shlex
import shutil
import sys
import tempfile
from pathlib import Path
from textwrap import dedent
import nox
try:
from nox_poetry import Session, session
except ImportError:
message = f"""\
Nox failed to import the 'nox-poetry' package.
Please install it using ... | statisticsnorway/ssb-fagfunksjoner | noxfile.py | .py | 43f2549a2e4e5b50 | 7.39 | 5 |
import datetime
from dataclasses import dataclass
from typing import Any
import pandas as pd
import requests
from dateutil import parser
@dataclass
class Link:
"""Represents a hyperlink related to the dataset.
Attributes:
rel: The relationship type of the link.
href: The URL of the link (if ... | statisticsnorway/ssb-fagfunksjoner | src/fagfunksjoner/api/valuta.py | .py | df89a5baa332277c | 7.39 | 5 |
"""This module contains functions to create a xml file that can be loaded in the KLASS UI.
It passes data through a pandas DataFrame from a list of codes and names, to an XML from the pandas dataframe.
"""
import pandas as pd
from dateutil import parser
PARAM_COLS = { # Order is important?
"codes": "kode",
... | statisticsnorway/ssb-fagfunksjoner | src/fagfunksjoner/data/klass_xml.py | .py | 7307f4d2711f5716 | 7.39 | 5 |
"""Automatically changes dtypes on pandas dataframes using logic.
Tries to keep objects as strings if numeric, but with leading zeros.
Downcasts ints to smalles size. Changes possible columns to categoricals.
The function you most likely want is "auto_dype".
"""
import gc
import json
from typing import Final, Literal... | statisticsnorway/ssb-fagfunksjoner | src/fagfunksjoner/data/pandas_dtypes.py | .py | 1b4d392aa5bf732d | 7.39 | 5 |
import pyarrow as pa
def cast_pyarrow_table_schema(data: pa.Table, schema: pa.Schema) -> pa.Table:
"""Set correct schema on Pyarrow Table, especially when dictionary datatype is wanted.
Args:
data: The pyarrow table data
schema: The wanted schema to cast to the table data.
All col... | statisticsnorway/ssb-fagfunksjoner | src/fagfunksjoner/data/pyarrow.py | .py | 7499dc9938c8fae6 | 7.39 | 5 |
"""Reproduce the functionality of the default round function from Excel or SAS, rounding data up to a given number of decimal places.
Instead of Python's default of rounding to even.
"""
from decimal import ROUND_HALF_UP, Decimal, localcontext
from typing import TYPE_CHECKING, Any, overload
import pandas as pd
# Al... | statisticsnorway/ssb-fagfunksjoner | src/fagfunksjoner/data/round_ssb.py | .py | 65daae7897347fbb | 7.39 | 5 |
from __future__ import annotations
import logging
import sys
from collections.abc import Callable
from typing import Any
from colorama import Back, Fore, Style
def silence_logger(func: Callable[..., Any], *args: Any, **kwargs: Any) -> Any:
"""Silences INFO and WARNING logs for the duration of the function call.... | statisticsnorway/ssb-fagfunksjoner | src/fagfunksjoner/fagfunksjoner_logger.py | .py | daa7ee36a4d17f44 | 7.39 | 5 |
import json
from pathlib import Path
from typing import Any
import pandas as pd
from pandas._libs.missing import NAType
SSBFORMAT_INPUT_TYPE = dict[str | int, Any] | dict[str, Any]
class SsbFormat(dict[Any, Any]):
"""Custom dictionary class designed to handle specific formatting conventions, including mapping i... | statisticsnorway/ssb-fagfunksjoner | src/fagfunksjoner/formats/formats.py | .py | 455dcba017c1c7f6 | 7.39 | 5 |
"""StatLogger module.
This module is designed to set up and manage logging within an application.
The :class:`StatLogger` class is meant to be the root-level logger in the application, that
receives log messages from all other modules. It formats the messages in a uniform way
and directs the messages to the specified ... | statisticsnorway/ssb-fagfunksjoner | src/fagfunksjoner/log/statlogger.py | .py | 67aae649970299b9 | 7.39 | 5 |
"""Code that uses things from git-files."""
import os
from pathlib import Path
def name_from_gitconfig() -> str:
"""Find the username from the git config in the current system.
Returns:
str: The found Username
Raises:
FileNotFoundError: if the .gitconfig file is not found by navigating o... | statisticsnorway/ssb-fagfunksjoner | src/fagfunksjoner/paths/git.py | .py | d111903ac1c55b95 | 7.39 | 5 |
"""This module lets you easily navigate to the root of your local project files.
One of the main uses will be importing local functions in a notebook based project.
As notebooks run from the folder they are opened from, not root, and functions usually will be .py files located in other folders than the notebooks.
"""
... | statisticsnorway/ssb-fagfunksjoner | src/fagfunksjoner/paths/project_root.py | .py | ce813448546c829e | 7.39 | 5 |
from __future__ import annotations
from collections.abc import Mapping, Sequence
from dataclasses import dataclass, field
from datetime import datetime
from enum import StrEnum
from pathlib import Path
from typing import Any
from ..fagfunksjoner_logger import silence_logger
from .git import repo_root_dir
from .versio... | statisticsnorway/ssb-fagfunksjoner | src/fagfunksjoner/paths/shared_files.py | .py | da4964b5a372d453 | 7.39 | 5 |
"""Extract user information from the environment."""
import getpass
import os
import subprocess
def find_email() -> str:
"""Find the users email from the environment.
Returns:
str: Hopefully the users email.
Raises:
ValueError: If we cant find any sources of the users email.
"""
... | statisticsnorway/ssb-fagfunksjoner | src/fagfunksjoner/paths/user.py | .py | a40f60131d9752b4 | 7.39 | 5 |
"""This module works with filepaths and the versioning convention at SSB.
The main purpose is fileversions according to Statistics Norway standards.
The aim is to help versioning up and getting the latest version of paths in use on storage.
The module is not targeted at files that do not follow the naming convention ... | statisticsnorway/ssb-fagfunksjoner | src/fagfunksjoner/paths/versions.py | .py | ac44bcdb0ca3be78 | 7.39 | 5 |
"""To write "environment-aware code", we need to know where we are.
This module extracts information from the current environment,
and can help differentiate between the different places we develop code.
"""
import os
from typing import Any
from dapla_auth_client import AuthClient
from dapla_auth_client.const import... | statisticsnorway/ssb-fagfunksjoner | src/fagfunksjoner/prodsone/check_env.py | .py | d3fbb2901b265e36 | 7.39 | 5 |
from getpass import getpass, getuser
from types import TracebackType
from typing import Any, cast
import oracledb
class Oracle:
"""Class for working with an Oracle database with most common queries.
This class supports the most used SQL queries to a table in a database.
It gives us the possibilities to ... | statisticsnorway/ssb-fagfunksjoner | src/fagfunksjoner/prodsone/oradb.py | .py | ec91208df84c0767 | 7.39 | 5 |
"""Simplifications of saspy package for SSB use.
Helps you store password in prodsone.
Sets libnames automatically for you when just wanting to open a file,
or convert it.
"""
import getpass
import os
import re
import shutil
from pathlib import Path
from typing import Any
import pandas as pd
import saspy
from fagfu... | statisticsnorway/ssb-fagfunksjoner | src/fagfunksjoner/prodsone/saspy_ssb.py | .py | 39137fbd96ddb222 | 7.39 | 5 |
from fman import DirectoryPaneCommand, DirectoryPane, ApplicationCommand, show_alert, FMAN_VERSION, DirectoryPaneListener, load_json, save_json, show_prompt, YES, NO
from fman.fs import copy, move, exists
from fman.url import as_human_readable, basename, dirname
from subprocess import Popen
import os.path
import re
fro... | BenjaminKobjolke/FManDuplicateFilesAndIncrementExtension | duplicate_extension/__init__.py | .py | edd19228f3396978 | 7.24 | 2 |
# -*- coding: utf-8 -*-
"""Helpers and calcfunctions for DFT+U+V (extended Hubbard) support in ``OCVWorkChain``.
This module is only exercised when the workchain runs in *Hubbard mode*. The plain-GGA
path never imports from here at runtime (the workchain only touches these functions when a
``hubbard_sc`` namespace is ... | tsthakur/aiida-open_circuit_voltage | aiida_open_circuit_voltage/calculations/functions/hubbard_functions.py | .py | a59830e412d1b86b | 7 | 0 |
# -*- coding: utf-8 -*-
"""Shared cation metadata and inference helpers."""
SUPPORTED_CATIONS = {
"Li": 1,
"Na": 1,
"K": 1,
"Mg": 2,
"Ca": 2,
"Al": 3,
}
def is_missing_cation(cation):
"""Return True when a cation value should be inferred."""
return cation is None or (isinstance(cation... | tsthakur/aiida-open_circuit_voltage | aiida_open_circuit_voltage/cations.py | .py | 9aa23517d32cb963 | 7 | 0 |
"""一次性脚本:补全新标的 K 线数据 + 为所有标的拉取 4H K 线。
- 新标的(DB 中无日线):拉取近 3 个月日线 + 周线 + 4H
- 存量标的(DB 中已有日线):只拉取近 3 个月 4H
用法:
python scripts/backfill_klines.py [--dry-run] [--only-4h]
"""
import sys
import os
import time
import logging
from datetime import datetime, timedelta
import pandas as pd
sys.path.insert(0, os.path.join... | Chunxia-zzz/TraderAnalysis | scripts/backfill_klines.py | .py | 64fdb0a80ee64338 | 7 | 0 |
"""
批量拉取标的池的分析师目标价和晨星公允价值,写入 DB。
ETF/ETN 标的会跳过(无此类数据)。
用法: python scripts/fetch_fundamental_targets.py [--dry-run]
"""
import sys
import os
import json
import subprocess
import sqlite3
import time
sys.path.insert(0, os.path.join(os.path.dirname(__file__), '..', 'src'))
DB_PATH = os.path.join(os.path.dirname(__file_... | Chunxia-zzz/TraderAnalysis | scripts/fetch_fundamental_targets.py | .py | c36102c2a5927e16 | 7 | 0 |
"""底部支撑信号检测引擎。
纯计算模块:接收已含指标的日线 DataFrame,检测各类底部支撑信号。
不感知持仓状态,不做建仓决策。
信号类型(7 个):
1. NEAR_SUPPORT — 价格在关键均线支撑附近
2. DEEP_V — 日内跌破支撑均线但收回,收长下影线
3. VOLUME_SHRINK — 连续缩量(卖压衰竭)
4. RSI_BOTTOM_DIV— 日线 RSI 底背离
5. W_BOTTOM — W底/双底形态
6. SUPPORT_CONFIRM— 前日触底后今日确认反弹
7. RECLAIM_MA5 — 重新站上 MA5
"""
from __future__ im... | Chunxia-zzz/TraderAnalysis | src/trader_analysis/futu_strategy/bottom_detector.py | .py | d770d1afdab16bb9 | 7 | 0 |
"""每日增量更新脚本。
查询各标的本地最新日期,只拉取新增 K 线,与历史数据拼接后重新计算末尾指标,
将新增行 UPSERT 到 SQLite。由定时任务或 runner.py 在评分前调用。
用法:
python -m trader_analysis.futu_strategy.daily_update
"""
from __future__ import annotations
import argparse
import logging
import pandas as pd
from trader_analysis.futu_strategy import config
from trader_ana... | Chunxia-zzz/TraderAnalysis | src/trader_analysis/futu_strategy/daily_update.py | .py | 18dad2682721fbb5 | 7 | 0 |
"""K 线数据获取。
封装富途实时 API 调用,对外暴露 fetch_daily / fetch_weekly 两个函数。
所有数据均通过 FutuLiveDataProvider 拉取并经 normalize_ohlcv 标准化。
"""
from __future__ import annotations
import logging
import pandas as pd
from trader_analysis.futu_strategy.providers import DataProviderError, FutuLiveDataProvider
from trader_analysis.futu_stra... | Chunxia-zzz/TraderAnalysis | src/trader_analysis/futu_strategy/data_fetcher.py | .py | f2181ee1403f9c2b | 7 | 0 |
"""EMA 交叉信号检测引擎。
检测 EMA5/EMA30 的金叉(空转多)和死叉(多转空),
支持日线和 4H 两个维度。
信号类型:
- EMA_CROSS_BULL_1D / EMA_CROSS_BULL_4H — 空转多(EMA5 上穿 EMA30)
- EMA_CROSS_BEAR_1D / EMA_CROSS_BEAR_4H — 多转空(EMA5 下穿 EMA30)
"""
from __future__ import annotations
from dataclasses import dataclass, field
import pandas as pd
@dataclass
class EM... | Chunxia-zzz/TraderAnalysis | src/trader_analysis/futu_strategy/ema_cross_detector.py | .py | e535c3a95a1cd3b9 | 7 | 0 |
"""基本面数据获取层。
从 yfinance 批量拉取标的基本面数据(不依赖 Futu OpenD)。
"""
from __future__ import annotations
import logging
import time
from trader_analysis.futu_strategy import config
logger = logging.getLogger(__name__)
# yfinance info key → 内部字段名
_FIELD_MAP = {
"currentPrice": "current_price",
"regularMarketPrice": "cu... | Chunxia-zzz/TraderAnalysis | src/trader_analysis/futu_strategy/fundamental_fetcher.py | .py | c83e0f3ef804dff1 | 7 | 0 |
"""基本面多因子评分引擎。
5 维度加权评分,满分 100。与技术面评分(scorer.py)互补。
"""
from __future__ import annotations
from trader_analysis.futu_strategy import config
def _clamp(x: float, lo: float = 0.0, hi: float = 1.0) -> float:
return max(lo, min(hi, x))
def _score_valuation_discount(current_price: float | None, target_mean: float... | Chunxia-zzz/TraderAnalysis | src/trader_analysis/futu_strategy/fundamental_scorer.py | .py | b4e783cfb6d257c4 | 7 | 0 |
"""网格交易主引擎。
长驻进程,订阅实时行情,价格穿越网格线时自动下单。
用法:
from trader_analysis.futu_strategy.grid_trader.engine import GridEngine
engine = GridEngine(config_id=1)
engine.start() # 阻塞,Ctrl+C 停止
"""
from __future__ import annotations
import logging
import signal
import time
from datetime import datetime
from trader_ana... | Chunxia-zzz/TraderAnalysis | src/trader_analysis/futu_strategy/grid_trader/engine.py | .py | 11cec3c686d62914 | 7 | 0 |
"""行情推送回调处理。"""
from __future__ import annotations
import logging
logger = logging.getLogger("grid_trader")
def create_quote_handler(engine):
"""创建行情回调 handler,绑定到 engine。
返回 handler 类(需要在运行时 import futu)。
"""
from futu import RET_OK, StockQuoteHandlerBase
class GridQuoteHandler(StockQuoteHan... | Chunxia-zzz/TraderAnalysis | src/trader_analysis/futu_strategy/grid_trader/quote_handler.py | .py | 2f1b20f3e90be1c1 | 7 | 0 |
"""网格交易风控模块。"""
from __future__ import annotations
from datetime import datetime
import pytz
from trader_analysis.futu_strategy.grid_trader.models import GridConfig, GridState
ET = pytz.timezone("US/Eastern")
def is_trading_hours(cfg: GridConfig) -> bool:
"""判断当前是否在交易时段内(美东时间)。"""
now_et = datetime.now(E... | Chunxia-zzz/TraderAnalysis | src/trader_analysis/futu_strategy/grid_trader/risk_control.py | .py | fedc7a1b5a080e13 | 7 | 0 |
"""网格策略逻辑:网格线计算 + 信号判断 + 动作决策。"""
from __future__ import annotations
from trader_analysis.futu_strategy.grid_trader.models import GridConfig, Signal
def calculate_grid_lines(cfg: GridConfig) -> list[float]:
"""生成等间距网格线列表(从低到高)。
例: upper=250, lower=240, grid_count=5
间距 = 2.0, 网格线 = [240, 242, 244, 246, ... | Chunxia-zzz/TraderAnalysis | src/trader_analysis/futu_strategy/grid_trader/strategy.py | .py | 9d785f8874bbf5c6 | 7 | 0 |
"""历史数据初始化脚本。
拉取标的池的历史 K 线,计算全部指标,批量写入 SQLite。
支持断点续传:已有数据的标的自动跳过,中断后重跑即可从断点继续。
用法:
python -m trader_analysis.futu_strategy.init_history # 拉取全部 watchlist
python -m trader_analysis.futu_strategy.init_history --codes US.AAPL US.TSLA
python -m trader_analysis.futu_strategy.init_history --force # 强... | Chunxia-zzz/TraderAnalysis | src/trader_analysis/futu_strategy/init_history.py | .py | 1329c345085e23ee | 7 | 0 |
"""日志与审计。
评分结果写入 score_log.jsonl,交易记录写入 trade_log.jsonl。
每行一条 JSON,方便后续解析和审计。
"""
from __future__ import annotations
import json
import logging
import os
from datetime import datetime
from trader_analysis.futu_strategy import config
logging.basicConfig(
level=logging.INFO,
format="%(asctime)s [%(levelname)... | Chunxia-zzz/TraderAnalysis | src/trader_analysis/futu_strategy/logger.py | .py | 7852aa55c216c665 | 7 | 0 |
"""持仓阶段状态管理。
提供对 position_state 表的 CRUD 操作,供 sell_advisor 和 runner 调用。
"""
from __future__ import annotations
from trader_analysis.futu_strategy import storage
def get_state(code: str) -> dict:
"""查询单只标的的持仓状态。无记录时返回默认 HOLD 状态。"""
return storage.get_position_state(code)
def update_state(
code: str,
... | Chunxia-zzz/TraderAnalysis | src/trader_analysis/futu_strategy/position_state.py | .py | b4c6380a75baa639 | 7 | 0 |
"""富途股票信息获取与选股接口。
封装 get_stock_basicinfo / get_market_snapshot / get_stock_filter,
用于新增标的时自动填充和条件选股。OpenD 离线时优雅降级。
"""
from __future__ import annotations
import logging
from trader_analysis.futu_strategy import config
logger = logging.getLogger(__name__)
class OpenDNotConnected(Exception):
"""OpenD 连接失败。"""
... | Chunxia-zzz/TraderAnalysis | src/trader_analysis/futu_strategy/stock_info_fetcher.py | .py | 245d4b8917090d59 | 7 | 0 |
"""标的池持久化存储层。
管理 watchlist 表的 DDL 与 CRUD 操作。
"""
from __future__ import annotations
import json
import sqlite3
from datetime import datetime, timezone
from trader_analysis.futu_strategy import config
_CREATE_WATCHLIST_TABLE_SQL = """
CREATE TABLE IF NOT EXISTS watchlist (
code TEXT PRIMARY KEY,
... | Chunxia-zzz/TraderAnalysis | src/trader_analysis/futu_strategy/watchlist_storage.py | .py | 17986dd06bb67157 | 7 | 0 |
"""FastAPI 端点测试。"""
import pytest
from fastapi.testclient import TestClient
from trader_analysis.futu_strategy.api_server import app
client = TestClient(app)
def test_watchlist_returns_structure():
resp = client.get("/api/watchlist")
assert resp.status_code == 200
data = resp.json()
assert "categor... | Chunxia-zzz/TraderAnalysis | tests/test_api.py | .py | cbf9f3c88b3e7091 | 7.5 | 0 |
"""watchlist.json 加载和 Futu 代码格式转换测试。"""
from trader_analysis.futu_strategy import config
def test_watchlist_loaded():
assert len(config.WATCHLIST) > 0
def test_futu_code_format():
for code in config.WATCHLIST:
parts = code.split(".")
assert len(parts) >= 2, f"代码格式错误: {code}"
assert ... | Chunxia-zzz/TraderAnalysis | tests/test_config.py | .py | dbccc47637068992 | 7.5 | 0 |
"""市场温度 API 端点测试。"""
from __future__ import annotations
import pytest
from httpx import ASGITransport, AsyncClient
from trader_analysis.futu_strategy import storage
from trader_analysis.futu_strategy.api_server import app
@pytest.fixture(autouse=True)
def _isolate_db(monkeypatch, tmp_path):
"""所有测试使用临时数据库,绝不触碰... | Chunxia-zzz/TraderAnalysis | tests/test_market_api.py | .py | f06512d8b2d49c4b | 7.5 | 0 |
# check that sequences were added to the reference alignment and exit if not
from Bio import SeqIO
# Files from Snakemake
seqs_to_add = snakemake.input.seqs_to_add
combined_alignment = snakemake.input.combined_alignment
reflibrary = snakemake.params.reflibrary
logfile = snakemake.output.log
def count_fasta_records(... | davelunt/NemaTree | workflow/scripts/check_added.py | .py | 96ca00940e1f5964 | 7 | 0 |
import json
import os
import country_converter as coco
import pandas as pd
from country_converter import country_converter
from scripts.config import PATHS
WEO_YEAR: int = 2024
CAUSES_OF_DEATH_YEAR = 2019
DEBT_YEAR: int = 2024
def get_full_africa_iso3() -> list:
africa = (
coco.CountryConverter()
... | ONEcampaign/aftershocks_data | scripts/common.py | .py | fcb4f3edb2bdaa19 | 7.15 | 1 |
import time
import pandas as pd
import requests
from bblocks import WFPData, WorldBankData, WorldEconomicOutlook, set_bblocks_data_path
from scripts.common import CAUSES_OF_DEATH_YEAR
from scripts.config import PATHS
from scripts.country_page import (
financial_security,
food_security,
health,
health_... | ONEcampaign/aftershocks_data | scripts/country_page/update.py | .py | 4fec60190aeae762 | 7.15 | 1 |
import datetime
import pandas as pd
from bblocks import (
WFPData,
WorldBankData,
WorldEconomicOutlook,
add_iso_codes_column,
clean_numeric_series,
set_bblocks_data_path,
)
from bblocks.dataframe_tools.add import (
add_flourish_geometries,
add_population_column,
add_population_share... | ONEcampaign/aftershocks_data | scripts/economy_picker/site_country_picker.py | .py | f5a1072ba14991a4 | 7.15 | 1 |
import pandas as pd
import requests
from scripts.config import PATHS
WHO_API_URL = "https://ghoapi.azureedge.net/api/"
def query_who(code: str):
"""Query the WHO website for a given code.
To be replaced in bblocks
"""
request = requests.get(WHO_API_URL + code)
data = request.json()
df = pd.... | ONEcampaign/aftershocks_data | scripts/health/common.py | .py | aecf801f4879335e | 7.15 | 1 |
"""HIV charts for health topic page"""
import pandas as pd
import numpy as np
from scripts.config import PATHS
from scripts.logger import logger
HIV_DATA = pd.read_csv(f"{PATHS.raw_data}/health/unaids_hiv_data.csv")
INDICATORS = {
"unaids_new_hiv_infections": "New HIV infections",
"unaids_aids_related_deaths... | ONEcampaign/aftershocks_data | scripts/health/hiv.py | .py | 7578b9a7b11e0d8b | 7.15 | 1 |
import pandas as pd
from bblocks import WorldBankData, set_bblocks_data_path
from scripts.common import clean_wb_overview
from scripts.config import PATHS
from scripts.health.common import get_malaria_data
from scripts.logger import logger
from scripts.owid_covid import tools as owid_tools
set_bblocks_data_path(PATHS... | ONEcampaign/aftershocks_data | scripts/health/overview_charts.py | .py | 02898775c1def261 | 7.15 | 1 |
import io
from zipfile import ZipFile
import country_converter as coco
import pandas as pd
import requests
from bblocks import WorldBankData, set_bblocks_data_path
from bblocks.dataframe_tools import add
from scripts.config import PATHS
from scripts.health.common import query_who
from scripts.logger import logger
se... | ONEcampaign/aftershocks_data | scripts/health/topic_charts.py | .py | 09c298dc7ba3a51e | 7.15 | 1 |
from scripts.health import dynamic_text as health_dynamic_text
from scripts.health import overview_charts as health_overview_charts
from scripts.health import topic_charts as health_topic
from scripts.health import common as health_common
from scripts.logger import logger
from scripts.owid_covid import tools as ot
... | ONEcampaign/aftershocks_data | scripts/health/update.py | .py | 1a7e1b2e3abcc565 | 7.15 | 1 |
"""Create dynamic text for the hunger topic"""
import datetime
import json
import pandas as pd
from bblocks import WorldBankData, set_bblocks_data_path
from scripts.config import PATHS
from scripts.hunger.common import aggregate_insufficient_food
set_bblocks_data_path(PATHS.bblocks_data)
def stunting() -> dict:
... | ONEcampaign/aftershocks_data | scripts/hunger/dynamic_text.py | .py | 6ca7987399c93b0c | 7.15 | 1 |
"""Create hunger overview charts for the topic carrousel"""
import pandas as pd
from scripts.config import PATHS
from scripts.common import clean_wb_overview
from scripts.hunger.common import wb_indicators
from scripts.hunger.common import aggregate_insufficient_food
import datetime
def wb_charts(indicators: dict) -... | ONEcampaign/aftershocks_data | scripts/hunger/overview_charts.py | .py | 2f60697d395ccbf9 | 7.15 | 1 |
"""Update data chats and text for hunger topic"""
import os
from bblocks import WorldBankData, set_bblocks_data_path
from bblocks.import_tools.world_bank import PinkSheet
from scripts.config import PATHS
from scripts.hunger.common import get_insufficient_food, wb_indicators
from scripts.hunger.dynamic_text import up... | ONEcampaign/aftershocks_data | scripts/hunger/update.py | .py | 00229646d6d12069 | 7.15 | 1 |
import numpy as np
import pandas as pd
from bblocks import convert_id, format_number
from oda_data import provider_groupings
from oda_data.clean_data.common import dac_deflate
from pydeflate import deflate, set_pydeflate_path
from scripts.config import PATHS
set_pydeflate_path(PATHS.raw_data)
# Define a year for th... | ONEcampaign/aftershocks_data | scripts/oda/common.py | .py | db511e80746057ea | 7.15 | 1 |
#!/usr/bin/env python3
import math
import rclpy
from geometry_msgs.msg import Twist
from rclpy.node import Node
from turtlesim.msg import Pose
class GoToPose(Node):
"""Move the turtlesim turtle to a target position and orientation."""
MOVE_TO_POSITION = 0
ROTATE_TO_FINAL_ORIENTATION = 1
IDLE = 2
... | manelpuig/ROS2_rUBot_tutorial | Documentation/Files/01_Doc/03_Distributed_Control_templates/go_to_pose_template.py | .py | 865d7d49959b2c37 | 7.15 | 1 |
#!/usr/bin/env python3
"""Student template: execute a YAML sequence through the RunPose service."""
import yaml
import rclpy
from rclpy.node import Node
from turtle_interfaces.srv import RunPose
class RunPoseSequenceClient(Node):
"""Load and execute a sequence of target poses."""
def __init__(self) -> No... | manelpuig/ROS2_rUBot_tutorial | Documentation/Files/01_Doc/03_Distributed_Control_templates/run_pose_sequence_client_template.py | .py | 0ed8ed58aa96762e | 7.15 | 1 |
#!/usr/bin/env python3
import math
import threading
import time
import rclpy
from geometry_msgs.msg import Twist
from rclpy.callback_groups import ReentrantCallbackGroup
from rclpy.executors import MultiThreadedExecutor
from rclpy.node import Node
from turtle_interfaces.srv import RunPose
from turtlesim.msg import Po... | manelpuig/ROS2_rUBot_tutorial | Documentation/Files/01_Doc/03_Distributed_Control_templates/run_pose_server_template.py | .py | 1f8730a81af07b2f | 7.15 | 1 |
"""Publish the Exercise 4 pose using spatialmath.base conversions."""
from geometry_msgs.msg import TransformStamped
import numpy as np
import rclpy
from rclpy.node import Node
from spatialmath.base import r2q, rpy2r, tr2angvec, tr2eul
from tf2_ros import TransformBroadcaster
class Exercise4SpatialMath(Node):
""... | manelpuig/ROS2_rUBot_tutorial | src/pose_tf2/pose_tf2/exercise4_rpy_spatialmath.py | .py | e36a14d9fb6b14cc | 7.15 | 1 |
"""Student template for publishing the Exercise 4 Target B pose."""
import math
from geometry_msgs.msg import TransformStamped
import rclpy
from rclpy.node import Node
from tf2_ros import TransformBroadcaster
class Exercise4BroadcasterTemplate(Node):
"""Complete the RPY-to-quaternion conversion and TF message f... | manelpuig/ROS2_rUBot_tutorial | src/pose_tf2/pose_tf2/exercise4_rpy_template.py | .py | a64a064e6e1d4c5f | 7.15 | 1 |
"""Small, explicit pose-conversion helpers used by the TF2 exercise."""
import math
import numpy as np
def rotation_matrix_from_rpy(
roll: float,
pitch: float,
yaw: float,
) -> np.ndarray:
"""Return Rz(yaw) @ Ry(pitch) @ Rx(roll), with angles in radians."""
cr = math.cos(roll)
sr = math.sin(... | manelpuig/ROS2_rUBot_tutorial | src/pose_tf2/pose_tf2/pose_math.py | .py | d23f317af35aa64e | 7.15 | 1 |
#!/usr/bin/env python3
import math
import rclpy
from geometry_msgs.msg import Twist
from rclpy.node import Node
from turtlesim.msg import Pose
class GoToPose(Node):
"""Move the turtlesim turtle to a target position and orientation."""
MOVE_TO_POSITION = 0
ROTATE_TO_FINAL_ORIENTATION = 1
... | manelpuig/ROS2_rUBot_tutorial | src/ros2_move_turtle/ros2_move_turtle/go_to_pose.py | .py | 4553499949bb580a | 7.15 | 1 |
#!/usr/bin/env python3
import math
import threading
import time
import rclpy
from geometry_msgs.msg import Twist
from rclpy.callback_groups import ReentrantCallbackGroup
from rclpy.executors import MultiThreadedExecutor
from rclpy.node import Node
from turtle_interfaces.srv import RunPose
from turtlesim.msg import Po... | manelpuig/ROS2_rUBot_tutorial | src/ros2_move_turtle/ros2_move_turtle/run_pose_server.py | .py | 8efa25be85e1674e | 7.15 | 1 |
from OpenSSL import SSL, crypto
import socket
import pem
import certifi
from logging import getLogger, StreamHandler, Formatter, INFO
from functools import reduce
# Default logger
logger = getLogger(__name__)
handler = StreamHandler()
formatter = Formatter('%(asctime)s - %(name)s - %(levelname)s - %(message)s')
handle... | junkurihara/python-check_certchain | src/CertChain.py | .py | 536523d32ac0c730 | 7.3 | 3 |
# Copyright 2021 SAP SE
#
# Licensed under the Apache License, Version 2.0 (the "License"); you may
# not use this file except in compliance with the License. You may obtain
# a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to i... | sapcc/networking-ccloud | networking_ccloud/common/config/__init__.py | .py | 8104b83cc1917e09 | 7.35 | 4 |
# Copyright 2021 SAP SE
#
# Licensed under the Apache License, Version 2.0 (the "License"); you may
# not use this file except in compliance with the License. You may obtain
# a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to i... | sapcc/networking-ccloud | networking_ccloud/common/exceptions.py | .py | 23a785da0059805f | 7.35 | 4 |
# Copyright 2021 SAP SE
#
# Licensed under the Apache License, Version 2.0 (the "License"); you may
# not use this file except in compliance with the License. You may obtain
# a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to i... | sapcc/networking-ccloud | networking_ccloud/common/helper.py | .py | 1ca2187107f1f7f2 | 7.35 | 4 |
# Copyright 2022 SAP SE
#
# Licensed under the Apache License, Version 2.0 (the "License"); you may
# not use this file except in compliance with the License. You may obtain
# a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to i... | sapcc/networking-ccloud | networking_ccloud/ml2/agent/common/backdoor.py | .py | b07949b5c0c3af52 | 7.35 | 4 |
# Copyright 2022 SAP SE
#
# Licensed under the Apache License, Version 2.0 (the "License"); you may
# not use this file except in compliance with the License. You may obtain
# a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to i... | sapcc/networking-ccloud | networking_ccloud/ml2/agent/common/loopingcall.py | .py | 0bee0a1510ec8579 | 7.35 | 4 |
# Copyright 2022 SAP SE
#
# Licensed under the Apache License, Version 2.0 (the "License"); you may
# not use this file except in compliance with the License. You may obtain
# a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to i... | sapcc/networking-ccloud | networking_ccloud/ml2/agent/common/service.py | .py | 0f33c843eccc9afe | 7.35 | 4 |
# Copyright 2021 SAP SE
#
# Licensed under the Apache License, Version 2.0 (the "License"); you may
# not use this file except in compliance with the License. You may obtain
# a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to i... | sapcc/networking-ccloud | networking_ccloud/ml2/agent/eos/agent.py | .py | f51370edf3453699 | 7.35 | 4 |
# Copyright 2021 SAP SE
#
# Licensed under the Apache License, Version 2.0 (the "License"); you may
# not use this file except in compliance with the License. You may obtain
# a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to i... | sapcc/networking-ccloud | networking_ccloud/ml2/agent/nxos/agent.py | .py | 05acf03aa92a913c | 7.35 | 4 |
# Copyright 2022 SAP SE
#
# Licensed under the Apache License, Version 2.0 (the "License"); you may
# not use this file except in compliance with the License. You may obtain
# a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to i... | sapcc/networking-ccloud | networking_ccloud/ml2/agent/test/agent.py | .py | 3caf076210ee325b | 7.85 | 4 |
# Copyright 2021 SAP SE
#
# Licensed under the Apache License, Version 2.0 (the "License"); you may
# not use this file except in compliance with the License. You may obtain
# a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to i... | sapcc/networking-ccloud | networking_ccloud/ml2/driver_rpc_api.py | .py | da079177d33a1512 | 7.35 | 4 |
"""Golden-utterance end-to-end coverage for ovos-skill-application-launcher (en-US).
The golden corpus (``golden_utterances.jsonl``) is a vendored slice of the
shared ovoscope golden-utterance dataset, keyed by
``skill_id == "ovos-skill-application-launcher.openvoiceos"``.
This skill does not register regular padatio... | OpenVoiceOS/ovos-skill-application-launcher | test/end2end/test_golden_utterances.py | .py | 457b30f000308a1d | 7.8 | 3 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.