instruction stringclasses 100
values | code stringlengths 78 193k | response stringlengths 259 170k | file stringlengths 59 203 |
|---|---|---|---|
Improve documentation using docstrings | # Copyright 2020-2026 The HuggingFace Team. All rights reserved.
#
# 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 appl... | --- +++ @@ -45,6 +45,7 @@
def remove_hooks(model: "DeepSpeedEngine") -> None:
+ """Removes the optimizer hooks from a DeepSpeed ZeRO-3 model."""
if not hasattr(model, "optimizer"): # before the first training step, the model has no optimizer
return
if model.optimizer is not None and hasattr(m... | https://raw.githubusercontent.com/huggingface/trl/HEAD/trl/models/utils.py |
Improve documentation using docstrings | # Copyright 2020-2026 The HuggingFace Team. All rights reserved.
#
# 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 appl... | --- +++ @@ -102,6 +102,67 @@
class OnlineDPOTrainer(_BaseTrainer):
+ r"""
+ Initialize OnlineDPOTrainer.
+
+ Args:
+ model (`str | nn.Module | PreTrainedModel`):
+ Model to be trained. Can be either:
+
+ - A string, being the *model id* of a pretrained model hosted inside a mod... | https://raw.githubusercontent.com/huggingface/trl/HEAD/trl/experimental/online_dpo/online_dpo_trainer.py |
Write docstrings describing each step | # Copyright 2020-2026 The HuggingFace Team. All rights reserved.
#
# 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 appl... | --- +++ @@ -27,6 +27,7 @@
# From transformers: https://github.com/huggingface/transformers/blob/556312cd45a5e619c41b0f8adf680eab0d334324/src/transformers/utils/import_utils.py#L48-L77
def _is_package_available(pkg_name: str, return_version: bool = False) -> tuple[bool, str] | bool:
+ """Check if `pkg_name` exist,... | https://raw.githubusercontent.com/huggingface/trl/HEAD/trl/import_utils.py |
Improve documentation using docstrings | # Copyright 2020-2026 The HuggingFace Team. All rights reserved.
#
# 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 appl... | --- +++ @@ -84,6 +84,26 @@ def generate(
lm_backbone: torch.nn.Module, queries: torch.Tensor, pad_token_id: int, generation_config: GenerationConfig
) -> tuple[torch.Tensor, torch.Tensor]:
+ """
+ Generates sequences from the language model backbone in a way that does not affect padding tokens.
+
+ Args:... | https://raw.githubusercontent.com/huggingface/trl/HEAD/trl/experimental/ppo/ppo_trainer.py |
Write docstrings for algorithm functions | # Copyright 2020-2026 The HuggingFace Team. All rights reserved.
#
# 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 appl... | --- +++ @@ -47,6 +47,17 @@
def _get_unique_tensor_key(tensor: torch.Tensor) -> tuple:
+ """
+ Get a unique key for a tensor based on its storage pointer and dtype. This allows deduplication of tensors that
+ share the same underlying storage. From:
+ https://github.com/volcengine/verl/blob/main/verl/uti... | https://raw.githubusercontent.com/huggingface/trl/HEAD/trl/models/activation_offloading.py |
Add verbose docstrings with examples | # Copyright 2020-2026 The HuggingFace Team. All rights reserved.
#
# 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 appl... | --- +++ @@ -25,6 +25,71 @@
class PAPOTrainer(GRPOTrainer):
+ """
+ Trainer for Perception-Aware Policy Optimization (PAPO).
+
+ PAPO extends GRPO/DAPO for multimodal reasoning by adding an implicit perception loss that encourages the model to
+ better utilize visual information. The key innovation is co... | https://raw.githubusercontent.com/huggingface/trl/HEAD/trl/experimental/papo/papo_trainer.py |
Add docstrings that explain logic | # Copyright 2020-2026 The HuggingFace Team. All rights reserved.
#
# 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 appl... | --- +++ @@ -44,6 +44,15 @@
@dataclass
class DPODataCollatorWithPadding:
+ r"""
+ DPO DataCollator class that pads the tokenized inputs to the maximum length of the batch.
+
+ Args:
+ pad_token_id (`int` defaults to 0):
+ The tokenizer's pad_token_id.
+ is_encoder_decoder (`bool` or ... | https://raw.githubusercontent.com/huggingface/trl/HEAD/trl/experimental/utils.py |
Provide clean and structured docstrings | # Copyright 2020-2026 The HuggingFace Team. All rights reserved.
#
# 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 appl... | --- +++ @@ -47,6 +47,20 @@ generation_config: GenerationConfig | None,
batch_size: int = 1,
) -> list[str]:
+ """
+ Generates completions for a list of pre-formatted prompts from the given model.
+
+ Args:
+ prompts (list[str]): A list of input prompts for which completions are to be generated... | https://raw.githubusercontent.com/huggingface/trl/HEAD/trl/experimental/winrate_callback.py |
Create docstrings for each class method | # Copyright 2020-2026 The HuggingFace Team. All rights reserved.
#
# 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 appl... | --- +++ @@ -92,6 +92,52 @@
@dataclass
class DataCollatorForPreference(DataCollatorMixin):
+ """
+ Data collator used for preference data. Inputs are dynamically padded to the maximum length of a batch.
+
+ This collator expects each example in the input list to be a dictionary containing the keys `"prompt_i... | https://raw.githubusercontent.com/huggingface/trl/HEAD/trl/trainer/dpo_trainer.py |
Generate docstrings for this script | # Copyright 2020-2026 The HuggingFace Team. All rights reserved.
#
# 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 appl... | --- +++ @@ -56,6 +56,68 @@
class VLLMClient:
+ """
+ A client class to interact with a vLLM server.
+
+ This class provides methods to generate completions, initialize and manage weight update groups, and update model
+ weights in a distributed setting. Before using it, start the vLLM server with `trl v... | https://raw.githubusercontent.com/huggingface/trl/HEAD/trl/generation/vllm_client.py |
Document this code for team use | # Copyright 2020-2026 The HuggingFace Team. All rights reserved.
#
# 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 appl... | --- +++ @@ -12,6 +12,7 @@ # See the License for the specific language governing permissions and
# limitations under the License.
+"""vLLM-based generation backend for TRL trainers."""
import logging
import math
@@ -41,6 +42,13 @@
def empty_cache() -> None:
+ """Empties the cache of the available torch dev... | https://raw.githubusercontent.com/huggingface/trl/HEAD/trl/generation/vllm_generation.py |
Write beginner-friendly docstrings | # Copyright 2020-2026 The HuggingFace Team. All rights reserved.
#
# 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 appl... | --- +++ @@ -17,8 +17,37 @@
def get_soft_overlong_punishment(max_completion_len: int, soft_punish_cache: int) -> Callable:
# docstyle-ignore
+ r"""
+ Reward function that penalizes overlong completions. It is used to penalize overlong completions, but not to reward
+ shorter completions. Reference: Eq. (... | https://raw.githubusercontent.com/huggingface/trl/HEAD/trl/rewards/other_rewards.py |
Expand my code with proper documentation strings | # Copyright 2020-2026 The HuggingFace Team. All rights reserved.
#
# 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 appl... | --- +++ @@ -137,6 +137,61 @@
@dataclass
class DataCollatorForPreference(DataCollatorMixin):
+ """
+ Data collator used for preference data. Inputs are dynamically padded to the maximum length of a batch.
+
+ This collator expects each example in the input list to be a dictionary containing the `"chosen_ids"... | https://raw.githubusercontent.com/huggingface/trl/HEAD/trl/trainer/reward_trainer.py |
Generate helpful docstrings for debugging | # Copyright 2020-2026 The HuggingFace Team. All rights reserved.
#
# 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 appl... | --- +++ @@ -51,6 +51,16 @@
def make_choice_type_function(choices: list) -> Callable[[str], Any]:
+ """
+ Creates a mapping function from each choices string representation to the actual value. Used to support multiple
+ value types for a single argument.
+
+ Args:
+ choices (list): List of choice... | https://raw.githubusercontent.com/huggingface/trl/HEAD/trl/scripts/_hf_argparser.py |
Add concise docstrings to each method | # Copyright 2020-2026 The HuggingFace Team. All rights reserved.
#
# 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 appl... | --- +++ @@ -91,6 +91,14 @@
def ensure_master_addr_port(addr: str | None = None, port: int | None = None) -> None:
+ """
+ Ensure `MASTER_ADDR`/`MASTER_PORT` are set safely.
+
+ - Respects existing environment variables.
+ - Defaults `MASTER_ADDR` to localhost if unset.
+ - Chooses a free TCP port if ... | https://raw.githubusercontent.com/huggingface/trl/HEAD/trl/trainer/utils.py |
Write docstrings for this repository | # Copyright 2020-2026 The HuggingFace Team. All rights reserved.
#
# 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 appl... | --- +++ @@ -12,6 +12,11 @@ # See the License for the specific language governing permissions and
# limitations under the License.
+"""
+CLI commands for TRL skills installation and management.
+
+This module provides command-line interface for installing TRL skills to various AI agent directories.
+"""
import arg... | https://raw.githubusercontent.com/huggingface/trl/HEAD/trl/skills/cli.py |
Generate consistent documentation across files | # Copyright 2020-2026 The HuggingFace Team. All rights reserved.
#
# 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 appl... | --- +++ @@ -128,6 +128,126 @@
class GRPOTrainer(_BaseTrainer):
+ """
+ Trainer for the Group Relative Policy Optimization (GRPO) method. This algorithm was initially proposed in the
+ paper [DeepSeekMath: Pushing the Limits of Mathematical Reasoning in Open Language
+ Models](https://huggingface.co/pape... | https://raw.githubusercontent.com/huggingface/trl/HEAD/trl/trainer/grpo_trainer.py |
Help me add docstrings to my project | # Copyright 2020-2026 The HuggingFace Team. All rights reserved.
#
# 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 appl... | --- +++ @@ -38,6 +38,29 @@
@dataclass
class DatasetConfig:
+ """
+ Configuration for a dataset.
+
+ This class matches the signature of [`~datasets.load_dataset`] and the arguments are used directly in the
+ [`~datasets.load_dataset`] function. You can refer to the [`~datasets.load_dataset`] documentatio... | https://raw.githubusercontent.com/huggingface/trl/HEAD/trl/scripts/utils.py |
Add docstrings for internal functions | # Copyright 2020-2026 The HuggingFace Team. All rights reserved.
#
# 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 appl... | --- +++ @@ -67,6 +67,20 @@ generation_config: GenerationConfig | None,
batch_size: int = 1,
) -> list[str]:
+ """
+ Generates completions for a list of pre-formatted prompts from the given model.
+
+ Args:
+ prompts (list[str]): A list of input prompts for which completions are to be generated... | https://raw.githubusercontent.com/huggingface/trl/HEAD/trl/trainer/callbacks.py |
Create Google-style docstrings for my code | # Copyright 2020-2026 The HuggingFace Team. All rights reserved.
#
# 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 appl... | --- +++ @@ -12,6 +12,19 @@ # See the License for the specific language governing permissions and
# limitations under the License.
+"""
+Agent Skills.
+
+This module:
+- provides utilities for discovering and accessing TRL skills that can be used by AI agents to learn how to use the TRL
+ CLI
+- handles installation... | https://raw.githubusercontent.com/huggingface/trl/HEAD/trl/skills/skills.py |
Document my Python code with docstrings | # Copyright 2020-2026 The HuggingFace Team. All rights reserved.
#
# 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 appl... | --- +++ @@ -89,6 +89,71 @@
@dataclass
class DataCollatorForLanguageModeling(DataCollatorMixin):
+ """
+ Data collator used for language modeling data. Inputs are dynamically padded to the maximum length of a batch.
+
+ This collator expects each example in the input list to be a dictionary containing at lea... | https://raw.githubusercontent.com/huggingface/trl/HEAD/trl/trainer/sft_trainer.py |
Document this script properly | # Copyright 2020-2026 The HuggingFace Team. All rights reserved.
#
# 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 appl... | --- +++ @@ -102,6 +102,102 @@
class RLOOTrainer(_BaseTrainer):
+ """
+ Trainer for the Reinforce Leave One Out (RLOO) method. This algorithm was initially proposed in the paper [Back to
+ Basics: Revisiting REINFORCE Style Optimization for Learning from Human Feedback in
+ LLMs](https://huggingface.co/p... | https://raw.githubusercontent.com/huggingface/trl/HEAD/trl/trainer/rloo_trainer.py |
Add docstrings that explain logic | # Copyright 2020-2026 The HuggingFace Team. All rights reserved.
#
# 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 appl... | --- +++ @@ -32,12 +32,37 @@
class WeightSyncWorkerExtension:
+ """
+ A vLLM worker extension that enables weight synchronization between a client and multiple server workers.
+
+ This worker uses a `StatelessProcessGroup` to establish communication and a `PyNcclCommunicator` or
+ `ProcessGroupXCCL` to h... | https://raw.githubusercontent.com/huggingface/trl/HEAD/trl/scripts/vllm_serve.py |
Generate documentation strings for clarity | from __future__ import annotations
import functools
from concurrent.futures import ThreadPoolExecutor
from typing import TYPE_CHECKING, AbstractSet, Collection, Literal, NoReturn, Sequence
from tiktoken import _tiktoken
if TYPE_CHECKING:
import re
import numpy as np
import numpy.typing as npt
class En... | --- +++ @@ -23,6 +23,21 @@ special_tokens: dict[str, int],
explicit_n_vocab: int | None = None,
):
+ """Creates an Encoding object.
+
+ See openai_public.py for examples of how to construct an Encoding object.
+
+ Args:
+ name: The name of the encoding. It should be... | https://raw.githubusercontent.com/openai/tiktoken/HEAD/tiktoken/core.py |
Create docstrings for reusable components |
from __future__ import annotations
import collections
import regex
import tiktoken
class SimpleBytePairEncoding:
def __init__(self, *, pat_str: str, mergeable_ranks: dict[bytes, int]) -> None:
# A regex pattern string that is used to split the input text
self.pat_str = pat_str
# A dict... | --- +++ @@ -1,3 +1,4 @@+"""This is an educational implementation of the byte pair encoding algorithm."""
from __future__ import annotations
@@ -10,6 +11,7 @@
class SimpleBytePairEncoding:
def __init__(self, *, pat_str: str, mergeable_ranks: dict[bytes, int]) -> None:
+ """Creates an Encoding object."... | https://raw.githubusercontent.com/openai/tiktoken/HEAD/tiktoken/_educational.py |
Document classes and their methods | from __future__ import annotations
from .core import Encoding
from .registry import get_encoding
# TODO: these will likely be replaced by an API endpoint
MODEL_PREFIX_TO_ENCODING: dict[str, str] = {
"o1-": "o200k_base",
"o3-": "o200k_base",
"o4-mini-": "o200k_base",
# chat
"gpt-5-": "o200k_base",
... | --- +++ @@ -86,6 +86,10 @@
def encoding_name_for_model(model_name: str) -> str:
+ """Returns the name of the encoding used by a model.
+
+ Raises a KeyError if the model name is not recognised.
+ """
encoding_name = None
if model_name in MODEL_TO_ENCODING:
encoding_name = MODEL_TO_ENCODI... | https://raw.githubusercontent.com/openai/tiktoken/HEAD/tiktoken/model.py |
Document this code for team use |
# Standard library
import json
import random
import sys
# My library
sys.path.append('../src/')
import mnist_loader
import network2
# Third-party libraries
import matplotlib.pyplot as plt
import numpy as np
def main(filename, num_epochs,
training_cost_xmin=200,
test_accuracy_xmin=200,
... | --- +++ @@ -1,158 +1,179 @@-
-# Standard library
-import json
-import random
-import sys
-
-# My library
-sys.path.append('../src/')
-import mnist_loader
-import network2
-
-# Third-party libraries
-import matplotlib.pyplot as plt
-import numpy as np
-
-
-def main(filename, num_epochs,
- training_cost_xmin=200,... | https://raw.githubusercontent.com/mnielsen/neural-networks-and-deep-learning/HEAD/fig/overfitting.py |
Generate consistent docstrings |
#### Libraries
# Standard library
import cPickle
import gzip
# Third-party libraries
import numpy as np
def load_data():
f = gzip.open('../data/mnist.pkl.gz', 'rb')
training_data, validation_data, test_data = cPickle.load(f)
f.close()
return (training_data, validation_data, test_data)
def load_data_... | --- +++ @@ -1,30 +1,85 @@-
-#### Libraries
-# Standard library
-import cPickle
-import gzip
-
-# Third-party libraries
-import numpy as np
-
-def load_data():
- f = gzip.open('../data/mnist.pkl.gz', 'rb')
- training_data, validation_data, test_data = cPickle.load(f)
- f.close()
- return (training_data, vali... | https://raw.githubusercontent.com/mnielsen/neural-networks-and-deep-learning/HEAD/src/mnist_loader.py |
Generate NumPy-style docstrings |
#### Libraries
# Standard library
import cPickle
import sys
# My library
sys.path.append('../src/')
import mnist_loader
# Third-party libraries
import matplotlib
import matplotlib.pyplot as plt
import numpy as np
def main():
training_set, validation_set, test_set = mnist_loader.load_data()
images = get_imag... | --- +++ @@ -1,208 +1,234 @@-
-#### Libraries
-# Standard library
-import cPickle
-import sys
-
-# My library
-sys.path.append('../src/')
-import mnist_loader
-
-# Third-party libraries
-import matplotlib
-import matplotlib.pyplot as plt
-import numpy as np
-
-def main():
- training_set, validation_set, test_set = mn... | https://raw.githubusercontent.com/mnielsen/neural-networks-and-deep-learning/HEAD/fig/mnist.py |
Improve my code by adding docstrings | # Copyright (c) 2024, Tri Dao, Albert Gu.
import math
import torch
import torch.nn as nn
import torch.nn.functional as F
from einops import rearrange
try:
from flash_attn import flash_attn_with_kvcache
except ImportError:
flash_attn_with_kvcache = None
try:
from flash_attn.layers.rotary import RotaryEmb... | --- +++ @@ -24,6 +24,7 @@
def _update_kv_cache(kv, inference_params, layer_idx):
+ """kv: (batch_size, seqlen, 2, nheads, head_dim) or (batch_size, 1, 2, nheads, head_dim)"""
# Pre-allocate memory for key-values for inference.
num_heads, head_dim = kv.shape[-2:]
assert layer_idx in inference_param... | https://raw.githubusercontent.com/state-spaces/mamba/HEAD/mamba_ssm/modules/mha.py |
Please document this code using docstrings |
import torch
import tilelang
import tilelang.language as T
from triton.testing import do_bench
from tilelang.autotuner import autotune
import itertools
import argparse
from einops import rearrange
from typing import Optional, Tuple
from mamba_ssm.ops.triton.mamba3.mamba3_mimo_utils import bwd_dadt_fused_triton, bwd... | --- +++ @@ -1,3 +1,10 @@+"""
+Tilelang implementation of Mamba3 backward kernels,
+with MIMO support.
+
+Copyright (c) 2026, Dao AI Lab, Goombalab
+
+"""
import torch
import tilelang
@@ -88,6 +95,29 @@
SEGSUM: T.Tensor([B, H, nchunks, chunk_size, chunk_size], T.float32), # type: ignore
... | https://raw.githubusercontent.com/state-spaces/mamba/HEAD/mamba_ssm/ops/tilelang/mamba3/mamba3_mimo_bwd.py |
Add docstrings following best practices | # Copyright (c) 2024, Tri Dao, Albert Gu.
import math
from packaging import version
import torch
import torch.nn.functional as F
import triton
import triton.language as tl
from einops import rearrange, repeat
from mamba_ssm.ops.triton.ssd_bmm import _bmm_chunk_fwd, _bmm_chunk_bwd
from mamba_ssm.utils.determinism ... | --- +++ @@ -1,5 +1,7 @@ # Copyright (c) 2024, Tri Dao, Albert Gu.
+"""We want triton==2.1.0 or 2.2.0 for this
+"""
import math
from packaging import version
@@ -1614,6 +1616,8 @@
def _chunk_scan_bwd_ddAcs_unstable(x, dt, out, dout, ddt, D=None, subtract_ddtdt=True):
+ """Not numerically stable and should n... | https://raw.githubusercontent.com/state-spaces/mamba/HEAD/mamba_ssm/ops/triton/ssd_chunk_scan.py |
Improve documentation using docstrings |
from typing import Optional, Tuple
import math
import torch
import torch.nn.functional as F
from einops import rearrange, repeat
import triton
import triton.language as tl
from mamba_ssm.ops.triton.mamba3.utils import cos_approx, sin_approx, tanh_approx, silu, sigmoid_approx
@triton.autotune(
configs=[
... | --- +++ @@ -1,3 +1,8 @@+"""
+Mamba-3 SISO Forward Pass Triton Kernel.
+
+Copyright (c) 2025, Dao AI Lab, Goombalab
+"""
from typing import Optional, Tuple
import math
@@ -72,6 +77,63 @@ HAS_Z: tl.constexpr,
IS_VARLEN: tl.constexpr,
):
+ """
+ Mamba-3 forward kernel.
+
+ Grid: (nheads, batch) for ... | https://raw.githubusercontent.com/state-spaces/mamba/HEAD/mamba_ssm/ops/triton/mamba3/mamba3_siso_fwd.py |
Add docstrings to improve readability |
import torch
import triton
import triton.language as tl
import math
from typing import Optional, Tuple
# Constants
LOG2 = math.log(2.0)
NEG_LOG2E = -math.log2(math.e)
# ============================================================================
# Kernel 1: Fused Cumsum Operations (forward exclusive + reverse)
# ==... | --- +++ @@ -1,3 +1,13 @@+"""
+Fused Triton kernels for Mamba3 backward pass ddt computation.
+
+This module implements fused kernels that combine three separate backward operations:
+1. bwd_segsum_ddt_from_dSSdA - Complex 2D segsum operation
+2. bwd_ddt_from_ddA_cs_rev - Forward exclusive cumsum operation
+3. bwd_ddt_f... | https://raw.githubusercontent.com/state-spaces/mamba/HEAD/mamba_ssm/ops/triton/mamba3/mamba3_mimo_utils.py |
Add docstrings following best practices |
from __future__ import annotations
from dataclasses import dataclass
from typing import Optional, Tuple
import torch
from torch import Tensor
import triton
# Import kernels
from mamba_ssm.ops.triton.mamba3.mamba3_siso_fwd import mamba3_siso_fwd
from mamba_ssm.ops.triton.mamba3.mamba3_siso_bwd import compute_dzdo, c... | --- +++ @@ -1,3 +1,7 @@+"""Mamba-3 Triton Autograd Wrapper
+
+Copyright (c) 2025, Dao AI Lab, Goombalab
+"""
from __future__ import annotations
@@ -15,6 +19,7 @@
def _triton_alloc_fn(size: int, alignment: int, stream: Optional[int]):
+ """Allocator for Triton runtime memory (TMA descriptors, scratch)."""
... | https://raw.githubusercontent.com/state-spaces/mamba/HEAD/mamba_ssm/ops/triton/mamba3/mamba3_siso_combined.py |
Generate docstrings for script automation | # Copyright (c) 2024, Tri Dao, Albert Gu.
from typing import Optional
import math
from packaging import version
import torch
import torch.nn.functional as F
from torch import Tensor
from mamba_ssm.utils.torch import custom_bwd, custom_fwd
import triton
import triton.language as tl
from einops import rearrange, re... | --- +++ @@ -1,5 +1,7 @@ # Copyright (c) 2024, Tri Dao, Albert Gu.
+"""We want triton==2.1.0 or 2.2.0 for this
+"""
from typing import Optional
@@ -55,6 +57,20 @@
def ensure_stride(inp):
+ """
+ Return inp, while ensuring that stride(1) of the returned tensor is a multiple of 8.
+
+ The inp tensor is... | https://raw.githubusercontent.com/state-spaces/mamba/HEAD/mamba_ssm/ops/triton/ssd_combined.py |
Generate docstrings for each module | # Copyright (c) 2024, Albert Gu and Tri Dao.
import torch
import torch.nn.functional as F
from einops import rearrange, repeat
from mamba_ssm.ops.triton.ssd_combined import mamba_chunk_scan_combined
def segsum_unstable(x):
T = x.size(-1)
x_cumsum = torch.cumsum(x, dim=-1)
x_segsum = x_cumsum[..., :, Non... | --- +++ @@ -1,4 +1,8 @@ # Copyright (c) 2024, Albert Gu and Tri Dao.
+"""Minimal implementation of SSD.
+
+This is the same as Listing 1 from the paper.
+"""
import torch
import torch.nn.functional as F
@@ -8,6 +12,7 @@
def segsum_unstable(x):
+ """Naive segment sum calculation."""
T = x.size(-1)
x... | https://raw.githubusercontent.com/state-spaces/mamba/HEAD/mamba_ssm/modules/ssd_minimal.py |
Create structured documentation for my script | # Copyright (c) 2025, Tri Dao.
from typing import Optional
import math
import torch
import triton
import triton.language as tl
from triton.language.extra import libdevice
class AngleDtFn(torch.autograd.Function):
@staticmethod
def forward(ctx,
angle: torch.Tensor, # (B, S, H, D)
... | --- +++ @@ -309,6 +309,21 @@ dt: torch.Tensor, # (batch, seqlen, nheads)
chunk_size: int = 128,
) -> tuple[torch.Tensor, torch.Tensor]:
+ """
+ Multiply angle and dt tensors element-wise and compute chunk sums.
+
+ Arguments:
+ angle: (batch, seqlen, nheads, dim)
+ dt: (batch, seqle... | https://raw.githubusercontent.com/state-spaces/mamba/HEAD/mamba_ssm/ops/triton/angle_cumsum.py |
Add return value explanations in docstrings | # Copyright (c) 2024, Tri Dao, Albert Gu.
import math
import torch
import torch.nn.functional as F
import triton
import triton.language as tl
from einops import rearrange, repeat
from mamba_ssm.utils.determinism import autotune_configs
def init_to_zero(names):
return lambda nargs: [nargs[name].zero_() for na... | --- +++ @@ -1,5 +1,7 @@ # Copyright (c) 2024, Tri Dao, Albert Gu.
+"""We want triton==2.1.0 or 2.2.0 for this
+"""
import math
import torch
@@ -161,6 +163,16 @@
def _bmm_chunk_fwd(a, b, chunk_size, seq_idx=None, causal=False, output_dtype=None):
+ """
+ Argument:
+ a: (batch, seqlen, k) or (batch... | https://raw.githubusercontent.com/state-spaces/mamba/HEAD/mamba_ssm/ops/triton/ssd_bmm.py |
Create Google-style docstrings for my code |
from typing import Optional, Tuple
import math
import torch
import triton
import triton.language as tl
from mamba_ssm.ops.triton.mamba3.utils import cos_approx, sin_approx, silu, tanh_approx, sigmoid_approx
@triton.autotune(
configs=[
triton.Config({}, num_stages=s, num_warps=w)
for s in [1, 2,... | --- +++ @@ -1,3 +1,8 @@+"""
+Mamba-3 Step Kernel.
+
+Copyright (c) 2025, Dao AI Lab, Goombalab
+"""
from typing import Optional, Tuple
import math
@@ -55,6 +60,37 @@ HAS_D: tl.constexpr,
HAS_Z: tl.constexpr,
):
+ """
+ Mamba-3 Step kernel.
+
+ Inputs:
+ Q, K: (batch, ... | https://raw.githubusercontent.com/state-spaces/mamba/HEAD/mamba_ssm/ops/triton/mamba3/mamba3_siso_step.py |
Generate docstrings with examples | from typing import Tuple, Optional
import torch
from torch import Tensor
import triton
import triton.language as tl
from mamba_ssm.ops.triton.mamba3.utils import tanh_approx, sech2_approx
# -----------------------------------------------------------------------------
# Forward kernel
# -----------------------------... | --- +++ @@ -130,6 +130,24 @@ return_output_state: bool = False,
cu_seqlens: Optional[Tensor] = None,
) -> Tensor | Tuple[Tensor, Tensor]:
+ """Forward pass for angle * dt cumsum.
+
+ Args:
+ angle: Angle tensor (batch, seqlen, nheads, dim)
+ dt: Time delta tensor (bat... | https://raw.githubusercontent.com/state-spaces/mamba/HEAD/mamba_ssm/ops/triton/mamba3/angle_dt.py |
Please document this code using docstrings | # Copyright (c) 2025, Tri Dao.
# Modified to use tvm-ffi and fake tensors instead of dlpack.
# Modified to optionally update state in place (state_out=None) or write to separate state_out.
import math
from typing import Optional, Type, Literal, List
import torch
import torch.nn.functional as F
from torch import Tenso... | --- +++ @@ -20,6 +20,7 @@
def transpose_view(a: cute.Tensor) -> cute.Tensor:
+ """Transpose the first two dimensions of a tensor on smem."""
shape = (a.shape[1], a.shape[0], *a.shape[2:])
order = (1, 0, *range(2, cute.rank(a)))
return cute.composition(a, cute.make_ordered_layout(shape, order=order... | https://raw.githubusercontent.com/state-spaces/mamba/HEAD/mamba_ssm/ops/cute/mamba3/mamba3_step_fn.py |
Add docstrings to existing functions | # Copyright (c) 2024, Tri Dao, Albert Gu.
import math
import torch
import torch.nn.functional as F
import triton
import triton.language as tl
from einops import rearrange, repeat
from mamba_ssm.ops.triton.softplus import softplus
@triton.heuristics({"HAS_DT_BIAS": lambda args: args["dt_bias_ptr"] is not None})
@... | --- +++ @@ -1,5 +1,7 @@ # Copyright (c) 2024, Tri Dao, Albert Gu.
+"""We want triton==2.1.0 or triton==2.2.0 or triton==2.3.0 for this
+"""
import math
import torch
@@ -132,6 +134,20 @@
def selective_state_update(state, x, dt, A, B, C, D=None, z=None, dt_bias=None, dt_softplus=False,
... | https://raw.githubusercontent.com/state-spaces/mamba/HEAD/mamba_ssm/ops/triton/selective_state_update.py |
Add docstrings to improve collaboration | # Copyright (c) 2023, Albert Gu, Tri Dao.
import sys
import warnings
import os
import re
import ast
from pathlib import Path
from packaging.version import parse, Version
import platform
import shutil
from setuptools import setup, find_packages
import subprocess
import urllib.request
import urllib.error
from wheel.bdi... | --- +++ @@ -45,6 +45,9 @@
def get_platform():
+ """
+ Returns the platform name as used in wheel filenames.
+ """
if sys.platform.startswith("linux"):
return f"linux_{platform.machine()}"
elif sys.platform == "darwin":
@@ -323,6 +326,12 @@
class CachedWheelsCommand(_bdist_wheel):
+ ... | https://raw.githubusercontent.com/state-spaces/mamba/HEAD/setup.py |
Add documentation for all methods | # Copyright (c) 2024, Tri Dao.
# Based on the Triton LayerNorm tutorial: https://triton-lang.org/main/getting-started/tutorials/05-layer-norm.html
# For the backward pass, we keep weight_grad and bias_grad in registers and accumulate.
# This backward pass is faster for dimensions up to 8k, but after that it's much slow... | --- +++ @@ -340,6 +340,8 @@ @staticmethod
def forward(ctx, x, weight, bias, z=None, eps=1e-6, group_size=None, norm_before_gate=True,
is_rms_norm=False):
+ """If z is not None, we do norm(x) * silu(z) if norm_before_gate, else norm(x * silu(z))
+ """
x_shape_og = x.sha... | https://raw.githubusercontent.com/state-spaces/mamba/HEAD/mamba_ssm/ops/triton/layernorm_gated.py |
Add docstrings to improve code quality |
import torch
import tilelang
import tilelang.language as T
from tilelang.profiler import do_bench
from tilelang.autotuner import autotune
import itertools
import argparse
from typing import Optional, Tuple
# NOTE: Uncomment the following to autotune:
# def get_configs():
# iter_params = dict(num_stages=[0, 1, 2... | --- +++ @@ -1,3 +1,10 @@+"""
+Tilelang implementation of Mamba3 forward kernel,
+with MIMO support.
+
+Copyright (c) 2026, Dao AI Lab, Goombalab
+
+"""
import torch
import tilelang
@@ -84,6 +91,30 @@ FINAL_STATE: T.Tensor([B, H, N, P], T.float32), # type: ignore
FINAL_K: T.Tensor([B, R, H,... | https://raw.githubusercontent.com/state-spaces/mamba/HEAD/mamba_ssm/ops/tilelang/mamba3/mamba3_mimo_fwd.py |
Document functions with clear intent | # Copyright (c) 2024, Tri Dao.
# The TensorParallel linear modules are inspired by https://github.com/NVIDIA/apex/blob/master/apex/transformer/tensor_parallel/layers.py
from typing import Optional
import torch
import torch.nn as nn
import torch.nn.functional as F
from torch import Tensor
from torch.distributed import ... | --- +++ @@ -24,6 +24,10 @@ @staticmethod
@custom_fwd
def forward(ctx, x, weight, bias, process_group=None, sequence_parallel=True):
+ """
+ If process_group is not None and sequence_parallel=True, we're doing Tensor Parallel
+ with sequence parallelism: we do an all_gather_raw of x be... | https://raw.githubusercontent.com/state-spaces/mamba/HEAD/mamba_ssm/distributed/tensor_parallel.py |
Write docstrings for this repository | # Copyright (c) 2023, Albert Gu, Tri Dao.
import math
from functools import partial
import json
import os
import copy
from collections import namedtuple
import torch
import torch.nn as nn
from mamba_ssm.models.config_mamba import MambaConfig
from mamba_ssm.modules.mamba_simple import Mamba
from mamba_ssm.modules.ma... | --- +++ @@ -272,6 +272,10 @@ return self.backbone.allocate_inference_cache(batch_size, max_seqlen, dtype=dtype, **kwargs)
def forward(self, input_ids, position_ids=None, inference_params=None, num_last_tokens=0, **mixer_kwargs):
+ """
+ "position_ids" is just to be compatible with Transform... | https://raw.githubusercontent.com/state-spaces/mamba/HEAD/mamba_ssm/models/mixer_seq_simple.py |
Write docstrings describing each step | # Copyright (c) 2023, Albert Gu, Tri Dao.
import gc
import time
from collections import namedtuple
from dataclasses import dataclass, field
from functools import partial
from typing import Callable, Optional, Sequence, Union
import torch
import torch.nn.functional as F
from einops import rearrange, repeat
from torch i... | --- +++ @@ -16,6 +16,8 @@
@dataclass
class InferenceParams:
+ """Inference parameters that are passed to the main model in order
+ to efficienly calculate and store the context during inference."""
max_seqlen: int
max_batch_size: int
@@ -33,6 +35,7 @@
def modify_logits_for_min_p_filtering(logit... | https://raw.githubusercontent.com/state-spaces/mamba/HEAD/mamba_ssm/utils/generation.py |
Improve documentation using docstrings | # Copyright (c) 2024, Tri Dao, Albert Gu.
from typing import Optional
import torch
from torch import nn, Tensor
from mamba_ssm.ops.triton.layer_norm import RMSNorm, layer_norm_fn
class Block(nn.Module):
def __init__(
self, dim, mixer_cls, mlp_cls, norm_cls=nn.LayerNorm, fused_add_norm=False, residual_in... | --- +++ @@ -11,6 +11,18 @@ def __init__(
self, dim, mixer_cls, mlp_cls, norm_cls=nn.LayerNorm, fused_add_norm=False, residual_in_fp32=False
):
+ """
+ Simple block wrapping a mixer class with LayerNorm/RMSNorm and residual connection"
+
+ This Block has a slightly different struct... | https://raw.githubusercontent.com/state-spaces/mamba/HEAD/mamba_ssm/modules/block.py |
Add concise docstrings to each method |
from typing import Optional, Tuple
import math
import torch
import torch.nn.functional as F
from einops import rearrange, repeat
import triton
import triton.language as tl
from mamba_ssm.ops.triton.mamba3.utils import cos_approx, sin_approx, sigmoid_approx
# =========================================================... | --- +++ @@ -1,3 +1,8 @@+"""
+Mamba-3 Backward Pass Triton Kernels.
+
+Copyright (c) 2026, Dao AI Lab, Goombalab
+"""
from typing import Optional, Tuple
import math
@@ -45,6 +50,17 @@ CHUNK_SIZE: tl.constexpr,
HEADDIM_V: tl.constexpr,
):
+ """
+ Backward kernel for Z-gating: computes dZ and scales dO... | https://raw.githubusercontent.com/state-spaces/mamba/HEAD/mamba_ssm/ops/triton/mamba3/mamba3_siso_bwd.py |
Add docstrings to improve code quality | # Copyright (c) 2024, Tri Dao, Albert Gu.
import os
import warnings
from packaging import version
import torch
try:
import triton
TRITON_VERSION = version.parse(triton.__version__)
except ImportError:
TRITON_VERSION = version.parse("0.0.0")
TRITON_HAS_CACHE_RESULTS = TRITON_VERSION >= version.parse("3.4... | --- +++ @@ -33,6 +33,7 @@
def _estimate_config_cost(cfg):
+ """Estimate shared memory cost of a config. Lower is cheaper."""
block_product = 1
for key, val in cfg.kwargs.items():
if key.startswith('BLOCK_SIZE_'):
@@ -41,6 +42,7 @@
def _filter_configs_by_block_sizes(configs):
+ """Filter... | https://raw.githubusercontent.com/state-spaces/mamba/HEAD/mamba_ssm/utils/determinism.py |
Add structured docstrings to improve clarity | # Copyright (c) 2025, Tri Dao.
# We need a pretty recent version of triton to support tuples. 3.3 definitely will work,
# idk which is the minimum version.
import math
from typing import Optional, Tuple
import torch
import triton
import triton.language as tl
import triton.testing
#from flash_attn.cute.benchmark impo... | --- +++ @@ -160,6 +160,22 @@ conjugate=False,
rotate_pairwise=True,
) -> tuple[torch.Tensor, torch.Tensor, torch.Tensor]:
+ """
+ Apply rotary embedding to both q and k tensors using the same angle.
+ Also computes output angle state for next step.
+
+ Arguments:
+ q: (batch, mimo_dim, nhea... | https://raw.githubusercontent.com/state-spaces/mamba/HEAD/mamba_ssm/ops/triton/mamba3/mamba3_mimo_rotary_step.py |
Help me comply with documentation standards | # Copyright (c) 2024, Tri Dao, Albert Gu.
import math
import torch
import torch.nn.functional as F
import triton
import triton.language as tl
from einops import rearrange, repeat
from mamba_ssm.ops.triton.softplus import softplus
from mamba_ssm.utils.determinism import (
alloc_tile_workspace,
finalize_tile... | --- +++ @@ -1,5 +1,7 @@ # Copyright (c) 2024, Tri Dao, Albert Gu.
+"""We want triton==2.1.0 or 2.2.0 for this
+"""
import math
import torch
@@ -1077,10 +1079,28 @@
def chunk_state(B, x, dt, dA_cumsum, states_in_fp32=True):
+ """
+ Argument:
+ B: (batch, seqlen, ngroups, dstate)
+ x: (batch... | https://raw.githubusercontent.com/state-spaces/mamba/HEAD/mamba_ssm/ops/triton/ssd_chunk_state.py |
Help me write clear docstrings |
from __future__ import annotations
from typing import Optional, Tuple, Union
import torch
from torch import Tensor
# Import kernels
from mamba_ssm.ops.tilelang.mamba3.mamba3_mimo_fwd import mamba_mimo_forward
from mamba_ssm.ops.triton.mamba3.mamba3_mimo_utils import compute_dacs_segsum_triton
from mamba_ssm.ops.til... | --- +++ @@ -1,3 +1,9 @@+"""Mamba-3 Tilelang Autograd Wrapper
+
+Interface for Mamba-3 Tilelang kernels with automatic differentiation
+
+Copyright (c) 2026, Dao AI Lab, Goombalab
+"""
from __future__ import annotations
@@ -16,6 +22,7 @@ # ============================================================================... | https://raw.githubusercontent.com/state-spaces/mamba/HEAD/mamba_ssm/ops/tilelang/mamba3/mamba3_mimo.py |
Add docstrings following best practices | # Copyright (c) 2023, Tri Dao, Albert Gu.
import torch
import torch.nn.functional as F
from mamba_ssm.utils.torch import custom_bwd, custom_fwd
from einops import rearrange, repeat
try:
from causal_conv1d import causal_conv1d_fn
from causal_conv1d.cpp_functions import causal_conv1d_fwd_function, causal_conv1... | --- +++ @@ -105,11 +105,28 @@
def selective_scan_fn(u, delta, A, B, C, D=None, z=None, delta_bias=None, delta_softplus=False,
return_last_state=False):
+ """if return_last_state is True, returns (out, last_state)
+ last_state has shape (batch, dim, dstate). Note that the gradient of the la... | https://raw.githubusercontent.com/state-spaces/mamba/HEAD/mamba_ssm/ops/selective_scan_interface.py |
Add verbose docstrings with examples |
import triton
import triton.language as tl
# We use PTX approximations instead of triton built-in functions
# to trade off a bit of accuracy for much faster speed.
@triton.jit
def cos_approx(x):
return tl.inline_asm_elementwise(
"cos.approx.f32 $0, $1;",
constraints="=f,f",
args=[x],
... | --- +++ @@ -1,3 +1,8 @@+"""
+Mamba-3 Util Functions.
+
+Copyright (c) 2025, Dao AI Lab, Goombalab
+"""
import triton
import triton.language as tl
@@ -7,6 +12,14 @@
@triton.jit
def cos_approx(x):
+ """
+ (Fast) Cosine approximation using PTX inline assembly.
+
+ Args:
+ x: Input triton tensor (any... | https://raw.githubusercontent.com/state-spaces/mamba/HEAD/mamba_ssm/ops/triton/mamba3/utils.py |
Add docstrings for production code | # Copyright (c) 2026, Dao AI Lab, Goombalab.
import math
from einops import rearrange, repeat
import torch
import torch.nn as nn
import torch.nn.functional as F
from mamba_ssm.ops.triton.layernorm_gated import RMSNorm as RMSNormGated
from mamba_ssm.ops.tilelang.mamba3.mamba3_mimo import mamba3_mimo as mamba3_mimo_c... | --- +++ @@ -125,6 +125,10 @@
def forward(self, u, seq_idx=None, cu_seqlens=None, inference_params=None):
+ """
+ u: (batch, seqlen, hidden_dim)
+ Returns: same shape as u
+ """
batch, seqlen, dim = u.shape
if cu_seqlens is not None:
raise NotImplemented... | https://raw.githubusercontent.com/state-spaces/mamba/HEAD/mamba_ssm/modules/mamba3.py |
Add docstrings following best practices | # Copyright (c) 2024, Tri Dao, Albert Gu.
import math
import torch
import torch.nn.functional as F
import triton
import triton.language as tl
from einops import rearrange, repeat
from mamba_ssm.utils.determinism import autotune_configs
@triton.autotune(
configs=autotune_configs([
triton.Config({'BLOC... | --- +++ @@ -1,5 +1,7 @@ # Copyright (c) 2024, Tri Dao, Albert Gu.
+"""We want triton==2.1.0 or 2.2.0 for this
+"""
import math
import torch
@@ -226,6 +228,9 @@ states, dA_chunk_cumsum, dout, dfinal_states=None, seq_idx=None, has_initial_states=None,
dstates_dtype=None, states_dtype=None, chunk_si... | https://raw.githubusercontent.com/state-spaces/mamba/HEAD/mamba_ssm/ops/triton/ssd_state_passing.py |
Add minimal docstrings for each function | #!/usr/bin/env python
# -*- coding:utf-8 -*-
from io import BytesIO
import pandas as pd
import requests
def bond_cash_summary_sse(date: str = "20210111") -> pd.DataFrame:
url = "http://query.sse.com.cn/commonExcelDd.do"
headers = {
"Accept": "text/html,application/xhtml+xml,application/xml;q=0.9,ima... | --- +++ @@ -1,5 +1,10 @@ #!/usr/bin/env python
# -*- coding:utf-8 -*-
+"""
+Date: 2022/3/5 12:55
+Desc: 上登债券信息网-债券成交概览
+http://bond.sse.com.cn/data/statistics/overview/turnover/
+"""
from io import BytesIO
@@ -8,6 +13,14 @@
def bond_cash_summary_sse(date: str = "20210111") -> pd.DataFrame:
+ """
+ 上登债券信... | https://raw.githubusercontent.com/akfamily/akshare/HEAD/akshare/bond/bond_summary.py |
Provide docstrings following PEP 257 | #!/usr/bin/env python
# -*- coding:utf-8 -*-
import pandas as pd
import requests
def macro_china_hk_core(symbol: str = "EMG00341602") -> pd.DataFrame:
url = "https://datacenter-web.eastmoney.com/api/data/v1/get"
params = {
"reportName": "RPT_ECONOMICVALUE_HK",
"columns": "ALL",
"filte... | --- +++ @@ -1,11 +1,24 @@ #!/usr/bin/env python
# -*- coding:utf-8 -*-
+"""
+Date: 2024/4/3 16:21
+Desc: 中国-香港-宏观指标
+https://data.eastmoney.com/cjsj/foreign_8_0.html
+"""
import pandas as pd
import requests
def macro_china_hk_core(symbol: str = "EMG00341602") -> pd.DataFrame:
+ """
+ 东方财富-数据中心-经济数据一览-宏观... | https://raw.githubusercontent.com/akfamily/akshare/HEAD/akshare/economic/macro_china_hk.py |
Generate consistent documentation across files | #!/usr/bin/env python
# -*- coding:utf-8 -*-
import pandas as pd
import requests
def macro_swiss_core(symbol: str = "EMG00341602") -> pd.DataFrame:
url = "https://datacenter-web.eastmoney.com/api/data/v1/get"
params = {
"reportName": "RPT_ECONOMICVALUE_CH",
"columns": "ALL",
"filter":... | --- +++ @@ -1,11 +1,24 @@ #!/usr/bin/env python
# -*- coding:utf-8 -*-
+"""
+Date: 2022/11/8 10:00
+Desc: 东方财富-经济数据-瑞士
+http://data.eastmoney.com/cjsj/foreign_2_0.html
+"""
import pandas as pd
import requests
def macro_swiss_core(symbol: str = "EMG00341602") -> pd.DataFrame:
+ """
+ 东方财富-数据中心-经济数据一览-宏观经... | https://raw.githubusercontent.com/akfamily/akshare/HEAD/akshare/economic/macro_swiss.py |
Document helper functions with docstrings | #!/usr/bin/env python
# -*- coding:utf-8 -*-
from io import StringIO
import pandas as pd
import requests
def fund_overview_em(symbol: str = "015641") -> pd.DataFrame:
url = f"https://fundf10.eastmoney.com/jbgk_{symbol}.html"
r = requests.get(url)
html_content = pd.read_html(StringIO(r.text))
if len... | --- +++ @@ -1,5 +1,10 @@ #!/usr/bin/env python
# -*- coding:utf-8 -*-
+"""
+Date: 2025/9/16 21:00
+Desc: 天天基金-基金档案
+https://fundf10.eastmoney.com/jbgk_015641.html
+"""
from io import StringIO
@@ -8,6 +13,14 @@
def fund_overview_em(symbol: str = "015641") -> pd.DataFrame:
+ """
+ 天天基金-基金档案-基本概况
+ http... | https://raw.githubusercontent.com/akfamily/akshare/HEAD/akshare/fund/fund_overview_em.py |
Replace inline comments with docstrings | #!/usr/bin/env python
# -*- coding:utf-8 -*-
import warnings
from io import StringIO
import pandas as pd
import requests
from tqdm import tqdm
from akshare.bank.cons import cbirc_headers_without_cookie_2020
def bank_fjcf_total_num(item: str = "分局本级") -> int:
item_id_list = {
"机关": "4113",
"本级":... | --- +++ @@ -1,5 +1,13 @@ #!/usr/bin/env python
# -*- coding:utf-8 -*-
+"""
+Date: 2025/2/4 23:00
+Desc: 中国银行保险监督管理委员会-首页-政务信息-行政处罚-银保监分局本级-XXXX行政处罚信息公开表
+https://www.nfra.gov.cn/cn/view/pages/ItemList.html?itemPId=923&itemId=4115&itemUrl=ItemListRightList.html&itemName=%E9%93%B6%E4%BF%9D%E7%9B%91%E5%88%86%E5%B1%80%E6%... | https://raw.githubusercontent.com/akfamily/akshare/HEAD/akshare/bank/bank_cbirc_2020.py |
Write docstrings describing functionality | # -*- coding:utf-8 -*-
# !/usr/bin/env python
import pandas as pd
import requests
import py_mini_racer
from akshare.datasets import get_ths_js
def _get_file_content_cninfo(file: str = "cninfo.js") -> str:
setting_file_path = get_ths_js(file)
with open(setting_file_path, encoding="utf-8") as f:
file_... | --- +++ @@ -1,5 +1,10 @@ # -*- coding:utf-8 -*-
# !/usr/bin/env python
+"""
+Date: 2024/6/19 22:00
+Desc: 巨潮资讯-数据中心-专题统计-债券报表-债券发行
+http://webapi.cninfo.com.cn/#/thematicStatistics
+"""
import pandas as pd
import requests
@@ -9,6 +14,13 @@
def _get_file_content_cninfo(file: str = "cninfo.js") -> str:
+ """
... | https://raw.githubusercontent.com/akfamily/akshare/HEAD/akshare/bond/bond_issue_cninfo.py |
Add return value explanations in docstrings | #!/usr/bin/env python
# -*- coding:utf-8 -*-
import warnings
import pandas as pd
import requests
from bs4 import BeautifulSoup
def hurun_rank(indicator: str = "胡润百富榜", year: str = "2023") -> pd.DataFrame:
url = "https://www.hurun.net/zh-CN/Rank/HsRankDetails?pagetype=rich"
r = requests.get(url)
soup = B... | --- +++ @@ -1,5 +1,10 @@ #!/usr/bin/env python
# -*- coding:utf-8 -*-
+"""
+Date: 2023/12/22 20:00
+Desc: 胡润排行榜
+https://www.hurun.net/
+"""
import warnings
@@ -9,6 +14,16 @@
def hurun_rank(indicator: str = "胡润百富榜", year: str = "2023") -> pd.DataFrame:
+ """
+ 胡润排行榜
+ https://www.hurun.net/CN/HuList/... | https://raw.githubusercontent.com/akfamily/akshare/HEAD/akshare/fortune/fortune_hurun.py |
Add docstrings following best practices | #!/usr/bin/env python
# -*- coding:utf-8 -*-
import pandas as pd
import requests
from bs4 import BeautifulSoup
def air_quality_hebei() -> pd.DataFrame:
url = "http://218.11.10.130:8080/api/hour/130000.xml"
r = requests.get(url)
soup = BeautifulSoup(r.content, features="xml")
data = []
cities = so... | --- +++ @@ -1,5 +1,19 @@ #!/usr/bin/env python
# -*- coding:utf-8 -*-
+"""
+Date: 2024/4/25 17:20
+Desc: 河北省空气质量预报信息发布系统
+https://110.249.223.67/publish
+每日 17 时发布
+等级划分
+1. 空气污染指数为0-50,空气质量级别为一级,空气质量状况属于优。此时,空气质量令人满意,基本无空气污染,各类人群可正常活动。
+2. 空气污染指数为51-100,空气质量级别为二级,空气质量状况属于良。此时空气质量可接受,但某些污染物可能对极少数异常敏感人群健康有较弱影响,建议极少数异常敏... | https://raw.githubusercontent.com/akfamily/akshare/HEAD/akshare/air/air_hebei.py |
Expand my code with proper documentation strings | #!/usr/bin/env python
# -*- coding:utf-8 -*-
from io import StringIO
import pandas as pd
import requests
def sunrise_city_list() -> list:
url = "https://www.timeanddate.com/astronomy/china"
r = requests.get(url)
city_list = []
china_city_one_df = pd.read_html(StringIO(r.text))[1]
china_city_two_... | --- +++ @@ -1,5 +1,10 @@ #!/usr/bin/env python
# -*- coding:utf-8 -*-
+"""
+Date: 2024/4/29 16:00
+Desc: 日出和日落数据
+https://www.timeanddate.com
+"""
from io import StringIO
@@ -8,6 +13,12 @@
def sunrise_city_list() -> list:
+ """
+ 查询日出与日落数据的城市列表
+ https://www.timeanddate.com/astronomy/china
+ :retu... | https://raw.githubusercontent.com/akfamily/akshare/HEAD/akshare/air/sunrise_tad.py |
Add standardized docstrings across the file | #!/usr/bin/env python
# -*- coding:utf-8 -*-
import pandas as pd
def fred_md(date: str = "2020-01") -> pd.DataFrame:
url = (
f"https://s3.amazonaws.com/files.fred.stlouisfed.org/fred-md/monthly/{date}.csv"
)
temp_df = pd.read_csv(url)
return temp_df
def fred_qd(date: str = "2020-01") -> pd.... | --- +++ @@ -1,10 +1,23 @@ #!/usr/bin/env python
# -*- coding:utf-8 -*-
+"""
+Date: 2020/4/10 19:58
+Desc: Economic Research from Federal Reserve Bank of St. Louis
+https://research.stlouisfed.org/econ/mccracken/fred-databases/
+FRED-MD and FRED-QD are large macroeconomic databases designed for the empirical analysis o... | https://raw.githubusercontent.com/akfamily/akshare/HEAD/akshare/article/fred_md.py |
Add verbose docstrings with examples | #!/usr/bin/env python
# -*- coding:utf-8 -*-
import pandas as pd
import requests
def fund_etf_scale_sse(date: str = "20250115") -> pd.DataFrame:
data_str = "-".join([date[:4], date[4:6], date[6:]])
url = "https://query.sse.com.cn/commonQuery.do"
params = {
"isPagination": "true",
"pageHel... | --- +++ @@ -1,11 +1,24 @@ #!/usr/bin/env python
# -*- coding:utf-8 -*-
+"""
+Date: 2026/1/20 15:00
+Desc: 上海证券交易所-ETF基金份额数据
+https://www.sse.com.cn/assortment/fund/etf/list/scale/
+"""
import pandas as pd
import requests
def fund_etf_scale_sse(date: str = "20250115") -> pd.DataFrame:
+ """
+ 上海证券交易所-产品-... | https://raw.githubusercontent.com/akfamily/akshare/HEAD/akshare/fund/fund_etf_sse.py |
Write docstrings that follow conventions | #!/usr/bin/env python
# -*- coding:utf-8 -*-
from io import StringIO
import pandas as pd
import requests
from bs4 import BeautifulSoup
from akshare.utils import demjson
def fund_portfolio_hold_em(symbol: str = "000001", date: str = "2024") -> pd.DataFrame:
url = "https://fundf10.eastmoney.com/FundArchivesDatas... | --- +++ @@ -1,5 +1,10 @@ #!/usr/bin/env python
# -*- coding:utf-8 -*-
+"""
+Date: 2024/6/7 20:00
+Desc: 天天基金网-基金档案-投资组合
+https://fundf10.eastmoney.com/ccmx_000001.html
+"""
from io import StringIO
@@ -11,6 +16,16 @@
def fund_portfolio_hold_em(symbol: str = "000001", date: str = "2024") -> pd.DataFrame:
+ "... | https://raw.githubusercontent.com/akfamily/akshare/HEAD/akshare/fund/fund_portfolio_em.py |
Provide docstrings following PEP 257 | # -*- coding:utf-8 -*-
# !/usr/bin/env python
import pathlib
from importlib import resources
def get_ths_js(file: str = "ths.js") -> pathlib.Path:
with resources.path("akshare.data", file) as f:
data_file_path = f
return data_file_path
def get_crypto_info_csv(file: str = "crypto_info.zip") -> p... | --- +++ @@ -1,17 +1,31 @@ # -*- coding:utf-8 -*-
# !/usr/bin/env python
+"""
+Date: 2024/12/30 15:30
+Desc: 导入文件工具,可以正确处理路径问题
+"""
import pathlib
from importlib import resources
def get_ths_js(file: str = "ths.js") -> pathlib.Path:
+ """
+ get path to data "ths.js" text file.
+ :return: 文件路径
+ :rt... | https://raw.githubusercontent.com/akfamily/akshare/HEAD/akshare/datasets.py |
Write beginner-friendly docstrings | #!/usr/bin/env python
# -*- coding:utf-8 -*-
import pandas as pd
import requests
from akshare.stock_feature.stock_a_indicator import get_token_lg, get_cookie_csrf
def fund_stock_position_lg() -> pd.DataFrame:
url = "https://legulegu.com/api/stockdata/fund-position"
token = get_token_lg()
params = {
... | --- +++ @@ -1,5 +1,10 @@ #!/usr/bin/env python
# -*- coding:utf-8 -*-
+"""
+Date: 2023/4/5 22:05
+Desc: 乐咕乐股-基金仓位
+https://legulegu.com/stockdata/fund-position/pos-stock
+"""
import pandas as pd
import requests
@@ -8,6 +13,12 @@
def fund_stock_position_lg() -> pd.DataFrame:
+ """
+ 乐咕乐股-基金仓位-股票型基金仓位
+ ... | https://raw.githubusercontent.com/akfamily/akshare/HEAD/akshare/fund/fund_position_lg.py |
Fill in missing docstrings in my code | #!/usr/bin/env python
# -*- coding:utf-8 -*-
from datetime import datetime
import pandas as pd
import requests
def crypto_js_spot() -> pd.DataFrame:
url = "https://datacenter-api.jin10.com/crypto_currency/list"
headers = {
"user-agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (... | --- +++ @@ -1,5 +1,9 @@ #!/usr/bin/env python
# -*- coding:utf-8 -*-
+"""
+Date: 2024/4/3 16:36
+Desc: 金十数据-其他-加密货币实时行情
+"""
from datetime import datetime
@@ -8,6 +12,11 @@
def crypto_js_spot() -> pd.DataFrame:
+ """
+ 主流加密货币的实时行情数据, 一次请求返回具体某一时刻行情数据
+ https://datacenter.jin10.com/reportType/dc_bitco... | https://raw.githubusercontent.com/akfamily/akshare/HEAD/akshare/economic/macro_other.py |
Document helper functions with docstrings | #!/usr/bin/env python
# -*- coding:utf-8 -*-
import json
import pandas as pd
import requests
import urllib3
from bs4 import BeautifulSoup
urllib3.disable_warnings(urllib3.exceptions.InsecureRequestWarning)
def article_oman_rv(symbol: str = "FTSE", index: str = "rk_th2") -> pd.DataFrame:
url = "https://realized... | --- +++ @@ -1,5 +1,9 @@ #!/usr/bin/env python
# -*- coding:utf-8 -*-
+"""
+Date: 2024/1/20 20:51
+Desc: 修大成主页-Risk Lab-Realized Volatility; Oxford-Man Institute of Quantitative Finance Realized Library
+"""
import json
@@ -12,6 +16,51 @@
def article_oman_rv(symbol: str = "FTSE", index: str = "rk_th2") -> pd.D... | https://raw.githubusercontent.com/akfamily/akshare/HEAD/akshare/article/risk_rv.py |
Help me document legacy Python code | #!/usr/bin/env python
# -*- coding:utf-8 -*-
import pandas as pd
import requests
def macro_uk_core(symbol: str = "EMG00010348") -> pd.DataFrame:
url = "https://datacenter-web.eastmoney.com/api/data/v1/get"
params = {
"reportName": "RPT_ECONOMICVALUE_BRITAIN",
"columns": "ALL",
"filter... | --- +++ @@ -1,11 +1,24 @@ #!/usr/bin/env python
# -*- coding:utf-8 -*-
+"""
+Date: 2022/11/12 17:14
+Desc: 东方财富-经济数据-英国
+https://data.eastmoney.com/cjsj/foreign_4_0.html
+"""
import pandas as pd
import requests
def macro_uk_core(symbol: str = "EMG00010348") -> pd.DataFrame:
+ """
+ 东方财富-数据中心-经济数据一览-宏观经济... | https://raw.githubusercontent.com/akfamily/akshare/HEAD/akshare/economic/macro_uk.py |
Can you add docstrings to this Python file? |
import warnings
import numpy as np
import pandas as pd
def rv_from_stock_zh_a_hist_min_em(
symbol="000001",
start_date="2021-10-20 09:30:00",
end_date="2024-11-01 15:00:00",
period="1",
adjust="hfq",
) -> pd.DataFrame:
from akshare.stock_feature.stock_hist_em import stock_zh_a_hist_min_em
... | --- +++ @@ -1,3 +1,8 @@+"""
+Yang-Zhang-s-Realized-Volatility-Automated-Estimation-in-Python
+https://github.com/hugogobato/Yang-Zhang-s-Realized-Volatility-Automated-Estimation-in-Python
+论文地址:https://www.jstor.org/stable/10.1086/209650
+"""
import warnings
@@ -12,6 +17,22 @@ period="1",
adjust="hfq",
)... | https://raw.githubusercontent.com/akfamily/akshare/HEAD/akshare/cal/rv.py |
Generate documentation strings for clarity | #!/usr/bin/env python
# -*- coding:utf-8 -*-
import pandas as pd
import requests
from akshare.forex.cons import symbol_market_map
from akshare.utils.func import fetch_paginated_data
def forex_spot_em() -> pd.DataFrame:
url = "https://push2.eastmoney.com/api/qt/clist/get"
params = {
"np": "1",
... | --- +++ @@ -1,5 +1,10 @@ #!/usr/bin/env python
# -*- coding:utf-8 -*-
+"""
+Date: 2025/6/23 15:00
+Desc: 东方财富网-行情中心-外汇市场-所有汇率
+https://quote.eastmoney.com/center/gridlist.html#forex_all
+"""
import pandas as pd
import requests
@@ -9,6 +14,12 @@
def forex_spot_em() -> pd.DataFrame:
+ """
+ 东方财富网-行情中心-外汇市场... | https://raw.githubusercontent.com/akfamily/akshare/HEAD/akshare/forex/forex_em.py |
Add docstrings including usage examples | #!/usr/bin/env python
# -*- coding:utf-8 -*-
import datetime
import re
import pandas as pd
import py_mini_racer
import requests
from akshare.bond.cons import (
zh_sina_bond_hs_cov_count_url,
zh_sina_bond_hs_cov_payload,
zh_sina_bond_hs_cov_url,
zh_sina_bond_hs_cov_hist_url,
)
from akshare.stock.cons ... | --- +++ @@ -1,5 +1,10 @@ #!/usr/bin/env python
# -*- coding:utf-8 -*-
+"""
+Date: 2025/7/4 15:00
+Desc: 新浪财经-债券-沪深可转债-实时行情数据和历史行情数据
+https://vip.stock.finance.sina.com.cn/mkt/#hskzz_z
+"""
import datetime
import re
@@ -21,6 +26,12 @@
def _get_zh_bond_hs_cov_page_count() -> int:
+ """
+ 新浪财经-行情中心-债券-沪深可转债... | https://raw.githubusercontent.com/akfamily/akshare/HEAD/akshare/bond/bond_zh_cov.py |
Expand my code with proper documentation strings | #!/usr/bin/env python
# -*- coding:utf-8 -*-
import pandas as pd
import requests
from akshare.utils.tqdm import get_tqdm
def bond_zh_us_rate(start_date: str = "19901219") -> pd.DataFrame:
url = "https://datacenter.eastmoney.com/api/data/get"
params = {
"type": "RPTA_WEB_TREASURYYIELD",
"sty":... | --- +++ @@ -1,5 +1,10 @@ #!/usr/bin/env python
# -*- coding:utf-8 -*-
+"""
+Date: 2025/4/5 17:00
+Desc: 东方财富网-数据中心-经济数据-中美国债收益率
+https://data.eastmoney.com/cjsj/zmgzsyl.html
+"""
import pandas as pd
import requests
@@ -7,6 +12,14 @@
def bond_zh_us_rate(start_date: str = "19901219") -> pd.DataFrame:
+ """
+ ... | https://raw.githubusercontent.com/akfamily/akshare/HEAD/akshare/bond/bond_em.py |
Improve documentation using docstrings | #!/usr/bin/env python
# -*- coding:utf-8 -*-
import json
import pandas as pd
import requests
def fund_etf_category_ths(symbol: str = "ETF", date: str = "") -> pd.DataFrame:
symbol_map = {
"股票型": "gpx",
"债券型": "zqx",
"混合型": "hhx",
"ETF": "ETF",
"LOF": "LOF",
"QDII"... | --- +++ @@ -1,5 +1,10 @@ #!/usr/bin/env python
# -*- coding:utf-8 -*-
+"""
+Date: 2026/2/10 16:00
+Desc: 同花顺理财-基金数据-每日净值-ETF
+https://fund.10jqka.com.cn/datacenter/jz/kfs/etf/
+"""
import json
@@ -8,6 +13,16 @@
def fund_etf_category_ths(symbol: str = "ETF", date: str = "") -> pd.DataFrame:
+ """
+ 同花顺理财... | https://raw.githubusercontent.com/akfamily/akshare/HEAD/akshare/fund/fund_etf_ths.py |
Create structured documentation for my script | #!/usr/bin/env python
# -*- coding:utf-8 -*-
import pandas as pd
def macro_cnbs() -> pd.DataFrame:
url = "http://114.115.232.154:8080/handler/download.ashx"
temp_df = pd.read_excel(
url, sheet_name="Data", header=0, skiprows=1, engine="openpyxl"
)
temp_df["Period"] = pd.to_datetime(temp_df["... | --- +++ @@ -1,10 +1,21 @@ #!/usr/bin/env python
# -*- coding:utf-8 -*-
+"""
+Date: 2023/8/14 11:10
+Desc: 国家金融与发展实验室-中国宏观杠杆率数据
+http://114.115.232.154:8080/
+"""
import pandas as pd
def macro_cnbs() -> pd.DataFrame:
+ """
+ 国家金融与发展实验室-中国宏观杠杆率数据
+ http://114.115.232.154:8080/
+ :return: 中国宏观杠杆率数据
+ ... | https://raw.githubusercontent.com/akfamily/akshare/HEAD/akshare/economic/marco_cnbs.py |
Document all endpoints with docstrings | #!/usr/bin/env python
# -*- coding:utf-8 -*-
import pandas as pd
def article_epu_index(symbol: str = "China") -> pd.DataFrame:
# 切勿修改 http 否则会读取不到 csv 文件
if symbol == "China New":
symbol = "SCMP_China"
if symbol == "China":
symbol = "SCMP_China"
if symbol == "USA":
symbol = "U... | --- +++ @@ -1,10 +1,23 @@ #!/usr/bin/env python
# -*- coding:utf-8 -*-
+"""
+Date: 2024/1/20 22:00
+Desc: 经济政策不确定性指数
+https://www.policyuncertainty.com/index.html
+"""
import pandas as pd
def article_epu_index(symbol: str = "China") -> pd.DataFrame:
+ """
+ 经济政策不确定性指数
+ https://www.policyuncertainty.c... | https://raw.githubusercontent.com/akfamily/akshare/HEAD/akshare/article/epu_index.py |
Add concise docstrings to each method | #!/usr/bin/env python
# -*- coding:utf-8 -*-
from datetime import datetime, timedelta
import numpy as np
import pandas as pd
import requests
def __convert_date_format(date: str) -> str:
datetime_obj = datetime.strptime(date, "%Y%m%d")
return datetime_obj.strftime("%Y-%m-%d %H:%M:%S")
def __format_date(dat... | --- +++ @@ -1,5 +1,10 @@ #!/usr/bin/env python
# -*- coding:utf-8 -*-
+"""
+Date: 2024/5/15 18:20
+Desc: 华尔街见闻-日历-宏观
+https://wallstreetcn.com/calendar
+"""
from datetime import datetime, timedelta
@@ -9,16 +14,36 @@
def __convert_date_format(date: str) -> str:
+ """
+ 将日期字符串从格式'%Y%m%d'转换为格式'%Y-%m-%d %H... | https://raw.githubusercontent.com/akfamily/akshare/HEAD/akshare/economic/macro_info_ws.py |
Generate NumPy-style docstrings | #!/usr/bin/env python
# -*- coding:utf-8 -*-
import pandas as pd
import requests
def bond_gb_zh_sina(symbol: str = "中国10年期国债") -> pd.DataFrame:
symbol_map = {
"中国1年期国债": "CN1YT",
"中国2年期国债": "CN2YT",
"中国3年期国债": "CN3YT",
"中国5年期国债": "CN5YT",
"中国7年期国债": "CN7YT",
"中国10年... | --- +++ @@ -1,11 +1,24 @@ #!/usr/bin/env python
# -*- coding:utf-8 -*-
+"""
+Date: 2026/2/4 17:00
+Desc: 新浪财经-债券-中国/美国国债收益率
+https://vip.stock.finance.sina.com.cn/mkt/#hs_z
+"""
import pandas as pd
import requests
def bond_gb_zh_sina(symbol: str = "中国10年期国债") -> pd.DataFrame:
+ """
+ 新浪财经-债券-中国国债收益率行情数据... | https://raw.githubusercontent.com/akfamily/akshare/HEAD/akshare/bond/bond_gb_sina.py |
Add inline docstrings for readability | #!/usr/bin/env python
# -*- coding:utf-8 -*-
from functools import lru_cache
import pandas as pd
import requests
from akshare.utils.tqdm import get_tqdm
def __bond_register_service() -> requests.Session:
session = requests.Session()
headers = {
"User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64... | --- +++ @@ -1,5 +1,10 @@ #!/usr/bin/env python
# -*- coding:utf-8 -*-
+"""
+Date: 2024/6/27 16:00
+Desc: 收盘收益率曲线历史数据
+https://www.chinamoney.com.cn/chinese/bkcurvclosedyhis/?bondType=CYCC000&reference=1
+"""
from functools import lru_cache
@@ -9,6 +14,12 @@
def __bond_register_service() -> requests.Session:
+... | https://raw.githubusercontent.com/akfamily/akshare/HEAD/akshare/bond/bond_china_money.py |
Add docstrings that explain logic | #!/usr/bin/env python
# -*- coding:utf-8 -*-
import pandas as pd
import requests
def currency_latest(
base: str = "USD", symbols: str = "", api_key: str = ""
) -> pd.DataFrame:
params = {"base": base, "symbols": symbols, "api_key": api_key}
url = "https://api.currencyscoop.com/v1/latest"
r = requests... | --- +++ @@ -1,5 +1,11 @@ #!/usr/bin/env python
# -*- coding:utf-8 -*-
+"""
+Date: 2023/7/24 18:30
+Desc: currencybeacon 提供的外汇数据
+该网站需要先注册后获取 API 使用
+https://currencyscoop.com/
+"""
import pandas as pd
import requests
@@ -8,6 +14,18 @@ def currency_latest(
base: str = "USD", symbols: str = "", api_key: str = "... | https://raw.githubusercontent.com/akfamily/akshare/HEAD/akshare/currency/currency.py |
Write clean docstrings for readability | #!/usr/bin/env python
# -*- coding:utf-8 -*-
import pandas as pd
import requests
def energy_oil_hist() -> pd.DataFrame:
url = "https://datacenter-web.eastmoney.com/api/data/v1/get"
params = {
"reportName": "RPTA_WEB_YJ_BD",
"columns": "ALL",
"sortColumns": "dim_date",
"sortTyp... | --- +++ @@ -1,11 +1,22 @@ #!/usr/bin/env python
# -*- coding:utf-8 -*-
+"""
+Date: 2024/1/20 23:00
+Desc: 东方财富-数据中心-中国油价
+https://data.eastmoney.com/cjsj/oil_default.html
+"""
import pandas as pd
import requests
def energy_oil_hist() -> pd.DataFrame:
+ """
+ 汽柴油历史调价信息
+ https://data.eastmoney.com/cjs... | https://raw.githubusercontent.com/akfamily/akshare/HEAD/akshare/energy/energy_oil_em.py |
Document this module using docstrings | #!/usr/bin/env python
# -*- coding:utf-8 -*-
from io import StringIO
import pandas as pd
import requests
def fund_aum_em() -> pd.DataFrame:
url = "https://fund.eastmoney.com/Company/home/gspmlist"
params = {"fundType": "0"}
r = requests.get(url, params=params)
temp_df = pd.read_html(StringIO(r.text)... | --- +++ @@ -1,5 +1,9 @@ #!/usr/bin/env python
# -*- coding:utf-8 -*-
+"""
+Date: 2023/11/11 16:30
+Desc: 东方财富-基金
+"""
from io import StringIO
@@ -8,6 +12,12 @@
def fund_aum_em() -> pd.DataFrame:
+ """
+ 东方财富-基金-基金公司排名列表
+ https://fund.eastmoney.com/Company/lsgm.html
+ :return: 基金公司排名列表
+ :rtype... | https://raw.githubusercontent.com/akfamily/akshare/HEAD/akshare/fund/fund_aum_em.py |
Generate docstrings for script automation | #!/usr/bin/env python
# -*- coding:utf-8 -*-
from io import StringIO
import pandas as pd
import requests
def macro_stock_finance() -> pd.DataFrame:
url = "https://data.10jqka.com.cn/macro/finance/"
headers = {
"User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 "
"(KH... | --- +++ @@ -1,5 +1,10 @@ #!/usr/bin/env python
# -*- coding:utf-8 -*-
+"""
+Date: 2025/10/21 20:00
+Desc: 同花顺-数据中心-宏观数据-股票筹资
+https://data.10jqka.com.cn/macro/finance/
+"""
from io import StringIO
@@ -8,6 +13,12 @@
def macro_stock_finance() -> pd.DataFrame:
+ """
+ 同花顺-数据中心-宏观数据-股票筹资
+ https://data.1... | https://raw.githubusercontent.com/akfamily/akshare/HEAD/akshare/economic/macro_finance_ths.py |
Document this module using docstrings | #!/usr/bin/env python
# -*- coding:utf-8 -*-
import time
import pandas as pd
import requests
def fund_announcement_dividend_em(symbol: str = "000001") -> pd.DataFrame:
url = "http://api.fund.eastmoney.com/f10/JJGG"
headers = {
"User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.... | --- +++ @@ -1,5 +1,10 @@ #!/usr/bin/env python
# -*- coding:utf-8 -*-
+"""
+Date: 2025/9/20 17:40
+Desc: 东方财富网站-天天基金网-基金档案-基金公告
+https://fundf10.eastmoney.com/jjgg_000001.html
+"""
import time
@@ -8,6 +13,14 @@
def fund_announcement_dividend_em(symbol: str = "000001") -> pd.DataFrame:
+ """
+ 东方财富网站-天天基... | https://raw.githubusercontent.com/akfamily/akshare/HEAD/akshare/fund/fund_announcement_em.py |
Provide docstrings following PEP 257 | # -*- coding:utf-8 -*-
# !/usr/bin/env python
from io import StringIO
import pandas as pd
import requests
def bond_cb_profile_sina(symbol: str = "sz128039") -> pd.DataFrame:
url = f"https://money.finance.sina.com.cn/bond/info/{symbol}.html"
r = requests.get(url)
temp_df = pd.read_html(StringIO(r.text))[... | --- +++ @@ -1,5 +1,10 @@ # -*- coding:utf-8 -*-
# !/usr/bin/env python
+"""
+Date: 2023/9/12 16:50
+Desc: 新浪财经-债券-可转债
+https://money.finance.sina.com.cn/bond/info/sz128039.html
+"""
from io import StringIO
@@ -8,6 +13,14 @@
def bond_cb_profile_sina(symbol: str = "sz128039") -> pd.DataFrame:
+ """
+ 新浪财经... | https://raw.githubusercontent.com/akfamily/akshare/HEAD/akshare/bond/bond_cb_sina.py |
Write Python docstrings for this snippet | #!/usr/bin/env python
# -*- coding:utf-8 -*-
import datetime
import time
import pandas as pd
import requests
def __macro_usa_base_func(symbol: str, params: dict) -> pd.DataFrame:
import warnings
warnings.filterwarnings(action="ignore", category=FutureWarning)
headers = {
"user-agent": "Mozilla/... | --- +++ @@ -1,5 +1,10 @@ #!/usr/bin/env python
# -*- coding:utf-8 -*-
+"""
+Date: 2024/4/4 18:00
+Desc: 金十数据中心-经济指标-美国
+https://datacenter.jin10.com/economic
+"""
import datetime
import time
@@ -9,6 +14,12 @@
def __macro_usa_base_func(symbol: str, params: dict) -> pd.DataFrame:
+ """
+ 金十数据中心-经济指标-美国-基础函... | https://raw.githubusercontent.com/akfamily/akshare/HEAD/akshare/economic/macro_usa.py |
Write docstrings that follow conventions | #!/usr/bin/env python
# -*- coding:utf-8 -*-
import pandas as pd
import requests
# 零售销售月率
def macro_australia_retail_rate_monthly() -> pd.DataFrame:
url = "https://datacenter-web.eastmoney.com/api/data/v1/get"
params = {
"reportName": "RPT_ECONOMICVALUE_AUSTRALIA",
"columns": "ALL",
"... | --- +++ @@ -1,5 +1,10 @@ #!/usr/bin/env python
# -*- coding:utf-8 -*-
+"""
+Date: 2025/1/17 15:30
+Desc: 东方财富-经济数据-澳大利亚
+https://data.eastmoney.com/cjsj/foreign_5_0.html
+"""
import pandas as pd
import requests
@@ -7,6 +12,12 @@
# 零售销售月率
def macro_australia_retail_rate_monthly() -> pd.DataFrame:
+ """
+ 东... | https://raw.githubusercontent.com/akfamily/akshare/HEAD/akshare/economic/macro_australia.py |
Include argument descriptions in docstrings | #!/usr/bin/env python
# -*- coding:utf-8 -*-
import json
import pandas as pd
import requests
def xincaifu_rank(year: str = "2022") -> pd.DataFrame:
url = "http://service.ikuyu.cn/XinCaiFu2/pcremoting/bdListAction.do"
params = {
"method": "getPage",
"callback": "jsonpCallback",
"sortB... | --- +++ @@ -1,5 +1,10 @@ #!/usr/bin/env python
# -*- coding:utf-8 -*-
+"""
+Date: 2022/10/30 21:12
+Desc: 新财富 500 人富豪榜
+http://www.xcf.cn/zhuanti/ztzz/hdzt1/500frb/index.html
+"""
import json
@@ -8,6 +13,14 @@
def xincaifu_rank(year: str = "2022") -> pd.DataFrame:
+ """
+ 新财富 500 人富豪榜
+ http://www.xc... | https://raw.githubusercontent.com/akfamily/akshare/HEAD/akshare/fortune/fortune_xincaifu_500.py |
Write docstrings for backend logic | #!/usr/bin/env python
# -*- coding:utf-8 -*-
import json
import os
import re
from io import StringIO
import pandas as pd
import requests
from py_mini_racer import MiniRacer
from akshare.utils import demjson
def _get_js_path(name: str = None, module_file: str = None) -> str:
module_folder = os.path.abspath(os.p... | --- +++ @@ -1,5 +1,12 @@ #!/usr/bin/env python
# -*- coding:utf-8 -*-
+"""
+Date: 2024/4/2 22:40
+Desc: 真气网-空气质量
+https://www.zq12369.com/environment.php
+空气质量在线监测分析平台的空气质量数据
+https://www.aqistudy.cn/
+"""
import json
import os
@@ -14,12 +21,28 @@
def _get_js_path(name: str = None, module_file: str = None) -> ... | https://raw.githubusercontent.com/akfamily/akshare/HEAD/akshare/air/air_zhenqi.py |
Write docstrings describing each step | #!/usr/bin/env python
# -*- coding:utf-8 -*-
import time
from functools import lru_cache
from typing import Union, Literal, List, Dict
import jsonpath as jp
import numpy as np
import pandas as pd
import requests
import urllib3
from urllib3.exceptions import InsecureRequestWarning
# 忽略InsecureRequestWarning警告
urllib3... | --- +++ @@ -1,5 +1,10 @@ #!/usr/bin/env python
# -*- coding:utf-8 -*-
+"""
+Date: 2024/6/30 22:00
+Desc: 中国-国家统计局-宏观数据
+https://data.stats.gov.cn/easyquery.htm
+"""
import time
from functools import lru_cache
@@ -18,6 +23,12 @@
@lru_cache
def _get_nbs_tree(idcode: str, dbcode: str) -> List[Dict]:
+ """
+ ... | https://raw.githubusercontent.com/akfamily/akshare/HEAD/akshare/economic/macro_china_nbs.py |
Add docstrings that explain purpose and usage | #!/usr/bin/env python
# -*- coding:utf-8 -*-
import pandas as pd
import requests
def macro_germany_core(symbol: str = "EMG00179154") -> pd.DataFrame:
url = "https://datacenter-web.eastmoney.com/api/data/v1/get"
params = {
"reportName": "RPT_ECONOMICVALUE_GER",
"columns": "ALL",
"filte... | --- +++ @@ -1,11 +1,23 @@ #!/usr/bin/env python
# -*- coding:utf-8 -*-
+"""
+Date: 2022/11/5 17:08
+Desc: 东方财富-德国-经济数据
+"""
import pandas as pd
import requests
def macro_germany_core(symbol: str = "EMG00179154") -> pd.DataFrame:
+ """
+ 东方财富-数据中心-经济数据一览-宏观经济-德国-核心代码
+ https://data.eastmoney.com/cjsj/... | https://raw.githubusercontent.com/akfamily/akshare/HEAD/akshare/economic/macro_germany.py |
Can you add docstrings to this Python file? | #!/usr/bin/env python
# -*- coding:utf-8 -*-
import json
import pandas as pd
import requests
def fund_new_found_ths(symbol: str = "全部") -> pd.DataFrame:
url = "https://fund.10jqka.com.cn/datacenter/xfjj/"
r = requests.get(url, timeout=15)
r.encoding = "utf-8"
# 从页面中提取 jsonData
# 找到 jsonData= 的位... | --- +++ @@ -1,5 +1,10 @@ #!/usr/bin/env python
# -*- coding:utf-8 -*-
+"""
+Date: 2026/2/27
+Desc: 同花顺-新发基金
+https://fund.10jqka.com.cn/datacenter/xfjj/
+"""
import json
@@ -8,6 +13,14 @@
def fund_new_found_ths(symbol: str = "全部") -> pd.DataFrame:
+ """
+ 同花顺-基金数据-新发基金
+ https://fund.10jqka.com.cn/da... | https://raw.githubusercontent.com/akfamily/akshare/HEAD/akshare/fund/fund_init_ths.py |
Create documentation for each function signature | # -*- coding:utf-8 -*-
# !/usr/bin/env python
import pandas as pd
import requests
def bond_new_composite_index_cbond(
indicator: str = "财富", period: str = "总值"
) -> pd.DataFrame:
indicator_map = {
"全价": "QJZS",
"净价": "JJZS",
"财富": "CFZS",
"平均市值法久期": "PJSZFJQ",
"平均现金流法久... | --- +++ @@ -1,5 +1,9 @@ # -*- coding:utf-8 -*-
# !/usr/bin/env python
+"""
+Date: 2022/9/20 17:46
+Desc: 中国债券信息网-中债指数-中债指数族系-总指数-综合类指数
+"""
import pandas as pd
import requests
@@ -8,6 +12,16 @@ def bond_new_composite_index_cbond(
indicator: str = "财富", period: str = "总值"
) -> pd.DataFrame:
+ """
+ 中国债券... | https://raw.githubusercontent.com/akfamily/akshare/HEAD/akshare/bond/bond_cbond.py |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.