美股恐惧贪婪指数监控

1. 创建索引

PUT fear_greed_stock
{
  "mappings": {
    "dynamic": "strict",
    "properties": {
      "c_date": {
        "type": "date",
        "format": "yyyy-MM-dd"
      },
      "val": {
        "type": "float"
      },
      "tag": {
        "type": "keyword"
      },
      "type": {
        "type": "keyword"
      },
      "previous_close": {
        "type": "float"
      },
      "previous_1_week": {
        "type": "float"
      },
      "previous_1_month": {
        "type": "float"
      },
      "previous_1_year": {
        "type": "float"
      },
      "metric_value": {
        "type": "float"
      }
    }
  }
}

2. Python核心代码

import requests
import json
from datetime import datetime
from elasticsearch import helpers
import time
import logging
from requests.adapters import HTTPAdapter
from urllib3.util.retry import Retry

from utils.datautils import get_unique_id
from utils.esutils import es_client

# 配置日志
logging.basicConfig(level=logging.INFO, format='%(asctime)s - %(levelname)s - %(message)s')
logger = logging.getLogger(__name__)

# 索引名称
INDEX_NAME = "fear_greed_stock"


def parse_timestamp(timestamp):
    """解析时间戳,支持字符串和毫秒时间戳格式"""
    try:
        if isinstance(timestamp, str):
            return datetime.strptime(timestamp, "%Y-%m-%dT%H:%M:%S+00:00").strftime("%Y-%m-%d")
        else:
            return datetime.fromtimestamp(int(timestamp) / 1000).strftime("%Y-%m-%d")
    except Exception as e:
        logger.error(f"时间戳解析失败: {timestamp}, 错误: {e}")
        return None


def process_fear_greed_data(data, es_client, index_name=INDEX_NAME):
    """处理Fear and Greed Index数据并存储到Elasticsearch"""
    actions = []
    processed_count = 0

    try:
        # 提取总体指数
        fear_greed = data.get('fear_and_greed', {})
        if not fear_greed:
            logger.warning("未找到fear_and_greed数据")
            return processed_count

        # 解析总体指数
        score = fear_greed.get('score')
        rating = fear_greed.get('rating')
        timestamp = fear_greed.get('timestamp')
        previous_close = fear_greed.get('previous_close')
        previous_1_week = fear_greed.get('previous_1_week')
        previous_1_month = fear_greed.get('previous_1_month')
        previous_1_year = fear_greed.get('previous_1_year')

        date = parse_timestamp(timestamp)
        if not date:
            logger.warning("无效的时间戳,跳过记录")
            return processed_count

        # 构造总体指数记录
        info = {
            "c_date": date,
            "val": score,
            "tag": rating,
            "previous_close": previous_close,
            "previous_1_week": previous_1_week,
            "previous_1_month": previous_1_month,
            "previous_1_year": previous_1_year,
            "type": "overall"
        }

        action = {
            "_op_type": "index",
            "_index": index_name,
            "_id": get_unique_id(f"{date}_overall"),
            "_source": info
        }
        actions.append(action)
        processed_count += 1

        # 提取子指标
        sub_metrics = [
            "market_momentum_sp500", "market_momentum_sp125", "stock_price_strength",
            "stock_price_breadth", "put_call_options", "market_volatility_vix",
            "market_volatility_vix_50", "junk_bond_demand", "safe_haven_demand"
        ]

        for metric in sub_metrics:
            metric_data = data.get(metric, {})
            metric_timestamp = metric_data.get('timestamp')
            metric_score = metric_data.get('score')
            metric_rating = metric_data.get('rating')
            metric_value = metric_data.get('data', [{}])[0].get('y') if metric_data.get('data') else None

            metric_date = parse_timestamp(metric_timestamp)
            if not metric_date:
                logger.warning(f"{metric} 时间戳无效,跳过")
                continue

            metric_info = {
                "c_date": metric_date,
                "val": metric_score,
                "tag": metric_rating,
                "metric_value": metric_value,
                "type": metric
            }

            action = {
                "_op_type": "index",
                "_index": index_name,
                "_id": get_unique_id(f"{metric_date}_{metric}"),
                "_source": metric_info
            }
            actions.append(action)
            processed_count += 1

            # 批量写入
            if len(actions) >= 5000:
                try:
                    helpers.bulk(es_client, actions)
                    logger.info(f"已处理 {processed_count} 条数据")
                    actions.clear()
                    time.sleep(0.5)  # 每次批量操作后休眠0.5秒
                except Exception as e:
                    logger.error(f"批量写入失败: {e}")
                    time.sleep(2)  # 失败后稍长休眠

        # 处理剩余数据
        if actions:
            try:
                helpers.bulk(es_client, actions)
                logger.info(f"已处理 {processed_count} 条数据")
            except Exception as e:
                logger.error(f"剩余数据写入失败: {e}")

    except Exception as e:
        logger.error(f"数据处理失败: {e}")

    return processed_count


