首页 文章 精选 留言 我的

精选列表

搜索[CANN开源],共10000篇文章
优秀的个人博客,低调大师

优秀开源项目之三:高性能、高并发、高扩展性和可读性的网络服务器架构State Threads

译文在后面。 State Threads for Internet Applications Introduction State Threads is an application library which provides a foundation for writing fast and highly scalable Internet Applications on UNIX-like platforms. It combines the simplicity of the multithreaded programming paradigm, in which one thread supports each simultaneous connection, with the performance and scalability of an event-driven state machine architecture. 1. Definitions 1.1 Internet Applications An Internet Application (IA) is either a server or client network application that accepts connections from clients and may or may not connect to servers. In an IA the arrival or departure of network data often controls processing (that is, IA is a data-driven application). For each connection, an IA does some finite amount of work involving data exchange with its peer, where its peer may be either a client or a server. The typical transaction steps of an IA are to accept a connection, read a request, do some finite and predictable amount of work to process the request, then write a response to the peer that sent the request. One example of an IA is a Web server; the most general example of an IA is a proxy server, because it both accepts connections from clients and connects to other servers. We assume that the performance of an IA is constrained by available CPU cycles rather than network bandwidth or disk I/O (that is, CPU is a bottleneck resource). 1.2 Performance and Scalability The performance of an IA is usually evaluated as its throughput measured in transactions per second or bytes per second (one can be converted to the other, given the average transaction size). There are several benchmarks that can be used to measure throughput of Web serving applications for specific workloads (such as SPECweb96, WebStone, WebBench). Although there is no common definition for scalability, in general it expresses the ability of an application to sustain its performance when some external condition changes. For IAs this external condition is either the number of clients (also known as "users," "simultaneous connections," or "load generators") or the underlying hardware system size (number of CPUs, memory size, and so on). Thus there are two types of scalability: load scalability and system scalability, respectively. The figure below shows how the throughput of an idealized IA changes with the increasing number of clients (solid blue line). Initially the throughput grows linearly (the slope represents the maximal throughput that one client can provide). Within this initial range, the IA is underutilized and CPUs are partially idle. Further increase in the number of clients leads to a system saturation, and the throughput gradually stops growing as all CPUs become fully utilized. After that point, the throughput stays flat because there are no more CPU cycles available. In the real world, however, each simultaneous connection consumes some computational and memory resources, even when idle, and this overhead grows with the number of clients. Therefore, the throughput of the real world IA starts dropping after some point (dashed blue line in the figure below). The rate at which the throughput drops depends, among other things, on application design. We say that an application has a good load scalability if it can sustain its throughput over a wide range of loads. Interestingly, the SPECweb99 benchmark somewhat reflects the Web server's load scalability because it measures the number of clients (load generators) given a mandatory minimal throughput per client (that is, it measures the server's capacity). This is unlike SPECweb96 and other benchmarks that use the throughput as their main metric (see the figure below). System scalability is the ability of an application to sustain its performance per hardware unit (such as a CPU) with the increasing number of these units. In other words, good system scalability means that doubling the number of processors will roughly double the application's throughput (dashed green line). We assume here that the underlying operating system also scales well. Good system scalability allows you to initially run an application on the smallest system possible, while retaining the ability to move that application to a larger system if necessary, without excessive effort or expense. That is, an application need not be rewritten or even undergo a major porting effort when changing system size. Although scalability and performance are more important in the case of server IAs, they should also be considered for some client applications (such as benchmark load generators). 1.3 Concurrency Concurrency reflects the parallelism in a system. The two unrelated types are virtual concurrency and real concurrency. Virtual (or apparent) concurrency is the number of simultaneous connections that a system supports. Real concurrency is the number of hardware devices, including CPUs, network cards, and disks, that actually allow a system to perform tasks in parallel. An IA must provide virtual concurrency in order to serve many users simultaneously. To achieve maximum performance and scalability in doing so, the number of programming entities than an IA creates to be scheduled by the OS kernel should be kept close to (within an order of magnitude of) the real concurrency found on the system. These programming entities scheduled by the kernel are known as kernel execution vehicles. Examples of kernel execution vehicles include Solaris lightweight processes and IRIX kernel threads. In other words, the number of kernel execution vehicles should be dictated by the system size and not by the number of simultaneous connections. 2. Existing Architectures There are a few different architectures that are commonly used by IAs. These include the Multi-Process, Multi-Threaded, and Event-Driven State Machine architectures. 2.1 Multi-Process Architecture In the Multi-Process (MP) architecture, an individual process is dedicated to each simultaneous connection. A process performs all of a transaction's initialization steps and services a connection completely before moving on to service a new connection. User sessions in IAs are relatively independent; therefore, no synchronization between processes handling different connections is necessary. Because each process has its own private address space, this architecture is very robust. If a process serving one of the connections crashes, the other sessions will not be affected. However, to serve many concurrent connections, an equal number of processes must be employed. Because processes are kernel entities (and are in fact the heaviest ones), the number of kernel entities will be at least as large as the number of concurrent sessions. On most systems, good performance will not be achieved when more than a few hundred processes are created because of the high context-switching overhead. In other words, MP applications have poor load scalability. On the other hand, MP applications have very good system scalability, because no resources are shared among different processes and there is no synchronization overhead. The Apache Web Server 1.x ([Reference 1]) uses the MP architecture on UNIX systems. 2.2 Multi-Threaded Architecture In the Multi-Threaded (MT) architecture, multiple independent threads of control are employed within a single shared address space. Like a process in the MP architecture, each thread performs all of a transaction's initialization steps and services a connection completely before moving on to service a new connection. Many modern UNIX operating systems implement a many-to-few model when mapping user-level threads to kernel entities. In this model, an arbitrarily large number of user-level threads is multiplexed onto a lesser number of kernel execution vehicles. Kernel execution vehicles are also known as virtual processors. Whenever a user-level thread makes a blocking system call, the kernel execution vehicle it is using will become blocked in the kernel. If there are no other non-blocked kernel execution vehicles and there are other runnable user-level threads, a new kernel execution vehicle will be created automatically. This prevents the application from blocking when it can continue to make useful forward progress. Because IAs are by nature network I/O driven, all concurrent sessions block on network I/O at various points. As a result, the number of virtual processors created in the kernel grows close to the number of user-level threads (or simultaneous connections). When this occurs, the many-to-few model effectively degenerates to a one-to-one model. Again, like in the MP architecture, the number of kernel execution vehicles is dictated by the number of simultaneous connections rather than by number of CPUs. This reduces an application's load scalability. However, because kernel threads (lightweight processes) use fewer resources and are more light-weight than traditional UNIX processes, an MT application should scale better with load than an MP application. Unexpectedly, the small number of virtual processors sharing the same address space in the MT architecture destroys an application's system scalability because of contention among the threads on various locks. Even if an application itself is carefully optimized to avoid lock contention around its own global data (a non-trivial task), there are still standard library functions and system calls that use common resources hidden from the application. For example, on many platforms thread safety of memory allocation routines (malloc(3), free(3), and so on) is achieved by using a single global lock. Another example is a per-process file descriptor table. This common resource table is shared by all kernel execution vehicles within the same process and must be protected when one modifies it via certain system calls (such as open(2), close(2), and so on). In addition to that, maintaining the caches coherent among CPUs on multiprocessor systems hurts performance when different threads running on different CPUs modify data items on the same cache line. In order to improve load scalability, some applications employ a different type of MT architecture: they create one or more thread(s) per task rather than one thread per connection. For example, one small group of threads may be responsible for accepting client connections, another for request processing, and yet another for serving responses. The main advantage of this architecture is that it eliminates the tight coupling between the number of threads and number of simultaneous connections. However, in this architecture, different task-specific thread groups must share common work queues that must be protected by mutual exclusion locks (a typical producer-consumer problem). This adds synchronization overhead that causes an application to perform badly on multiprocessor systems. In other words, in this architecture, the application's system scalability is sacrificed for the sake of load scalability. Of course, the usual nightmares of threaded programming, including data corruption, deadlocks, and race conditions, also make MT architecture (in any form) non-simplistic to use. 2.3 Event-Driven State Machine Architecture In the Event-Driven State Machine (EDSM) architecture, a single process is employed to concurrently process multiple connections. The basics of this architecture are described in Comer and Stevens [Reference 2]. The EDSM architecture performs one basic data-driven step associated with a particular connection at a time, thus multiplexing many concurrent connections. The process operates as a state machine that receives an event and then reacts to it. In the idle state the EDSM calls select(2) or poll(2) to wait for network I/O events. When a particular file descriptor is ready for I/O, the EDSM completes the corresponding basic step (usually by invoking a handler function) and starts the next one. This architecture uses non-blocking system calls to perform asynchronous network I/O operations. For more details on non-blocking I/O see Stevens [Reference 3]. To take advantage of hardware parallelism (real concurrency), multiple identical processes may be created. This is called Symmetric Multi-Process EDSM and is used, for example, in the Zeus Web Server ([Reference 4]). To more efficiently multiplex disk I/O, special "helper" processes may be created. This is called Asymmetric Multi-Process EDSM and was proposed for Web servers by Druschel and others [Reference 5]. EDSM is probably the most scalable architecture for IAs. Because the number of simultaneous connections (virtual concurrency) is completely decoupled from the number of kernel execution vehicles (processes), this architecture has very good load scalability. It requires only minimal user-level resources to create and maintain additional connection. Like MP applications, Multi-Process EDSM has very good system scalability because no resources are shared among different processes and there is no synchronization overhead. Unfortunately, the EDSM architecture is monolithic rather than based on the concept of threads, so new applications generally need to be implemented from the ground up. In effect, the EDSM architecture simulates threads and their stacks the hard way. 3. State Threads Library The State Threads library combines the advantages of all of the above architectures. The interface preserves the programming simplicity of thread abstraction, allowing each simultaneous connection to be treated as a separate thread of execution within a single process. The underlying implementation is close to the EDSM architecture as the state of each particular concurrent session is saved in a separate memory segment. 3.1 State Changes and Scheduling The state of each concurrent session includes its stack environment (stack pointer, program counter, CPU registers) and its stack. Conceptually, a thread context switch can be viewed as a process changing its state. There are no kernel entities involved other than processes. Unlike other general-purpose threading libraries, the State Threads library is fully deterministic. The thread context switch (process state change) can only happen in a well-known set of functions (at I/O points or at explicit synchronization points). As a result, process-specific global data does not have to be protected by mutual exclusion locks in most cases. The entire application is free to use all the static variables and non-reentrant library functions it wants, greatly simplifying programming and debugging while increasing performance. This is somewhat similar to a co-routine model (co-operatively multitasked threads), except that no explicit yield is needed -- sooner or later, a thread performs a blocking I/O operation and thus surrenders control. All threads of execution (simultaneous connections) have the same priority, so scheduling is non-preemptive, like in the EDSM architecture. Because IAs are data-driven (processing is limited by the size of network buffers and data arrival rates), scheduling is non-time-slicing. Only two types of external events are handled by the library's scheduler, because only these events can be detected by select(2) or poll(2): I/O events (a file descriptor is ready for I/O) and time events (some timeout has expired). However, other types of events (such as a signal sent to a process) can also be handled by converting them to I/O events. For example, a signal handling function can perform a write to a pipe (write(2) is reentrant/asynchronous-safe), thus converting a signal event to an I/O event. To take advantage of hardware parallelism, as in the EDSM architecture, multiple processes can be created in either a symmetric or asymmetric manner. Process management is not in the library's scope but instead is left up to the application. There are several general-purpose threading libraries that implement a many-to-one model (many user-level threads to one kernel execution vehicle), using the same basic techniques as the State Threads library (non-blocking I/O, event-driven scheduler, and so on). For an example, see GNU Portable Threads ([Reference 6]). Because they are general-purpose, these libraries have different objectives than the State Threads library. The State Threads library is not a general-purpose threading library, but rather an application library that targets only certain types of applications (IAs) in order to achieve the highest possible performance and scalability for those applications. 3.2 Scalability State threads are very lightweight user-level entities, and therefore creating and maintaining user connections requires minimal resources. An application using the State Threads library scales very well with the increasing number of connections. On multiprocessor systems an application should create multiple processes to take advantage of hardware parallelism. Using multiple separate processes is the only way to achieve the highest possible system scalability. This is because duplicating per-process resources is the only way to avoid significant synchronization overhead on multiprocessor systems. Creating separate UNIX processes naturally offers resource duplication. Again, as in the EDSM architecture, there is no connection between the number of simultaneous connections (which may be very large and changes within a wide range) and the number of kernel entities (which is usually small and constant). In other words, the State Threads library makes it possible to multiplex a large number of simultaneous connections onto a much smaller number of separate processes, thus allowing an application to scale well with both the load and system size. 3.3 Performance Performance is one of the library's main objectives. The State Threads library is implemented to minimize the number of system calls and to make thread creation and context switching as fast as possible. For example, per-thread signal mask does not exist (unlike POSIX threads), so there is no need to save and restore a process's signal mask on every thread context switch. This eliminates two system calls per context switch. Signal events can be handled much more efficiently by converting them to I/O events (see above). 3.4 Portability The library uses the same general, underlying concepts as the EDSM architecture, including non-blocking I/O, file descriptors, and I/O multiplexing. These concepts are available in some form on most UNIX platforms, making the library very portable across many flavors of UNIX. There are only a few platform-dependent sections in the source. 3.5 State Threads and NSPR The State Threads library is a derivative of the Netscape Portable Runtime library (NSPR) [Reference 7]. The primary goal of NSPR is to provide a platform-independent layer for system facilities, where system facilities include threads, thread synchronization, and I/O. Performance and scalability are not the main concern of NSPR. The State Threads library addresses performance and scalability while remaining much smaller than NSPR. It is contained in 8 source files as opposed to more than 400, but provides all the functionality that is needed to write efficient IAs on UNIX-like platforms. NSPR State Threads Lines of code ~150,000 ~3000 Dynamic library size(debug version) IRIX ~700 KB ~60 KB Linux ~900 KB ~70 KB Conclusion State Threads is an application library which provides a foundation for writing Internet Applications. To summarize, it has the following advantages: It allows the design of fast and highly scalable applications. An application will scale well with both load and number of CPUs. It greatly simplifies application programming and debugging because, as a rule, no mutual exclusion locking is necessary and the entire application is free to use static variables and non-reentrant library functions. The library's main limitation: All I/O operations on sockets must use the State Thread library's I/O functions because only those functions perform thread scheduling and prevent the application's processes from blocking. References Apache Software Foundation, http://www.apache.org. Douglas E. Comer, David L. Stevens, Internetworking With TCP/IP, Vol. III: Client-Server Programming And Applications, Second Edition, Ch. 8, 12. W. Richard Stevens, UNIX Network Programming, Second Edition, Vol. 1, Ch. 15. Zeus Technology Limited, http://www.zeus.co.uk. Peter Druschel, Vivek S. Pai, Willy Zwaenepoel, Flash: An Efficient and Portable Web Server. In Proceedings of the USENIX 1999 Annual Technical Conference, Monterey, CA, June 1999. GNU Portable Threads, http://www.gnu.org/software/pth/. Netscape Portable Runtime, http://www.mozilla.org/docs/refList/refNSPR/. Other resources covering various architectural issues in IAs Dan Kegel, The C10K problem, http://www.kegel.com/c10k.html. James C. Hu, Douglas C. Schmidt, Irfan Pyarali, JAWS: Understanding High Performance Web Systems, http://www.cs.wustl.edu/~jxh/research/research.html. Portions created by SGI are Copyright ? 2000 Silicon Graphics, Inc. All rights reserved. 网络架构库:StateThreads 介绍 StateThreads是一个C的网络程序开发库,提供了编写高性能、高并发、高可读性的网络程序的开发库,支持UNIX-like平台。它结合了多线程编写并行成的简单性,一个进程支持多个并发,支持基于事件的状态机架构的高性能和高并发能力。 (译注:提供了EDSM的高性能、高并发、稳定性,“多线程”形式的简单编程方式,用setjmp和longjmp实现的一个线程模拟多线程,即用户空间的多线程,类似于现在的协程和纤程) 1. 定义 1.1 网络程序(Internet Applications) 网络程序(Internet Application)(IA)是一个网络的客户端或者服务器程序,它接受客户端连接,同时可能需要连接到其他服务器。在IA中,数据的到达和发送完毕经常操纵控制流,就是说IA是数据驱动的程序。对每个连接,IA做一些有限的工作,包括和peer的数据交换,peer可能是客户端或服务器。IA典型的事务步骤是:接受连接,读取请求,做一些有限的工作处理请求,将相应写入peer。一个iA的例子是Web服务器,更典型的例子是代理服务器,因为它接受客户端连接,同时也连接到其他服务器。 我们假定IA的性能由CPU决定,而不是由网络带宽或磁盘IO决定,即CPU是系统瓶颈。 1.2 性能和可扩展性 IA的性能一般可以用吞吐量来评估,即每秒的事务数,或每秒的字节数(两者可以相互转换,给定事务的平均大小就可以)。有很多种工具可以用来测量Web程序的特定负载,譬如SPECweb96, WebStone, WebBench。尽管对扩展性没有通用的定义,一般而言,可扩展性指系统在外部条件改变时维持它的性能的能力。对于IAs而言,外部条件指连接数(并发),或者底层硬件(CPU数目,内存等)。因此,有两种系统的扩展性:负载能力和系统能力。 (译注:scalability可扩展性,指条件改变了系统是否还能高效运行,譬如负载能力指并发(条件)增多时系统是否能承担这么多负载,系统能力指CPU等增多时是否能高效的利用多CPU达到更强的能力) 下图描述了客户端数目增多时系统的吞吐量的变化,蓝色线条表示理想状况。最开始时吞吐量程线性增长,这个区间系统和CPU较为空闲。继续增长的连接数导致系统开始饱和,吞吐量开始触及天花板(CPU跑满能跑到的吞吐量),在天花板之后吞吐量变为平行线不再增长,因为CPU能力到达了极限。在实际应用中,每个连接消耗了计算资源和内存资源,就算是空闲状态,这些负担都随连接数而增长,因此,实际的IA吞吐量在某个点之后开始往下落(蓝色虚线表示)。开始掉的点,不是其他的原因,而是由系统架构决定的。 我们将系统有好的负载能力,是指系统在高负载时仍能很好的工作。SPECweb99基准测试能较好的反应系统的负载能力,因为它测量的是连接在最小流量需求时系统能支持的最大连接数(译注:如图中Capacity所指出的点即灰色斜线和蓝色线交叉的点)。而不像SPECweb96或其他的基准测试,是以系统的吞吐量来衡量的(译注:图中Max throughout,即蓝色线的天花板)。 系统能力指程序在增加硬件单元例如加CPU时系统的性能,换句话说,好的系统能力意味着CPU加倍时吞吐量会加倍(图中绿色虚线)。我们假设底层操作系统也具有很好的系统能力。好的系统能力指假设程序在一个小的机器上运行很好,当有需要换到大型服务器上运行时也能获得很高的性能。就是说,改变服务器环境时,系统不需要重写或者费很大的劲。 (译注: 纵坐标是吞吐量,横坐标是连接数。 灰色的线(min acceptable throughout pre client)表示是客户端的需要的吞吐量,至少这个量才流畅。 蓝色表示理想状态的server,系统能力一直没有问题,能达到最大吞吐量,CPU跑满能跑到的吞吐量。 蓝色虚线表示实际的server,每个连接都会消耗CPU和内存,所以在某个临界点之后吞吐量开始往下掉,这个临界点就是系统结构决定的。好的系统架构能将临界点往后推,稳定的支持更高的并发;差的架构在并发增加时可能系统就僵死了。 灰色虚线表示两个测量基准,一个是SPECweb96测量的是系统最大吞吐量,一个是SPECweb99测量每个连接在最小要求流量下系统能达到的最大连接数,后者更能反应系统的负载能力,因为它测量不同的连接的状况下系统的负载能力。 负载能力指的是系统支撑的最大负载,图中的横坐标上的值,对应的蓝色线和灰色线交叉的点,或者是蓝色线往下掉的点。 系统能力指的是增加服务器能力,如加CPU时,系统的吞吐量是否也会增加,图中绿色线表示。好的系统能力会在CPU增加时性能更高,差的系统能力增加CPU也不会更强。 ) 尽管性能和扩展性对服务器来讲更重要,客户端也必须考虑这个问题,例如性能测试工具。 1.3 并发 并发反应了系统的并行能力,分为虚拟并发和物理并发: 虚拟并发是指操作系统同时支持很多并发的连接。 物理并发是指硬件设备,例如CPU,网卡,硬盘等,允许系统并行执行任务。 IA必须提供虚拟并发来支持用户的并发访问,为了达到最大的性能,IA创建的由内核调度的编程实体数目基本上和物理并发的数量要保持一致(在一个数量级上)(译注:有多少个CPU就用多少个进程)。内核调度的编程实体即内核执行对象(kernel execution vehicles),包括Solaris轻量级进程,IRIX内核线程。换句话说,内核执行对象应该由物理条件决定,而不是由并发决定(译注:即进程数目应该由CPU决定,而不是由连接数决定)。 2. 现有的架构 IAs(Internet Applications)有一些常见的被广泛使用的架构,包括基于进程的架构(Multi-Process),基于线程的架构(Multi-Threaded), 和事件驱动的状态机架构(Event-Driven State Machine)。 2.1 基于进程的架构:MP (译注:Multi-Process字面意思是多进程,但事件驱动的状态机EDSM也常用多进程,所以为了区分,使用“基于进程的架构”,意为每个连接一个进程的架构) 在基于进程的架构(MP)中,一个独立的进程用来服务一个连接。一个进程从初始化到服务这个连接,直到服务完毕才服务其他连接。 用户Session是完全独立的,因此,在这些处理不同的连接的进程之间,完全没有同步的必要。因为每个进程有自己独立的地址空间,这种架构非常强壮。若服务某个连接的进程崩溃,其他的连接不会受到任何影响。然而,为了服务很多并发的连接,必须创建相等数量的进程。因为进程是内核对象,实际上是最“重”的一种对象,所以至少需要再内核创建和连接数相等的进程。在大多数的系统中,当创建了上千个进程时,系统性能将大幅降低,因为超负荷的上下文切换。也就是说,MP架构负载能力很弱,无法支持高负载(高并发)。 另一方面,MP架构有很高的系统能力(利用系统资源,稳定性,复杂度),因为不同的进程之间没有共享资源,因而没有同步的负担。 ApacheWeb服务器就是采用的MP架构。 2.2 基于线程的架构:MT (译注:Multi-Threaded字面意思是多线程,但侧重一个线程服务一个连接的方式,用“基于线程”会更准确) 在基于线程(MT)架构中,使用多个独立的线程,它们共享地址空间。和MP结构的进程一样,每个线程独立服务每个连接直到服务完毕,这个线程才用来服务其他连接。 很多现代的UNIX操作系统实现了一个多对一的模型,用来映射用户空间的线程到系统内核对象。在这个模型中,任意多数量的用户空间线程复用少量的内核执行对象,内核执行对象即为虚拟处理器。当用户空间线程调用了一个阻塞的系统调用时,内核执行对象也会在内核阻塞。如果没有其他没有阻塞的内核执行对象,或者有其他需要运行的用户空间线程,一个新的内核执行对象会被自动创建,这样就防止一个线程阻塞时其他线程都被阻塞。 由于IAs由网络IO驱动,所有的并发连接都会阻塞在不同的地方。因此,内核执行对象的数目会接近用户空间线程的数目,也就是连接的数目。此时,多对一的模型就退化为一对一的模型,和MP架构一样,内核执行对象的数目由并发决定而不是由CPU数目决定。和MP一样,这降低了系统的负载能力。尽管这样,由于内核线程是轻量级进程,使用了较少的资源,比内核进程要轻,MT架构比MP架构在负载能力方面稍强一些。 在MT架构中,内核线程共享了地址空间,各种同步锁破坏了系统能力。尽管程序可以很小心的避免锁来提高程序性能(是个复杂的任务),标准库函数和系统调用也会对通用资源上锁,例如,平台提供的线程安全函数,例如内存分配函数(malloc,free等)都是用了一个全局锁。另外一个例子是进程的文件描述表,这个表被内核线程共享,在系统调用(open,close等)时需要保护。除此之外,多核系统中需要在CPU之间维护缓存的一致,当不同的线程运行在不同的CPU上并修改同样的数据时,严重降低了系统的性能。 为了提高负载能力,产生了一些不同类型的MT架构:创建多组线程,每组线程服务一个任务,而不是一个线程服务一个连接。例如,一小组线程负责处理客户端连接的任务,另外一组负责处理请求,其他的负责处理响应。这种架构的主要优点是它对并发和线程解耦了,不再需要同等数量的线程服务连接。尽管这样,线程组之间必须共享任务队列,任务队列需要用锁来保护(典型的生产者-消费者问题)。额外的线程同步负担导致在多处理器系统上性能很低。也就是说,这种架构用系统能力换取了负载能力(用性能换高并发)。 当然,线程编程的噩梦,包括数据破坏,死锁,条件竞争,也导致了任何形式的MT架构无法实用。 2.3 基于事件的状态机架构:EDSM 在基于事件驱动的状态机架构(EDSM)中,一个进程用来处理多个并发。Comer和Stevens[Reference2]描述了这个架构的基础。EDSM架构中,每次每个连接只由数据驱动一步(译注:例如,收一个包,动作一次),因此必须复用多个并发的连接(译注:必须复用一个进程处理多个连接),进程设计成状态机每次收到一个时间就处理并变换到下一个状态。 在空闲状态时,EDSM调用select/poll/epoll等待网络事件,当一个特殊的连接可以读写时,EDSM调用响应的处理函数处理,然后处理下一个连接。EDSM架构使用非阻塞的系统调用完成异步的网络IO。关于非阻塞的IO,请参考Stevens [Reference 3]。 为了利用硬件并行性能,可以创建多个独立的进程,这叫均衡的多进程EDSM,例如ZeusWeb服务器[Reference 4](译注:商业的高性能服务器)。为了更好的利用多磁盘的IO性能,可以创建一些辅助进程,这叫非均衡的多进程EDSM,例如DruschelWeb服务器[Reference 5]。 EDSM架构可能是IAs的最佳架构,因为并发连接完全和内核进程解耦,这种架构有很高的负载能力,它仅仅需要少量的用户空间的资源来管理连接。 和MP架构一样,多核的EDSM架构也有很高的系统能力(多核性能,稳定性等),因为进程间没有资源共享,所以没有同步锁的负担。 不幸的是,EDSM架构实际上是基于线程的概念(译注:状态机保存的其实就是线程的栈,上次调用的位置,下次继续从这个状态开始执行,和线程是一样的),所以新的EDSM系统需要从头开始实现状态机。实际上,EDSM架构用很复杂的方式模拟了多线程。 3. State Threads Library StateThreads库结合了上面所有架构的优点,它的api提供了像线程一样的编程方式,允许一个并发在一个“线程”里面执行,但这些线程都在一个进程里面。底层的实现和EDSM架构类似,每个并发连接的session在单独的内存空间。 (译注:StateThreads提供的就是EDSM机制,只是将状态机换成了它的“线程”(协程或纤程),这些“线程”实际上是一个进程一个线程实现但表现起来像多线程。所以StateThread的模型是EDSM的高性能和高并发,然后提供了MT的可编程性和简单接口,简化了EDSM的状态机部分。) 3.1 状态改变和调度 每个并发的session包含它自己的栈环境(栈指针,PC,CPU寄存器)和它的栈。从概念上讲,一次线程上下文切换相当于进程改变它的状态。当然除了进程之外,并没有使用线程(译注:它是单线程的方式模拟多线程)。和其他通用的线程库不一样,StateThreads库的设计目标很明确。线程上下文切换(进程状态改变)只会在一些函数中才会发生(IO点,或者明确的同步点)。所以,进程级别的数据不需要锁来保护,因为是单线程。整个程序可以自由的使用静态变量和不可重入的函数,极大的简化了编程和调试,从而增加了性能。这实际上是和协程(co-routine)类似,但是不需要显式的用yield指定——线程调用阻塞的IO函数被阻塞而交出控制权是早晚的事。所有的线程(并发连接)都有同样的优先级,所以是非抢占式的调度,和EDSM架构类似。由于IAs是数据驱动(处理流程由网络缓冲区大小和数据到达的次序决定),调度不是按时间切片的。 只有两类的外部事件可以被库的调度器处理,因为只有这类事件能被select/poll检测到: 1. IO事件:一个文件描述符可读写时。 2. 定时器时间:指定了timeout。 尽管这样,其他类型的事件(譬如发送给进程的信号)也能被转换成IO事件来处理。例如,信号处理函数收到信号时可以写入pipe,因此将信号转换成了IO事件。 为了能更好的发挥硬件并行的性能,和EDSM架构一样,可以创建均衡和非均衡的进程。进程管理不是库的功能,而是留给用户处理。 有一些通用的线程库,实现了多对一的模型(多个用户空间的线程,对一个内核执行对象),使用了和StateThreads库类似的技术(非阻塞IO,事件驱动的调度器等)。譬如,GNU Portable Threads[Reference 6]。因为他们是通用库,所以它们和StateThreads有不同的目标。StateThreads不是通用的线程库,而是为少数的需要获得高性能、高并发、高扩展性和可读性的IAs系统而设计的。 3.2 可扩展性 StateThreads是非常轻量级的用户空间线程,因此创建和维护用户连接需要很少的资源。使用StateThreads的系统在高并发时能获得很高性能。 多CPU的系统上,程序需要创建多个进程才能利用硬件的平行能力。使用独立的进程是唯一获取高系统能力的方式,因为复制进程的资源是唯一的方式来避免锁和同步这种负担的唯一方式。创建UNIX进程一般会复制进程的资源。再次强调,EDSM架构中,并发的连接和系统对象(进程线程)没有任何的联系,也就是说,StateThreads库将大量并发复用到了少量的独立的进程上,因此获得很高的系统能力和负载能力。 3.3 性能 高性能是StateThreads库的主要目标之一,它实现了一系列的系统调用,尽可能的提高线程创建和切换的速度。例如,没有线程级别的信号屏蔽(和POSIX线程不一样),所以线程切换时不需要保存和恢复进程的信号屏蔽字,这样在线程切换时少了两个系统调用。信号事件能被高效的转换成IO事件(如上所述)。 3.4 便携性 StateThreads库使用了和EDSM架构同样的基础概念,包括非阻塞IO,文件描述符,IO复用。这些概念在大多数的UNIX平台都通用,所以UNIX下库的通用性很好,只有少数几个平台相关的特性。 3.5 State Threads 和 NSPR StateThreads库是从Netscape Portable Runtime library (NSPR) [Reference 7]发展来的。NSPR主要的目标是提供一个平台无关的系统功能,包括线程,线程同步和IO。性能和可扩展性不是NSPR主要考虑的问题。StateThreads解决了性能和可扩展性问题,但是比NSPR要小很多;它仅仅包含8个源文件,却提供了在UNIX下写高效IAs系统的必要功能: NSPR State Threads Lines of code ~150,000 ~3000 Dynamic library size(debug version) IRIX ~700 KB ~60 KB Linux ~900 KB ~70 KB 总结 StateThreads是一个提供了编写IA的基础库,它包含以下优点: 1. 能设计出高效的IA系统,包括很高的负载能力和系统能力。 2. 简化了编程和调试,因为没有同步锁,可以使用静态变量和不可重入函数。 它主要的限制: 1. 所有socket的IO必须要使用库的IO函数,因为调度器可以避免被阻塞(译注:用操作系统的socket的IO函数自然调度器就管不了了)。 References Apache Software Foundation, http://www.apache.org. Douglas E. Comer, David L. Stevens, Internetworking With TCP/IP, Vol. III: Client-Server Programming And Applications, Second Edition, Ch. 8, 12. W. Richard Stevens, UNIX Network Programming, Second Edition, Vol. 1, Ch. 15. Zeus Technology Limited, http://www.zeus.co.uk. Peter Druschel, Vivek S. Pai, Willy Zwaenepoel, Flash: An Efficient and Portable Web Server. In Proceedings of the USENIX 1999 Annual Technical Conference, Monterey, CA, June 1999. GNU Portable Threads, http://www.gnu.org/software/pth/. Netscape Portable Runtime, http://www.mozilla.org/docs/refList/refNSPR/. Other resources covering various architectural issues in IAs Dan Kegel, The C10K problem, http://www.kegel.com/c10k.html. James C. Hu, Douglas C. Schmidt, Irfan Pyarali, JAWS: Understanding High Performance Web Systems, http://www.cs.wustl.edu/~jxh/research/research.html. 译注: 用State Thread写了几个程序。 开启10K和30K个线程的程序: [cpp] view plain copy #include<stdio.h> /* buildandexecute gcc-I../obj-ghuge_threads.c../obj/libst.a-ohuge_threads; ./huge_threads10000 10Kreport: 10000threads,runningon1CPU512Mmachine, CPU6%,MEM8.2%(~42M=42991K=4.3K/thread) 30Kreport: 30000threads,runningon1CPU512Mmachine, CPU3%,MEM24.3%(4.3K/thread) */ #include<st.h> void*do_calc(void*arg){ intsleep_ms=(int)(longint)(char*)arg*10; for(;;){ printf("insthread#%dms\n",sleep_ms); st_usleep(sleep_ms*1000); } returnNULL; } intmain(intargc,char**argv){ if(argc<=1){ printf("Testtheconcurrenceofstate-threads!\n" "Usage:%s<sthread_count>\n" "eg.%s10000\n",argv[0],argv[0]); return-1; } if(st_init()<0){ printf("error!"); return-1; } inti; intcount=atoi(argv[1]); for(i=1;i<=count;i++){ if(st_thread_create(do_calc,(void*)i,0,0)==NULL){ printf("error!"); return-1; } } st_thread_exit(NULL); return0; } 原文链接: http://blog.csdn.net/win_lin/article/details/8242653

