Skill: codecanvas762/akshare-finance-1-0-0 (version 1.0.0)

--- name: akshare-finance description: AKShare财经数据接口库封装，提供股票、期货、期权、基金、外汇、债券、指数、加密货币等金融产品的基本面数据、实时和历史行情数据、衍生数据。 metadata: { "openclaw": { "emoji": "📈", "requires": { "pip": ["akshare>=1.12", "pandas>=1.5"] }, "install": [ { "id": "pip-install", "kind": "pip", "packages": ["akshare>=1.12", "pandas>=1.5"], "label": "安装AKShare依赖" } ] } } keywords: - 股票 - 财经 - 行情 - 加密货币 - 宏观经济 - AKShare --- # AKShare财经数据技能 ## 快速开始 ```bash # 安装依赖 pip install akshare pandas # 测试安装 python -c "import akshare; print(akshare.__version__)" ``` ## 核心功能 ### 1. 股票行情 ```python import akshare as ak # A股实时行情 stock_zh_a_spot_em() # 东方财富A股 # 股票K线数据 stock_zh_kline(symbol="000001", period="daily", adjust="qfq") # 港股行情 stock_hk_spot_em() # 港股实时 # 美股 stock_us_spot() # 美股实时 ``` ### 2. 宏观经济 ```python # GDP数据 macro_china_gdp() # 中国GDP # CPI通胀 macro_china_cpi() # 中国CPI # PMI采购经理指数 macro_china_pmi() # 中国PMI # 货币供应量 macro_china_m2() # M2广义货币 ``` ### 3. 加密货币 ```python # 币种列表 crypto_binance_symbols() # 币安交易对 # 实时价格 crypto_binance_btc_usdt_spot() # BTC/USDT # K线数据 crypto_binance_btc_usdt_kline(period="daily") ``` ### 4. 外汇贵金属 ```python # 外汇汇率 forex_usd_cny() # 美元兑人民币 # 贵金属 metals_shibor() # 上海银行间拆借利率 # 金银价格 metals_gold() # 国际金价 ``` ### 5. 财务数据 ```python # 股票基本面 stock_fundamental(symbol="000001") # 基本面数据 # 估值指标 stock_valuation(symbol="000001") # PE、PB等 # 盈利能力 stock_profit_em(symbol="000001") ``` ## 常用组合 ### 投资组合监控 ```python import akshare as ak import pandas as pd # 监控自选股 tickers = ["000001", "000002", "600519"] for ticker in tickers: df = ak.stock_zh_kline(symbol=ticker, period="daily", adjust="qfq", start_date="20240101") latest = df.iloc[-1] print(f"{ticker}: 收盘价={latest['close']}, 涨跌幅={latest['pct_chg']}%") ``` ### 市场概览 ```python # A股大盘 index_zh_a_spot() # 大盘指数 # 涨跌幅排行 stock_zh_a_spot_em()[['代码', '名称', '涨跌幅']].sort_values('涨跌幅', ascending=False) ``` ## 注意事项 1. **数据来源**: 公开财经网站，仅用于学术研究 2. **商业风险**: 投资有风险，决策需谨慎 3. **更新频率**: 实时数据可能有延迟 4. **数据验证**: 建议多数据源交叉验证 ## 输出格式 默认返回Pandas DataFrame，可直接处理： ```python df = ak.stock_zh_a_spot_em() print(df.head()) # 查看前5行 print(df.columns) # 查看列名 df.to_csv("data.csv") # 保存CSV ``` ## 参考文档 - AKShare文档: https://akshare.akfamily.xyz/ - GitHub: https://github.com/akfamily/akshare

path: _meta.json
content: ownerId: kn75ncb7kangfy6hsnqr4mfyh580cqjg
slug: akshare-finance
version: 1.0.0
publishedAt: 1772204869129

path: references/README.md
content: # AKShare参考文档

## 安装

```bash
pip install akshare pandas
```

## 常用API速查

