同花順轉股溢價率中位數獲取

PinHsin發表於2024-06-26

Python環境配置

詳細安裝步驟參考Python安裝與環境配置超詳細保姆級教程

iFind Python 環境配置

  1. 點選下載同花順資料介面
  2. 第一次下載的使用者,請您先開啟資料夾內的SuperCommand並登入您的賬號
  3. 登入後,系統會要求您修復相關程式語言環境,請按照指示修復相關環境
  4. 或在登入後點選工具中的環境設定選項,選中Python後點選確定按鈕
  5. 然後選中安裝的Python路徑,點選繼續

安裝Pycharm

點選下載

詳細安裝步驟pycharm安裝教程

執行Python程式

"""
Author:binxin
Date:2023/11/18 14:44
"""
import os
import numpy as np
import pandas as pd
from iFinDPy import *
import datetime


# 登入函式
def login(username, password):
    thsLogin = THS_iFinDLogin(username, password)
    if thsLogin != 0:
        print('登入失敗')
    else:
        print('登入成功')


# 獲取資料
def get_data(edate):
    get_str = 'edate=' + edate + ';zqlx=全部'
    data_p00868 = THS_DR('p00868', get_str, 'p00868_f027:Y,p00868_f022:Y', 'format:list')
    return data_p00868


# 儲存資料到Excel
def save_to_excel(file_name, str_date, premium):
    if not os.path.exists(file_name):
        data = {"日期": [str_date], "轉股溢價率%": [premium]}
        df = pd.DataFrame(data)
    else:
        df = pd.read_excel(file_name)
        new_data = pd.DataFrame({"日期": [str_date], "轉股溢價率%": [premium]})
        df = pd.concat([df, new_data], ignore_index=True)

    df.to_excel(file_name, index=False)


# 計算中位數
def calculate_median(data):
	# 轉換價值範圍
    max_value = 101
    min_value = 99
    float_values = []

    data_f022 = data['p00868_f022']
    data_f027 = data['p00868_f027']

    for f027, f022 in zip(data_f027, data_f022):
        if '--' in f027 or '--' in f022:
            continue

        f027_value = float(f027)
        f022_value = float(f022)

        if min_value <= f027_value <= max_value:
            float_values.append(f022_value)

    return np.median(float_values) if float_values else None


# 獲取資料 - 單日
def get_today_data():
    today = datetime.date.today()
    edate = today.strftime("%Y%m%d")
    return get_data(edate)


# 獲取資料 - 區間
def get_interval_data(start_date, end_date):
    delta = datetime.timedelta(days=1)
    data_list = []

    while start_date <= end_date:
        edate = start_date.strftime("%Y%m%d")
        data = get_data(edate)
        if data.data is not None:
            data_list.append((start_date.strftime("%Y/%m/%d"), data))
        start_date += delta

    return data_list

# 主函式
def main():
    username = "賬號"
    password = "密碼"
    login(username, password)

    # 獲取本日資料
    # today_data = get_today_data()
    # if today_data.data is not None:
    #     today_median = calculate_median(today_data.data[0]['table'])
    #     if today_median is not None:
    #         save_to_excel("轉股溢價率記錄(轉換價值).xlsx", datetime.date.today().strftime("%Y/%m/%d"), today_median)

    # 獲取區間時間內的資料
    start_date = datetime.date(2023, 11, 1)
    end_date = datetime.date(2023, 11, 18)
    interval_data = get_interval_data(start_date, end_date)

    for date, data in interval_data:
        median_value = calculate_median(data.data[0]['table'])
        if median_value is not None:
            save_to_excel("轉股溢價率記錄(轉換價值).xlsx", date, median_value)


if __name__ == '__main__':
    main()

相關文章