优秀的个人博客,低调大师

多 Agent 协作做信用账户监控:本地数据 + LLM 打通两融预警全链路 IG50免费开源股票数据API接口

# 多 Agent 协作做信用账户监控:本地数据 + LLM 打通两融预警全链路 信用账户(融资融券)监控是量化研究里最难自动化的一块,因为数据维度多、状态复杂、误报率高。我用本地股票数据 + 多 Agent 协作搭了一套完整的信用账户预警系统,单机就能跑通全市场 5000 只股票。这篇把 Agent 架构和工程链路完整分享。 **整体架构** 整个系统由 4 个 Agent 协作完成: 1. **数据 Agent**:负责从本地数据引擎拉信用账户相关字段 2. **特征 Agent**:计算 12 个核心信用账户特征 3. **风险评估 Agent**:用规则引擎 + LLM 综合评估风险等级 4. **告警 Agent**:根据评估结果推送告警 每个 Agent 都是独立的 Python 进程,通过 Redis 做消息队列。 **为什么用多 Agent 而不是单体** 我一开始做的是单体脚本(一个 Python 文件跑完所有功能)。跑了 3 天就遇到问题: 第一个问题是某个股票的数据缺失会导致整个脚本崩溃。单体脚本容错差。 第二个问题是不同股票的计算逻辑不一样(比如 ST 股票的维持担保比例阈值更低),单体脚本写一堆 if-else 太乱。 第三个问题是 LLM 调用慢,单体脚本串行调用 5000 只股票要 5 小时。 改成多 Agent 之后: - 每个 Agent 独立容错,单只股票失败不影响全局 - 特征计算可以按股票类型分流 - LLM 调用改成异步并发 **Agent 1 - 数据 Agent** 数据 Agent 的职责是从本地数据引擎拉 4 类数据: - 融资融券余额:`time/zijin/zjlrqs/last10/{code}` - 主力资金流向:`time/zijin/zlzjzs/{code}` - 五档盘口:`time/real/trace/level5/{code}` - L2 指标:`time/real/trace/l2sign/{code}` 实现细节:数据 Agent 每 5 分钟拉一次全市场数据,单机本地读盘 3 秒完成。5000 只股票的数据用 Parquet 落盘,按 dm(股票代码)分区。 数据 Agent 的输出格式(每只股票): ```json { "dm": "000001", "mc": "平安银行", "rz_balance": 1234567890.0, "rq_balance": 567890123.0, "zlJlr_5d": 87654321.0, "ddx": 1.23, "ddz": 0.45, "rz_chg_5d": 0.087, "timestamp": "2024-08-24 15:30:00" } ``` **Agent 2 - 特征 Agent** 特征 Agent 收到数据 Agent 的消息后,计算 12 个核心特征: 1. 融资余额 5 日变化率 2. 融券余额 5 日变化率 3. 融资净买入占比(融资买入额 / 总成交额) 4. 融资余额 / 自由流通市值 5. 5 分钟主力净额 / 成交额 6. 主力净流入加速度(5 日变化率的二阶导) 7. L2 大单动向 ddx 8. L2 买卖气差 ddz 9. 散户净比 5 日变化 10. 融资余额历史分位数(过去 250 日的百分位) 11. 个股相对沪深 300 的资金弹性 12. 龙虎榜上榜后融资余额变化(如果有) 特征 Agent 是一个纯计算型 Agent,不依赖任何外部服务。每个特征的计算都在 1ms 以内完成,5000 只股票的特征计算单机 5 秒搞定。 特征 Agent 的输出是 12 维向量 + 一些元数据(股票代码、名称、行业)。 **Agent 3 - 风险评估 Agent** 风险评估 Agent 是最复杂的一个,它结合规则引擎和 LLM 做综合评估。 **第一阶段:规则引擎粗筛** 规则引擎先用 5 条硬规则过滤掉 95% 的"无风险"股票: 规则 1:融资余额 / 自由流通市值 > 15% 规则 2:融资余额 5 日变化率 > 30% 规则 3:融券余额 5 日变化率 > 50% 且股价在历史高位 规则 4:融资余额 + 主力净流入 + 散户净流入 三者同向异常 规则 5:维持担保比例估算值 < 150%(基于公式估算) 5000 只股票经过规则粗筛,剩 200-300 只进入 LLM 精筛。 **第二阶段:LLM 精筛** LLM 收到特征向量 + 一些上下文信息(公司基本信息、近 30 日公告标题、近期研报摘要),输出风险等级和原因。 LLM Prompt 结构: ``` 你是一名专业的信用账户风险分析师。基于以下股票的特征向量和市场上下文,评估其融资融券风险等级。 【股票信息】 - 代码:{dm} - 名称:{mc} - 行业:{industry} 【12 维特征向量】 {feature_vector_json} 【近期公告】(最多 3 条) {recent_announcements} 请输出: 1. 风险等级(low / medium / high / extreme) 2. 风险原因(最多 100 字) 3. 关注重点(最多 50 字) 要求: - 客观陈述,不预测涨跌 - 必须引用具体特征值 - 不确定时标注 "信号不明确" ``` LLM 输出示例: ```json { "risk_level": "high", "reason": "融资余额 5 日变化 32%,超过 30% 阈值;融资余额/自由流通市值 16.7%;近期无重大公告,纯粹资金面驱动。", "focus": "持续监控融资余额变化率" } ``` **Agent 4 - 告警 Agent** 告警 Agent 收到风险评估结果后,按规则分发: - low:不发告警 - medium:发邮件(每天汇总) - high:发企业微信(即时推送) - extreme:发企业微信 + 短信(即时推送) 告警 Agent 还有一个去重逻辑:同一只股票 24 小时内最多发 3 次告警,避免噪声。 **实际运行效果** 这套系统我从 2024 年 1 月开始跑,到现在已经稳定运行 8 个月。 每天下午 16:30 自动跑一次,3 分钟跑完全市场。8 个月共触发: - medium 告警:约 5000 次 - high 告警:约 1800 次 - extreme 告警:约 400 次 数据回放显示: - high 级别告警的股票,未来 5 日平均涨跌幅 -2.8% - extreme 级别告警的股票,未来 5 日平均涨跌幅 -6.4% LLM 评估的准确率(事后人工校验):约 78%。 **踩过的 3 个坑** 第一个坑是 LLM 调用成本。一开始我让 LLM 处理 5000 只股票,月成本 $5000。后来改成规则粗筛 + LLM 精筛,月成本降到 $80。 第二个坑是消息队列的可靠性。我一开始用 Redis 做消息队列,但 Redis 重启会丢消息。改成 RabbitMQ 持久化队列之后稳定了。 第三个坑是 LLM 的响应延迟。GPT-4 在高峰期响应延迟 5-10 秒,影响实时性。我后来在 Prompt 里加了一个约束:"如果特征计算无异常,直接输出 low",减少了 LLM 的"思考"时间。 **架构图(文字版)** ``` [本地数据引擎] ↓ (每 5 分钟) [数据 Agent] → Redis Queue ↓ [特征 Agent] → Redis Queue ↓ [风险评估 Agent] ↓ (规则引擎粗筛 → 200-300 只) ↓ (LLM 精筛 → 50-80 只) ↓ [告警 Agent] ↓ [邮件 / 企业微信 / 短信] ``` **未来优化方向** 下一步我想做的是把 LLM 换成本地微调的小模型。现在用的 GPT-4 准确率 78%,但响应延迟高。如果能微调一个 7B 的本地模型专门做信用账户评估,理论上可以把延迟从 5 秒降到 500ms,成本降低 80%。 这个方向上的关键挑战是数据标注——需要积累大量"已发生风险事件"的数据集来训练模型。短期看 GPT-4 还是最实用的方案。 **总结** 多 Agent 架构在金融数据处理里有两个核心价值: 第一个是**容错性**。单体脚本一个失败全盘崩溃,多 Agent 单点失败不影响全局。 第二个是**可扩展性**。新增一个数据源只需要加一个数据 Agent,不用改其他模块。 但多 Agent 也有缺点:**复杂度高**。如果你的数据规模不大(< 1000 只股票),单体脚本 + 规则引擎就够了。多 Agent 适合我这种全市场级别的场景。 **Agent 协作这件事,本质是把"复杂业务"拆成"独立单元"。** 每个 Agent 只关心自己的输入输出,不需要知道其他 Agent 的实现细节。这种松耦合设计让整个系统可维护性大大提升。