### 股票
| 函数 | 说明 | 示例 |
|-----|------|-----|
| stock_zh_a_spot_em() | A股实时行情 | df = stock_zh_a_spot_em() |
| stock_zh_kline() | K线数据 | stock_zh_kline(symbol="000001") |
| stock_hk_spot_em() | 港股实时 | stock_hk_spot_em() |

### 加密货币
| 函数 | 说明 | 示例 |
|-----|------|-----|
| crypto_binance_btc_usdt_spot() | BTC实时 | df = crypto_binance_btc_usdt_spot() |
| crypto_binance_btc_usdt_kline() | BTC K线 | crypto_binance_btc_usdt_kline(period="daily") |

### 宏观经济
| 函数 | 说明 | 示例 |
|-----|------|-----|
| macro_china_gdp() | GDP | macro_china_gdp() |
| macro_china_cpi() | CPI通胀 | macro_china_cpi() |
| macro_china_pmi() | PMI指数 | macro_china_pmi() |

### 外汇贵金属
| 函数 | 说明 | 示例 |
|-----|------|-----|
| forex_usd_cny() | 美元兑人民币 | forex_usd_cny() |
| metals_gold() | 黄金价格 | metals_gold() |

## 数据格式

所有函数返回Pandas DataFrame：

```python
df = ak.stock_zh_a_spot_em()
print(df.head())  # 前5行
print(df.columns) # 列名
print(df.dtypes)   # 数据类型
```

## 注意事项

1. 数据来源：公开财经网站
2. 更新延迟：实时数据可能有延迟
3. 使用限制：请参考官方文档


path: scripts/crypto_price.py
content: #!/usr/bin/env python3
"""获取加密货币价格"""
import sys
import json
import akshare as ak

def get_crypto_price(symbol="BTC/USDT"):
    """获取加密货币价格"""
    try:
        if symbol in ["BTC/USDT", "BTC", "btc"]:
            df = ak.crypto_binance_btc_usdt_spot()
        elif symbol in ["ETH/USDT", "ETH", "eth"]:
            df = ak.crypto_binance_eth_usdt_spot()
        else:
            # 尝试通用接口
            symbol_map = {
                "BTC/USDT": ak.crypto_binance_btc_usdt_spot,
                "ETH/USDT": ak.crypto_binance_eth_usdt_spot,
            }
            func = symbol_map.get(symbol, ak.crypto_binance_btc_usdt_spot)
            df = func()
        
        if df is not None and len(df) > 0:
            latest = df.iloc[-1]
            return {
                "symbol": symbol,
                "price": float(latest.get('close', latest.get('price', 0))),
                "volume": str(latest.get('volume', 'N/A'))
            }
        return {"error": "No data"}
    except Exception as e:
        return {"error": str(e)}

def get_crypto_kline(symbol="BTC/USDT", period="daily"):
    """获取加密货币K线"""
    try:
        if symbol in ["BTC/USDT", "BTC", "btc"]:
            df = ak.crypto_binance_btc_usdt_kline(period=period)
        else:
            return {"error": f"Unsupported symbol: {symbol}"}
        
        latest = df.iloc[-1]
        return {
            "symbol": symbol,
            "period": period,
            "open": float(latest['open']),
            "high": float(latest['high']),
            "low": float(latest['low']),
            "close": float(latest['close']),
            "volume": int(latest['volume'])
        }
    except Exception as e:
        return {"error": str(e)}

if __name__ == "__main__":
    if len(sys.argv) > 1:
        cmd = sys.argv[1]
        symbol = sys.argv[2] if len(sys.argv) > 2 else "BTC/USDT"
        
        if cmd == "price":
            result = get_crypto_price(symbol)
        elif cmd == "kline":
            period = sys.argv[3] if len(sys.argv) > 3 else "daily"
            result = get_crypto_kline(symbol, period)
        else:
            result = {"error": f"Unknown command: {cmd}"}
    else:
        result = {"usage": "python crypto.py price <symbol> | kline <symbol> <period>"}
    
    print(json.dumps(result, ensure_ascii=False, indent=2))


