第一版

This commit is contained in:
YuWuKunCheng
2026-05-25 02:16:35 +08:00
parent ff4e6ae570
commit f92eef11fb
37 changed files with 11615 additions and 0 deletions
+180
View File
@@ -0,0 +1,180 @@
use serde::{Deserialize, Serialize};
/// 相对强弱指数 (RSI)
///
/// 使用 Wilder 平滑(RMA)进行增量计算
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(default)]
pub struct {
pub : i64,
pub : f64,
pub : i64,
pub : f64,
pub : f64,
pub RSI_SMA周期: Option<i64>,
pub RSI: Option<f64>,
pub : Option<f64>,
pub : Option<f64>,
pub : f64,
pub : f64,
pub : f64,
pub RSI_SMA: Option<f64>,
pub RSI历史队列: Vec<f64>,
}
impl Default for {
fn default() -> Self {
Self {
: 0,
: 0.0,
: 14,
: 70.0,
: 30.0,
RSI_SMA周期: None,
RSI: None,
: None,
: None,
: 0.0,
: 0.0,
: 0.0,
RSI_SMA: None,
RSI历史队列: Vec::new(),
}
}
}
impl {
/// 首次计算 RSI(历史数据不足时)
pub fn (
: f64,
: i64,
: i64,
: f64,
: f64,
RSI_SMA周期: Option<i64>,
) -> Self {
Self {
: ,
: ,
,
,
,
RSI_SMA周期,
RSI: None,
: Some(0.0),
: Some(0.0),
: 0.0,
: 0.0,
: 1.0 / as f64,
RSI_SMA: None,
RSI历史队列: Vec::new(),
}
}
/// 基于前一个 RSI 增量计算当前 RSI
pub fn (RSI: &Self, : f64, : i64) -> Self {
let = RSI.;
let = RSI.;
let = RSI.;
let RSI_SMA周期 = RSI.RSI_SMA周期;
let = 1.0 / as f64;
// 价格变化
let = - RSI.;
let = .max(0.0);
let = (-).max(0.0);
// Wilder 平滑
let (, ) = match (RSI., RSI.) {
(Some(prev_up), Some(prev_down)) => {
let avg_up = prev_up * (1.0 - ) + * ;
let avg_down = prev_down * (1.0 - ) + * ;
(avg_up, avg_down)
}
_ => (, ),
};
// RSI
let RSI = if == 0.0 {
if > 0.0 {
100.0
} else {
50.0
}
} else {
let RS = / ;
100.0 - (100.0 / (1.0 + RS))
};
// RSI_SMA
let (RSI_SMA, RSI历史队列) = match RSI_SMA周期 {
Some(sma周期) if sma周期 > 0 => {
let mut = RSI.RSI历史队列.clone();
.push(RSI);
if .len() > sma周期 as usize {
.remove(0);
}
let sma = if .is_empty() {
None
} else {
Some(.iter().sum::<f64>() / .len() as f64)
};
(sma, )
}
_ => (None, Vec::new()),
};
Self {
: ,
: ,
,
,
,
RSI_SMA周期,
RSI: Some(RSI),
: Some(),
: Some(),
: ,
: ,
,
RSI_SMA,
RSI历史队列,
}
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn test_first_calc() {
let rsi = ::(100.0, 1000, 14, 70.0, 30.0, None);
assert_eq!(rsi.RSI, None);
assert_eq!(rsi., 1.0 / 14.0);
}
#[test]
fn test_incremental_calc() {
let first = ::(100.0, 1000, 14, 70.0, 30.0, None);
let second = ::(&first, 102.0, 1001);
// 价格上涨 → RSI > 50
assert!(second.RSI.unwrap() > 50.0);
let third = ::(&second, 98.0, 1002);
// 价格低于之前 → RSI 下降
assert!(third.RSI.unwrap() < second.RSI.unwrap());
}
#[test]
fn test_rsi_sma() {
let mut rsi = ::(100.0, 1000, 14, 70.0, 30.0, Some(5));
// 喂入多根K线来积累RSI历史队列
let prices = [102.0, 103.0, 101.0, 104.0, 105.0, 103.0, 106.0];
for (i, price) in prices.iter().enumerate() {
rsi = ::(&rsi, *price, 1001 + i as i64);
}
// SMA 应该已被计算(队列够长)
assert!(rsi.RSI_SMA.is_some());
}
}