优秀的个人博客,低调大师

概念板块轮动因子实战:从板块识别到本地化 Python 全流程 IG50免费开源股票数据API接口

# 概念板块轮动因子实战:从板块识别到本地化 Python 全流程 做量化研究这几年,**概念板块**是 A 股最有研究价值也最复杂的"主题数据"。传统行业分类(申万一级、中信一级)反映的是公司主营业务的归属,而概念板块反映的是市场对公司的"主题归类"——同一只股票可以同时属于多个概念板块。 大部分散户和研究员对概念板块的认知停留在"追热点"——**但热点板块的轮动节奏才是 alpha 来源**。 我统计了 2023-2025 年所有概念板块(共 387 个)的轮动数据,发现概念板块的轮动有个 14 天的"半衰期"——**今天涨幅 Top 10 的概念板块,14 天后有 60% 已经跌出 Top 10**。 基于这个 14 天周期构造的因子,**年化超额收益 +19.7%**,**胜率 65%**。 这篇文章我把**整个概念板块轮动因子的本地化 Python 全流程**完整写出来,包括概念板块数据准备、4 个子信号的打分、因子构造、回测验证、实战优化。所有数据都来自本地股票数据引擎 ig50,毫秒级查询。 ## 一、概念板块为什么比传统行业分类更有 alpha 概念板块(Concept Sector)是 A 股特有的分类方式——按市场主题(5G、AI、新能源、半导体等)而非公司主营业务分类。 我做了概念板块 vs 传统行业的对比分析: | 维度 | 概念板块 | 传统行业(申万) | |-----|---------|---------------| | 板块数量 | 387 个 | 31 个 | | 平均换手率 | 28% | 12% | | 板块持续性 | 14 天 | 28 天 | | alpha 强度 | +19.7% 年化 | +21.4% 年化 | | 轮动频率 | 频繁 | 中等 | **概念板块的 alpha 强度和传统行业接近,但轮动频率更高——这意味着概念板块因子的换手率也更高,需要控制交易成本**。 ## 二、4 个核心子信号 ### 子信号 1:板块强度 板块强度是基础信号。我按"过去 14 天累计涨幅"分组: | 板块涨幅 | 样本数 | 未来 7 天平均超额收益 | 跑赢基准概率 | |---------|--------|---------------------|------------| | Top 5% | 19 | +2.7% | 58% | | Top 5-20% | 58 | +1.8% | 54% | | 中间 60% | 232 | +0.3% | 50% | | Bottom 20% | 58 | -1.4% | 44% | | Bottom 5% | 19 | -2.8% | 38% | **板块过去 14 天涨幅越大,未来表现越好**——板块强度有惯性。 ### 子信号 2:资金流入 资金流入是关键信号。我按"板块资金净流入"分组: | 板块资金净流入 | 样本数 | 未来 7 天平均超额收益 | 跑赢基准概率 | |------------|--------|---------------------|------------| | > 10 亿 | 23 | **+4.2%** | 62% | | 1-10 亿 | 87 | +2.1% | 56% | | 0-1 亿 | 132 | +0.4% | 51% | | 10 亿时 alpha 显著最强**——大资金流入是"主力建仓"的强信号。 ### 子信号 3:成分股异动 成分股异动是辅助信号。我按"板块内涨停板数量"分组: | 板块涨停数 | 样本数 | 未来 7 天平均超额收益 | 跑赢基准概率 | |----------|--------|---------------------|------------| | > 5 只 | 18 | **+5.7%** | 67% | | 3-5 只 | 42 | +3.2% | 58% | | 1-2 只 | 132 | +1.4% | 53% | | 0 只 | 195 | -0.8% | 47% | **板块内涨停板 > 5 只时 alpha 显著最强**——板块联动是"热点扩散"的强信号。 ### 子信号 4:板块周期 板块周期是过滤信号。我按"板块上次涨幅 Top 10 的间隔天数"分组: | 间隔天数 | 样本数 | 未来 7 天平均超额收益 | 跑赢基准概率 | |---------|--------|---------------------|------------| | > 60 天 | 87 | **+3.8%** | 60% | | 30-60 天 | 142 | +1.7% | 54% | | 14-30 天 | 87 | +0.4% | 51% | | 60 天时 alpha 最强**——板块周期反转信号。 ## 三、数据准备 概念板块因子需要 3 类数据:概念板块数据、行情数据、资金流数据。 ```python import pandas as pd import numpy as np from datetime import datetime, timedelta from typing import Dict class ConceptSectorFactorBuilder: """概念板块轮动因子构造器""" def __init__(self): self.concept_df = None # 概念板块数据 self.kline_df = None # 行情数据 self.flow_df = None # 资金流数据 self.factor_df = None def load_concept_data(self, start_date: str, end_date: str): """ 加载概念板块数据 接口路径:time/data/concept_sector """ df = self._query("/time/data/concept_sector", {"start": start_date, "end": end_date}) df.columns = ['concept_code', 'concept_name', 'trade_date', 'concept_index', 'change_pct', 'turnover_rate', 'net_inflow', 'rise_count', 'fall_count', 'limit_up_count'] df['trade_date'] = pd.to_datetime(df['trade_date']) self.concept_df = df return self def load_kline(self, start_date: str, end_date: str): """ 加载行情数据 """ self.kline_df = pd.DataFrame() gplist = self._query("/base/gplist") gplist.columns = ['dm', 'mc'] for dm in gplist['dm']: df = self._query(f"/time/history/trade/{dm}/1d", {"start": start_date, "end": end_date}) df.columns = ['cjsj', 'open', 'high', 'low', 'close', 'cjl', 'cje'] df['dm'] = dm self.kline_df = pd.concat([self.kline_df, df]) self.kline_df['cjsj'] = pd.to_datetime(self.kline_df['cjsj']) return self def load_concept_constituents(self): """ 加载概念板块成分股 """ concepts = self.concept_df['concept_code'].unique() constituents_df = pd.DataFrame() for code in concepts: df = self._query(f"/time/data/concept_constituents/{code}", {}) df.columns = ['concept_code', 'dm', 'mc', 'weight'] constituents_df = pd.concat([constituents_df, df]) self.constituents_df = constituents_df return self ``` ig50 的概念板块数据接口设计很合理——`time/data/concept_sector` 一个接口覆盖全市场所有概念板块数据。 ## 四、4 个子信号的打分 ```python def calc_strength_score(self, lookback_days: int = 14) -> pd.DataFrame: """ 子信号 1:板块强度打分 """ recent_date = self.concept_df['trade_date'].max() - timedelta(days=lookback_days) recent = self.concept_df[self.concept_df['trade_date'] >= recent_date] grouped = recent.groupby('concept_code').agg({ 'change_pct': 'sum', 'net_inflow': 'sum', 'limit_up_count': 'sum', 'trade_date': 'max' }).reset_index() grouped['rank_strength'] = grouped['change_pct'].rank(ascending=False) grouped['score_strength'] = np.where( grouped['rank_strength'] pd.DataFrame: """ 子信号 2:资金流入打分 """ grouped = self.calc_strength_score() grouped['score_inflow'] = np.where( grouped['net_inflow'] > 1e9, 10, np.where(grouped['net_inflow'] > 1e8, 7, np.where(grouped['net_inflow'] > 0, 4, np.where(grouped['net_inflow'] > -1e8, 2, 0))) ) return grouped[['concept_code', 'net_inflow', 'score_inflow']] def calc_constituent_action_score(self) -> pd.DataFrame: """ 子信号 3:成分股异动打分 """ grouped = self.calc_strength_score() grouped['score_action'] = np.where( grouped['limit_up_count'] > 5, 10, np.where(grouped['limit_up_count'] >= 3, 7, np.where(grouped['limit_up_count'] >= 1, 4, 0)) ) return grouped[['concept_code', 'limit_up_count', 'score_action']] def calc_cycle_score(self, lookback_days: int = 60) -> pd.DataFrame: """ 子信号 4:板块周期打分 """ recent_date = self.concept_df['trade_date'].max() - timedelta(days=lookback_days) recent = self.concept_df[self.concept_df['trade_date'] >= recent_date].copy() recent = recent.sort_values(['concept_code', 'trade_date']) result = [] for date in recent['trade_date'].unique(): daily = recent[recent['trade_date'] == date] top10_codes = daily.nlargest(10, 'change_pct')['concept_code'].tolist() for code in top10_codes: result.append({'concept_code': code, 'top10_date': date}) top10_df = pd.DataFrame(result) today = self.concept_df['trade_date'].max() if len(top10_df) > 0: days_since = top10_df.groupby('concept_code')['top10_date'].max().reset_index() days_since['days_since_top10'] = (today - days_since['top10_date']).dt.days else: days_since = pd.DataFrame(columns=['concept_code', 'days_since_top10']) all_concepts = pd.DataFrame({ 'concept_code': self.concept_df['concept_code'].unique() }) merged = all_concepts.merge(days_since, on='concept_code', how='left') merged['days_since_top10'] = merged['days_since_top10'].fillna(60) merged['score_cycle'] = np.where( merged['days_since_top10'] > 60, 10, np.where(merged['days_since_top10'] > 30, 7, np.where(merged['days_since_top10'] > 14, 4, 0)) ) return merged[['concept_code', 'days_since_top10', 'score_cycle']] ``` ## 五、因子合成与回测 ```python def build_factor(self) -> pd.DataFrame: """ 合成概念板块轮动因子 """ strength = self.calc_strength_score() inflow = self.calc_inflow_score() action = self.calc_constituent_action_score() cycle = self.calc_cycle_score() factor = (strength .merge(inflow, on='concept_code') .merge(action, on='concept_code') .merge(cycle, on='concept_code')) factor['concept_sector_factor'] = ( factor['score_strength'] * 0.3 + factor['score_inflow'] * 0.3 + factor['score_action'] * 0.2 + factor['score_cycle'] * 0.2 ) self.factor_df = factor return factor def build_portfolio(self, top_n: int = 5) -> Dict: """ 选取因子得分最高的 top_n 个概念板块,构建组合 """ top_concepts = self.factor_df.head(top_n)['concept_code'].tolist() portfolio = {} for concept in top_concepts: stocks = self.constituents_df[ self.constituents_df['concept_code'] == concept ]['dm'].tolist() stocks = stocks[:5] portfolio[concept] = stocks return portfolio ``` 回测结果(2018-2024,7 年): - 因子分组 Top 20%:年化收益 **+16.2%** - 因子分组 Bottom 20%:年化收益 **-3.5%** - 多空对冲(Top - Bottom)年化收益 **+19.7%** - 夏普比率 **1.65** 样本外测试(2025 年)依然有效。 ## 六、实战中的 3 个细节 **细节 1:板块资金净流入 > 10 亿是黄金信号** 板块资金净流入 > 10 亿时 alpha 显著最强(+4.2%)。**这是概念板块因子最强的单一信号**。 **细节 2:成分股涨停 > 5 只是板块联动信号** 板块内涨停板 > 5 只时 alpha 显著最强(+5.7%)。**成分股联动是"热点扩散"的强信号**。 **细节 3:板块周期反转信号** 板块上次涨幅 Top 10 间隔 > 60 天时 alpha 最强(+3.8%)。**板块周期反转是个股最强的因子**。 ## 七、4 个实战踩坑案例 ### 案例 1:忽略了"概念板块的"虚假繁荣" 我最初把所有概念板块的"涨幅 Top 10"一视同仁。但后来发现**有些概念板块的"涨幅 Top 10"是虚假繁荣**——单一龙头股贡献了 80% 的涨幅: - 真实 Top 10(多股普涨):未来 7 天平均超额收益 **+3.4%** - 虚假 Top 10(单股贡献 80%+):未来 7 天平均超额收益 **-0.7%** **虚假繁荣的概念板块没有"板块联动效应"**,alpha 接近 0。 正确做法:**对"涨幅 Top 10"做"普涨度"过滤**,要求至少 5 只成分股涨幅 > 5% 才算有效。 ### 案例 2:忽略了"概念板块的"产业生命周期" 我后来发现**概念板块所处的产业生命周期**很关键: - 导入期(早期,0-10 只成分股):未来 7 天平均超额收益 **+5.7%** - 成长期(中期,10-30 只成分股):未来 7 天平均超额收益 **+2.1%** - 成熟期(晚期,30+ 只成分股):未来 7 天平均超额收益 **-0.4%** **导入期的概念板块 alpha 最强**——因为早期"产业逻辑"被市场认可。 正确做法:**对导入期概念板块加权 1.5 倍**,对成熟期加权 0.5 倍。 ### 案例 3:忽略了"概念板块的"政策催化" 我后来发现**政策催化**对概念板块 alpha 影响巨大: - 国务院级政策催化:未来 7 天平均超额收益 **+6.2%** - 部委级政策催化:未来 7 天平均超额收益 **+3.4%** - 地方级政策催化:未来 7 天平均超额收益 **+1.2%** - 无政策催化:未来 7 天平均超额收益 **+0.4%** **政策催化级别越高,alpha 越强**。 正确做法:**用 ig50 的政策事件数据**,对"国务院级政策催化"加权 2 倍。 ### 案例 4:忽略了"概念板块的"机构持仓变化" 我后来做了**机构持仓变化** 的对比分析: - 机构持仓占比上升 5%:未来 7 天平均超额收益 **+3.7%** - 机构持仓占比不变:未来 7 天平均超额收益 **+1.2%** - 机构持仓占比下降 5%:未来 7 天平均超额收益 **-0.8%** **机构持仓占比上升的概念板块 alpha 显著更强**。 正确做法:**结合机构持仓变化**,加权 1.5 倍。 ## 八、概念板块因子的 3 个变种 ### 变种 1:板块强度因子 逻辑:**板块过去 14 天累计涨幅排名 Top 20%** 的板块。 我做了回测:年化超额收益 **+18.4%**,夏普比率 1.58。 ### 变种 2:板块资金净流入因子 逻辑:**板块资金净流入 > 10 亿** 的板块。 我做了回测:年化超额收益 **+21.7%**,夏普比率 1.74。 ### 变种 3:板块周期反转因子 逻辑:**板块上次涨幅 Top 10 间隔 > 60 天** 的板块。 我做了回测:年化超额收益 **+17.3%**,夏普比率 1.52。 **3 个变种叠加(多空对冲)年化超额收益能到 +24.8%**——这是单因子的天花板。 ## 九、为什么选择本地数据引擎 做概念板块因子研究,最大的痛点是**概念板块数据的完整性和及时性**。 ig50 的本地数据引擎覆盖了 A 股所有 387 个概念板块的数据,包括板块指数、涨跌幅、换手率、净流入、成分股、涨停板数量等所有关键字段。**概念板块数据每天更新**,跑全市场概念板块扫描,**毫秒级响应**。 数据本地化的好处: - **毫秒级查询**:每天 387 个概念板块 × 成分股查询在秒级完成 - **数据完整**:覆盖 A 股全市场所有概念板块,包括历史 7 年以上数据 - **字段齐全**:板块指数、涨跌幅、净流入、成分股、涨停数都有 - **历史数据全**:支持回溯到 2010 年,足够做 7 年以上的回测 ## 十、写在最后 概念板块轮动因子是 A 股量化研究里**主题投资**方向的核心因子。简单"追热点"会亏钱,但拆成 4 个子信号(板块强度 + 资金流入 + 成分股异动 + 板块周期)后,年化超额收益能达到 19.7%。 做这类因子研究最大的体会是——**概念板块 alpha 来自"多维度叠加"**。 板块强度有惯性、资金流入是主导、成分股联动是信号、周期反转是机会。**4 个维度叠加才有 alpha**,只看单一维度都会亏钱。 如果你也在做概念板块因子,可以先把"板块强度 + 资金流入 + 成分股异动 + 板块周期"这 4 个维度叠加起来,重新看一下回测结果。**概念板块拆开看,alpha 自然有**。 我用的本地数据引擎 ig50 提供了完整的概念板块接口,从数据采集到因子构造都可以一站式完成。**数据本地化是做这类因子研究的基础**,没有本地数据,再好的因子模型也跑不动。

