1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63
| from IPython.core.display import display, HTML display(HTML("<style>.container { width:100% !important; }</style>")) from warnings import filterwarnings filterwarnings('ignore')
from numpy import maximum, minimum from tqdm import tqdm from pandas import DataFrame from matplotlib import pyplot from matplotlib.pylab import date2num import matplotlib.ticker as ticker import matplotlib.pyplot as plt plt.rcParams["font.sans-serif"]=["SimHei"] plt.rcParams["axes.unicode_minus"]=False
def plot_adline(index_symbol = "000300.XSHG", start_date="2021-01-01", end_date="2021-12-22"): cal_dates = get_price(index_symbol, start_date=start_date, end_date=end_date).dropna().index.tolist() cal_dates = [i.strftime("%Y-%m-%d") for i in cal_dates] cal_dates.sort()
ad_df = [] for date in tqdm(cal_dates): universe = get_index_stocks(index_symbol, date=date)
data = get_price(security=universe, end_date=date, count=2, fields="close", panel=False) data = data.sort_values("time") size = int(data.shape[0]/2) pre_data = data.iloc[:size] data = data.iloc[size:]
data = data.set_index("code")["close"] pre_data = pre_data.set_index("code")["close"] diff = data - pre_data a = sign(maximum(diff, 0)).sum() d = sign(minimum(diff, 0)).sum() ad_df.append([date, a, d, a+d])
ad_df = DataFrame(ad_df) ad_df.columns = ["date", "a", "d", "diff"] ad_df["ad_line"] = ad_df["diff"].cumsum()
ad_df = ad_df.set_index("date") index_price = get_price(index_symbol, start_date=cal_dates[0], end_date=cal_dates[-1])["close"] index_price.index = index_price.index.strftime("%Y-%m-%d") ad_df["index"] = index_price
fig = pyplot.figure(figsize=(30, 6)) ax = fig.add_subplot(111) ad_df["index"].reset_index(drop=True).plot(ax=ax) ax = ax.twinx() ad_df["ad_line"].reset_index(drop=True).plot(ax=ax, color="r", linestyle="-")
ax.xaxis.set_major_locator(ticker.MultipleLocator(120)) date_tickers = ad_df.index.tolist() ax.xaxis.set_major_formatter(ticker.FuncFormatter(lambda x, y: "" if (x<0 or x>len(date_tickers)-1) else date_tickers[int(x)])) pyplot.xlim(0, ad_df.shape[0]) pyplot.title("Index Symbol: {}".format(index_symbol)) pyplot.grid() return ad_df data = plot_adline("000300.XSHG", "2013-01-01", "2021-12-23")
|