Home > Mobile >  For loop only showing last value instead of them all | Cryptocurrency
For loop only showing last value instead of them all | Cryptocurrency

Time:09-17

I'm trying to make a crypto scanner but I'm stuck on a problem. I made a small csv file with some crypto currencies looking as follows:

BTC-USD
ETH-USD
ADA-USD
BNB-USD

Now I want to loop through this csv file and put all the values in the function for df. The problem now is that it only inserts the last value of the file and gives the graph of that coin. I tried this as follows:

with open('symbols.csv') as f:
    symbols = f.read().splitlines()
    for symbol in symbols:
        df = yf.download(symbol, start='2020-01-01')

I feel like it's doing it's job because I get the following output:

[*********************100%***********************]  1 of 1 completed
[*********************100%***********************]  1 of 1 completed
[*********************100%***********************]  1 of 1 completed
[*********************100%***********************]  1 of 1 completed

Now I want to get the 4 graphs from all the coins and not only the last coin in the csv file. Could anyone help me figure this out? Thanks in advance!

NOTE: The rest of the code is working and giving the correct values, the only thing missing now is the loop to get outputs from different coins.

My entire code is:

import yfinance as yf
import numpy as np
import matplotlib.pyplot as plt
import pandas as pd


with open('symbols.csv') as f:
    symbols = f.read().splitlines()
    for symbol in symbols:
        df = yf.download(symbol, start='2020-01-01')

# df = yf.download('ADA-USD', start='2021-01-01')

df['SMA'] = df.Close.rolling(window=20).mean()
df['stddev'] = df.Close.rolling(window=20).std()
df['Upper'] = df.SMA   2* df.stddev
df['Lower'] = df.SMA - 2* df.stddev
df['Buy_Signal'] = np.where(df.Lower > df.Close, True, False)
df['Sell_Signal'] = np.where(df.Upper < df.Close, True, False)

buys = []
sells = []
open_pos = False

for i in range(len(df)):
    if df.Lower[i] > df.Close[i]:
        if open_pos == False:
            buys.append(i)
            open_pos = True
    elif df.Upper[i] < df.Close[i]:
        if open_pos:
            sells.append(i)
            open_pos = False

print('zoveel buys:', buys)
print('zoveel sells:', sells)

# print(df.dropna())

plt.figure(figsize=(12, 6))
# plt.scatter(df.index[df.Buy_Signal], df[df.Buy_Signal].Close, marker = '^', color ='g')
# plt.scatter(df.index[df.Sell_Signal], df[df.Sell_Signal].Close, marker = '^', color ='r')
plt.scatter(df.iloc[buys].index, df.iloc[buys].Close, marker = '^', color ='g')
plt.scatter(df.iloc[sells].index, df.iloc[sells].Close, marker = '^', color ='r')

plt.plot(df[['Close', 'SMA', 'Upper', 'Lower']])
plt.fill_between(df.index, df.Upper, df.Lower, color='grey', alpha=0.3)
plt.legend(['Close', 'SMA', 'Upper', 'Lower'])
plt.show()

merged = pd.concat([df.iloc[buys].Close, df.iloc[sells].Close], axis=1)
merged.columns = ['Buys', 'Sells']
print(merged)
# #
totalprofit = merged.shift(-1).Sells - merged.Buys
print(totalprofit)

relprofits = (merged.shift(-1).Sells - merged.Buys) / merged.Buys
print(relprofits.mean())

CodePudding user response:

In this line

df = yf.download(symbol, start='2020-01-01')

you are assigning the result of the download to a dataframe. However, each time you create a new dataframe instead of adding to it.

As such, you either need to do everything you want with the df within the loop by calling a function on the df, for example do_something(df) Or you could store it in some dfs = [] with dfs.append(df), then you'd have each dataframe in an array of dataframes.

  • Related