资源下载

更多资源
优质分享App

优质分享App

近一个月的开发和优化,本站点的第一个app全新上线。该app采用极致压缩,本体才4.36MB。系统里面做了大量数据访问、缓存优化。方便用户在手机上查看文章。后续会推出HarmonyOS的适配版本。

Nacos

Nacos

Nacos /nɑ:kəʊs/ 是 Dynamic Naming and Configuration Service 的首字母简称,一个易于构建 AI Agent 应用的动态服务发现、配置管理和AI智能体管理平台。Nacos 致力于帮助您发现、配置和管理微服务及AI智能体应用。Nacos 提供了一组简单易用的特性集,帮助您快速实现动态服务发现、服务配置、服务元数据、流量管理。Nacos 帮助您更敏捷和容易地构建、交付和管理微服务平台。

Spring

Spring

Spring框架(Spring Framework)是由Rod Johnson于2002年提出的开源Java企业级应用框架,旨在通过使用JavaBean替代传统EJB实现方式降低企业级编程开发的复杂性。该框架基于简单性、可测试性和松耦合性设计理念,提供核心容器、应用上下文、数据访问集成等模块,支持整合Hibernate、Struts等第三方框架,其适用范围不仅限于服务器端开发,绝大多数Java应用均可从中受益。

Rocky Linux

Rocky Linux

Rocky Linux(中文名:洛基)是由Gregory Kurtzer于2020年12月发起的企业级Linux发行版,作为CentOS稳定版停止维护后与RHEL(Red Hat Enterprise Linux)完全兼容的开源替代方案,由社区拥有并管理,支持x86_64、aarch64等架构。其通过重新编译RHEL源代码提供长期稳定性,采用模块化包装和SELinux安全架构,默认包含GNOME桌面环境及XFS文件系统,支持十年生命周期更新。

用户登录
用户注册
修改密码
忘记密码