path: scripts/macro_data.py
content: #!/usr/bin/env python3
"""获取宏观经济数据"""
import sys
import json
import akshare as ak

def get_macro_data(indicator="gdp"):
    """获取宏观经济指标"""
    try:
        indicators = {
            "gdp": ("GDP", ak.macro_china_gdp),
            "cpi": ("CPI通胀", ak.macro_china_cpi),
            "pmi": ("PMI采购经理指数", ak.macro_china_pmi),
            "m2": ("M2货币供应", ak.macro_china_m2),
        }
        
        if indicator not in indicators:
            return {"error": f"Unknown indicator: {indicator}"}
        
        name, func = indicators[indicator]
        df = func()
        
        # 获取最新数据
        latest = df.iloc[-1]
        return {
            "indicator": indicator,
            "name": name,
            "date": str(latest.iloc[0]),
            "value": float(latest.iloc[1]) if len(latest) > 1 else None
        }
    except Exception as e:
        return {"error": str(e)}

def get_macro_summary():
    """获取宏观经济概览"""
    try:
        result = {}
        for ind in ["gdp", "cpi", "pmi", "m2"]:
            data = get_macro_data(ind)
            if "error" not in data:
                result[ind] = {
                    "value": data.get("value"),
                    "date": data.get("date")
                }
        return result
    except Exception as e:
        return {"error": str(e)}

if __name__ == "__main__":
    if len(sys.argv) > 1:
        cmd = sys.argv[1]
        if cmd == "data":
            indicator = sys.argv[2] if len(sys.argv) > 2 else "gdp"
            result = get_macro_data(indicator)
        elif cmd == "summary":
            result = get_macro_summary()
        else:
            result = {"error": f"Unknown command: {cmd}"}
    else:
        result = {"usage": "python macro.py data <indicator> | summary"}
    
    print(json.dumps(result, ensure_ascii=False, indent=2))


path: scripts/stock_price.py
content: #!/usr/bin/env python3
"""获取股票实时价格和K线数据"""
import sys
import json
import akshare as ak

def get_stock_price(symbol, period="daily", start_date=None):
    """获取股票价格"""
    try:
        df = ak.stock_zh_kline(
            symbol=symbol,
            period=period,
            adjust="qfq",
            start_date=start_date
        )
        latest = df.iloc[-1]
        return {
            "symbol": symbol,
            "date": str(latest['date']),
            "open": float(latest['open']),
            "high": float(latest['high']),
            "low": float(latest['low']),
            "close": float(latest['close']),
            "volume": int(latest['volume']),
            "pct_chg": float(latest['pct_chg'])
        }
    except Exception as e:
        return {"error": str(e)}

def get_market_overview():
    """获取大盘概览"""
    try:
        df = ak.stock_zh_a_spot_em()
        # 涨跌幅排行
        top_gainers = df.nlargest(5, '涨跌幅')[['代码', '名称', '涨跌幅']].to_dict('records')
        top_losers = df.nsmallest(5, '涨跌幅')[['代码', '名称', '涨跌幅']].to_dict('records')
        return {
            "total_stocks": len(df),
            "top_gainers": top_gainers,
            "top_losers": top_losers
        }
    except Exception as e:
        return {"error": str(e)}

if __name__ == "__main__":
    if len(sys.argv) > 1:
        cmd = sys.argv[1]
        if cmd == "price":
            symbol = sys.argv[2] if len(sys.argv) > 2 else "000001"
            result = get_stock_price(symbol)
        elif cmd == "overview":
            result = get_market_overview()
        else:
            result = {"error": f"Unknown command: {cmd}"}
    else:
        result = {"usage": "python stock.py price <symbol> | overview"}
    
    print(json.dumps(result, ensure_ascii=False, indent=2))


Security scan verdicts — ClawScan: clean | static analysis: clean | VirusTotal: clean | SkillSpector: clean (LOW)