我正在尝试以更好的方式查看我的股票分析结果。有两种方法我真的想在csv中保存我的分析(其中一个会为我做)
AAPL,momentum,250.45,active,No cross,MACD above 0
我更喜欢第一种解决方案,因为它只需要将其保存到文件中,但我无法使用writerow将其写入一行。我计划添加3到4个零件分析并将它们组合起来。 以下代码适用于解决方案2,但我有问题,将标题。我标记为hdm和part2(未放入脚本)的part1的标题是不同的,它不能在for循环中,因为它将重复标题。 请帮助我了解此代码的最佳方法。谢谢!
import pandas as pd
import numpy as np
import csv
import datetime
import matplotlib.pyplot as plt
import talib as ta
now = datetime.datetime.now()
KLSEData = ['AAPL','MSFT','IBM','WDC','STX','EMC','NCR','XRX']
KLSElen = len(KLSEData)
hdm = ['Stock','Mom','Pct','Liquidity']
csvout = open('stock_mo'+now.strftime("%Y-%m-%d")+".csv", 'a')
csvwrite = csv.writer(csvout)
csvwrite.writerow(hdm)
for x in range (1,len(KLSEData),1):
data = pd.read_csv(KLSEData [x][0]+".csv", index_col='Stock', usecols =[0,6,7])
high = pd.read_csv(KLSEData [x][0]+".csv", index_col='Stock', usecols =[0,4])
h=np.array(high['High'])
low = pd.read_csv(KLSEData [x][0]+".csv", index_col='Stock', usecols =[0,5])
l = np.array(low['Low'])
close = pd.read_csv(KLSEData [x][0]+".csv", index_col='Stock', usecols =[0,6])
c = np.array(close['Close'])
vol = high = pd.read_csv(KLSEData [x][0]+".csv", index_col='Stock', usecols =[0,7])
v = np.array(vol['Volume'])
#data = pd.read_csv(KLSEData [x]+".csv", index_col='Stock', usecols =[0,7])
print data.head(3)
vol1 = data['Volume']
print vol
volmean5 = pd.rolling_mean(vol1,5)
#print volmean5
volmean20 = pd.rolling_mean(vol1,20)
#print volmean20
mo_ratio = volmean5/volmean20
print mo_ratio[-1]
mo_pc = (mo_ratio[-1]-1)*100
#print mo_ratio
MACD = ta.MACD(c)
#part1 momentum analysis
if mo_ratio[-1]>= 2.5:
print '+ve momentum'
active = vol.tail(30)==0
"""for y in range (len(data)-30,len(data),1):
active=[data.iloc[y,1]==0]"""
if any(active):
csvwrite.writerow([KLSEData [x][0]]+[" momentum "]+["%.2f"%mo_pc]+["not active"])
csvout.close()
else:
csvwrite.writerow([KLSEData [x][0]]+[" momentum "]+["%.2f"%mo_pc]+["active"])
csvout.close()
else:
print 'no momentum'
#part2 MACD analysis
csvout1 = open('stock_macd'+now.strftime("%Y-%m-%d")+".csv", 'a')
csvwrite1 = csv.writer(csvout1)
if MACD[2][-1]>1e-08 and MACD[2][-3]<MACD[2][-2]<MACD[2][-1]:
if MACD[0][-1]>MACD[1][-1] and MACD[1][-1]>0.0:
csvwrite.writerow([KLSEData [x][0]]+["Golden Cross"]+["MACD above 0"])
csvout.close()
else:
csvwrite.writerow([KLSEData [x][0]]+["Golden Cross"]+["MACD below 0"])
csvout.close()
else:
if MACD[0][-1]>MACD[1][-1] and MACD[1][-1]>0.0:
csvwrite.writerow([KLSEData [x][0]]+["No Cross"]+["MACD above 0"])
csvout.close()
else:
print "No MACD signal"
我想要的输出:
AAPL,momentum,250.45,active,No cross,MACD above 0
MSFT,momentum,130.59,not active, Golden cross,MACD above 0
当前输出:
Stock,Mom,Pct,Liquidity
AAPL, momentum ,251.77,not active
AAPL,No Cross,MACD above 0
Stock,Mom,Pct,Liquidity
MSFT, momentum ,251.77,not active
MSFT,No Cross,MACD above 0