问题描述
我有一个使用 API 收集财务数据并将其转换为 ecxel 文件的代码。在我的列中,我有考虑到最后一天股票价格变化的数据,我希望 python 用红色写负变化,用绿色写正变化。我知道如何使用它,使用 if/else 语句,但问题是我应该在 if 语句中调用哪个变量。
这是我使用 request.get 函数从 API 附加数据时的部分。
data = requests.get(batch_apu_call_url).json()
for symbol in symbol_string.split(','):
final_dataframe = final_dataframe.append(
pd.Series(
[
data[symbol]['quote']['companyName'],symbol,data[symbol]['quote']['latestPrice'],data[symbol]['quote']['changePercent'],#This is the line thats collects the changes in the stock prices
data[symbol]['quote']['marketCap'],'N/A',data[symbol]['quote']['latestTime']
],index=my_columns),ignore_index=True,)
她是我想格式化特殊列的部分
change_format = writer.book.add_format(
{
'num_format': '0.00%','font_color': 'EA1009' if [] < 0 else '2AEA09',#insted of the square brackets I want to put the variabel
'bg_color': background_color,'border': 1
}
)
这是python中部分结果的示例:
Name Ticker Stock Price +/-% Market Cap
0 Agilent Technologies Inc. A 127.120 0.01096 38026751371
1 American Airlines Group Inc AAL 26.301 0.02625 16894821033
2 Advance Auto Parts Inc AAP 184.060 0.01200 12369889031
3 Apple Inc AAPL 125.884 -0.02000 2114224151643
4 Abbvie Inc ABBV 109.250 -0.00430 191633606290
Process finished with exit code 0
和 ecxel 中的结果相同。 ecxel 文件今天没有更新,所以数据可能与python 数据不同。 https://i.stack.imgur.com/i9PIz.png
这是我希望它锁定的: https://i.stack.imgur.com/G8xA5.png
解决方法
我找到了解决方案,最好的方法是:
change_format = writer.book.add_format(
{
'num_format': '0.00%[Green];-0.00%[Red]','font_color': '','bg_color': background_color,'border': 1
}
)