### Full Workflow: Fetch Data, Compute Indicators, and Plot Source: https://context7.com/mpquant/ashare/llms.txt An end-to-end example demonstrating fetching historical stock data, calculating multiple technical indicators (MA, BOLL, MACD, KDJ), detecting trading signals, and plotting the results using matplotlib. Requires Ashare, MyTT, and matplotlib libraries. ```python from Ashare import * from MyTT import * import matplotlib.pyplot as plt from matplotlib.ticker import MultipleLocator # 1. Fetch 120 days of daily data for SSE Composite Index df = get_price('000001.XSHG', frequency='1d', count=120) print(df.tail(5)) # 2. Extract OHLCV arrays CLOSE = df.close.values OPEN = df.open.values HIGH = df.high.values LOW = df.low.values VOLUME = df.volume.values # 3. Compute indicators ma5, ma10 = MA(CLOSE, 5), MA(CLOSE, 10) upper, mid, lower = BOLL(CLOSE) DIF, DEA, MACD_h = MACD(CLOSE) K, D, J = KDJ(CLOSE, HIGH, LOW) print(f'Latest — Close: {RET(CLOSE):.2f} | MA5: {RET(ma5):.2f} | MA10: {RET(ma10):.2f}') print(f'BOLL — Upper: {RET(upper):.2f} | Mid: {RET(mid):.2f} | Lower: {RET(lower):.2f}') print(f'MACD — DIF: {RET(DIF):.3f} | DEA: {RET(DEA):.3f} | Hist: {RET(MACD_h):.3f}') print(f'KDJ — K: {RET(K):.2f} | D: {RET(D):.2f} | J: {RET(J):.2f}') # 4. Signal detection if CROSS(ma5, ma10): print('Signal: MA5 golden cross above MA10') if RET(K) < 20 and CROSS(K, D): print('Signal: KDJ golden cross in oversold zone') # 5. Plot price + Bollinger Bands plt.figure(figsize=(15, 8)) plt.plot(CLOSE, label='CLOSE', linewidth=1.5) plt.plot(upper, label='BOLL Upper', linestyle='--', alpha=0.7) plt.plot(mid, label='BOLL Mid') plt.plot(lower, label='BOLL Lower', linestyle='--', alpha=0.7) plt.plot(ma10, label='MA10', linewidth=0.8, alpha=0.7) plt.title('SSE Composite Index — Price & Bollinger Bands', fontsize=16) plt.legend(); plt.grid(linewidth=0.4, alpha=0.6) plt.gca().xaxis.set_major_locator(MultipleLocator(len(CLOSE) // 30)) plt.gcf().autofmt_xdate(rotation=45) plt.tight_layout(); plt.show() ``` -------------------------------- ### Fetch and Plot Stock Data with Ashare and MyTT Source: https://github.com/mpquant/ashare/blob/main/README.md This example shows how to fetch historical daily stock data using Ashare and then use the MyTT library to calculate technical indicators like Moving Averages (MA) and Bollinger Bands (BOLL). It also demonstrates plotting the data and indicators using Matplotlib. ```python #股市行情数据获取和作图 -2 from Ashare import * #股票数据库 https://github.com/mpquant/Ashare from MyTT import * #myTT麦语言工具函数指标库 https://github.com/mpquant/MyTT # 证券代码兼容多种格式 通达信,同花顺,聚宽 # sh000001 (000001.XSHG) sz399006 (399006.XSHE) sh600519 ( 600519.XSHG ) df=get_price('000001.XSHG',frequency='1d',count=120) #获取今天往前120天的日线实时行情 print('上证指数日线行情\n',df.tail(5)) #-------有数据了,下面开始正题 ------------- CLOSE=df.close.values; OPEN=df.open.values #基础数据定义,只要传入的是序列都可以 HIGH=df.high.values; LOW=df.low.values #例如 CLOSE=list(df.close) 都是一样 MA5=MA(CLOSE,5) #获取5日均线序列 MA10=MA(CLOSE,10) #获取10日均线序列 up,mid,lower=BOLL(CLOSE) #获取布林带指标数据 #-------------------------作图显示----------------------------------------------------------------- import matplotlib.pyplot as plt ; from matplotlib.ticker import MultipleLocator plt.figure(figsize=(15,8)) plt.plot(CLOSE,label='SHZS'); plt.plot(up,label='UP'); #画图显示 plt.plot(mid,label='MID'); plt.plot(lower,label='LOW'); plt.plot(MA10,label='MA10',linewidth=0.5,alpha=0.7); plt.show() ``` -------------------------------- ### Get Daily, Weekly, and Minute Stock Data with Ashare Source: https://github.com/mpquant/ashare/blob/main/README.md Demonstrates fetching historical and real-time stock data using `get_price()`. Supports various frequencies ('1d', '1w', '1M', '1m', '5m', '15m', '30m', '60m') and allows specifying the number of data points or an end date. Stock codes are compatible with multiple formats. ```python from Ashare import * # 证券代码兼容多种格式 通达信,同花顺,聚宽 # sh000001 (000001.XSHG) sz399006 (399006.XSHE) sh600519 ( 600519.XSHG ) df=get_price('sh000001',frequency='1d',count=5) #默认获取今天往前5天的日线实时行情 print('上证指数日线行情\n',df) df=get_price('000001.XSHG',frequency='1d',count=5,end_date='2021-04-30') #可以指定结束日期,获取历史行情 print('上证指数历史行情\n',df) df=get_price('000001.XSHG',frequency='1w',count=5,end_date='2018-06-15') #支持'1d'日, '1w'周, '1M'月 print('上证指数历史周线\n',df) df=get_price('sh600519',frequency='15m',count=5) #分钟线实时行情,可用'1m','5m','15m','30m','60m' print('贵州茅台15分钟线\n',df) df=get_price('600519.XSHG',frequency='60m',count=6) #分钟线实时行情,可用'1m','5m','15m','30m','60m' print('贵州茅台60分钟线\n',df) ``` -------------------------------- ### Calculate and Print ATR, CCI, and Williams %R Source: https://context7.com/mpquant/ashare/llms.txt Calculates Average True Range (ATR), Commodity Channel Index (CCI), and Williams %R (WR) using provided price data. Prints the results, including overbought/oversold signals for CCI. ```python atr = ATR(CLOSE, HIGH, LOW, N=20) print(f'ATR(20): {RET(atr):.2f}') cci = CCI(CLOSE, HIGH, LOW, N=14) print(f'CCI(14): {RET(cci):.2f}') if RET(cci) > 100: print('CCI: Overbought') elif RET(cci) < -100: print('CCI: Oversold') wr10, wr6 = WR(CLOSE, HIGH, LOW, N=10, N1=6) print(f'WR(10): {RET(wr10):.2f}, WR(6): {RET(wr6):.2f}') ``` -------------------------------- ### get_price() — Universal Market Data Fetch Source: https://context7.com/mpquant/ashare/llms.txt The single public entry point of Ashare. Accepts a security code in any of the common Chinese brokerage formats. Internally routes to the Sina Finance API for daily/weekly/monthly and 5m–60m bars, and to the Tencent Finance API for 1-minute bars and as an automatic failover. Returns a DataFrame with columns open, close, high, low, volume indexed by a DatetimeIndex. ```APIDOC ## `get_price()` — Universal Market Data Fetch ### Description The single public entry point of Ashare. Accepts a security code in any of the common Chinese brokerage formats (prefixed `sh`/`sz`, `.XSHG`/`.XSHE` JoinQuant style, or bare numeric). Internally routes to the Sina Finance API for daily/weekly/monthly and 5m–60m bars, and to the Tencent Finance API for 1-minute bars and as an automatic failover. Returns a `DataFrame` with columns `open`, `close`, `high`, `low`, `volume` indexed by a `DatetimeIndex`. ### Parameters - **security_code** (string) - Required - The stock code (e.g., 'sh000001', '000001.XSHG'). - **frequency** (string) - Required - The data frequency ('1d', '1w', '1M', '1m', '5m', '15m', '30m', '60m'). - **count** (integer) - Required - The number of periods to retrieve. - **end_date** (string) - Optional - The end date for historical data (YYYY-MM-DD). ### Supported frequency values: | Value | Description | |-------|-------------| | `'1d'` | Daily bars | | `'1w'` | Weekly bars | | `'1M'` | Monthly bars | | `'1m'` | 1-minute bars (Tencent only) | | `'5m'` | 5-minute bars | | `'15m'` | 15-minute bars | | `'30m'` | 30-minute bars | | `'60m'` | 60-minute bars | ### Request Example ```python from Ashare import * # Daily bars (last 5 trading days) df = get_price('sh000001', frequency='1d', count=5) print('SSE Composite Index — daily:\n', df) # Historical daily bars with an end date df = get_price('000001.XSHG', frequency='1d', count=5, end_date='2021-04-30') print('SSE Composite Index — historical:\n', df) # Weekly bars df = get_price('000001.XSHG', frequency='1w', count=5, end_date='2018-06-15') print('SSE Composite Index — weekly:\n', df) # Monthly bars df = get_price('sh600519', frequency='1M', count=6) print('Kweichow Moutai — monthly:\n', df) # 15-minute intraday bars df = get_price('sh600519', frequency='15m', count=5) print('Kweichow Moutai — 15m:\n', df) # 60-minute intraday bars (JoinQuant code format) df = get_price('600519.XSHG', frequency='60m', count=6) print('Kweichow Moutai — 60m:\n', df) # 1-minute bars (Tencent backend only) df = get_price('sh600519', frequency='1m', count=10) print('Kweichow Moutai — 1m:\n', df) ``` ### Response #### Success Response (200) - **open** (float) - Opening price for the period. - **close** (float) - Closing price for the period. - **high** (float) - Highest price during the period. - **low** (float) - Lowest price during the period. - **volume** (float) - Trading volume for the period. (Returned as a pandas DataFrame with a DatetimeIndex) ``` -------------------------------- ### Fetch Daily, Weekly, Monthly, and Intraday Stock Prices with Ashare Source: https://context7.com/mpquant/ashare/llms.txt Use get_price() to fetch OHLCV data for Chinese A-shares. Supports various frequencies and stock code formats. Data is returned as a pandas DataFrame. ```python from Ashare import * # --- Daily bars (last 5 trading days) --- # Supported formats: 'sh000001', '000001.XSHG', 'sz399006', '399006.XSHE' df = get_price('sh000001', frequency='1d', count=5) print('SSE Composite Index — daily:\n', df) # Expected output: # open close high low volume # 2021-06-07 3597.14 3599.54 3600.38 3581.90 303718677.0 # 2021-06-08 3598.75 3580.11 3621.52 3563.25 304491470.0 # ... # --- Historical daily bars with an end date --- df = get_price('000001.XSHG', frequency='1d', count=5, end_date='2021-04-30') print('SSE Composite Index — historical:\n', df) # --- Weekly bars --- df = get_price('000001.XSHG', frequency='1w', count=5, end_date='2018-06-15') print('SSE Composite Index — weekly:\n', df) # --- Monthly bars --- df = get_price('sh600519', frequency='1M', count=6) print('Kweichow Moutai — monthly:\n', df) # --- 15-minute intraday bars --- df = get_price('sh600519', frequency='15m', count=5) print('Kweichow Moutai — 15m:\n', df) # --- 60-minute intraday bars (JoinQuant code format) --- df = get_price('600519.XSHG', frequency='60m', count=6) print('Kweichow Moutai — 60m:\n', df) # Expected output: # open close high low volume # 2021-06-10 14:00:00 2237.00 2224.16 2245.00 2222.00 4541.53 # 2021-06-10 15:00:00 2222.21 2238.48 2240.34 2222.21 4146.88 # ... # --- 1-minute bars (Tencent backend only) --- df = get_price('sh600519', frequency='1m', count=10) print('Kweichow Moutai — 1m:\n', df) ``` -------------------------------- ### Calculate Moving Averages with MyTT Source: https://context7.com/mpquant/ashare/llms.txt MyTT provides MA (Simple Moving Average), EMA (Exponential Moving Average), and SMA (Chinese-style Weighted Exponential Smoothing) functions. Ensure you have fetched price data using Ashare first. ```python from Ashare import * from MyTT import * df = get_price('000001.XSHG', frequency='1d', count=120) CLOSE = df.close.values # Simple moving averages ma5 = MA(CLOSE, 5) ma10 = MA(CLOSE, 10) ma20 = MA(CLOSE, 20) print(f'MA5 last value: {RET(ma5):.2f}') print(f'MA10 last value: {RET(ma10):.2f}') # Exponential moving average (standard, needs ~120 periods for accuracy) ema12 = EMA(CLOSE, 12) ema26 = EMA(CLOSE, 26) print(f'EMA12 last: {RET(ema12):.2f}, EMA26 last: {RET(ema26):.2f}') # Chinese-style SMA (alpha = M/N), used internally in KDJ/RSI sma_val = SMA(CLOSE, 12, 1) print(f'SMA(12,1) last: {RET(sma_val):.2f}') ``` -------------------------------- ### Signal Logic Utilities: CROSS, COUNT, BARSLAST, EVERY Source: https://context7.com/mpquant/ashare/llms.txt Provides utility functions for building trading signals: CROSS detects when one series crosses above another, COUNT counts true conditions over N bars, BARSLAST finds bars since a condition was last true, and EVERY checks if a condition was true for all N bars. ```python from Ashare import * from MyTT import * df = get_price('sh600519', frequency='1d', count=120) CLOSE = df.close.values ma5 = MA(CLOSE, 5) ma10 = MA(CLOSE, 10) # Golden cross signal if CROSS(ma5, ma10): print('MA5 just crossed above MA10 — buy signal') # Count up-days in last 10 bars up_days = COUNT(CLOSE > REF(CLOSE, 1), 10) print(f'Up-days in last 10 bars: {int(RET(up_days))}') # Bars since last limit-up (≥10% gain) days_since_limit_up = BARSLAST(CLOSE / REF(CLOSE, 1) >= 1.10) print(f'Bars since last ≥10% gain: {days_since_limit_up}') # Check if ALL of the last 5 bars closed above open (all bullish) all_bullish_5 = EVERY(CLOSE > REF(CLOSE, 1), 5) print(f'All 5 bars bullish: {bool(RET(all_bullish_5))}') ``` -------------------------------- ### Compute Bollinger Bands (BOLL) Source: https://context7.com/mpquant/ashare/llms.txt Calculates the 20-period Bollinger Bands (upper, middle, lower) using population standard deviation. Requires price data and returns three NumPy arrays. ```python from Ashare import * from MyTT import * import matplotlib.pyplot as plt df = get_price('000001.XSHG', frequency='1d', count=120) CLOSE = df.close.values upper, mid, lower = BOLL(CLOSE, N=20, P=2) print(f'BOLL Upper: {RET(upper):.3f}') print(f'BOLL Mid: {RET(mid):.3f}') print(f'BOLL Lower: {RET(lower):.3f}') # Plot plt.figure(figsize=(15, 8)) plt.plot(CLOSE, label='CLOSE') plt.plot(upper, label='UPPER', linestyle='--') plt.plot(mid, label='MID') plt.plot(lower, label='LOWER', linestyle='--') plt.title('Bollinger Bands — SSE Composite Index') plt.legend(); plt.grid(alpha=0.4); plt.show() ``` -------------------------------- ### Calculate and Use SLOPE and FORCAST for Linear Regression Source: https://context7.com/mpquant/ashare/llms.txt Computes the linear regression slope and forecasts the next value using the SLOPE and FORCAST functions. Requires importing Ashare and MyTT libraries. The SLOPE function can also return the regression line. ```python from Ashare import * from MyTT import * df = get_price('000001.XSHG', frequency='1d', count=60) CLOSE = df.close.values # Slope of price over last 20 bars slope = SLOPE(CLOSE, N=20) print(f'Price slope (20 bars): {slope:.4f}') if slope > 0: print('Trend is upward') else: print('Trend is downward') # Regression line + slope together slope_val, regression_line = SLOPE(CLOSE, N=20, RS=True) print(f'Regression line start: {regression_line[0]:.2f}, end: {regression_line[-1]:.2f}') # One-bar-ahead forecast next_val = FORCAST(CLOSE, N=20) print(f'Forecasted next close: {next_val:.2f}') ``` -------------------------------- ### Compute Relative Strength Index (RSI) Source: https://context7.com/mpquant/ashare/llms.txt Calculates the Relative Strength Index (RSI) using the Chinese SMA smoothing method. Requires at least 120 periods for numerical accuracy. ```python from Ashare import * from MyTT import * df = get_price('000001.XSHG', frequency='1d', count=150) CLOSE = df.close.values rsi6 = RSI(CLOSE, N=6) rsi12 = RSI(CLOSE, N=12) rsi24 = RSI(CLOSE, N=24) print(f'RSI(6): {RET(rsi6):.2f}') print(f'RSI(12): {RET(rsi12):.2f}') print(f'RSI(24): {RET(rsi24):.2f}') ``` -------------------------------- ### MA() / EMA() / SMA() — Moving Averages Source: https://context7.com/mpquant/ashare/llms.txt MyTT provides three moving average variants matching Chinese platform conventions. `MA()` is a simple rolling mean; `EMA()` is the standard exponential moving average; `SMA()` is the Chinese-style weighted exponential smoothing (used in RSI, KDJ calculations) with configurable alpha via the `M` weight parameter. ```APIDOC ## `MA()` / `EMA()` / `SMA()` — Moving Averages ### Description MyTT provides three moving average variants matching Chinese platform conventions. `MA()` is a simple rolling mean; `EMA()` is the standard exponential moving average; `SMA()` is the Chinese-style weighted exponential smoothing (used in RSI, KDJ calculations) with configurable alpha via the `M` weight parameter. ### Parameters - **values** (numpy.ndarray) - Required - Array of prices (e.g., closing prices). - **period** (integer) - Required - The lookback period for the moving average. - **M** (integer) - Optional (for SMA) - The weight parameter for SMA calculation. ### Functions - **`MA(values, period)`**: Calculates the Simple Moving Average. - **`EMA(values, period)`**: Calculates the Exponential Moving Average. - **`SMA(values, period, M)`**: Calculates the Chinese-style Smoothed Moving Average. ### Request Example ```python from Ashare import * from MyTT import * df = get_price('000001.XSHG', frequency='1d', count=120) CLOSE = df.close.values # Simple moving averages ma5 = MA(CLOSE, 5) ma10 = MA(CLOSE, 10) ma20 = MA(CLOSE, 20) print(f'MA5 last value: {RET(ma5):.2f}') print(f'MA10 last value: {RET(ma10):.2f}') # Exponential moving average (standard, needs ~120 periods for accuracy) ema12 = EMA(CLOSE, 12) ema26 = EMA(CLOSE, 26) print(f'EMA12 last: {RET(ema12):.2f}, EMA26 last: {RET(ema26):.2f}') # Chinese-style SMA (alpha = M/N), used internally in KDJ/RSI sma_val = SMA(CLOSE, 12, 1) print(f'SMA(12,1) last: {RET(sma_val):.2f}') ``` ### Response Each function returns a numpy array containing the calculated moving average values. The `RET()` helper function can be used to get the last valid value from the array. ``` -------------------------------- ### Compute KDJ Stochastic Oscillator Source: https://context7.com/mpquant/ashare/llms.txt Calculates the KDJ indicator (K, D, J lines) using the Chinese RSV-based formula. Requires CLOSE, HIGH, and LOW price data. Results match Tongdaxin/Tonghuashun exactly. ```python from Ashare import * from MyTT import * df = get_price('sh600519', frequency='1d', count=120) CLOSE = df.close.values HIGH = df.high.values LOW = df.low.values K, D, J = KDJ(CLOSE, HIGH, LOW, N=9, M1=3, M2=3) print(f'K: {RET(K):.2f}') print(f'D: {RET(D):.2f}') print(f'J: {RET(J):.2f}') # Overbought / oversold check if RET(K) > 80: print('KDJ: Overbought zone (K > 80)') elif RET(K) < 20: print('KDJ: Oversold zone (K < 20)') ``` -------------------------------- ### Compute Directional Movement Index (DMI) Source: https://context7.com/mpquant/ashare/llms.txt Calculates the Directional Movement Index including PDI, MDI, ADX, and ADXR. Results match Tongdaxin and Tonghuashun. Useful for trend strength and direction analysis. ```python from Ashare import * from MyTT import * df = get_price('sh600519', frequency='1d', count=120) CLOSE = df.close.values HIGH = df.high.values LOW = df.low.values PDI, MDI, ADX, ADXR = DMI(CLOSE, HIGH, LOW, M1=14, M2=6) print(f'PDI: {RET(PDI):.2f}') print(f'MDI: {RET(MDI):.2f}') print(f'ADX: {RET(ADX):.2f}') print(f'ADXR: {RET(ADXR):.2f}') # Trend strength check if RET(ADX) > 25: direction = 'Uptrend' if RET(PDI) > RET(MDI) else 'Downtrend' print(f'Strong trend detected: {direction}') ``` -------------------------------- ### Volatility & Momentum Indicators: ATR, CCI, WR Source: https://context7.com/mpquant/ashare/llms.txt Suite of volatility and momentum indicators operating on OHLC data. ATR computes Average True Range, CCI is Commodity Channel Index, and WR is Williams %R oscillator. ```python from Ashare import * from MyTT import * df = get_price('sh600519', frequency='1d', count=120) CLOSE = df.close.values HIGH = df.high.values LOW = df.low.values # Example usage for ATR, CCI, WR would follow here, but are not provided in the source. ``` -------------------------------- ### Compute MACD Indicator Source: https://context7.com/mpquant/ashare/llms.txt Calculates the Moving Average Convergence Divergence (MACD) including DIF, DEA, and MACD histogram. Ensure at least 120 periods of data for accurate results matching common platforms. ```python from Ashare import * from MyTT import * df = get_price('sh600519', frequency='1d', count=250) CLOSE = df.close.values DIF, DEA, MACD_hist = MACD(CLOSE, SHORT=12, LONG=26, M=9) print(f'DIF: {RET(DIF):.3f}') print(f'DEA: {RET(DEA):.3f}') print(f'MACD: {RET(MACD_hist):.3f}') # Detect golden cross (DIF crosses above DEA) if CROSS(DIF, DEA): print('Golden cross detected on latest bar!') else: print('No golden cross on latest bar.') ``` === COMPLETE CONTENT === This response contains all available snippets from this library. No additional content exists. Do not make further requests.