编写 python 脚本 get_amplit.py 如下

# coding: utf-8
""" 计算每日振幅 amplitude 的平均值 """
import os, sys
import numpy as np
import pandas as pd
import tushare as ts
import talib
import math

if len(sys.argv) ==2:
    code = sys.argv[1]
else:
    print('usage: python get_amplit.py stockcode ')
    sys.exit(1)

if len(code) !=6:
    print('stock code length: 6')
    sys.exit(2)

df = ts.get_k_data(code)
if df.empty ==True:
    print(" df is empty ")
    sys.exit(2)

#df = df[ df['date'] > '2026-01-01']
if len(df) <5:
    print(" len(df) <5 ")
    sys.exit(2)

# 收盘价
close = np.array(df['close'])
# 计算振幅 %
df['amplitude'] = (df['high'] / df['low'] -1) *100
amplitude = np.array(df['amplitude'])

# 假设资金总量: 100万元,损益的期望值取百分之一
per = 10000
price = close[-1]
#print(df)
avg_rate = np.average(amplitude)
print(f"average rate: {round(avg_rate,2)}%")
share = math.floor(per /avg_rate/100)*100
print('share=',share)
print(code,':',price,'*',share,'=',price*share)

运行 python get_amplit.py 688820 

D:\stock> python get_amplit.py 688820
本接口即将停止更新,请尽快使用Pro版接口:https://tushare.pro/document/2
         date    open   close    high    low       volume    code  amplitude
0  2026-04-21   99.72   76.65  100.99  75.00  129928415.0  688820  34.653333
1  2026-04-22   76.01   95.00   96.22  75.02   94285134.0  688820  28.259131
2  2026-04-23   94.50   88.60  102.50  88.60   66385111.0  688820  15.688488
3  2026-04-24   90.50   93.82  103.00  86.10   66841683.0  688820  19.628339
4  2026-04-27   96.50  101.10  102.33  96.50   55228890.0  688820   6.041451
5  2026-04-28  100.00   93.00  100.00  91.72   55001485.0  688820   9.027475
6  2026-04-29   91.07   92.50   94.33  86.87   40984367.0  688820   8.587545
7  2026-04-30   93.79  103.00  107.00  91.00   59862912.0  688820  17.582418
average rate: 17.43%
share= 500
688820 : 103.0 * 500 = 51500.0

解释:假设资金总量: 100万元,损益的期望值取百分之一就是1万元;
每日振幅的平均值为:17.43%
盛合晶微(SH:688820) 按当前收盘价103元计算得出:适宜买入500股,投入资金:51500元

本文目的在于探讨股票风险控制算法,不推荐买入任何股票。读者不可据此操作,后果自负。

更多推荐