当前位置: 首页 > 科技观察

用 Python 筛选收益优秀的加密货币

时间:2023-03-18 23:07:24 科技观察

使用Python筛选回报丰厚的加密货币是哪种货币?信不信由你,Binance自己的BNB实际上远远优于其他所有加密货币。当我决定只包含前10种加密货币并查看哪些表现最佳时,我编写了一个脚本来帮助我了解几种加密货币的历史表现。在运行脚本之前,我很确定它可能是DOGE。所以我坐在这里,等待下载历史数据,以便我的脚本可以绘制一些密码图。脚本跑完了,结果出来了,感谢中本聪,这不是DOGE。哦等等,这更有趣——它是BNB。2017年以来,BNB涨幅超过20000%。该程序可以为您下载历史数据并分析任意数量的货币。如果您想对任意数量的加密货币的百分比收益进行快速比较分析,这将非常方便。您所需要的只是一些Python知识。编写一个加密货币分析工具代码也可以在GitHub上找到。https://github.com/Cyber??PunkMetalHead/crypto-performance-tracker首先创建一个文本文件并将其命名为coins.txt。在此文本文件中,放入一些您要分析的货币名称。它们需要包含成对的符号,并且每行必须是1个货币,没有逗号:BTCUSDTETHUSDTBNBUSDT创建一个binancedata.py文件。我们将使用此文件轮询BinanceAPI以获取我们需要的财务数据。由于我们使用的是开放端口,因此不需要API密钥和密码。让我们导入一些依赖项并定义一个空的Binance客户端:#neededforthebinanceAPIandwebsocketsfrombinance.clientimportClientimportcsvimportosimporttimefromdatetimeimportdate,datetimeclient=Client()现在让我们编写一个函数来打开并从coins.txt文件中读取硬币:defget_coins():withopen('coins.txt','r')asf:coins=f.readlines()coins=[coin.strip('\n')forcoinincoins]returncoins该文件中的最后一个函数将为我们获取历史数据并以CSV格式保存:defget_historical_data(coin,since,kline_interval):"""Argsexample:coin='BTCUSDT'since='1Jan2021'kline_interval=Client.KLINE_INTERVAL_1MINUTE"""ifos.path.isfile(f'data/{coin}_{since}.csv'):print('Datafilealreadyexists,loadingfile...')else:print(f'Fetchinghistoricaldatafor{coin},thismaytakeafewminutes...')start_time=time.perf_counter()data=client.get_historical_klines(coin,kline_interval,since)data=[item[0:5]foritemindata]#fieldnamesfields=['timstamp','high','low','open','close']#savethedatawithopen(f'data/{硬币}_{since}.csv','w',newline='')asf:#usingcsv.writermethodfromCSVpackagewrite=csv.writer(f)write.writerow(fields)write.writerows(data)end_time=time.perf_counter()#calculatehowlongittooktoproducethefiletime_elapsed=round(end_time-start_time)print(f'Historicaldatafor{coin}savedas{coin}_{since}.csv.Timeelapsed:{time_elapsed}seconds')returnf'{coin}_{since}.csv'此函数还会检查文件是否已经存在,如果存在则不会再次下载该函数接受3个参数:coin,since和kline_interval。检查函数下方的注释,了解我们将传递给这些参数的正确格式。保存文件,现在是时候创建我们的主要可执行文件了,我们将在其中导入该文件的内容。继续创建一个main.py文件并安装以下依赖项:该脚本旨在一次下载多个数据文件,因此为了避免一次等待下载每个历史数据文件,我们将使用线程并像这样下载文件:threads=[]coins=get_coins()forcoinincoins:t=线程.Thread(target=get_historical_data,args=(coin,'1Jan2017',Client.KLINE_INTERVAL_1DAY))#'get_historical_data('ETHUSDT','1Jan2021',Client.KLINE_INTERVAL_1MINUTE)t.start()threads.append(t)[thread.join()forthreadinthreads]现在我们需要一个函数来返回我们下载的所有数据文件的文件名:defget_all_filenames():return[get_historical_data(coin,'1Jan2017',Client.KLINE_INTERVAL_1DAY)forcoinincoins]main函数,我们将在其中绘制这些数据并运行脚本:defmain():historical_data=get_all_filenames()forfileinhistorical_data:data=pd.read_csv(f'data/{file}')rolling_percentage=data['close']rolling_percentage=[(item-rolling_percentage[0])/rolling_percentage[0]*100foriteminrolling_percentage]timestamp=data['timstamp']timestamp=[datetime.fromtimestamp(item/1000)foritemintimestamp]plt.legend()plt.plot(timestamp,rolling_percentage,label=file)plt.xlabel("Date")plt.ylabel("%gain")plt.show()if__name__=="__main__":main()现在剩下要做的就是在脚本目录中创建一个空文件夹,并将其命名为数据就大功告成了,你现在可以分析你想要的所有代币的历史收益。