【发布时间】:2015-08-05 07:26:35
【问题描述】:
我需要结合公司股票代码(Apple Computers 的 AAPL 等)创建一个数据帧 (df_max_res),其中包含我的股票策略中的 15 个最佳表现。我有一个包含 500 多个股票代码的列表,我使用我自己的四种策略对其进行分析。
在for eachP in perf_array 嵌套内部迭代中,我从策略和代码的所有组合中获得性能结果。我想使用此代码(或更好的建议)将这些结果保存到 DataFrame 和 csv 文件中:
#==============================================================================
# Saving results in pandas and to a csv-file
#==============================================================================
def saving_res_pandas():
global df_res, df_max_res
df_res = pd.DataFrame(columns=('Strategy', 'Ticker', 'Strat',
'ROI', 'Sharpe R', 'VaR'))
for eachP in perf_array:
df_res.loc[len(df_res) + 1] = [strategy, ticker, strat, stratROI]
# Select the top 15 of all results (ticker/strategy combo) into new df.
df_max_res = df_res[:15]
# Saving to a csv.
df_max_res.to_csv('df_performance_data_sp500ish.csv')
print('After analysing %1.1f Years ~ %d workdays - %d strategies and %d tickers' '\n'
'The following matrix of tickers and strategies show highest ROI: '
% (years, days, len(strategies), len(stock_list))
)
return df_res
#==============================================================================
# Chose which of below methods to save perf-data to disk with
#==============================================================================
saving_res_pandas()
# Reading in df_max_res with best ticker/strategy results
df_max_res = pd.read_csv('df_performance_data_sp500ish.csv')
print(df_max_res)
上面的代码可以很好地创建我的 DataFrame,但它并没有像我预期的那样保存迭代性能结果。
我得到这个输出:
=======================================================
aa === <function strategy1 at 0x00000000159A0BF8> ==
=======================================================
Holdings: 0
Funds: 14659
Starting Valuation: USD 15000.00 ~ DKK: 100000.50
Current Valuation: USD 14659.05 ~ DKK: 97727.49
=== aa == <function strategy1 at 0x00000000159A0BF8> ==
ROI: -1.9 perc. & Annual Profit -1894 DKK ==
######################################################################
cannot set a row with mismatched columns
== ALL Tickers Done for == <function strategy1 at 0x00000000159A0BF8> ==================
Strategy analysis pr ticker - COMPLETE !
Empty DataFrame
Columns: [Unnamed: 0, Strategy, Ticker, ROI, SharpeR, VaR]
Index: []
【问题讨论】:
-
提供一个好的例子将更有可能得到有用的答案:stackoverflow.com/help/mcve
-
你有多少列?这行
df_res[:15]正在选择最多 15 列,这是您想要的,因为您的评论似乎暗示您想要df_res.head(15) -
正是我想显示所有列,但只显示前 15 个组合。所以我想我必须写 df_res.head(15)。那会奏效。目前我只有 3 列,但还会有更多。我需要将它们全部转移到新的df。谢谢埃德。
-
Mike 我认为我已经为我的代码和我看到的输出提供了一个很好的示例 + 解释了我的预期以及这些情况之间的差异。我怎么可能更清楚。我不知道如何比这更具体。请解释...
-
关于如何提出一个好的熊猫问题的好帖子:stackoverflow.com/questions/20109391/…
标签: python csv pandas dataframe