栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > Python

python操作csv文档记录账户回撤

Python 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

python操作csv文档记录账户回撤

一. 实现内容:

将历史最高资产余额记录在csv文档中,每日余额收盘前进行对比,

1.如果大于历史数据,则写入csv文档记录,返回“new high”;

2.如果小于历史数据,则计算回撤比例,返回具体百分数;

输入今日余额,返回对应结果。

二. 实现效果:

效果截图如下:

三. 所需环境:

python环境+windows

代码+csv文件

 代码如下:

#实现文本写入,文本读取,
#实现定期写入日期及剩余金额,以及max日期和金额,
#写入日期金额时,打印最大回撤百分比,或者突破新高。
def highDrawdown(today):
    import csv,time
    #1.读取文件内历史高位数据
    with open(r'./test.csv', encoding='utf-8')as f:
        reader = csv.reader(f)
        next(reader)
        for row in reader:
            max = float(row[1])
    #2.对比当前余额,更新数据or计算回撤
    if (today > max):        
        #末尾追加写入,文件必须已存在
        with open(r'./test.csv',mode='a',newline='',encoding='utf-8') as cfa:
            wf = csv.writer(cfa)
            wf.writerow([time.strftime('%Y-%m-%d',time.localtime(time.time())), today])
            return ('new high')
    else:
        data = 1-(today/max)
        return ('%.2f%%' % (data * 100))
    

if __name__ == "__main__":
    today = 260
    print(highDrawdown(today))
# =============================================================================
#     #初始化模拟
#     #对csv文件进行写入操作,mode='w'表示操作模式为只写,如文件不存在则自动创建文件覆盖写入
#     with open(r'./test.csv',mode='w',newline='',encoding='utf-8') as cf:
#         wf=csv.writer(cf)
#         wf.writerow(['date', 'money'])
#         data = [['16:33:52', '100'], ['16:33:53', '120']]
#         for i in data:
#             wf.writerow(i)
# =============================================================================

csv截图:

大概就是这样子啦,可以复用到一键清仓,实现自动止损功能。

补:

#实现文本写入,文本读取,
def highDrawdown(today):
    import csv,time
    #1.读取文件内历史高位数据
    with open(r'./test.csv', encoding='utf-8')as f:
        reader = csv.reader(f)
        next(reader)
        for row in reader:
            max = float(row[1])
    #2.对比当前余额,更新数据or计算回撤
    if (today > max):        
        #末尾追加写入,文件必须已存在
        with open(r'./test.csv',mode='a',newline='',encoding='utf-8') as cfa:
            wf = csv.writer(cfa)
            wf.writerow([time.strftime('%Y-%m-%d',time.localtime(time.time())), today])
            return ('new high')
    else:
        data = 1-(today/max)
        return '距离前高'+row[0]+'已回撤'+('%.2f%%' % (data * 100))
    

if __name__ == "__main__":
    today = 280
    print(highDrawdown(today))

转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/822779.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号