k线dataframe数据校验;设置刚进入chart时可见的k线数量

This commit is contained in:
2025-10-19 11:06:56 +08:00
parent 2baf82b748
commit 643c99341e

View File

@@ -7,6 +7,7 @@ from lightweight_charts import Chart
import random
from datetime import datetime
horizontal_lines = {}
@@ -331,24 +332,59 @@ def on_range_change_poc(chart, bars_before, bars_after):
horizontal_lines[poc_line_name] = poc_line
def plot_chart(df, symbol: str, name: str, timeframe: str):
"""
df: DataFrame
time, open, high, low, close, volume, [buy, sell]可选 buy=1 买入信号, sell=1 卖出信号
def check_df(df: pd.DataFrame):
# basic type check
if not isinstance(df, pd.DataFrame):
raise TypeError("df must be a pandas DataFrame")
required_cols = ["time", "open", "high", "low", "close", "volume"]
missing = [c for c in required_cols if c not in df.columns]
if missing:
raise ValueError(
f"Missing required columns: {missing}. Required: {required_cols}"
)
# time column must be datetime.datetime or pd.Timestamp (or a datetime64 dtype)
time_series = df["time"]
if not (
pd.api.types.is_datetime64_any_dtype(time_series)
or time_series.apply(lambda x: isinstance(x, (pd.Timestamp, datetime))).all()
):
raise TypeError(
"Column 'time' must contain datetime values (python datetime.datetime or pandas.Timestamp) "
"or be a datetime64 dtype."
)
# other columns must be numeric (int or float)
for col in ["open", "high", "low", "close", "volume"]:
if not pd.api.types.is_numeric_dtype(df[col]):
raise TypeError(f"Column '{col}' must be numeric (int or float)")
def plot_chart(
df, symbol: str, name: str, timeframe: str, init_visible_num_bars: int = 90
):
# 校验数据是否满足
check_df(df)
"""
chart = Chart(toolbox=True, inner_height=0.8, maximize=True)
chart.topbar.textbox("symbol", symbol)
chart.topbar.textbox("name", name)
chart.topbar.textbox("timeframe", timeframe)
chart.legend(
visible=True, font_size=14, color="#FFFFFF", font_family="Times New Roman"
)
chart.set(df)
# 设置刚进入chart时的可见k线数量范围
end_time = df["time"].iloc[-1]
start_time = df["time"].iloc[-init_visible_num_bars]
chart.set_visible_range(start_time, end_time)
# 设置每次放缩k线范围时的回调函数计算实时计算poc
chart.events.range_change += on_range_change_poc
# 添加技术指标
# add_ema(df, chart, period=10)
# add_ema(df, chart, period=20)
add_ema(df, chart, period=30)