def do():
    # 主流程
    try:
        date = datetime.now().strftime("%Y-%m-%d")
        url = f"https://production.dataviz.cnn.io/index/fearandgreed/graphdata/{date}"

        # 设置请求头,模拟浏览器
        headers = {
            "Accept": "application/json",
            "User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/91.0.4472.124 Safari/537.36"
        }

        # 设置代理(可选)
        proxies = {
            "http": "http://127.0.0.1:7890",
            "https": "http://127.0.0.1:7890"
        }

        # 配置请求重试机制
        session = requests.Session()
        retries = Retry(total=3, backoff_factor=1, status_forcelist=[418, 429, 500, 502, 503, 504])
        session.mount("https://", HTTPAdapter(max_retries=retries))

        # 发送请求
        response = session.get(url, headers=headers, proxies=proxies, timeout=10)
        response.raise_for_status()  # 检查请求是否成功

        # 解析数据
        data = response.json()
        processed_count = process_fear_greed_data(data, es_client, INDEX_NAME)
        logger.info(f"总共处理 {processed_count} 条数据")

    except requests.exceptions.HTTPError as e:
        if response.status_code == 418:
            logger.error("遇到418错误:服务器检测到爬虫行为,建议更换代理或增加延迟后重试")
        else:
            logger.error(f"请求失败: {e}")
    except requests.exceptions.RequestException as e:
        logger.error(f"请求过程中发生错误: {e}")
    finally:
        session.close()

【最优潮流】直流最优潮流(OPF)课设(Matlab代码实现)内容概要:本文档主要围绕“直流最优潮流(OPF)课设”的Matlab代码实现展开,属于电力系统优化领域的教学与科实践内容。文档介绍了通过Matlab进行电力系统最优潮流计算的基本原理与编程实现方法,重点聚焦于直流最优潮流模型的构建与求解过程,适用于课程设计或科入门实践。文中提及使用YALMIP等优化工具包进行建模,并提供了相关资源下载链接,便于读者复现与学习。此外,文档还列举了大量与电力系统、智能优化算法、机器学习、路径规划等相关的Matlab仿真案例,体现出其服务于科仿真辅导的综合性平台性质。; 适合人群:电气工程、自动化、电力系统及相关专业的本科生、究生,以及从事电力系统优化、智能算法应用究的科人员。; 使用场景及目标:①掌握直流最优潮流的基本原理与Matlab实现方法;②完成课程设计或科项目中的电力系统优化任务;③借助提供的丰富案例资源,拓展在智能优化、状态估计、微电网调度等方向的究思路与技术手段。; 阅读建议:建议读者结合文档中提供的网盘资源,下载完整代码与工具包,边学习理论边动手实践。重点关注YALMIP工具的使用方法,并通过复现文中提到的多个案例,加深对电力系统优化问题建模与求解的理解。
评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

算法小生Đ

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值